Update makehrtf to use a larger FFT by default
[openal-soft.git] / utils / makehrtf.c
blob547c80db9b0876887f14bf80ad084ec54946cebc
1 /*
2 * HRTF utility for producing and demonstrating the process of creating an
3 * OpenAL Soft compatible HRIR data set.
5 * Copyright (C) 2011-2017 Christopher Fitzgerald
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Or visit: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
23 * --------------------------------------------------------------------------
25 * A big thanks goes out to all those whose work done in the field of
26 * binaural sound synthesis using measured HRTFs makes this utility and the
27 * OpenAL Soft implementation possible.
29 * The algorithm for diffuse-field equalization was adapted from the work
30 * done by Rio Emmanuel and Larcher Veronique of IRCAM and Bill Gardner of
31 * MIT Media Laboratory. It operates as follows:
33 * 1. Take the FFT of each HRIR and only keep the magnitude responses.
34 * 2. Calculate the diffuse-field power-average of all HRIRs weighted by
35 * their contribution to the total surface area covered by their
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-9)
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 (65536)
149 #define MAX_FFTSIZE (131072)
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 (16)
157 #define MAX_TRUNCSIZE (512)
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_FFTSIZE (65536)
169 #define DEFAULT_EQUALIZE (1)
170 #define DEFAULT_SURFACE (1)
171 #define DEFAULT_LIMIT (24.0)
172 #define DEFAULT_TRUNCSIZE (32)
173 #define DEFAULT_HEAD_MODEL (HM_DATASET)
174 #define DEFAULT_CUSTOM_RADIUS (0.0)
176 // The four-character-codes for RIFF/RIFX WAVE file chunks.
177 #define FOURCC_RIFF (0x46464952) // 'RIFF'
178 #define FOURCC_RIFX (0x58464952) // 'RIFX'
179 #define FOURCC_WAVE (0x45564157) // 'WAVE'
180 #define FOURCC_FMT (0x20746D66) // 'fmt '
181 #define FOURCC_DATA (0x61746164) // 'data'
182 #define FOURCC_LIST (0x5453494C) // 'LIST'
183 #define FOURCC_WAVL (0x6C766177) // 'wavl'
184 #define FOURCC_SLNT (0x746E6C73) // 'slnt'
186 // The supported wave formats.
187 #define WAVE_FORMAT_PCM (0x0001)
188 #define WAVE_FORMAT_IEEE_FLOAT (0x0003)
189 #define WAVE_FORMAT_EXTENSIBLE (0xFFFE)
191 // The maximum propagation delay value supported by OpenAL Soft.
192 #define MAX_HRTD (63.0)
194 // The OpenAL Soft HRTF format marker. It stands for minimum-phase head
195 // response protocol 01.
196 #define MHR_FORMAT ("MinPHR01")
198 // Byte order for the serialization routines.
199 typedef enum ByteOrderT {
200 BO_NONE,
201 BO_LITTLE,
202 BO_BIG
203 } ByteOrderT;
205 // Source format for the references listed in the data set definition.
206 typedef enum SourceFormatT {
207 SF_NONE,
208 SF_WAVE, // RIFF/RIFX WAVE file.
209 SF_BIN_LE, // Little-endian binary file.
210 SF_BIN_BE, // Big-endian binary file.
211 SF_ASCII // ASCII text file.
212 } SourceFormatT;
214 // Element types for the references listed in the data set definition.
215 typedef enum ElementTypeT {
216 ET_NONE,
217 ET_INT, // Integer elements.
218 ET_FP // Floating-point elements.
219 } ElementTypeT;
221 // Head model used for calculating the impulse delays.
222 typedef enum HeadModelT {
223 HM_NONE,
224 HM_DATASET, // Measure the onset from the dataset.
225 HM_SPHERE // Calculate the onset using a spherical head model.
226 } HeadModelT;
228 // Desired output format from the command line.
229 typedef enum OutputFormatT {
230 OF_NONE,
231 OF_MHR // OpenAL Soft MHR data set file.
232 } OutputFormatT;
234 // Unsigned integer type.
235 typedef unsigned int uint;
237 // Serialization types. The trailing digit indicates the number of bits.
238 typedef ALubyte uint8;
239 typedef ALint int32;
240 typedef ALuint uint32;
241 typedef ALuint64SOFT uint64;
243 // Token reader state for parsing the data set definition.
244 typedef struct TokenReaderT {
245 FILE *mFile;
246 const char *mName;
247 uint mLine;
248 uint mColumn;
249 char mRing[TR_RING_SIZE];
250 size_t mIn;
251 size_t mOut;
252 } TokenReaderT;
254 // Source reference state used when loading sources.
255 typedef struct SourceRefT {
256 SourceFormatT mFormat;
257 ElementTypeT mType;
258 uint mSize;
259 int mBits;
260 uint mChannel;
261 uint mSkip;
262 uint mOffset;
263 char mPath[MAX_PATH_LEN+1];
264 } SourceRefT;
266 // The HRIR metrics and data set used when loading, processing, and storing
267 // the resulting HRTF.
268 typedef struct HrirDataT {
269 uint mIrRate;
270 uint mIrCount;
271 uint mIrSize;
272 uint mIrPoints;
273 uint mFftSize;
274 uint mEvCount;
275 uint mEvStart;
276 uint mAzCount[MAX_EV_COUNT];
277 uint mEvOffset[MAX_EV_COUNT];
278 double mRadius;
279 double mDistance;
280 double *mHrirs;
281 double *mHrtds;
282 double mMaxHrtd;
283 } HrirDataT;
285 // The resampler metrics and FIR filter.
286 typedef struct ResamplerT {
287 uint mP, mQ, mM, mL;
288 double *mF;
289 } ResamplerT;
292 /*****************************
293 *** Token reader routines ***
294 *****************************/
296 /* Whitespace is not significant. It can process tokens as identifiers, numbers
297 * (integer and floating-point), strings, and operators. Strings must be
298 * encapsulated by double-quotes and cannot span multiple lines.
301 // Setup the reader on the given file. The filename can be NULL if no error
302 // output is desired.
303 static void TrSetup(FILE *fp, const char *filename, TokenReaderT *tr)
305 const char *name = NULL;
307 if(filename)
309 const char *slash = strrchr(filename, '/');
310 if(slash)
312 const char *bslash = strrchr(slash+1, '\\');
313 if(bslash) name = bslash+1;
314 else name = slash+1;
316 else
318 const char *bslash = strrchr(filename, '\\');
319 if(bslash) name = bslash+1;
320 else name = filename;
324 tr->mFile = fp;
325 tr->mName = name;
326 tr->mLine = 1;
327 tr->mColumn = 1;
328 tr->mIn = 0;
329 tr->mOut = 0;
332 // Prime the reader's ring buffer, and return a result indicating that there
333 // is text to process.
334 static int TrLoad(TokenReaderT *tr)
336 size_t toLoad, in, count;
338 toLoad = TR_RING_SIZE - (tr->mIn - tr->mOut);
339 if(toLoad >= TR_LOAD_SIZE && !feof(tr->mFile))
341 // Load TR_LOAD_SIZE (or less if at the end of the file) per read.
342 toLoad = TR_LOAD_SIZE;
343 in = tr->mIn&TR_RING_MASK;
344 count = TR_RING_SIZE - in;
345 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);
350 else
351 tr->mIn += fread(&tr->mRing[in], 1, toLoad, tr->mFile);
353 if(tr->mOut >= TR_RING_SIZE)
355 tr->mOut -= TR_RING_SIZE;
356 tr->mIn -= TR_RING_SIZE;
359 if(tr->mIn > tr->mOut)
360 return 1;
361 return 0;
364 // Error display routine. Only displays when the base name is not NULL.
365 static void TrErrorVA(const TokenReaderT *tr, uint line, uint column, const char *format, va_list argPtr)
367 if(!tr->mName)
368 return;
369 fprintf(stderr, "Error (%s:%u:%u): ", tr->mName, line, column);
370 vfprintf(stderr, format, argPtr);
373 // Used to display an error at a saved line/column.
374 static void TrErrorAt(const TokenReaderT *tr, uint line, uint column, const char *format, ...)
376 va_list argPtr;
378 va_start(argPtr, format);
379 TrErrorVA(tr, line, column, format, argPtr);
380 va_end(argPtr);
383 // Used to display an error at the current line/column.
384 static void TrError(const TokenReaderT *tr, const char *format, ...)
386 va_list argPtr;
388 va_start(argPtr, format);
389 TrErrorVA(tr, tr->mLine, tr->mColumn, format, argPtr);
390 va_end(argPtr);
393 // Skips to the next line.
394 static void TrSkipLine(TokenReaderT *tr)
396 char ch;
398 while(TrLoad(tr))
400 ch = tr->mRing[tr->mOut&TR_RING_MASK];
401 tr->mOut++;
402 if(ch == '\n')
404 tr->mLine++;
405 tr->mColumn = 1;
406 break;
408 tr->mColumn ++;
412 // Skips to the next token.
413 static int TrSkipWhitespace(TokenReaderT *tr)
415 char ch;
417 while(TrLoad(tr))
419 ch = tr->mRing[tr->mOut&TR_RING_MASK];
420 if(isspace(ch))
422 tr->mOut++;
423 if(ch == '\n')
425 tr->mLine++;
426 tr->mColumn = 1;
428 else
429 tr->mColumn++;
431 else if(ch == '#')
432 TrSkipLine(tr);
433 else
434 return 1;
436 return 0;
439 // Get the line and/or column of the next token (or the end of input).
440 static void TrIndication(TokenReaderT *tr, uint *line, uint *column)
442 TrSkipWhitespace(tr);
443 if(line) *line = tr->mLine;
444 if(column) *column = tr->mColumn;
447 // Checks to see if a token is the given operator. It does not display any
448 // errors and will not proceed to the next token.
449 static int TrIsOperator(TokenReaderT *tr, const char *op)
451 size_t out, len;
452 char ch;
454 if(!TrSkipWhitespace(tr))
455 return 0;
456 out = tr->mOut;
457 len = 0;
458 while(op[len] != '\0' && out < tr->mIn)
460 ch = tr->mRing[out&TR_RING_MASK];
461 if(ch != op[len]) break;
462 len++;
463 out++;
465 if(op[len] == '\0')
466 return 1;
467 return 0;
470 /* The TrRead*() routines obtain the value of a matching token type. They
471 * display type, form, and boundary errors and will proceed to the next
472 * token.
475 // Reads and validates an identifier token.
476 static int TrReadIdent(TokenReaderT *tr, const uint maxLen, char *ident)
478 uint col, len;
479 char ch;
481 col = tr->mColumn;
482 if(TrSkipWhitespace(tr))
484 col = tr->mColumn;
485 ch = tr->mRing[tr->mOut&TR_RING_MASK];
486 if(ch == '_' || isalpha(ch))
488 len = 0;
489 do {
490 if(len < maxLen)
491 ident[len] = ch;
492 len++;
493 tr->mOut++;
494 if(!TrLoad(tr))
495 break;
496 ch = tr->mRing[tr->mOut&TR_RING_MASK];
497 } while(ch == '_' || isdigit(ch) || isalpha(ch));
499 tr->mColumn += len;
500 if(len < maxLen)
502 ident[len] = '\0';
503 return 1;
505 TrErrorAt(tr, tr->mLine, col, "Identifier is too long.\n");
506 return 0;
509 TrErrorAt(tr, tr->mLine, col, "Expected an identifier.\n");
510 return 0;
513 // Reads and validates (including bounds) an integer token.
514 static int TrReadInt(TokenReaderT *tr, const int loBound, const int hiBound, int *value)
516 uint col, digis, len;
517 char ch, temp[64+1];
519 col = tr->mColumn;
520 if(TrSkipWhitespace(tr))
522 col = tr->mColumn;
523 len = 0;
524 ch = tr->mRing[tr->mOut&TR_RING_MASK];
525 if(ch == '+' || ch == '-')
527 temp[len] = ch;
528 len++;
529 tr->mOut++;
531 digis = 0;
532 while(TrLoad(tr))
534 ch = tr->mRing[tr->mOut&TR_RING_MASK];
535 if(!isdigit(ch)) break;
536 if(len < 64)
537 temp[len] = ch;
538 len++;
539 digis++;
540 tr->mOut++;
542 tr->mColumn += len;
543 if(digis > 0 && ch != '.' && !isalpha(ch))
545 if(len > 64)
547 TrErrorAt(tr, tr->mLine, col, "Integer is too long.");
548 return 0;
550 temp[len] = '\0';
551 *value = strtol(temp, NULL, 10);
552 if(*value < loBound || *value > hiBound)
554 TrErrorAt(tr, tr->mLine, col, "Expected a value from %d to %d.\n", loBound, hiBound);
555 return (0);
557 return (1);
560 TrErrorAt(tr, tr->mLine, col, "Expected an integer.\n");
561 return 0;
564 // Reads and validates (including bounds) a float token.
565 static int TrReadFloat(TokenReaderT *tr, const double loBound, const double hiBound, double *value)
567 uint col, digis, len;
568 char ch, temp[64+1];
570 col = tr->mColumn;
571 if(TrSkipWhitespace(tr))
573 col = tr->mColumn;
574 len = 0;
575 ch = tr->mRing[tr->mOut&TR_RING_MASK];
576 if(ch == '+' || ch == '-')
578 temp[len] = ch;
579 len++;
580 tr->mOut++;
583 digis = 0;
584 while(TrLoad(tr))
586 ch = tr->mRing[tr->mOut&TR_RING_MASK];
587 if(!isdigit(ch)) break;
588 if(len < 64)
589 temp[len] = ch;
590 len++;
591 digis++;
592 tr->mOut++;
594 if(ch == '.')
596 if(len < 64)
597 temp[len] = ch;
598 len++;
599 tr->mOut++;
601 while(TrLoad(tr))
603 ch = tr->mRing[tr->mOut&TR_RING_MASK];
604 if(!isdigit(ch)) break;
605 if(len < 64)
606 temp[len] = ch;
607 len++;
608 digis++;
609 tr->mOut++;
611 if(digis > 0)
613 if(ch == 'E' || ch == 'e')
615 if(len < 64)
616 temp[len] = ch;
617 len++;
618 digis = 0;
619 tr->mOut++;
620 if(ch == '+' || ch == '-')
622 if(len < 64)
623 temp[len] = ch;
624 len++;
625 tr->mOut++;
627 while(TrLoad(tr))
629 ch = tr->mRing[tr->mOut&TR_RING_MASK];
630 if(!isdigit(ch)) break;
631 if(len < 64)
632 temp[len] = ch;
633 len++;
634 digis++;
635 tr->mOut++;
638 tr->mColumn += len;
639 if(digis > 0 && ch != '.' && !isalpha(ch))
641 if(len > 64)
643 TrErrorAt(tr, tr->mLine, col, "Float is too long.");
644 return 0;
646 temp[len] = '\0';
647 *value = strtod(temp, NULL);
648 if(*value < loBound || *value > hiBound)
650 TrErrorAt (tr, tr->mLine, col, "Expected a value from %f to %f.\n", loBound, hiBound);
651 return 0;
653 return 1;
656 else
657 tr->mColumn += len;
659 TrErrorAt(tr, tr->mLine, col, "Expected a float.\n");
660 return 0;
663 // Reads and validates a string token.
664 static int TrReadString(TokenReaderT *tr, const uint maxLen, char *text)
666 uint col, len;
667 char ch;
669 col = tr->mColumn;
670 if(TrSkipWhitespace(tr))
672 col = tr->mColumn;
673 ch = tr->mRing[tr->mOut&TR_RING_MASK];
674 if(ch == '\"')
676 tr->mOut++;
677 len = 0;
678 while(TrLoad(tr))
680 ch = tr->mRing[tr->mOut&TR_RING_MASK];
681 tr->mOut++;
682 if(ch == '\"')
683 break;
684 if(ch == '\n')
686 TrErrorAt (tr, tr->mLine, col, "Unterminated string at end of line.\n");
687 return 0;
689 if(len < maxLen)
690 text[len] = ch;
691 len++;
693 if(ch != '\"')
695 tr->mColumn += 1 + len;
696 TrErrorAt(tr, tr->mLine, col, "Unterminated string at end of input.\n");
697 return 0;
699 tr->mColumn += 2 + len;
700 if(len > maxLen)
702 TrErrorAt (tr, tr->mLine, col, "String is too long.\n");
703 return 0;
705 text[len] = '\0';
706 return 1;
709 TrErrorAt(tr, tr->mLine, col, "Expected a string.\n");
710 return 0;
713 // Reads and validates the given operator.
714 static int TrReadOperator(TokenReaderT *tr, const char *op)
716 uint col, len;
717 char ch;
719 col = tr->mColumn;
720 if(TrSkipWhitespace(tr))
722 col = tr->mColumn;
723 len = 0;
724 while(op[len] != '\0' && TrLoad(tr))
726 ch = tr->mRing[tr->mOut&TR_RING_MASK];
727 if(ch != op[len]) break;
728 len++;
729 tr->mOut++;
731 tr->mColumn += len;
732 if(op[len] == '\0')
733 return 1;
735 TrErrorAt(tr, tr->mLine, col, "Expected '%s' operator.\n", op);
736 return 0;
739 /* Performs a string substitution. Any case-insensitive occurrences of the
740 * pattern string are replaced with the replacement string. The result is
741 * truncated if necessary.
743 static int StrSubst(const char *in, const char *pat, const char *rep, const size_t maxLen, char *out)
745 size_t inLen, patLen, repLen;
746 size_t si, di;
747 int truncated;
749 inLen = strlen(in);
750 patLen = strlen(pat);
751 repLen = strlen(rep);
752 si = 0;
753 di = 0;
754 truncated = 0;
755 while(si < inLen && di < maxLen)
757 if(patLen <= inLen-si)
759 if(strncasecmp(&in[si], pat, patLen) == 0)
761 if(repLen > maxLen-di)
763 repLen = maxLen - di;
764 truncated = 1;
766 strncpy(&out[di], rep, repLen);
767 si += patLen;
768 di += repLen;
771 out[di] = in[si];
772 si++;
773 di++;
775 if(si < inLen)
776 truncated = 1;
777 out[di] = '\0';
778 return !truncated;
782 /*********************
783 *** Math routines ***
784 *********************/
786 // Provide missing math routines for MSVC versions < 1800 (Visual Studio 2013).
787 #if defined(_MSC_VER) && _MSC_VER < 1800
788 static double round(double val)
790 if(val < 0.0)
791 return ceil(val-0.5);
792 return floor(val+0.5);
795 static double fmin(double a, double b)
797 return (a<b) ? a : b;
800 static double fmax(double a, double b)
802 return (a>b) ? a : b;
804 #endif
806 // Simple clamp routine.
807 static double Clamp(const double val, const double lower, const double upper)
809 return fmin(fmax(val, lower), upper);
812 // Performs linear interpolation.
813 static double Lerp(const double a, const double b, const double f)
815 return a + (f * (b - a));
818 // Performs a high-passed triangular probability density function dither from
819 // a double to an integer. It assumes the input sample is already scaled.
820 static int HpTpdfDither(const double in, int *hpHist)
822 static const double PRNG_SCALE = 1.0 / (RAND_MAX+1.0);
823 int prn;
824 double out;
826 prn = rand();
827 out = round(in + (PRNG_SCALE * (prn - *hpHist)));
828 *hpHist = prn;
829 return (int)out;
832 // Allocates an array of doubles.
833 static double *CreateArray(size_t n)
835 double *a;
837 if(n == 0) n = 1;
838 a = calloc(n, sizeof(double));
839 if(a == NULL)
841 fprintf(stderr, "Error: Out of memory.\n");
842 exit(-1);
844 return a;
847 // Frees an array of doubles.
848 static void DestroyArray(double *a)
849 { free(a); }
851 // Complex number routines. All outputs must be non-NULL.
853 // Magnitude/absolute value.
854 static double ComplexAbs(const double r, const double i)
856 return sqrt(r*r + i*i);
859 // Multiply.
860 static void ComplexMul(const double aR, const double aI, const double bR, const double bI, double *outR, double *outI)
862 *outR = (aR * bR) - (aI * bI);
863 *outI = (aI * bR) + (aR * bI);
866 // Base-e exponent.
867 static void ComplexExp(const double inR, const double inI, double *outR, double *outI)
869 double e = exp(inR);
870 *outR = e * cos(inI);
871 *outI = e * sin(inI);
874 /* Fast Fourier transform routines. The number of points must be a power of
875 * two. In-place operation is possible only if both the real and imaginary
876 * parts are in-place together.
879 // Performs bit-reversal ordering.
880 static void FftArrange(const uint n, const double *inR, const double *inI, double *outR, double *outI)
882 uint rk, k, m;
883 double tempR, tempI;
885 if(inR == outR && inI == outI)
887 // Handle in-place arrangement.
888 rk = 0;
889 for(k = 0;k < n;k++)
891 if(rk > k)
893 tempR = inR[rk];
894 tempI = inI[rk];
895 outR[rk] = inR[k];
896 outI[rk] = inI[k];
897 outR[k] = tempR;
898 outI[k] = tempI;
900 m = n;
901 while(rk&(m >>= 1))
902 rk &= ~m;
903 rk |= m;
906 else
908 // Handle copy arrangement.
909 rk = 0;
910 for(k = 0;k < n;k++)
912 outR[rk] = inR[k];
913 outI[rk] = inI[k];
914 m = n;
915 while(rk&(m >>= 1))
916 rk &= ~m;
917 rk |= m;
922 // Performs the summation.
923 static void FftSummation(const uint n, const double s, double *re, double *im)
925 double pi;
926 uint m, m2;
927 double vR, vI, wR, wI;
928 uint i, k, mk;
929 double tR, tI;
931 pi = s * M_PI;
932 for(m = 1, m2 = 2;m < n; m <<= 1, m2 <<= 1)
934 // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
935 vR = sin(0.5 * pi / m);
936 vR = -2.0 * vR * vR;
937 vI = -sin(pi / m);
938 // w = Complex (1.0, 0.0)
939 wR = 1.0;
940 wI = 0.0;
941 for(i = 0;i < m;i++)
943 for(k = i;k < n;k += m2)
945 mk = k + m;
946 // t = ComplexMul(w, out[km2])
947 tR = (wR * re[mk]) - (wI * im[mk]);
948 tI = (wR * im[mk]) + (wI * re[mk]);
949 // out[mk] = ComplexSub (out [k], t)
950 re[mk] = re[k] - tR;
951 im[mk] = im[k] - tI;
952 // out[k] = ComplexAdd (out [k], t)
953 re[k] += tR;
954 im[k] += tI;
956 // t = ComplexMul (v, w)
957 tR = (vR * wR) - (vI * wI);
958 tI = (vR * wI) + (vI * wR);
959 // w = ComplexAdd (w, t)
960 wR += tR;
961 wI += tI;
966 // Performs a forward FFT.
967 static void FftForward(const uint n, const double *inR, const double *inI, double *outR, double *outI)
969 FftArrange(n, inR, inI, outR, outI);
970 FftSummation(n, 1.0, outR, outI);
973 // Performs an inverse FFT.
974 static void FftInverse(const uint n, const double *inR, const double *inI, double *outR, double *outI)
976 double f;
977 uint i;
979 FftArrange(n, inR, inI, outR, outI);
980 FftSummation(n, -1.0, outR, outI);
981 f = 1.0 / n;
982 for(i = 0;i < n;i++)
984 outR[i] *= f;
985 outI[i] *= f;
989 /* Calculate the complex helical sequence (or discrete-time analytical signal)
990 * of the given input using the Hilbert transform. Given the natural logarithm
991 * of a signal's magnitude response, the imaginary components can be used as
992 * the angles for minimum-phase reconstruction.
994 static void Hilbert(const uint n, const double *in, double *outR, double *outI)
996 uint i;
998 if(in == outR)
1000 // Handle in-place operation.
1001 for(i = 0;i < n;i++)
1002 outI[i] = 0.0;
1004 else
1006 // Handle copy operation.
1007 for(i = 0;i < n;i++)
1009 outR[i] = in[i];
1010 outI[i] = 0.0;
1013 FftInverse(n, outR, outI, outR, outI);
1014 for(i = 1;i < (n+1)/2;i++)
1016 outR[i] *= 2.0;
1017 outI[i] *= 2.0;
1019 /* Increment i if n is even. */
1020 i += (n&1)^1;
1021 for(;i < n;i++)
1023 outR[i] = 0.0;
1024 outI[i] = 0.0;
1026 FftForward(n, outR, outI, outR, outI);
1029 /* Calculate the magnitude response of the given input. This is used in
1030 * place of phase decomposition, since the phase residuals are discarded for
1031 * minimum phase reconstruction. The mirrored half of the response is also
1032 * discarded.
1034 static void MagnitudeResponse(const uint n, const double *inR, const double *inI, double *out)
1036 const uint m = 1 + (n / 2);
1037 uint i;
1038 for(i = 0;i < m;i++)
1039 out[i] = fmax(ComplexAbs(inR[i], inI[i]), EPSILON);
1042 /* Apply a range limit (in dB) to the given magnitude response. This is used
1043 * to adjust the effects of the diffuse-field average on the equalization
1044 * process.
1046 static void LimitMagnitudeResponse(const uint n, const double limit, const double *in, double *out)
1048 const uint m = 1 + (n / 2);
1049 double halfLim;
1050 uint i, lower, upper;
1051 double ave;
1053 halfLim = limit / 2.0;
1054 // Convert the response to dB.
1055 for(i = 0;i < m;i++)
1056 out[i] = 20.0 * log10(in[i]);
1057 // Use six octaves to calculate the average magnitude of the signal.
1058 lower = ((uint)ceil(n / pow(2.0, 8.0))) - 1;
1059 upper = ((uint)floor(n / pow(2.0, 2.0))) - 1;
1060 ave = 0.0;
1061 for(i = lower;i <= upper;i++)
1062 ave += out[i];
1063 ave /= upper - lower + 1;
1064 // Keep the response within range of the average magnitude.
1065 for(i = 0;i < m;i++)
1066 out[i] = Clamp(out[i], ave - halfLim, ave + halfLim);
1067 // Convert the response back to linear magnitude.
1068 for(i = 0;i < m;i++)
1069 out[i] = pow(10.0, out[i] / 20.0);
1072 /* Reconstructs the minimum-phase component for the given magnitude response
1073 * of a signal. This is equivalent to phase recomposition, sans the missing
1074 * residuals (which were discarded). The mirrored half of the response is
1075 * reconstructed.
1077 static void MinimumPhase(const uint n, const double *in, double *outR, double *outI)
1079 const uint m = 1 + (n / 2);
1080 double *mags;
1081 double aR, aI;
1082 uint i;
1084 mags = CreateArray(n);
1085 for(i = 0;i < m;i++)
1087 mags[i] = fmax(EPSILON, in[i]);
1088 outR[i] = log(mags[i]);
1090 for(;i < n;i++)
1092 mags[i] = mags[n - i];
1093 outR[i] = outR[n - i];
1095 Hilbert(n, outR, outR, outI);
1096 // Remove any DC offset the filter has.
1097 mags[0] = EPSILON;
1098 for(i = 0;i < n;i++)
1100 ComplexExp(0.0, outI[i], &aR, &aI);
1101 ComplexMul(mags[i], 0.0, aR, aI, &outR[i], &outI[i]);
1103 DestroyArray(mags);
1107 /***************************
1108 *** Resampler functions ***
1109 ***************************/
1111 /* This is the normalized cardinal sine (sinc) function.
1113 * sinc(x) = { 1, x = 0
1114 * { sin(pi x) / (pi x), otherwise.
1116 static double Sinc(const double x)
1118 if(fabs(x) < EPSILON)
1119 return 1.0;
1120 return sin(M_PI * x) / (M_PI * x);
1123 /* The zero-order modified Bessel function of the first kind, used for the
1124 * Kaiser window.
1126 * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
1127 * = sum_{k=0}^inf ((x / 2)^k / k!)^2
1129 static double BesselI_0(const double x)
1131 double term, sum, x2, y, last_sum;
1132 int k;
1134 // Start at k=1 since k=0 is trivial.
1135 term = 1.0;
1136 sum = 1.0;
1137 x2 = x/2.0;
1138 k = 1;
1140 // Let the integration converge until the term of the sum is no longer
1141 // significant.
1142 do {
1143 y = x2 / k;
1144 k++;
1145 last_sum = sum;
1146 term *= y * y;
1147 sum += term;
1148 } while(sum != last_sum);
1149 return sum;
1152 /* Calculate a Kaiser window from the given beta value and a normalized k
1153 * [-1, 1].
1155 * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
1156 * { 0, elsewhere.
1158 * Where k can be calculated as:
1160 * k = i / l, where -l <= i <= l.
1162 * or:
1164 * k = 2 i / M - 1, where 0 <= i <= M.
1166 static double Kaiser(const double b, const double k)
1168 if(!(k >= -1.0 && k <= 1.0))
1169 return 0.0;
1170 return BesselI_0(b * sqrt(1.0 - k*k)) / BesselI_0(b);
1173 // Calculates the greatest common divisor of a and b.
1174 static uint Gcd(uint x, uint y)
1176 while(y > 0)
1178 uint z = y;
1179 y = x % y;
1180 x = z;
1182 return x;
1185 /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
1186 * the transition width is normalized frequency (0.5 is nyquist).
1188 * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
1189 * { ceil(5.79 / 2 pi f_t), r <= 21.
1192 static uint CalcKaiserOrder(const double rejection, const double transition)
1194 double w_t = 2.0 * M_PI * transition;
1195 if(rejection > 21.0)
1196 return (uint)ceil((rejection - 7.95) / (2.285 * w_t));
1197 return (uint)ceil(5.79 / w_t);
1200 // Calculates the beta value of the Kaiser window. Rejection is in dB.
1201 static double CalcKaiserBeta(const double rejection)
1203 if(rejection > 50.0)
1204 return 0.1102 * (rejection - 8.7);
1205 if(rejection >= 21.0)
1206 return (0.5842 * pow(rejection - 21.0, 0.4)) +
1207 (0.07886 * (rejection - 21.0));
1208 return 0.0;
1211 /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
1212 * width, beta, gain, and cutoff. The point is specified in non-normalized
1213 * samples, from 0 to M, where M = (2 l + 1).
1215 * w(k) 2 p f_t sinc(2 f_t x)
1217 * x -- centered sample index (i - l)
1218 * k -- normalized and centered window index (x / l)
1219 * w(k) -- window function (Kaiser)
1220 * p -- gain compensation factor when sampling
1221 * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
1223 static double SincFilter(const int l, const double b, const double gain, const double cutoff, const int i)
1225 return Kaiser(b, (double)(i - l) / l) * 2.0 * gain * cutoff * Sinc(2.0 * cutoff * (i - l));
1228 /* This is a polyphase sinc-filtered resampler.
1230 * Upsample Downsample
1232 * p/q = 3/2 p/q = 3/5
1234 * M-+-+-+-> M-+-+-+->
1235 * -------------------+ ---------------------+
1236 * p s * f f f f|f| | p s * f f f f f |
1237 * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
1238 * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
1239 * s * f|f|f f f | s * f f|f|f f |
1240 * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
1241 * --------+=+--------+ 0 * |0|0 0 0 0 |
1242 * d . d .|d|. d . d ----------+=+--------+
1243 * d . . . .|d|. . . .
1244 * q->
1245 * q-+-+-+->
1247 * P_f(i,j) = q i mod p + pj
1248 * P_s(i,j) = floor(q i / p) - j
1249 * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
1250 * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
1251 * { 0, P_f(i,j) >= M. }
1254 // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
1255 // that's used to cut frequencies above the destination nyquist.
1256 static void ResamplerSetup(ResamplerT *rs, const uint srcRate, const uint dstRate)
1258 double cutoff, width, beta;
1259 uint gcd, l;
1260 int i;
1262 gcd = Gcd(srcRate, dstRate);
1263 rs->mP = dstRate / gcd;
1264 rs->mQ = srcRate / gcd;
1265 /* The cutoff is adjusted by half the transition width, so the transition
1266 * ends before the nyquist (0.5). Both are scaled by the downsampling
1267 * factor.
1269 if(rs->mP > rs->mQ)
1271 cutoff = 0.475 / rs->mP;
1272 width = 0.05 / rs->mP;
1274 else
1276 cutoff = 0.475 / rs->mQ;
1277 width = 0.05 / rs->mQ;
1279 // A rejection of -180 dB is used for the stop band.
1280 l = CalcKaiserOrder(180.0, width) / 2;
1281 beta = CalcKaiserBeta(180.0);
1282 rs->mM = (2 * l) + 1;
1283 rs->mL = l;
1284 rs->mF = CreateArray(rs->mM);
1285 for(i = 0;i < ((int)rs->mM);i++)
1286 rs->mF[i] = SincFilter((int)l, beta, rs->mP, cutoff, i);
1289 // Clean up after the resampler.
1290 static void ResamplerClear(ResamplerT *rs)
1292 DestroyArray(rs->mF);
1293 rs->mF = NULL;
1296 // Perform the upsample-filter-downsample resampling operation using a
1297 // polyphase filter implementation.
1298 static void ResamplerRun(ResamplerT *rs, const uint inN, const double *in, const uint outN, double *out)
1300 const uint p = rs->mP, q = rs->mQ, m = rs->mM, l = rs->mL;
1301 const double *f = rs->mF;
1302 uint j_f, j_s;
1303 double *work;
1304 uint i;
1306 if(outN == 0)
1307 return;
1309 // Handle in-place operation.
1310 if(in == out)
1311 work = CreateArray(outN);
1312 else
1313 work = out;
1314 // Resample the input.
1315 for(i = 0;i < outN;i++)
1317 double r = 0.0;
1318 // Input starts at l to compensate for the filter delay. This will
1319 // drop any build-up from the first half of the filter.
1320 j_f = (l + (q * i)) % p;
1321 j_s = (l + (q * i)) / p;
1322 while(j_f < m)
1324 // Only take input when 0 <= j_s < inN. This single unsigned
1325 // comparison catches both cases.
1326 if(j_s < inN)
1327 r += f[j_f] * in[j_s];
1328 j_f += p;
1329 j_s--;
1331 work[i] = r;
1333 // Clean up after in-place operation.
1334 if(in == out)
1336 for(i = 0;i < outN;i++)
1337 out[i] = work[i];
1338 DestroyArray(work);
1342 /*************************
1343 *** File source input ***
1344 *************************/
1346 // Read a binary value of the specified byte order and byte size from a file,
1347 // storing it as a 32-bit unsigned integer.
1348 static int ReadBin4(FILE *fp, const char *filename, const ByteOrderT order, const uint bytes, uint32 *out)
1350 uint8 in[4];
1351 uint32 accum;
1352 uint i;
1354 if(fread(in, 1, bytes, fp) != bytes)
1356 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1357 return 0;
1359 accum = 0;
1360 switch(order)
1362 case BO_LITTLE:
1363 for(i = 0;i < bytes;i++)
1364 accum = (accum<<8) | in[bytes - i - 1];
1365 break;
1366 case BO_BIG:
1367 for(i = 0;i < bytes;i++)
1368 accum = (accum<<8) | in[i];
1369 break;
1370 default:
1371 break;
1373 *out = accum;
1374 return 1;
1377 // Read a binary value of the specified byte order from a file, storing it as
1378 // a 64-bit unsigned integer.
1379 static int ReadBin8(FILE *fp, const char *filename, const ByteOrderT order, uint64 *out)
1381 uint8 in [8];
1382 uint64 accum;
1383 uint i;
1385 if(fread(in, 1, 8, fp) != 8)
1387 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1388 return 0;
1390 accum = 0ULL;
1391 switch(order)
1393 case BO_LITTLE:
1394 for(i = 0;i < 8;i++)
1395 accum = (accum<<8) | in[8 - i - 1];
1396 break;
1397 case BO_BIG:
1398 for(i = 0;i < 8;i++)
1399 accum = (accum<<8) | in[i];
1400 break;
1401 default:
1402 break;
1404 *out = accum;
1405 return 1;
1408 /* Read a binary value of the specified type, byte order, and byte size from
1409 * a file, converting it to a double. For integer types, the significant
1410 * bits are used to normalize the result. The sign of bits determines
1411 * whether they are padded toward the MSB (negative) or LSB (positive).
1412 * Floating-point types are not normalized.
1414 static int ReadBinAsDouble(FILE *fp, const char *filename, const ByteOrderT order, const ElementTypeT type, const uint bytes, const int bits, double *out)
1416 union {
1417 uint32 ui;
1418 int32 i;
1419 float f;
1420 } v4;
1421 union {
1422 uint64 ui;
1423 double f;
1424 } v8;
1426 *out = 0.0;
1427 if(bytes > 4)
1429 if(!ReadBin8(fp, filename, order, &v8.ui))
1430 return 0;
1431 if(type == ET_FP)
1432 *out = v8.f;
1434 else
1436 if(!ReadBin4(fp, filename, order, bytes, &v4.ui))
1437 return 0;
1438 if(type == ET_FP)
1439 *out = v4.f;
1440 else
1442 if(bits > 0)
1443 v4.ui >>= (8*bytes) - ((uint)bits);
1444 else
1445 v4.ui &= (0xFFFFFFFF >> (32+bits));
1447 if(v4.ui&(uint)(1<<(abs(bits)-1)))
1448 v4.ui |= (0xFFFFFFFF << abs (bits));
1449 *out = v4.i / (double)(1<<(abs(bits)-1));
1452 return 1;
1455 /* Read an ascii value of the specified type from a file, converting it to a
1456 * double. For integer types, the significant bits are used to normalize the
1457 * result. The sign of the bits should always be positive. This also skips
1458 * up to one separator character before the element itself.
1460 static int ReadAsciiAsDouble(TokenReaderT *tr, const char *filename, const ElementTypeT type, const uint bits, double *out)
1462 if(TrIsOperator(tr, ","))
1463 TrReadOperator(tr, ",");
1464 else if(TrIsOperator(tr, ":"))
1465 TrReadOperator(tr, ":");
1466 else if(TrIsOperator(tr, ";"))
1467 TrReadOperator(tr, ";");
1468 else if(TrIsOperator(tr, "|"))
1469 TrReadOperator(tr, "|");
1471 if(type == ET_FP)
1473 if(!TrReadFloat(tr, -HUGE_VAL, HUGE_VAL, out))
1475 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1476 return 0;
1479 else
1481 int v;
1482 if(!TrReadInt(tr, -(1<<(bits-1)), (1<<(bits-1))-1, &v))
1484 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1485 return 0;
1487 *out = v / (double)((1<<(bits-1))-1);
1489 return 1;
1492 // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
1493 // the source parameters and data set metrics.
1494 static int ReadWaveFormat(FILE *fp, const ByteOrderT order, const uint hrirRate, SourceRefT *src)
1496 uint32 fourCC, chunkSize;
1497 uint32 format, channels, rate, dummy, block, size, bits;
1499 chunkSize = 0;
1500 do {
1501 if (chunkSize > 0)
1502 fseek (fp, (long) chunkSize, SEEK_CUR);
1503 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
1504 !ReadBin4(fp, src->mPath, order, 4, &chunkSize))
1505 return 0;
1506 } while(fourCC != FOURCC_FMT);
1507 if(!ReadBin4(fp, src->mPath, order, 2, & format) ||
1508 !ReadBin4(fp, src->mPath, order, 2, & channels) ||
1509 !ReadBin4(fp, src->mPath, order, 4, & rate) ||
1510 !ReadBin4(fp, src->mPath, order, 4, & dummy) ||
1511 !ReadBin4(fp, src->mPath, order, 2, & block))
1512 return (0);
1513 block /= channels;
1514 if(chunkSize > 14)
1516 if(!ReadBin4(fp, src->mPath, order, 2, &size))
1517 return 0;
1518 size /= 8;
1519 if(block > size)
1520 size = block;
1522 else
1523 size = block;
1524 if(format == WAVE_FORMAT_EXTENSIBLE)
1526 fseek(fp, 2, SEEK_CUR);
1527 if(!ReadBin4(fp, src->mPath, order, 2, &bits))
1528 return 0;
1529 if(bits == 0)
1530 bits = 8 * size;
1531 fseek(fp, 4, SEEK_CUR);
1532 if(!ReadBin4(fp, src->mPath, order, 2, &format))
1533 return 0;
1534 fseek(fp, (long)(chunkSize - 26), SEEK_CUR);
1536 else
1538 bits = 8 * size;
1539 if(chunkSize > 14)
1540 fseek(fp, (long)(chunkSize - 16), SEEK_CUR);
1541 else
1542 fseek(fp, (long)(chunkSize - 14), SEEK_CUR);
1544 if(format != WAVE_FORMAT_PCM && format != WAVE_FORMAT_IEEE_FLOAT)
1546 fprintf(stderr, "Error: Unsupported WAVE format in file '%s'.\n", src->mPath);
1547 return 0;
1549 if(src->mChannel >= channels)
1551 fprintf(stderr, "Error: Missing source channel in WAVE file '%s'.\n", src->mPath);
1552 return 0;
1554 if(rate != hrirRate)
1556 fprintf(stderr, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src->mPath);
1557 return 0;
1559 if(format == WAVE_FORMAT_PCM)
1561 if(size < 2 || size > 4)
1563 fprintf(stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src->mPath);
1564 return 0;
1566 if(bits < 16 || bits > (8*size))
1568 fprintf (stderr, "Error: Bad significant bits in WAVE file '%s'.\n", src->mPath);
1569 return 0;
1571 src->mType = ET_INT;
1573 else
1575 if(size != 4 && size != 8)
1577 fprintf(stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src->mPath);
1578 return 0;
1580 src->mType = ET_FP;
1582 src->mSize = size;
1583 src->mBits = (int)bits;
1584 src->mSkip = channels;
1585 return 1;
1588 // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
1589 static int ReadWaveData(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
1591 int pre, post, skip;
1592 uint i;
1594 pre = (int)(src->mSize * src->mChannel);
1595 post = (int)(src->mSize * (src->mSkip - src->mChannel - 1));
1596 skip = 0;
1597 for(i = 0;i < n;i++)
1599 skip += pre;
1600 if(skip > 0)
1601 fseek(fp, skip, SEEK_CUR);
1602 if(!ReadBinAsDouble(fp, src->mPath, order, src->mType, src->mSize, src->mBits, &hrir[i]))
1603 return 0;
1604 skip = post;
1606 if(skip > 0)
1607 fseek(fp, skip, SEEK_CUR);
1608 return 1;
1611 // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
1612 // doubles.
1613 static int ReadWaveList(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
1615 uint32 fourCC, chunkSize, listSize, count;
1616 uint block, skip, offset, i;
1617 double lastSample;
1619 for (;;) {
1620 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, & fourCC) ||
1621 !ReadBin4(fp, src->mPath, order, 4, & chunkSize))
1622 return (0);
1624 if(fourCC == FOURCC_DATA)
1626 block = src->mSize * src->mSkip;
1627 count = chunkSize / block;
1628 if(count < (src->mOffset + n))
1630 fprintf(stderr, "Error: Bad read from file '%s'.\n", src->mPath);
1631 return 0;
1633 fseek(fp, (long)(src->mOffset * block), SEEK_CUR);
1634 if(!ReadWaveData(fp, src, order, n, &hrir[0]))
1635 return 0;
1636 return 1;
1638 else if(fourCC == FOURCC_LIST)
1640 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC))
1641 return 0;
1642 chunkSize -= 4;
1643 if(fourCC == FOURCC_WAVL)
1644 break;
1646 if(chunkSize > 0)
1647 fseek(fp, (long)chunkSize, SEEK_CUR);
1649 listSize = chunkSize;
1650 block = src->mSize * src->mSkip;
1651 skip = src->mOffset;
1652 offset = 0;
1653 lastSample = 0.0;
1654 while(offset < n && listSize > 8)
1656 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
1657 !ReadBin4(fp, src->mPath, order, 4, &chunkSize))
1658 return 0;
1659 listSize -= 8 + chunkSize;
1660 if(fourCC == FOURCC_DATA)
1662 count = chunkSize / block;
1663 if(count > skip)
1665 fseek(fp, (long)(skip * block), SEEK_CUR);
1666 chunkSize -= skip * block;
1667 count -= skip;
1668 skip = 0;
1669 if(count > (n - offset))
1670 count = n - offset;
1671 if(!ReadWaveData(fp, src, order, count, &hrir[offset]))
1672 return 0;
1673 chunkSize -= count * block;
1674 offset += count;
1675 lastSample = hrir [offset - 1];
1677 else
1679 skip -= count;
1680 count = 0;
1683 else if(fourCC == FOURCC_SLNT)
1685 if(!ReadBin4(fp, src->mPath, order, 4, &count))
1686 return 0;
1687 chunkSize -= 4;
1688 if(count > skip)
1690 count -= skip;
1691 skip = 0;
1692 if(count > (n - offset))
1693 count = n - offset;
1694 for(i = 0; i < count; i ++)
1695 hrir[offset + i] = lastSample;
1696 offset += count;
1698 else
1700 skip -= count;
1701 count = 0;
1704 if(chunkSize > 0)
1705 fseek(fp, (long)chunkSize, SEEK_CUR);
1707 if(offset < n)
1709 fprintf(stderr, "Error: Bad read from file '%s'.\n", src->mPath);
1710 return 0;
1712 return 1;
1715 // Load a source HRIR from a RIFF/RIFX WAVE file.
1716 static int LoadWaveSource(FILE *fp, SourceRefT *src, const uint hrirRate, const uint n, double *hrir)
1718 uint32 fourCC, dummy;
1719 ByteOrderT order;
1721 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
1722 !ReadBin4(fp, src->mPath, BO_LITTLE, 4, &dummy))
1723 return 0;
1724 if(fourCC == FOURCC_RIFF)
1725 order = BO_LITTLE;
1726 else if(fourCC == FOURCC_RIFX)
1727 order = BO_BIG;
1728 else
1730 fprintf(stderr, "Error: No RIFF/RIFX chunk in file '%s'.\n", src->mPath);
1731 return 0;
1734 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC))
1735 return 0;
1736 if(fourCC != FOURCC_WAVE)
1738 fprintf(stderr, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src->mPath);
1739 return 0;
1741 if(!ReadWaveFormat(fp, order, hrirRate, src))
1742 return 0;
1743 if(!ReadWaveList(fp, src, order, n, hrir))
1744 return 0;
1745 return 1;
1748 // Load a source HRIR from a binary file.
1749 static int LoadBinarySource(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
1751 uint i;
1753 fseek(fp, (long)src->mOffset, SEEK_SET);
1754 for(i = 0;i < n;i++)
1756 if(!ReadBinAsDouble(fp, src->mPath, order, src->mType, src->mSize, src->mBits, &hrir[i]))
1757 return 0;
1758 if(src->mSkip > 0)
1759 fseek(fp, (long)src->mSkip, SEEK_CUR);
1761 return 1;
1764 // Load a source HRIR from an ASCII text file containing a list of elements
1765 // separated by whitespace or common list operators (',', ';', ':', '|').
1766 static int LoadAsciiSource(FILE *fp, const SourceRefT *src, const uint n, double *hrir)
1768 TokenReaderT tr;
1769 uint i, j;
1770 double dummy;
1772 TrSetup(fp, NULL, &tr);
1773 for(i = 0;i < src->mOffset;i++)
1775 if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &dummy))
1776 return (0);
1778 for(i = 0;i < n;i++)
1780 if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &hrir[i]))
1781 return 0;
1782 for(j = 0;j < src->mSkip;j++)
1784 if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &dummy))
1785 return 0;
1788 return 1;
1791 // Load a source HRIR from a supported file type.
1792 static int LoadSource(SourceRefT *src, const uint hrirRate, const uint n, double *hrir)
1794 int result;
1795 FILE *fp;
1797 if (src->mFormat == SF_ASCII)
1798 fp = fopen(src->mPath, "r");
1799 else
1800 fp = fopen(src->mPath, "rb");
1801 if(fp == NULL)
1803 fprintf(stderr, "Error: Could not open source file '%s'.\n", src->mPath);
1804 return 0;
1806 if(src->mFormat == SF_WAVE)
1807 result = LoadWaveSource(fp, src, hrirRate, n, hrir);
1808 else if(src->mFormat == SF_BIN_LE)
1809 result = LoadBinarySource(fp, src, BO_LITTLE, n, hrir);
1810 else if(src->mFormat == SF_BIN_BE)
1811 result = LoadBinarySource(fp, src, BO_BIG, n, hrir);
1812 else
1813 result = LoadAsciiSource(fp, src, n, hrir);
1814 fclose(fp);
1815 return result;
1819 /***************************
1820 *** File storage output ***
1821 ***************************/
1823 // Write an ASCII string to a file.
1824 static int WriteAscii(const char *out, FILE *fp, const char *filename)
1826 size_t len;
1828 len = strlen(out);
1829 if(fwrite(out, 1, len, fp) != len)
1831 fclose(fp);
1832 fprintf(stderr, "Error: Bad write to file '%s'.\n", filename);
1833 return 0;
1835 return 1;
1838 // Write a binary value of the given byte order and byte size to a file,
1839 // loading it from a 32-bit unsigned integer.
1840 static int WriteBin4(const ByteOrderT order, const uint bytes, const uint32 in, FILE *fp, const char *filename)
1842 uint8 out[4];
1843 uint i;
1845 switch(order)
1847 case BO_LITTLE:
1848 for(i = 0;i < bytes;i++)
1849 out[i] = (in>>(i*8)) & 0x000000FF;
1850 break;
1851 case BO_BIG:
1852 for(i = 0;i < bytes;i++)
1853 out[bytes - i - 1] = (in>>(i*8)) & 0x000000FF;
1854 break;
1855 default:
1856 break;
1858 if(fwrite(out, 1, bytes, fp) != bytes)
1860 fprintf(stderr, "Error: Bad write to file '%s'.\n", filename);
1861 return 0;
1863 return 1;
1866 // Store the OpenAL Soft HRTF data set.
1867 static int StoreMhr(const HrirDataT *hData, const char *filename)
1869 uint e, step, end, n, j, i;
1870 int hpHist, v;
1871 FILE *fp;
1873 if((fp=fopen(filename, "wb")) == NULL)
1875 fprintf(stderr, "Error: Could not open MHR file '%s'.\n", filename);
1876 return 0;
1878 if(!WriteAscii(MHR_FORMAT, fp, filename))
1879 return 0;
1880 if(!WriteBin4(BO_LITTLE, 4, (uint32)hData->mIrRate, fp, filename))
1881 return 0;
1882 if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mIrPoints, fp, filename))
1883 return 0;
1884 if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mEvCount, fp, filename))
1885 return 0;
1886 for(e = 0;e < hData->mEvCount;e++)
1888 if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mAzCount[e], fp, filename))
1889 return 0;
1891 step = hData->mIrSize;
1892 end = hData->mIrCount * step;
1893 n = hData->mIrPoints;
1894 srand(0x31DF840C);
1895 for(j = 0;j < end;j += step)
1897 hpHist = 0;
1898 for(i = 0;i < n;i++)
1900 v = HpTpdfDither(32767.0 * hData->mHrirs[j+i], &hpHist);
1901 if(!WriteBin4(BO_LITTLE, 2, (uint32)v, fp, filename))
1902 return 0;
1905 for(j = 0;j < hData->mIrCount;j++)
1907 v = (int)fmin(round(hData->mIrRate * hData->mHrtds[j]), MAX_HRTD);
1908 if(!WriteBin4(BO_LITTLE, 1, (uint32)v, fp, filename))
1909 return 0;
1911 fclose(fp);
1912 return 1;
1916 /***********************
1917 *** HRTF processing ***
1918 ***********************/
1920 // Calculate the onset time of an HRIR and average it with any existing
1921 // timing for its elevation and azimuth.
1922 static void AverageHrirOnset(const double *hrir, const double f, const uint ei, const uint ai, const HrirDataT *hData)
1924 double mag;
1925 uint n, i, j;
1927 mag = 0.0;
1928 n = hData->mIrPoints;
1929 for(i = 0;i < n;i++)
1930 mag = fmax(fabs(hrir[i]), mag);
1931 mag *= 0.15;
1932 for(i = 0;i < n;i++)
1934 if(fabs(hrir[i]) >= mag)
1935 break;
1937 j = hData->mEvOffset[ei] + ai;
1938 hData->mHrtds[j] = Lerp(hData->mHrtds[j], ((double)i) / hData->mIrRate, f);
1941 // Calculate the magnitude response of an HRIR and average it with any
1942 // existing responses for its elevation and azimuth.
1943 static void AverageHrirMagnitude(const double *hrir, const double f, const uint ei, const uint ai, const HrirDataT *hData)
1945 double *re, *im;
1946 uint n, m, i, j;
1948 n = hData->mFftSize;
1949 re = CreateArray(n);
1950 im = CreateArray(n);
1951 for(i = 0;i < hData->mIrPoints;i++)
1953 re[i] = hrir[i];
1954 im[i] = 0.0;
1956 for(;i < n;i++)
1958 re[i] = 0.0;
1959 im[i] = 0.0;
1961 FftForward(n, re, im, re, im);
1962 MagnitudeResponse(n, re, im, re);
1963 m = 1 + (n / 2);
1964 j = (hData->mEvOffset[ei] + ai) * hData->mIrSize;
1965 for(i = 0;i < m;i++)
1966 hData->mHrirs[j+i] = Lerp(hData->mHrirs[j+i], re[i], f);
1967 DestroyArray(im);
1968 DestroyArray(re);
1971 /* Calculate the contribution of each HRIR to the diffuse-field average based
1972 * on the area of its surface patch. All patches are centered at the HRIR
1973 * coordinates on the unit sphere and are measured by solid angle.
1975 static void CalculateDfWeights(const HrirDataT *hData, double *weights)
1977 double evs, sum, ev, up_ev, down_ev, solidAngle;
1978 uint ei;
1980 evs = 90.0 / (hData->mEvCount - 1);
1981 sum = 0.0;
1982 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
1984 // For each elevation, calculate the upper and lower limits of the
1985 // patch band.
1986 ev = -90.0 + (ei * 2.0 * evs);
1987 if(ei < (hData->mEvCount - 1))
1988 up_ev = (ev + evs) * M_PI / 180.0;
1989 else
1990 up_ev = M_PI / 2.0;
1991 if(ei > 0)
1992 down_ev = (ev - evs) * M_PI / 180.0;
1993 else
1994 down_ev = -M_PI / 2.0;
1995 // Calculate the area of the patch band.
1996 solidAngle = 2.0 * M_PI * (sin(up_ev) - sin(down_ev));
1997 // Each weight is the area of one patch.
1998 weights[ei] = solidAngle / hData->mAzCount [ei];
1999 // Sum the total surface area covered by the HRIRs.
2000 sum += solidAngle;
2002 // Normalize the weights given the total surface coverage.
2003 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
2004 weights[ei] /= sum;
2007 /* Calculate the diffuse-field average from the given magnitude responses of
2008 * the HRIR set. Weighting can be applied to compensate for the varying
2009 * surface area covered by each HRIR. The final average can then be limited
2010 * by the specified magnitude range (in positive dB; 0.0 to skip).
2012 static void CalculateDiffuseFieldAverage(const HrirDataT *hData, const int weighted, const double limit, double *dfa)
2014 uint ei, ai, count, step, start, end, m, j, i;
2015 double *weights;
2017 weights = CreateArray(hData->mEvCount);
2018 if(weighted)
2020 // Use coverage weighting to calculate the average.
2021 CalculateDfWeights(hData, weights);
2023 else
2025 // If coverage weighting is not used, the weights still need to be
2026 // averaged by the number of HRIRs.
2027 count = 0;
2028 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
2029 count += hData->mAzCount [ei];
2030 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
2031 weights[ei] = 1.0 / count;
2033 ei = hData->mEvStart;
2034 ai = 0;
2035 step = hData->mIrSize;
2036 start = hData->mEvOffset[ei] * step;
2037 end = hData->mIrCount * step;
2038 m = 1 + (hData->mFftSize / 2);
2039 for(i = 0;i < m;i++)
2040 dfa[i] = 0.0;
2041 for(j = start;j < end;j += step)
2043 // Get the weight for this HRIR's contribution.
2044 double weight = weights[ei];
2045 // Add this HRIR's weighted power average to the total.
2046 for(i = 0;i < m;i++)
2047 dfa[i] += weight * hData->mHrirs[j+i] * hData->mHrirs[j+i];
2048 // Determine the next weight to use.
2049 ai++;
2050 if(ai >= hData->mAzCount[ei])
2052 ei++;
2053 ai = 0;
2056 // Finish the average calculation and keep it from being too small.
2057 for(i = 0;i < m;i++)
2058 dfa[i] = fmax(sqrt(dfa[i]), EPSILON);
2059 // Apply a limit to the magnitude range of the diffuse-field average if
2060 // desired.
2061 if(limit > 0.0)
2062 LimitMagnitudeResponse(hData->mFftSize, limit, dfa, dfa);
2063 DestroyArray(weights);
2066 // Perform diffuse-field equalization on the magnitude responses of the HRIR
2067 // set using the given average response.
2068 static void DiffuseFieldEqualize(const double *dfa, const HrirDataT *hData)
2070 uint step, start, end, m, j, i;
2072 step = hData->mIrSize;
2073 start = hData->mEvOffset[hData->mEvStart] * step;
2074 end = hData->mIrCount * step;
2075 m = 1 + (hData->mFftSize / 2);
2076 for(j = start;j < end;j += step)
2078 for(i = 0;i < m;i++)
2079 hData->mHrirs[j+i] /= dfa[i];
2083 // Perform minimum-phase reconstruction using the magnitude responses of the
2084 // HRIR set.
2085 static void ReconstructHrirs(const HrirDataT *hData)
2087 uint step, start, end, n, j, i;
2088 double *re, *im;
2090 step = hData->mIrSize;
2091 start = hData->mEvOffset[hData->mEvStart] * step;
2092 end = hData->mIrCount * step;
2093 n = hData->mFftSize;
2094 re = CreateArray(n);
2095 im = CreateArray(n);
2096 for(j = start;j < end;j += step)
2098 MinimumPhase(n, &hData->mHrirs[j], re, im);
2099 FftInverse(n, re, im, re, im);
2100 for(i = 0;i < hData->mIrPoints;i++)
2101 hData->mHrirs[j+i] = re[i];
2103 DestroyArray (im);
2104 DestroyArray (re);
2107 // Resamples the HRIRs for use at the given sampling rate.
2108 static void ResampleHrirs(const uint rate, HrirDataT *hData)
2110 uint n, step, start, end, j;
2111 ResamplerT rs;
2113 ResamplerSetup(&rs, hData->mIrRate, rate);
2114 n = hData->mIrPoints;
2115 step = hData->mIrSize;
2116 start = hData->mEvOffset[hData->mEvStart] * step;
2117 end = hData->mIrCount * step;
2118 for(j = start;j < end;j += step)
2119 ResamplerRun(&rs, n, &hData->mHrirs[j], n, &hData->mHrirs[j]);
2120 ResamplerClear(&rs);
2121 hData->mIrRate = rate;
2124 /* Given an elevation index and an azimuth, calculate the indices of the two
2125 * HRIRs that bound the coordinate along with a factor for calculating the
2126 * continous HRIR using interpolation.
2128 static void CalcAzIndices(const HrirDataT *hData, const uint ei, const double az, uint *j0, uint *j1, double *jf)
2130 double af;
2131 uint ai;
2133 af = ((2.0*M_PI) + az) * hData->mAzCount[ei] / (2.0*M_PI);
2134 ai = ((uint)af) % hData->mAzCount[ei];
2135 af -= floor(af);
2137 *j0 = hData->mEvOffset[ei] + ai;
2138 *j1 = hData->mEvOffset[ei] + ((ai+1) % hData->mAzCount [ei]);
2139 *jf = af;
2142 // Synthesize any missing onset timings at the bottom elevations. This just
2143 // blends between slightly exaggerated known onsets. Not an accurate model.
2144 static void SynthesizeOnsets(HrirDataT *hData)
2146 uint oi, e, a, j0, j1;
2147 double t, of, jf;
2149 oi = hData->mEvStart;
2150 t = 0.0;
2151 for(a = 0;a < hData->mAzCount[oi];a++)
2152 t += hData->mHrtds[hData->mEvOffset[oi] + a];
2153 hData->mHrtds[0] = 1.32e-4 + (t / hData->mAzCount[oi]);
2154 for(e = 1;e < hData->mEvStart;e++)
2156 of = ((double)e) / hData->mEvStart;
2157 for(a = 0;a < hData->mAzCount[e];a++)
2159 CalcAzIndices(hData, oi, a * 2.0 * M_PI / hData->mAzCount[e], &j0, &j1, &jf);
2160 hData->mHrtds[hData->mEvOffset[e] + a] = Lerp(hData->mHrtds[0], Lerp(hData->mHrtds[j0], hData->mHrtds[j1], jf), of);
2165 /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
2166 * now this just blends the lowest elevation HRIRs together and applies some
2167 * attenuation and high frequency damping. It is a simple, if inaccurate
2168 * model.
2170 static void SynthesizeHrirs (HrirDataT *hData)
2172 uint oi, a, e, step, n, i, j;
2173 double lp[4], s0, s1;
2174 double of, b;
2175 uint j0, j1;
2176 double jf;
2178 if(hData->mEvStart <= 0)
2179 return;
2180 step = hData->mIrSize;
2181 oi = hData->mEvStart;
2182 n = hData->mIrPoints;
2183 for(i = 0;i < n;i++)
2184 hData->mHrirs[i] = 0.0;
2185 for(a = 0;a < hData->mAzCount[oi];a++)
2187 j = (hData->mEvOffset[oi] + a) * step;
2188 for(i = 0;i < n;i++)
2189 hData->mHrirs[i] += hData->mHrirs[j+i] / hData->mAzCount[oi];
2191 for(e = 1;e < hData->mEvStart;e++)
2193 of = ((double)e) / hData->mEvStart;
2194 b = (1.0 - of) * (3.5e-6 * hData->mIrRate);
2195 for(a = 0;a < hData->mAzCount[e];a++)
2197 j = (hData->mEvOffset[e] + a) * step;
2198 CalcAzIndices(hData, oi, a * 2.0 * M_PI / hData->mAzCount[e], &j0, &j1, &jf);
2199 j0 *= step;
2200 j1 *= step;
2201 lp[0] = 0.0;
2202 lp[1] = 0.0;
2203 lp[2] = 0.0;
2204 lp[3] = 0.0;
2205 for(i = 0;i < n;i++)
2207 s0 = hData->mHrirs[i];
2208 s1 = Lerp(hData->mHrirs[j0+i], hData->mHrirs[j1+i], jf);
2209 s0 = Lerp(s0, s1, of);
2210 lp[0] = Lerp(s0, lp[0], b);
2211 lp[1] = Lerp(lp[0], lp[1], b);
2212 lp[2] = Lerp(lp[1], lp[2], b);
2213 lp[3] = Lerp(lp[2], lp[3], b);
2214 hData->mHrirs[j+i] = lp[3];
2218 b = 3.5e-6 * hData->mIrRate;
2219 lp[0] = 0.0;
2220 lp[1] = 0.0;
2221 lp[2] = 0.0;
2222 lp[3] = 0.0;
2223 for(i = 0;i < n;i++)
2225 s0 = hData->mHrirs[i];
2226 lp[0] = Lerp(s0, lp[0], b);
2227 lp[1] = Lerp(lp[0], lp[1], b);
2228 lp[2] = Lerp(lp[1], lp[2], b);
2229 lp[3] = Lerp(lp[2], lp[3], b);
2230 hData->mHrirs[i] = lp[3];
2232 hData->mEvStart = 0;
2235 // The following routines assume a full set of HRIRs for all elevations.
2237 // Normalize the HRIR set and slightly attenuate the result.
2238 static void NormalizeHrirs (const HrirDataT *hData)
2240 uint step, end, n, j, i;
2241 double maxLevel;
2243 step = hData->mIrSize;
2244 end = hData->mIrCount * step;
2245 n = hData->mIrPoints;
2246 maxLevel = 0.0;
2247 for(j = 0;j < end;j += step)
2249 for(i = 0;i < n;i++)
2250 maxLevel = fmax(fabs(hData->mHrirs[j+i]), maxLevel);
2252 maxLevel = 1.01 * maxLevel;
2253 for(j = 0;j < end;j += step)
2255 for(i = 0;i < n;i++)
2256 hData->mHrirs[j+i] /= maxLevel;
2260 // Calculate the left-ear time delay using a spherical head model.
2261 static double CalcLTD(const double ev, const double az, const double rad, const double dist)
2263 double azp, dlp, l, al;
2265 azp = asin(cos(ev) * sin(az));
2266 dlp = sqrt((dist*dist) + (rad*rad) + (2.0*dist*rad*sin(azp)));
2267 l = sqrt((dist*dist) - (rad*rad));
2268 al = (0.5 * M_PI) + azp;
2269 if(dlp > l)
2270 dlp = l + (rad * (al - acos(rad / dist)));
2271 return (dlp / 343.3);
2274 // Calculate the effective head-related time delays for each minimum-phase
2275 // HRIR.
2276 static void CalculateHrtds (const HeadModelT model, const double radius, HrirDataT *hData)
2278 double minHrtd, maxHrtd;
2279 uint e, a, j;
2280 double t;
2282 minHrtd = 1000.0;
2283 maxHrtd = -1000.0;
2284 for(e = 0;e < hData->mEvCount;e++)
2286 for(a = 0;a < hData->mAzCount[e];a++)
2288 j = hData->mEvOffset[e] + a;
2289 if(model == HM_DATASET)
2290 t = hData->mHrtds[j] * radius / hData->mRadius;
2291 else
2292 t = CalcLTD((-90.0 + (e * 180.0 / (hData->mEvCount - 1))) * M_PI / 180.0,
2293 (a * 360.0 / hData->mAzCount [e]) * M_PI / 180.0,
2294 radius, hData->mDistance);
2295 hData->mHrtds[j] = t;
2296 maxHrtd = fmax(t, maxHrtd);
2297 minHrtd = fmin(t, minHrtd);
2300 maxHrtd -= minHrtd;
2301 for(j = 0;j < hData->mIrCount;j++)
2302 hData->mHrtds[j] -= minHrtd;
2303 hData->mMaxHrtd = maxHrtd;
2307 // Process the data set definition to read and validate the data set metrics.
2308 static int ProcessMetrics(TokenReaderT *tr, const uint fftSize, const uint truncSize, HrirDataT *hData)
2310 int hasRate = 0, hasPoints = 0, hasAzimuths = 0;
2311 int hasRadius = 0, hasDistance = 0;
2312 char ident[MAX_IDENT_LEN+1];
2313 uint line, col;
2314 double fpVal;
2315 uint points;
2316 int intVal;
2318 while(!(hasRate && hasPoints && hasAzimuths && hasRadius && hasDistance))
2320 TrIndication(tr, & line, & col);
2321 if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
2322 return 0;
2323 if(strcasecmp(ident, "rate") == 0)
2325 if(hasRate)
2327 TrErrorAt(tr, line, col, "Redefinition of 'rate'.\n");
2328 return 0;
2330 if(!TrReadOperator(tr, "="))
2331 return 0;
2332 if(!TrReadInt(tr, MIN_RATE, MAX_RATE, &intVal))
2333 return 0;
2334 hData->mIrRate = (uint)intVal;
2335 hasRate = 1;
2337 else if(strcasecmp(ident, "points") == 0)
2339 if (hasPoints) {
2340 TrErrorAt(tr, line, col, "Redefinition of 'points'.\n");
2341 return 0;
2343 if(!TrReadOperator(tr, "="))
2344 return 0;
2345 TrIndication(tr, &line, &col);
2346 if(!TrReadInt(tr, MIN_POINTS, MAX_POINTS, &intVal))
2347 return 0;
2348 points = (uint)intVal;
2349 if(fftSize > 0 && points > fftSize)
2351 TrErrorAt(tr, line, col, "Value exceeds the overridden FFT size.\n");
2352 return 0;
2354 if(points < truncSize)
2356 TrErrorAt(tr, line, col, "Value is below the truncation size.\n");
2357 return 0;
2359 hData->mIrPoints = points;
2360 if(fftSize <= 0)
2362 hData->mFftSize = DEFAULT_FFTSIZE;
2363 hData->mIrSize = 1 + (DEFAULT_FFTSIZE / 2);
2365 else
2367 hData->mFftSize = fftSize;
2368 hData->mIrSize = 1 + (fftSize / 2);
2369 if(points > hData->mIrSize)
2370 hData->mIrSize = points;
2372 hasPoints = 1;
2374 else if(strcasecmp(ident, "azimuths") == 0)
2376 if(hasAzimuths)
2378 TrErrorAt(tr, line, col, "Redefinition of 'azimuths'.\n");
2379 return 0;
2381 if(!TrReadOperator(tr, "="))
2382 return 0;
2383 hData->mIrCount = 0;
2384 hData->mEvCount = 0;
2385 hData->mEvOffset[0] = 0;
2386 for(;;)
2388 if(!TrReadInt(tr, MIN_AZ_COUNT, MAX_AZ_COUNT, &intVal))
2389 return 0;
2390 hData->mAzCount[hData->mEvCount] = (uint)intVal;
2391 hData->mIrCount += (uint)intVal;
2392 hData->mEvCount ++;
2393 if(!TrIsOperator(tr, ","))
2394 break;
2395 if(hData->mEvCount >= MAX_EV_COUNT)
2397 TrError(tr, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT);
2398 return 0;
2400 hData->mEvOffset[hData->mEvCount] = hData->mEvOffset[hData->mEvCount - 1] + ((uint)intVal);
2401 TrReadOperator(tr, ",");
2403 if(hData->mEvCount < MIN_EV_COUNT)
2405 TrErrorAt(tr, line, col, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT);
2406 return 0;
2408 hasAzimuths = 1;
2410 else if(strcasecmp(ident, "radius") == 0)
2412 if(hasRadius)
2414 TrErrorAt(tr, line, col, "Redefinition of 'radius'.\n");
2415 return 0;
2417 if(!TrReadOperator(tr, "="))
2418 return 0;
2419 if(!TrReadFloat(tr, MIN_RADIUS, MAX_RADIUS, &fpVal))
2420 return 0;
2421 hData->mRadius = fpVal;
2422 hasRadius = 1;
2424 else if(strcasecmp(ident, "distance") == 0)
2426 if(hasDistance)
2428 TrErrorAt(tr, line, col, "Redefinition of 'distance'.\n");
2429 return 0;
2431 if(!TrReadOperator(tr, "="))
2432 return 0;
2433 if(!TrReadFloat(tr, MIN_DISTANCE, MAX_DISTANCE, & fpVal))
2434 return 0;
2435 hData->mDistance = fpVal;
2436 hasDistance = 1;
2438 else
2440 TrErrorAt(tr, line, col, "Expected a metric name.\n");
2441 return 0;
2443 TrSkipWhitespace (tr);
2445 return 1;
2448 // Parse an index pair from the data set definition.
2449 static int ReadIndexPair(TokenReaderT *tr, const HrirDataT *hData, uint *ei, uint *ai)
2451 int intVal;
2452 if(!TrReadInt(tr, 0, (int)hData->mEvCount, &intVal))
2453 return 0;
2454 *ei = (uint)intVal;
2455 if(!TrReadOperator(tr, ","))
2456 return 0;
2457 if(!TrReadInt(tr, 0, (int)hData->mAzCount[*ei], &intVal))
2458 return 0;
2459 *ai = (uint)intVal;
2460 return 1;
2463 // Match the source format from a given identifier.
2464 static SourceFormatT MatchSourceFormat(const char *ident)
2466 if(strcasecmp(ident, "wave") == 0)
2467 return SF_WAVE;
2468 if(strcasecmp(ident, "bin_le") == 0)
2469 return SF_BIN_LE;
2470 if(strcasecmp(ident, "bin_be") == 0)
2471 return SF_BIN_BE;
2472 if(strcasecmp(ident, "ascii") == 0)
2473 return SF_ASCII;
2474 return SF_NONE;
2477 // Match the source element type from a given identifier.
2478 static ElementTypeT MatchElementType(const char *ident)
2480 if(strcasecmp(ident, "int") == 0)
2481 return ET_INT;
2482 if(strcasecmp(ident, "fp") == 0)
2483 return ET_FP;
2484 return ET_NONE;
2487 // Parse and validate a source reference from the data set definition.
2488 static int ReadSourceRef(TokenReaderT *tr, SourceRefT *src)
2490 char ident[MAX_IDENT_LEN+1];
2491 uint line, col;
2492 int intVal;
2494 TrIndication(tr, &line, &col);
2495 if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
2496 return 0;
2497 src->mFormat = MatchSourceFormat(ident);
2498 if(src->mFormat == SF_NONE)
2500 TrErrorAt(tr, line, col, "Expected a source format.\n");
2501 return 0;
2503 if(!TrReadOperator(tr, "("))
2504 return 0;
2505 if(src->mFormat == SF_WAVE)
2507 if(!TrReadInt(tr, 0, MAX_WAVE_CHANNELS, &intVal))
2508 return 0;
2509 src->mType = ET_NONE;
2510 src->mSize = 0;
2511 src->mBits = 0;
2512 src->mChannel = (uint)intVal;
2513 src->mSkip = 0;
2515 else
2517 TrIndication(tr, &line, &col);
2518 if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
2519 return 0;
2520 src->mType = MatchElementType(ident);
2521 if(src->mType == ET_NONE)
2523 TrErrorAt(tr, line, col, "Expected a source element type.\n");
2524 return 0;
2526 if(src->mFormat == SF_BIN_LE || src->mFormat == SF_BIN_BE)
2528 if(!TrReadOperator(tr, ","))
2529 return 0;
2530 if(src->mType == ET_INT)
2532 if(!TrReadInt(tr, MIN_BIN_SIZE, MAX_BIN_SIZE, &intVal))
2533 return 0;
2534 src->mSize = (uint)intVal;
2535 if(!TrIsOperator(tr, ","))
2536 src->mBits = (int)(8*src->mSize);
2537 else
2539 TrReadOperator(tr, ",");
2540 TrIndication(tr, &line, &col);
2541 if(!TrReadInt(tr, -2147483647-1, 2147483647, &intVal))
2542 return 0;
2543 if(abs(intVal) < MIN_BIN_BITS || ((uint)abs(intVal)) > (8*src->mSize))
2545 TrErrorAt(tr, line, col, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS, 8*src->mSize);
2546 return 0;
2548 src->mBits = intVal;
2551 else
2553 TrIndication(tr, &line, &col);
2554 if(!TrReadInt(tr, -2147483647-1, 2147483647, &intVal))
2555 return 0;
2556 if(intVal != 4 && intVal != 8)
2558 TrErrorAt(tr, line, col, "Expected a value of 4 or 8.\n");
2559 return 0;
2561 src->mSize = (uint)intVal;
2562 src->mBits = 0;
2565 else if(src->mFormat == SF_ASCII && src->mType == ET_INT)
2567 if(!TrReadOperator(tr, ","))
2568 return 0;
2569 if(!TrReadInt(tr, MIN_ASCII_BITS, MAX_ASCII_BITS, &intVal))
2570 return 0;
2571 src->mSize = 0;
2572 src->mBits = intVal;
2574 else
2576 src->mSize = 0;
2577 src->mBits = 0;
2580 if(!TrIsOperator(tr, ";"))
2581 src->mSkip = 0;
2582 else
2584 TrReadOperator(tr, ";");
2585 if(!TrReadInt (tr, 0, 0x7FFFFFFF, &intVal))
2586 return 0;
2587 src->mSkip = (uint)intVal;
2590 if(!TrReadOperator(tr, ")"))
2591 return 0;
2592 if(TrIsOperator(tr, "@"))
2594 TrReadOperator(tr, "@");
2595 if(!TrReadInt(tr, 0, 0x7FFFFFFF, &intVal))
2596 return 0;
2597 src->mOffset = (uint)intVal;
2599 else
2600 src->mOffset = 0;
2601 if(!TrReadOperator(tr, ":"))
2602 return 0;
2603 if(!TrReadString(tr, MAX_PATH_LEN, src->mPath))
2604 return 0;
2605 return 1;
2608 // Process the list of sources in the data set definition.
2609 static int ProcessSources(const HeadModelT model, TokenReaderT *tr, HrirDataT *hData)
2611 uint *setCount, *setFlag;
2612 uint line, col, ei, ai;
2613 SourceRefT src;
2614 double factor;
2615 double *hrir;
2617 setCount = (uint*)calloc(hData->mEvCount, sizeof(uint));
2618 setFlag = (uint*)calloc(hData->mIrCount, sizeof(uint));
2619 hrir = CreateArray(hData->mIrPoints);
2620 while(TrIsOperator(tr, "["))
2622 TrIndication(tr, & line, & col);
2623 TrReadOperator(tr, "[");
2624 if(!ReadIndexPair(tr, hData, &ei, &ai))
2625 goto error;
2626 if(!TrReadOperator(tr, "]"))
2627 goto error;
2628 if(setFlag[hData->mEvOffset[ei] + ai])
2630 TrErrorAt(tr, line, col, "Redefinition of source.\n");
2631 goto error;
2633 if(!TrReadOperator(tr, "="))
2634 goto error;
2636 factor = 1.0;
2637 for(;;)
2639 if(!ReadSourceRef(tr, &src))
2640 goto error;
2641 if(!LoadSource(&src, hData->mIrRate, hData->mIrPoints, hrir))
2642 goto error;
2644 if(model == HM_DATASET)
2645 AverageHrirOnset(hrir, 1.0 / factor, ei, ai, hData);
2646 AverageHrirMagnitude(hrir, 1.0 / factor, ei, ai, hData);
2647 factor += 1.0;
2648 if(!TrIsOperator(tr, "+"))
2649 break;
2650 TrReadOperator(tr, "+");
2652 setFlag[hData->mEvOffset[ei] + ai] = 1;
2653 setCount[ei]++;
2656 ei = 0;
2657 while(ei < hData->mEvCount && setCount[ei] < 1)
2658 ei++;
2659 if(ei < hData->mEvCount)
2661 hData->mEvStart = ei;
2662 while(ei < hData->mEvCount && setCount[ei] == hData->mAzCount[ei])
2663 ei++;
2664 if(ei >= hData->mEvCount)
2666 if(!TrLoad(tr))
2668 DestroyArray(hrir);
2669 free(setFlag);
2670 free(setCount);
2671 return 1;
2673 TrError(tr, "Errant data at end of source list.\n");
2675 else
2676 TrError(tr, "Missing sources for elevation index %d.\n", ei);
2678 else
2679 TrError(tr, "Missing source references.\n");
2681 error:
2682 DestroyArray(hrir);
2683 free(setFlag);
2684 free(setCount);
2685 return 0;
2688 /* Parse the data set definition and process the source data, storing the
2689 * resulting data set as desired. If the input name is NULL it will read
2690 * from standard input.
2692 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)
2694 char rateStr[8+1], expName[MAX_PATH_LEN];
2695 TokenReaderT tr;
2696 HrirDataT hData;
2697 double *dfa;
2698 FILE *fp;
2700 hData.mIrRate = 0;
2701 hData.mIrPoints = 0;
2702 hData.mFftSize = 0;
2703 hData.mIrSize = 0;
2704 hData.mIrCount = 0;
2705 hData.mEvCount = 0;
2706 hData.mRadius = 0;
2707 hData.mDistance = 0;
2708 fprintf(stdout, "Reading HRIR definition...\n");
2709 if(inName != NULL)
2711 fp = fopen(inName, "r");
2712 if(fp == NULL)
2714 fprintf(stderr, "Error: Could not open definition file '%s'\n", inName);
2715 return 0;
2717 TrSetup(fp, inName, &tr);
2719 else
2721 fp = stdin;
2722 TrSetup(fp, "<stdin>", &tr);
2724 if(!ProcessMetrics(&tr, fftSize, truncSize, &hData))
2726 if(inName != NULL)
2727 fclose(fp);
2728 return 0;
2730 hData.mHrirs = CreateArray(hData.mIrCount * hData.mIrSize);
2731 hData.mHrtds = CreateArray(hData.mIrCount);
2732 if(!ProcessSources(model, &tr, &hData))
2734 DestroyArray(hData.mHrtds);
2735 DestroyArray(hData.mHrirs);
2736 if(inName != NULL)
2737 fclose(fp);
2738 return 0;
2740 if(inName != NULL)
2741 fclose(fp);
2742 if(equalize)
2744 dfa = CreateArray(1 + (hData.mFftSize/2));
2745 fprintf(stdout, "Calculating diffuse-field average...\n");
2746 CalculateDiffuseFieldAverage(&hData, surface, limit, dfa);
2747 fprintf(stdout, "Performing diffuse-field equalization...\n");
2748 DiffuseFieldEqualize(dfa, &hData);
2749 DestroyArray(dfa);
2751 fprintf(stdout, "Performing minimum phase reconstruction...\n");
2752 ReconstructHrirs(&hData);
2753 if(outRate != 0 && outRate != hData.mIrRate)
2755 fprintf(stdout, "Resampling HRIRs...\n");
2756 ResampleHrirs(outRate, &hData);
2758 fprintf(stdout, "Truncating minimum-phase HRIRs...\n");
2759 hData.mIrPoints = truncSize;
2760 fprintf(stdout, "Synthesizing missing elevations...\n");
2761 if(model == HM_DATASET)
2762 SynthesizeOnsets(&hData);
2763 SynthesizeHrirs(&hData);
2764 fprintf(stdout, "Normalizing final HRIRs...\n");
2765 NormalizeHrirs(&hData);
2766 fprintf(stdout, "Calculating impulse delays...\n");
2767 CalculateHrtds(model, (radius > DEFAULT_CUSTOM_RADIUS) ? radius : hData.mRadius, &hData);
2768 snprintf(rateStr, 8, "%u", hData.mIrRate);
2769 StrSubst(outName, "%r", rateStr, MAX_PATH_LEN, expName);
2770 switch(outFormat)
2772 case OF_MHR:
2773 fprintf(stdout, "Creating MHR data set file...\n");
2774 if(!StoreMhr(&hData, expName))
2776 DestroyArray(hData.mHrtds);
2777 DestroyArray(hData.mHrirs);
2778 return 0;
2780 break;
2781 default:
2782 break;
2784 DestroyArray(hData.mHrtds);
2785 DestroyArray(hData.mHrirs);
2786 return 1;
2789 static void PrintHelp(const char *argv0, FILE *ofile)
2791 fprintf(ofile, "Usage: %s <command> [<option>...]\n\n", argv0);
2792 fprintf(ofile, "Commands:\n");
2793 fprintf(ofile, " -m, --make-mhr Makes an OpenAL Soft compatible HRTF data set.\n");
2794 fprintf(ofile, " Defaults output to: ./oalsoft_hrtf_%%r.mhr\n");
2795 fprintf(ofile, " -h, --help Displays this help information.\n\n");
2796 fprintf(ofile, "Options:\n");
2797 fprintf(ofile, " -r=<rate> Change the data set sample rate to the specified value and\n");
2798 fprintf(ofile, " resample the HRIRs accordingly.\n");
2799 fprintf(ofile, " -f=<points> Override the FFT window size (default: %u).\n", DEFAULT_FFTSIZE);
2800 fprintf(ofile, " -e={on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE ? "on" : "off"));
2801 fprintf(ofile, " -s={on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE ? "on" : "off"));
2802 fprintf(ofile, " -l={<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
2803 fprintf(ofile, " average (default: %.2f).\n", DEFAULT_LIMIT);
2804 fprintf(ofile, " -w=<points> Specify the size of the truncation window that's applied\n");
2805 fprintf(ofile, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE);
2806 fprintf(ofile, " -d={dataset| Specify the model used for calculating the head-delay timing\n");
2807 fprintf(ofile, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL == HM_DATASET) ? "dataset" : "sphere"));
2808 fprintf(ofile, " -c=<size> Use a customized head radius measured ear-to-ear in meters.\n");
2809 fprintf(ofile, " -i=<filename> Specify an HRIR definition file to use (defaults to stdin).\n");
2810 fprintf(ofile, " -o=<filename> Specify an output file. Overrides command-selected default.\n");
2811 fprintf(ofile, " Use of '%%r' will be substituted with the data set sample rate.\n");
2814 // Standard command line dispatch.
2815 int main(const int argc, const char *argv[])
2817 const char *inName = NULL, *outName = NULL;
2818 OutputFormatT outFormat;
2819 uint outRate, fftSize;
2820 int equalize, surface;
2821 char *end = NULL;
2822 HeadModelT model;
2823 uint truncSize;
2824 double radius;
2825 double limit;
2826 int argi;
2828 if(argc < 2 || strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0)
2830 fprintf(stdout, "HRTF Processing and Composition Utility\n\n");
2831 PrintHelp(argv[0], stdout);
2832 return 0;
2835 if(strcmp(argv[1], "--make-mhr") == 0 || strcmp(argv[1], "-m") == 0)
2837 outName = "./oalsoft_hrtf_%r.mhr";
2838 outFormat = OF_MHR;
2840 else
2842 fprintf(stderr, "Error: Invalid command '%s'.\n\n", argv[1]);
2843 PrintHelp(argv[0], stderr);
2844 return -1;
2847 outRate = 0;
2848 fftSize = 0;
2849 equalize = DEFAULT_EQUALIZE;
2850 surface = DEFAULT_SURFACE;
2851 limit = DEFAULT_LIMIT;
2852 truncSize = DEFAULT_TRUNCSIZE;
2853 model = DEFAULT_HEAD_MODEL;
2854 radius = DEFAULT_CUSTOM_RADIUS;
2856 argi = 2;
2857 while(argi < argc)
2859 if(strncmp(argv[argi], "-r=", 3) == 0)
2861 outRate = strtoul(&argv[argi][3], &end, 10);
2862 if(end[0] != '\0' || outRate < MIN_RATE || outRate > MAX_RATE)
2864 fprintf(stderr, "Error: Expected a value from %u to %u for '-r'.\n", MIN_RATE, MAX_RATE);
2865 return -1;
2868 else if(strncmp(argv[argi], "-f=", 3) == 0)
2870 fftSize = strtoul(&argv[argi][3], &end, 10);
2871 if(end[0] != '\0' || (fftSize&(fftSize-1)) || fftSize < MIN_FFTSIZE || fftSize > MAX_FFTSIZE)
2873 fprintf(stderr, "Error: Expected a power-of-two value from %u to %u for '-f'.\n", MIN_FFTSIZE, MAX_FFTSIZE);
2874 return -1;
2877 else if(strncmp(argv[argi], "-e=", 3) == 0)
2879 if(strcmp(&argv[argi][3], "on") == 0)
2880 equalize = 1;
2881 else if(strcmp(&argv[argi][3], "off") == 0)
2882 equalize = 0;
2883 else
2885 fprintf(stderr, "Error: Expected 'on' or 'off' for '-e'.\n");
2886 return -1;
2889 else if(strncmp(argv[argi], "-s=", 3) == 0)
2891 if(strcmp(&argv[argi][3], "on") == 0)
2892 surface = 1;
2893 else if(strcmp(&argv[argi][3], "off") == 0)
2894 surface = 0;
2895 else
2897 fprintf(stderr, "Error: Expected 'on' or 'off' for '-s'.\n");
2898 return -1;
2901 else if(strncmp(argv[argi], "-l=", 3) == 0)
2903 if(strcmp(&argv[argi][3], "none") == 0)
2904 limit = 0.0;
2905 else
2907 limit = strtod(&argv[argi] [3], &end);
2908 if(end[0] != '\0' || limit < MIN_LIMIT || limit > MAX_LIMIT)
2910 fprintf(stderr, "Error: Expected 'none' or a value from %.2f to %.2f for '-l'.\n", MIN_LIMIT, MAX_LIMIT);
2911 return -1;
2915 else if(strncmp(argv[argi], "-w=", 3) == 0)
2917 truncSize = strtoul(&argv[argi][3], &end, 10);
2918 if(end[0] != '\0' || truncSize < MIN_TRUNCSIZE || truncSize > MAX_TRUNCSIZE || (truncSize%MOD_TRUNCSIZE))
2920 fprintf(stderr, "Error: Expected a value from %u to %u in multiples of %u for '-w'.\n", MIN_TRUNCSIZE, MAX_TRUNCSIZE, MOD_TRUNCSIZE);
2921 return -1;
2924 else if(strncmp(argv[argi], "-d=", 3) == 0)
2926 if(strcmp(&argv[argi][3], "dataset") == 0)
2927 model = HM_DATASET;
2928 else if(strcmp(&argv[argi][3], "sphere") == 0)
2929 model = HM_SPHERE;
2930 else
2932 fprintf(stderr, "Error: Expected 'dataset' or 'sphere' for '-d'.\n");
2933 return -1;
2936 else if(strncmp(argv[argi], "-c=", 3) == 0)
2938 radius = strtod(&argv[argi][3], &end);
2939 if(end[0] != '\0' || radius < MIN_CUSTOM_RADIUS || radius > MAX_CUSTOM_RADIUS)
2941 fprintf(stderr, "Error: Expected a value from %.2f to %.2f for '-c'.\n", MIN_CUSTOM_RADIUS, MAX_CUSTOM_RADIUS);
2942 return -1;
2945 else if(strncmp(argv[argi], "-i=", 3) == 0)
2946 inName = &argv[argi][3];
2947 else if(strncmp(argv[argi], "-o=", 3) == 0)
2948 outName = &argv[argi][3];
2949 else
2951 fprintf(stderr, "Error: Invalid option '%s'.\n", argv[argi]);
2952 return -1;
2954 argi++;
2956 if(!ProcessDefinition(inName, outRate, fftSize, equalize, surface, limit, truncSize, model, radius, outFormat, outName))
2957 return -1;
2958 fprintf(stdout, "Operation completed.\n");
2959 return 0;