Reorganize and reformat makehrtf code
[openal-soft.git] / utils / makehrtf.c
blob4141065cea7253d53d6af1112ba3fbaf4813baa3
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 typedef enum ByteOrderT {
199 BO_NONE,
200 BO_LITTLE,
201 BO_BIG
202 } ByteOrderT;
204 // Source format for the references listed in the data set definition.
205 typedef enum SourceFormatT {
206 SF_NONE,
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.
211 } SourceFormatT;
213 // Element types for the references listed in the data set definition.
214 typedef enum ElementTypeT {
215 ET_NONE,
216 ET_INT, // Integer elements.
217 ET_FP // Floating-point elements.
218 } ElementTypeT;
220 // Head model used for calculating the impulse delays.
221 typedef enum HeadModelT {
222 HM_NONE0,
223 HM_DATASET, // Measure the onset from the dataset.
224 HM_SPHERE // Calculate the onset using a spherical head model.
225 } HeadModelT;
227 // Desired output format from the command line.
228 typedef enum OutputFormatT {
229 OF_NONE,
230 OF_MHR // OpenAL Soft MHR data set file.
231 } OutputFormatT;
233 // Unsigned integer type.
234 typedef unsigned int uint;
236 // Serialization types. The trailing digit indicates the number of bits.
237 typedef ALubyte uint8;
238 typedef ALint int32;
239 typedef ALuint uint32;
240 typedef ALuint64SOFT uint64;
242 // Token reader state for parsing the data set definition.
243 typedef struct TokenReaderT {
244 FILE *mFile;
245 const char *mName;
246 uint mLine;
247 uint mColumn;
248 char mRing[TR_RING_SIZE];
249 size_t mIn;
250 size_t mOut;
251 } TokenReaderT;
253 // Source reference state used when loading sources.
254 typedef struct SourceRefT {
255 SourceFormatT mFormat;
256 ElementTypeT mType;
257 uint mSize;
258 int mBits;
259 uint mChannel;
260 uint mSkip;
261 uint mOffset;
262 char mPath[MAX_PATH_LEN+1];
263 } SourceRefT;
265 // The HRIR metrics and data set used when loading, processing, and storing
266 // the resulting HRTF.
267 typedef struct HrirDataT {
268 uint mIrRate;
269 uint mIrCount;
270 uint mIrSize;
271 uint mIrPoints;
272 uint mFftSize;
273 uint mEvCount;
274 uint mEvStart;
275 uint mAzCount[MAX_EV_COUNT];
276 uint mEvOffset[MAX_EV_COUNT];
277 double mRadius;
278 double mDistance;
279 double *mHrirs;
280 double *mHrtds;
281 double mMaxHrtd;
282 } HrirDataT;
284 // The resampler metrics and FIR filter.
285 typedef struct ResamplerT {
286 uint mP, mQ, mM, mL;
287 double *mF;
288 } ResamplerT;
290 /*****************************
291 *** Token reader routines ***
292 *****************************/
293 /* Whitespace is not significant. It can process tokens as identifiers, numbers
294 * (integer and floating-point), strings, and operators. Strings must be
295 * encapsulated by double-quotes and cannot span multiple lines.
298 // Setup the reader on the given file. The filename can be NULL if no error
299 // output is desired.
300 static void TrSetup(FILE *fp, const char *filename, TokenReaderT *tr)
302 const char *name = NULL;
304 if(filename)
306 const char *slash = strrchr(filename, '/');
307 if(slash)
309 const char *bslash = strrchr(slash+1, '\\');
310 if(bslash) name = bslash+1;
311 else name = slash+1;
313 else
315 const char *bslash = strrchr(filename, '\\');
316 if(bslash) name = bslash+1;
317 else name = filename;
321 tr->mFile = fp;
322 tr->mName = name;
323 tr->mLine = 1;
324 tr->mColumn = 1;
325 tr->mIn = 0;
326 tr->mOut = 0;
329 // Prime the reader's ring buffer, and return a result indicating that there
330 // is text to process.
331 static int TrLoad(TokenReaderT *tr)
333 size_t toLoad, in, count;
335 toLoad = TR_RING_SIZE - (tr->mIn - tr->mOut);
336 if(toLoad >= TR_LOAD_SIZE && !feof(tr->mFile))
338 // Load TR_LOAD_SIZE (or less if at the end of the file) per read.
339 toLoad = TR_LOAD_SIZE;
340 in = tr->mIn&TR_RING_MASK;
341 count = TR_RING_SIZE - in;
342 if(count < toLoad)
344 tr->mIn += fread(&tr->mRing[in], 1, count, tr->mFile);
345 tr->mIn += fread(&tr->mRing[0], 1, toLoad-count, tr->mFile);
347 else
348 tr->mIn += fread(&tr->mRing[in], 1, toLoad, tr->mFile);
350 if(tr->mOut >= TR_RING_SIZE)
352 tr->mOut -= TR_RING_SIZE;
353 tr->mIn -= TR_RING_SIZE;
356 if(tr->mIn > tr->mOut)
357 return 1;
358 return 0;
361 // Error display routine. Only displays when the base name is not NULL.
362 static void TrErrorVA(const TokenReaderT *tr, uint line, uint column, const char *format, va_list argPtr)
364 if(!tr->mName)
365 return;
366 fprintf(stderr, "Error (%s:%u:%u): ", tr->mName, line, column);
367 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, ...)
373 va_list argPtr;
375 va_start(argPtr, format);
376 TrErrorVA(tr, line, column, format, argPtr);
377 va_end(argPtr);
380 // Used to display an error at the current line/column.
381 static void TrError(const TokenReaderT *tr, const char *format, ...)
383 va_list argPtr;
385 va_start(argPtr, format);
386 TrErrorVA(tr, tr->mLine, tr->mColumn, format, argPtr);
387 va_end(argPtr);
390 // Skips to the next line.
391 static void TrSkipLine(TokenReaderT *tr)
393 char ch;
395 while(TrLoad(tr))
397 ch = tr->mRing[tr->mOut&TR_RING_MASK];
398 tr->mOut++;
399 if(ch == '\n')
401 tr->mLine++;
402 tr->mColumn = 1;
403 break;
405 tr->mColumn ++;
409 // Skips to the next token.
410 static int TrSkipWhitespace(TokenReaderT *tr)
412 char ch;
414 while(TrLoad(tr))
416 ch = tr->mRing[tr->mOut&TR_RING_MASK];
417 if(isspace(ch))
419 tr->mOut++;
420 if(ch == '\n')
422 tr->mLine++;
423 tr->mColumn = 1;
425 else
426 tr->mColumn++;
428 else if(ch == '#')
429 TrSkipLine(tr);
430 else
431 return 1;
433 return 0;
436 // Get the line and/or column of the next token (or the end of input).
437 static void TrIndication(TokenReaderT *tr, uint *line, uint *column)
439 TrSkipWhitespace(tr);
440 if(line) *line = tr->mLine;
441 if(column) *column = tr->mColumn;
444 // Checks to see if a token is the given operator. It does not display any
445 // errors and will not proceed to the next token.
446 static int TrIsOperator(TokenReaderT *tr, const char *op)
448 size_t out, len;
449 char ch;
451 if(!TrSkipWhitespace(tr))
452 return 0;
453 out = tr->mOut;
454 len = 0;
455 while(op[len] != '\0' && out < tr->mIn)
457 ch = tr->mRing[out&TR_RING_MASK];
458 if(ch != op[len]) break;
459 len++;
460 out++;
462 if(op[len] == '\0')
463 return 1;
464 return 0;
467 /* The TrRead*() routines obtain the value of a matching token type. They
468 * display type, form, and boundary errors and will proceed to the next
469 * token.
472 // Reads and validates an identifier token.
473 static int TrReadIdent(TokenReaderT *tr, const uint maxLen, char *ident)
475 uint col, len;
476 char ch;
478 col = tr->mColumn;
479 if(TrSkipWhitespace(tr))
481 col = tr->mColumn;
482 ch = tr->mRing[tr->mOut&TR_RING_MASK];
483 if(ch == '_' || isalpha(ch))
485 len = 0;
486 do {
487 if(len < maxLen)
488 ident[len] = ch;
489 len++;
490 tr->mOut++;
491 if(!TrLoad(tr))
492 break;
493 ch = tr->mRing[tr->mOut&TR_RING_MASK];
494 } while(ch == '_' || isdigit(ch) || isalpha(ch));
496 tr->mColumn += len;
497 if(len < maxLen)
499 ident[len] = '\0';
500 return 1;
502 TrErrorAt(tr, tr->mLine, col, "Identifier is too long.\n");
503 return 0;
506 TrErrorAt(tr, tr->mLine, col, "Expected an identifier.\n");
507 return 0;
510 // Reads and validates (including bounds) an integer token.
511 static int TrReadInt(TokenReaderT *tr, const int loBound, const int hiBound, int *value)
513 uint col, digis, len;
514 char ch, temp[64+1];
516 col = tr->mColumn;
517 if(TrSkipWhitespace(tr))
519 col = tr->mColumn;
520 len = 0;
521 ch = tr->mRing[tr->mOut&TR_RING_MASK];
522 if(ch == '+' || ch == '-')
524 temp[len] = ch;
525 len++;
526 tr->mOut++;
528 digis = 0;
529 while(TrLoad(tr))
531 ch = tr->mRing[tr->mOut&TR_RING_MASK];
532 if(!isdigit(ch)) break;
533 if(len < 64)
534 temp[len] = ch;
535 len++;
536 digis++;
537 tr->mOut++;
539 tr->mColumn += len;
540 if(digis > 0 && ch != '.' && !isalpha(ch))
542 if(len > 64)
544 TrErrorAt(tr, tr->mLine, col, "Integer is too long.");
545 return 0;
547 temp[len] = '\0';
548 *value = strtol(temp, NULL, 10);
549 if(*value < loBound || *value > hiBound)
551 TrErrorAt(tr, tr->mLine, col, "Expected a value from %d to %d.\n", loBound, hiBound);
552 return (0);
554 return (1);
557 TrErrorAt(tr, tr->mLine, col, "Expected an integer.\n");
558 return 0;
561 // Reads and validates (including bounds) a float token.
562 static int TrReadFloat(TokenReaderT *tr, const double loBound, const double hiBound, double *value)
564 uint col, digis, len;
565 char ch, temp[64+1];
567 col = tr->mColumn;
568 if(TrSkipWhitespace(tr))
570 col = tr->mColumn;
571 len = 0;
572 ch = tr->mRing[tr->mOut&TR_RING_MASK];
573 if(ch == '+' || ch == '-')
575 temp[len] = ch;
576 len++;
577 tr->mOut++;
580 digis = 0;
581 while(TrLoad(tr))
583 ch = tr->mRing[tr->mOut&TR_RING_MASK];
584 if(!isdigit(ch)) break;
585 if(len < 64)
586 temp[len] = ch;
587 len++;
588 digis++;
589 tr->mOut++;
591 if(ch == '.')
593 if(len < 64)
594 temp[len] = ch;
595 len++;
596 tr->mOut++;
598 while(TrLoad(tr))
600 ch = tr->mRing[tr->mOut&TR_RING_MASK];
601 if(!isdigit(ch)) break;
602 if(len < 64)
603 temp[len] = ch;
604 len++;
605 digis++;
606 tr->mOut++;
608 if(digis > 0)
610 if(ch == 'E' || ch == 'e')
612 if(len < 64)
613 temp[len] = ch;
614 len++;
615 digis = 0;
616 tr->mOut++;
617 if(ch == '+' || ch == '-')
619 if(len < 64)
620 temp[len] = ch;
621 len++;
622 tr->mOut++;
624 while(TrLoad(tr))
626 ch = tr->mRing[tr->mOut&TR_RING_MASK];
627 if(!isdigit(ch)) break;
628 if(len < 64)
629 temp[len] = ch;
630 len++;
631 digis++;
632 tr->mOut++;
635 tr->mColumn += len;
636 if(digis > 0 && ch != '.' && !isalpha(ch))
638 if(len > 64)
640 TrErrorAt(tr, tr->mLine, col, "Float is too long.");
641 return 0;
643 temp[len] = '\0';
644 *value = strtod(temp, NULL);
645 if(*value < loBound || *value > hiBound)
647 TrErrorAt (tr, tr->mLine, col, "Expected a value from %f to %f.\n", loBound, hiBound);
648 return 0;
650 return 1;
653 else
654 tr->mColumn += len;
656 TrErrorAt(tr, tr->mLine, col, "Expected a float.\n");
657 return 0;
660 // Reads and validates a string token.
661 static int TrReadString(TokenReaderT *tr, const uint maxLen, char *text)
663 uint col, len;
664 char ch;
666 col = tr->mColumn;
667 if(TrSkipWhitespace(tr))
669 col = tr->mColumn;
670 ch = tr->mRing[tr->mOut&TR_RING_MASK];
671 if(ch == '\"')
673 tr->mOut++;
674 len = 0;
675 while(TrLoad(tr))
677 ch = tr->mRing[tr->mOut&TR_RING_MASK];
678 tr->mOut++;
679 if(ch == '\"')
680 break;
681 if(ch == '\n')
683 TrErrorAt (tr, tr->mLine, col, "Unterminated string at end of line.\n");
684 return 0;
686 if(len < maxLen)
687 text[len] = ch;
688 len++;
690 if(ch != '\"')
692 tr->mColumn += 1 + len;
693 TrErrorAt(tr, tr->mLine, col, "Unterminated string at end of input.\n");
694 return 0;
696 tr->mColumn += 2 + len;
697 if(len > maxLen)
699 TrErrorAt (tr, tr->mLine, col, "String is too long.\n");
700 return 0;
702 text[len] = '\0';
703 return 1;
706 TrErrorAt(tr, tr->mLine, col, "Expected a string.\n");
707 return 0;
710 // Reads and validates the given operator.
711 static int TrReadOperator(TokenReaderT *tr, const char *op)
713 uint col, len;
714 char ch;
716 col = tr->mColumn;
717 if(TrSkipWhitespace(tr))
719 col = tr->mColumn;
720 len = 0;
721 while(op[len] != '\0' && TrLoad(tr))
723 ch = tr->mRing[tr->mOut&TR_RING_MASK];
724 if(ch != op[len]) break;
725 len++;
726 tr->mOut++;
728 tr->mColumn += len;
729 if(op[len] == '\0')
730 return 1;
732 TrErrorAt(tr, tr->mLine, col, "Expected '%s' operator.\n", op);
733 return 0;
736 /* Performs a string substitution. Any case-insensitive occurrences of the
737 * pattern string are replaced with the replacement string. The result is
738 * truncated if necessary.
740 static int StrSubst(const char *in, const char *pat, const char *rep, const size_t maxLen, char *out)
742 size_t inLen, patLen, repLen;
743 size_t si, di;
744 int truncated;
746 inLen = strlen(in);
747 patLen = strlen(pat);
748 repLen = strlen(rep);
749 si = 0;
750 di = 0;
751 truncated = 0;
752 while(si < inLen && di < maxLen)
754 if(patLen <= inLen-si)
756 if(strncasecmp(&in[si], pat, patLen) == 0)
758 if(repLen > maxLen-di)
760 repLen = maxLen - di;
761 truncated = 1;
763 strncpy(&out[di], rep, repLen);
764 si += patLen;
765 di += repLen;
768 out[di] = in[si];
769 si++;
770 di++;
772 if(si < inLen)
773 truncated = 1;
774 out[di] = '\0';
775 return !truncated;
779 /*********************
780 *** Math routines ***
781 *********************/
783 // Provide missing math routines for MSVC versions < 1800 (Visual Studio 2013).
784 #if defined(_MSC_VER) && _MSC_VER < 1800
785 static double round(double val)
787 if(val < 0.0)
788 return ceil(val-0.5);
789 return floor(val+0.5);
792 static double fmin(double a, double b)
794 return (a<b) ? a : b;
797 static double fmax(double a, double b)
799 return (a>b) ? a : b;
801 #endif
803 // Simple clamp routine.
804 static double Clamp(const double val, const double lower, const double upper)
806 return fmin(fmax(val, lower), upper);
809 // Performs linear interpolation.
810 static double Lerp(const double a, const double b, const double f)
812 return a + (f * (b - a));
815 // Performs a high-passed triangular probability density function dither from
816 // a double to an integer. It assumes the input sample is already scaled.
817 static int HpTpdfDither(const double in, int *hpHist)
819 static const double PRNG_SCALE = 1.0 / (RAND_MAX+1.0);
820 int prn;
821 double out;
823 prn = rand();
824 out = round(in + (PRNG_SCALE * (prn - *hpHist)));
825 *hpHist = prn;
826 return (int)out;
829 // Allocates an array of doubles.
830 static double *CreateArray(size_t n)
832 double *a;
834 if(n == 0) n = 1;
835 a = calloc(n, sizeof(double));
836 if(a == NULL)
838 fprintf(stderr, "Error: Out of memory.\n");
839 exit(-1);
841 return a;
844 // Frees an array of doubles.
845 static void DestroyArray(double *a)
846 { free(a); }
848 // Complex number routines. All outputs must be non-NULL.
850 // Magnitude/absolute value.
851 static double ComplexAbs(const double r, const double i)
853 return sqrt(r*r + i*i);
856 // Multiply.
857 static void ComplexMul(const double aR, const double aI, const double bR, const double bI, double *outR, double *outI)
859 *outR = (aR * bR) - (aI * bI);
860 *outI = (aI * bR) + (aR * bI);
863 // Base-e exponent.
864 static void ComplexExp(const double inR, const double inI, double *outR, double *outI)
866 double e = exp(inR);
867 *outR = e * cos(inI);
868 *outI = e * sin(inI);
871 /* Fast Fourier transform routines. The number of points must be a power of
872 * two. In-place operation is possible only if both the real and imaginary
873 * parts are in-place together.
876 // Performs bit-reversal ordering.
877 static void FftArrange(const uint n, const double *inR, const double *inI, double *outR, double *outI)
879 uint rk, k, m;
880 double tempR, tempI;
882 if(inR == outR && inI == outI)
884 // Handle in-place arrangement.
885 rk = 0;
886 for(k = 0;k < n;k++)
888 if(rk > k)
890 tempR = inR[rk];
891 tempI = inI[rk];
892 outR[rk] = inR[k];
893 outI[rk] = inI[k];
894 outR[k] = tempR;
895 outI[k] = tempI;
897 m = n;
898 while(rk&(m >>= 1))
899 rk &= ~m;
900 rk |= m;
903 else
905 // Handle copy arrangement.
906 rk = 0;
907 for(k = 0;k < n;k++)
909 outR[rk] = inR[k];
910 outI[rk] = inI[k];
911 m = n;
912 while(rk&(m >>= 1))
913 rk &= ~m;
914 rk |= m;
919 // Performs the summation.
920 static void FftSummation(const uint n, const double s, double *re, double *im)
922 double pi;
923 uint m, m2;
924 double vR, vI, wR, wI;
925 uint i, k, mk;
926 double tR, tI;
928 pi = s * M_PI;
929 for(m = 1, m2 = 2;m < n; m <<= 1, m2 <<= 1)
931 // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
932 vR = sin(0.5 * pi / m);
933 vR = -2.0 * vR * vR;
934 vI = -sin(pi / m);
935 // w = Complex (1.0, 0.0)
936 wR = 1.0;
937 wI = 0.0;
938 for(i = 0;i < m;i++)
940 for(k = i;k < n;k += m2)
942 mk = k + m;
943 // t = ComplexMul(w, out[km2])
944 tR = (wR * re[mk]) - (wI * im[mk]);
945 tI = (wR * im[mk]) + (wI * re[mk]);
946 // out[mk] = ComplexSub (out [k], t)
947 re[mk] = re[k] - tR;
948 im[mk] = im[k] - tI;
949 // out[k] = ComplexAdd (out [k], t)
950 re[k] += tR;
951 im[k] += tI;
953 // t = ComplexMul (v, w)
954 tR = (vR * wR) - (vI * wI);
955 tI = (vR * wI) + (vI * wR);
956 // w = ComplexAdd (w, t)
957 wR += tR;
958 wI += tI;
963 // Performs a forward FFT.
964 static void FftForward(const uint n, const double *inR, const double *inI, double *outR, double *outI)
966 FftArrange(n, inR, inI, outR, outI);
967 FftSummation(n, 1.0, outR, outI);
970 // Performs an inverse FFT.
971 static void FftInverse(const uint n, const double *inR, const double *inI, double *outR, double *outI)
973 double f;
974 uint i;
976 FftArrange(n, inR, inI, outR, outI);
977 FftSummation(n, -1.0, outR, outI);
978 f = 1.0 / n;
979 for(i = 0;i < n;i++)
981 outR[i] *= f;
982 outI[i] *= f;
986 /* Calculate the complex helical sequence (or discrete-time analytical
987 * signal) of the given input using the Hilbert transform. Given the
988 * negative natural logarithm of a signal's magnitude response, the imaginary
989 * components can be used as the angles for minimum-phase reconstruction.
991 static void Hilbert(const uint n, const double *in, double *outR, double *outI)
993 uint i;
995 if(in == outR)
997 // Handle in-place operation.
998 for(i = 0;i < n;i++)
999 outI[i] = 0.0;
1001 else
1003 // Handle copy operation.
1004 for(i = 0;i < n;i++)
1006 outR[i] = in[i];
1007 outI[i] = 0.0;
1010 FftForward(n, outR, outI, outR, outI);
1011 /* Currently the Fourier routines operate only on point counts that are
1012 * powers of two. If that changes and n is odd, the following conditional
1013 * should be: i < (n + 1) / 2.
1015 for(i = 1;i < (n/2);i++)
1017 outR[i] *= 2.0;
1018 outI[i] *= 2.0;
1020 // If n is odd, the following increment should be skipped.
1021 i++;
1022 for(;i < n;i++)
1024 outR[i] = 0.0;
1025 outI[i] = 0.0;
1027 FftInverse(n, outR, outI, outR, outI);
1030 /* Calculate the magnitude response of the given input. This is used in
1031 * place of phase decomposition, since the phase residuals are discarded for
1032 * minimum phase reconstruction. The mirrored half of the response is also
1033 * discarded.
1035 static void MagnitudeResponse(const uint n, const double *inR, const double *inI, double *out)
1037 const uint m = 1 + (n / 2);
1038 uint i;
1039 for(i = 0;i < m;i++)
1040 out[i] = fmax(ComplexAbs(inR[i], inI[i]), EPSILON);
1043 /* Apply a range limit (in dB) to the given magnitude response. This is used
1044 * to adjust the effects of the diffuse-field average on the equalization
1045 * process.
1047 static void LimitMagnitudeResponse(const uint n, const double limit, const double *in, double *out)
1049 const uint m = 1 + (n / 2);
1050 double halfLim;
1051 uint i, lower, upper;
1052 double ave;
1054 halfLim = limit / 2.0;
1055 // Convert the response to dB.
1056 for(i = 0;i < m;i++)
1057 out[i] = 20.0 * log10(in[i]);
1058 // Use six octaves to calculate the average magnitude of the signal.
1059 lower = ((uint)ceil(n / pow(2.0, 8.0))) - 1;
1060 upper = ((uint)floor(n / pow(2.0, 2.0))) - 1;
1061 ave = 0.0;
1062 for(i = lower;i <= upper;i++)
1063 ave += out[i];
1064 ave /= upper - lower + 1;
1065 // Keep the response within range of the average magnitude.
1066 for(i = 0;i < m;i++)
1067 out[i] = Clamp(out[i], ave - halfLim, ave + halfLim);
1068 // Convert the response back to linear magnitude.
1069 for(i = 0;i < m;i++)
1070 out[i] = pow(10.0, out[i] / 20.0);
1073 /* Reconstructs the minimum-phase component for the given magnitude response
1074 * of a signal. This is equivalent to phase recomposition, sans the missing
1075 * residuals (which were discarded). The mirrored half of the response is
1076 * reconstructed.
1078 static void MinimumPhase(const uint n, const double *in, double *outR, double *outI)
1080 const uint m = 1 + (n / 2);
1081 double aR, aI;
1082 double *mags;
1083 uint i;
1085 mags = CreateArray(n);
1086 for(i = 0;i < m;i++)
1088 mags[i] = fmax(in[i], EPSILON);
1089 outR[i] = -log(mags[i]);
1091 for(;i < n;i++)
1093 mags[i] = mags[n - i];
1094 outR[i] = outR[n - i];
1096 Hilbert(n, outR, outR, outI);
1097 // Remove any DC offset the filter has.
1098 outR[0] = 0.0;
1099 outI[0] = 0.0;
1100 for(i = 1;i < n;i++)
1102 ComplexExp(0.0, outI[i], &aR, &aI);
1103 ComplexMul(mags[i], 0.0, aR, aI, &outR[i], &outI[i]);
1105 DestroyArray(mags);
1109 /***************************
1110 *** Resampler functions ***
1111 ***************************/
1113 /* This is the normalized cardinal sine (sinc) function.
1115 * sinc(x) = { 1, x = 0
1116 * { sin(pi x) / (pi x), otherwise.
1118 static double Sinc(const double x)
1120 if(fabs(x) < EPSILON)
1121 return 1.0;
1122 return sin(M_PI * x) / (M_PI * x);
1125 /* The zero-order modified Bessel function of the first kind, used for the
1126 * Kaiser window.
1128 * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
1129 * = sum_{k=0}^inf ((x / 2)^k / k!)^2
1131 static double BesselI_0(const double x)
1133 double term, sum, x2, y, last_sum;
1134 int k;
1136 // Start at k=1 since k=0 is trivial.
1137 term = 1.0;
1138 sum = 1.0;
1139 x2 = x/2.0;
1140 k = 1;
1142 // Let the integration converge until the term of the sum is no longer
1143 // significant.
1144 do {
1145 y = x2 / k;
1146 k++;
1147 last_sum = sum;
1148 term *= y * y;
1149 sum += term;
1150 } while(sum != last_sum);
1151 return sum;
1154 /* Calculate a Kaiser window from the given beta value and a normalized k
1155 * [-1, 1].
1157 * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
1158 * { 0, elsewhere.
1160 * Where k can be calculated as:
1162 * k = i / l, where -l <= i <= l.
1164 * or:
1166 * k = 2 i / M - 1, where 0 <= i <= M.
1168 static double Kaiser(const double b, const double k)
1170 if(!(k >= -1.0 && k <= 1.0))
1171 return 0.0;
1172 return BesselI_0(b * sqrt(1.0 - k*k)) / BesselI_0(b);
1175 // Calculates the greatest common divisor of a and b.
1176 static uint Gcd(uint x, uint y)
1178 while(y > 0)
1180 uint z = y;
1181 y = x % y;
1182 x = z;
1184 return x;
1187 /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
1188 * the transition width is normalized frequency (0.5 is nyquist).
1190 * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
1191 * { ceil(5.79 / 2 pi f_t), r <= 21.
1194 static uint CalcKaiserOrder(const double rejection, const double transition)
1196 double w_t = 2.0 * M_PI * transition;
1197 if(rejection > 21.0)
1198 return (uint)ceil((rejection - 7.95) / (2.285 * w_t));
1199 return (uint)ceil(5.79 / w_t);
1202 // Calculates the beta value of the Kaiser window. Rejection is in dB.
1203 static double CalcKaiserBeta(const double rejection)
1205 if(rejection > 50.0)
1206 return 0.1102 * (rejection - 8.7);
1207 if(rejection >= 21.0)
1208 return (0.5842 * pow(rejection - 21.0, 0.4)) +
1209 (0.07886 * (rejection - 21.0));
1210 return 0.0;
1213 /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
1214 * width, beta, gain, and cutoff. The point is specified in non-normalized
1215 * samples, from 0 to M, where M = (2 l + 1).
1217 * w(k) 2 p f_t sinc(2 f_t x)
1219 * x -- centered sample index (i - l)
1220 * k -- normalized and centered window index (x / l)
1221 * w(k) -- window function (Kaiser)
1222 * p -- gain compensation factor when sampling
1223 * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
1225 static double SincFilter(const int l, const double b, const double gain, const double cutoff, const int i)
1227 return Kaiser(b, (double)(i - l) / l) * 2.0 * gain * cutoff * Sinc(2.0 * cutoff * (i - l));
1230 /* This is a polyphase sinc-filtered resampler.
1232 * Upsample Downsample
1234 * p/q = 3/2 p/q = 3/5
1236 * M-+-+-+-> M-+-+-+->
1237 * -------------------+ ---------------------+
1238 * p s * f f f f|f| | p s * f f f f f |
1239 * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
1240 * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
1241 * s * f|f|f f f | s * f f|f|f f |
1242 * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
1243 * --------+=+--------+ 0 * |0|0 0 0 0 |
1244 * d . d .|d|. d . d ----------+=+--------+
1245 * d . . . .|d|. . . .
1246 * q->
1247 * q-+-+-+->
1249 * P_f(i,j) = q i mod p + pj
1250 * P_s(i,j) = floor(q i / p) - j
1251 * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
1252 * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
1253 * { 0, P_f(i,j) >= M. }
1256 // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
1257 // that's used to cut frequencies above the destination nyquist.
1258 static void ResamplerSetup(ResamplerT *rs, const uint srcRate, const uint dstRate)
1260 double cutoff, width, beta;
1261 uint gcd, l;
1262 int i;
1264 gcd = Gcd(srcRate, dstRate);
1265 rs->mP = dstRate / gcd;
1266 rs->mQ = srcRate / gcd;
1267 /* The cutoff is adjusted by half the transition width, so the transition
1268 * ends before the nyquist (0.5). Both are scaled by the downsampling
1269 * factor.
1271 if(rs->mP > rs->mQ)
1273 cutoff = 0.45 / rs->mP;
1274 width = 0.1 / rs->mP;
1276 else
1278 cutoff = 0.45 / rs->mQ;
1279 width = 0.1 / rs->mQ;
1281 // A rejection of -180 dB is used for the stop band.
1282 l = CalcKaiserOrder(180.0, width) / 2;
1283 beta = CalcKaiserBeta(180.0);
1284 rs->mM = (2 * l) + 1;
1285 rs->mL = l;
1286 rs->mF = CreateArray(rs->mM);
1287 for(i = 0;i < ((int)rs->mM);i++)
1288 rs->mF[i] = SincFilter((int)l, beta, rs->mP, cutoff, i);
1291 // Clean up after the resampler.
1292 static void ResamplerClear(ResamplerT *rs)
1294 DestroyArray(rs->mF);
1295 rs->mF = NULL;
1298 // Perform the upsample-filter-downsample resampling operation using a
1299 // polyphase filter implementation.
1300 static void ResamplerRun(ResamplerT *rs, const uint inN, const double *in, const uint outN, double *out)
1302 const uint p = rs->mP, q = rs->mQ, m = rs->mM, l = rs->mL;
1303 const double *f = rs->mF;
1304 uint j_f, j_s;
1305 double *work;
1306 uint i;
1308 if(outN == 0)
1309 return;
1311 // Handle in-place operation.
1312 if(in == out)
1313 work = CreateArray(outN);
1314 else
1315 work = out;
1316 // Resample the input.
1317 for(i = 0;i < outN;i++)
1319 double r = 0.0;
1320 // Input starts at l to compensate for the filter delay. This will
1321 // drop any build-up from the first half of the filter.
1322 j_f = (l + (q * i)) % p;
1323 j_s = (l + (q * i)) / p;
1324 while(j_f < m)
1326 // Only take input when 0 <= j_s < inN. This single unsigned
1327 // comparison catches both cases.
1328 if(j_s < inN)
1329 r += f[j_f] * in[j_s];
1330 j_f += p;
1331 j_s--;
1333 work[i] = r;
1335 // Clean up after in-place operation.
1336 if(in == out)
1338 for(i = 0;i < outN;i++)
1339 out[i] = work[i];
1340 DestroyArray(work);
1344 // Read a binary value of the specified byte order and byte size from a file,
1345 // storing it as a 32-bit unsigned integer.
1346 static int ReadBin4(FILE *fp, const char *filename, const ByteOrderT order, const uint bytes, uint32 *out)
1348 uint8 in[4];
1349 uint32 accum;
1350 uint i;
1352 if(fread(in, 1, bytes, fp) != bytes)
1354 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1355 return 0;
1357 accum = 0;
1358 switch(order)
1360 case BO_LITTLE:
1361 for(i = 0;i < bytes;i++)
1362 accum = (accum<<8) | in[bytes - i - 1];
1363 break;
1364 case BO_BIG:
1365 for(i = 0;i < bytes;i++)
1366 accum = (accum<<8) | in[i];
1367 break;
1368 default:
1369 break;
1371 *out = accum;
1372 return 1;
1375 // Read a binary value of the specified byte order from a file, storing it as
1376 // a 64-bit unsigned integer.
1377 static int ReadBin8(FILE *fp, const char *filename, const ByteOrderT order, uint64 *out)
1379 uint8 in [8];
1380 uint64 accum;
1381 uint i;
1383 if(fread(in, 1, 8, fp) != 8)
1385 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1386 return 0;
1388 accum = 0ULL;
1389 switch(order)
1391 case BO_LITTLE:
1392 for(i = 0;i < 8;i++)
1393 accum = (accum<<8) | in[8 - i - 1];
1394 break;
1395 case BO_BIG:
1396 for(i = 0;i < 8;i++)
1397 accum = (accum<<8) | in[i];
1398 break;
1399 default:
1400 break;
1402 *out = accum;
1403 return 1;
1406 // Write an ASCII string to a file.
1407 static int WriteAscii(const char *out, FILE *fp, const char *filename)
1409 size_t len;
1411 len = strlen(out);
1412 if(fwrite(out, 1, len, fp) != len)
1414 fclose(fp);
1415 fprintf(stderr, "Error: Bad write to file '%s'.\n", filename);
1416 return 0;
1418 return 1;
1421 // Write a binary value of the given byte order and byte size to a file,
1422 // loading it from a 32-bit unsigned integer.
1423 static int WriteBin4(const ByteOrderT order, const uint bytes, const uint32 in, FILE *fp, const char *filename)
1425 uint8 out[4];
1426 uint i;
1428 switch(order)
1430 case BO_LITTLE:
1431 for(i = 0;i < bytes;i++)
1432 out[i] = (in>>(i*8)) & 0x000000FF;
1433 break;
1434 case BO_BIG:
1435 for(i = 0;i < bytes;i++)
1436 out[bytes - i - 1] = (in>>(i*8)) & 0x000000FF;
1437 break;
1438 default:
1439 break;
1441 if(fwrite(out, 1, bytes, fp) != bytes)
1443 fprintf(stderr, "Error: Bad write to file '%s'.\n", filename);
1444 return 0;
1446 return 1;
1449 /* Read a binary value of the specified type, byte order, and byte size from
1450 * a file, converting it to a double. For integer types, the significant
1451 * bits are used to normalize the result. The sign of bits determines
1452 * whether they are padded toward the MSB (negative) or LSB (positive).
1453 * Floating-point types are not normalized.
1455 static int ReadBinAsDouble(FILE *fp, const char *filename, const ByteOrderT order, const ElementTypeT type, const uint bytes, const int bits, double *out)
1457 union {
1458 uint32 ui;
1459 int32 i;
1460 float f;
1461 } v4;
1462 union {
1463 uint64 ui;
1464 double f;
1465 } v8;
1467 *out = 0.0;
1468 if(bytes > 4)
1470 if(!ReadBin8(fp, filename, order, &v8.ui))
1471 return 0;
1472 if(type == ET_FP)
1473 *out = v8.f;
1475 else
1477 if(!ReadBin4(fp, filename, order, bytes, &v4.ui))
1478 return 0;
1479 if(type == ET_FP)
1480 *out = v4.f;
1481 else
1483 if(bits > 0)
1484 v4.ui >>= (8*bytes) - ((uint)bits);
1485 else
1486 v4.ui &= (0xFFFFFFFF >> (32+bits));
1488 if(v4.ui&(uint)(1<<(abs(bits)-1)))
1489 v4.ui |= (0xFFFFFFFF << abs (bits));
1490 *out = v4.i / (double)(1<<(abs(bits)-1));
1493 return 1;
1496 /* Read an ascii value of the specified type from a file, converting it to a
1497 * double. For integer types, the significant bits are used to normalize the
1498 * result. The sign of the bits should always be positive. This also skips
1499 * up to one separator character before the element itself.
1501 static int ReadAsciiAsDouble(TokenReaderT *tr, const char *filename, const ElementTypeT type, const uint bits, double *out)
1503 if(TrIsOperator(tr, ","))
1504 TrReadOperator(tr, ",");
1505 else if(TrIsOperator(tr, ":"))
1506 TrReadOperator(tr, ":");
1507 else if(TrIsOperator(tr, ";"))
1508 TrReadOperator(tr, ";");
1509 else if(TrIsOperator(tr, "|"))
1510 TrReadOperator(tr, "|");
1512 if(type == ET_FP)
1514 if(!TrReadFloat(tr, -HUGE_VAL, HUGE_VAL, out))
1516 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1517 return 0;
1520 else
1522 int v;
1523 if(!TrReadInt(tr, -(1<<(bits-1)), (1<<(bits-1))-1, &v))
1525 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1526 return 0;
1528 *out = v / (double)((1<<(bits-1))-1);
1530 return 1;
1533 // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
1534 // the source parameters and data set metrics.
1535 static int ReadWaveFormat(FILE *fp, const ByteOrderT order, const uint hrirRate, SourceRefT *src)
1537 uint32 fourCC, chunkSize;
1538 uint32 format, channels, rate, dummy, block, size, bits;
1540 chunkSize = 0;
1541 do {
1542 if (chunkSize > 0)
1543 fseek (fp, (long) chunkSize, SEEK_CUR);
1544 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
1545 !ReadBin4(fp, src->mPath, order, 4, &chunkSize))
1546 return 0;
1547 } while(fourCC != FOURCC_FMT);
1548 if(!ReadBin4(fp, src->mPath, order, 2, & format) ||
1549 !ReadBin4(fp, src->mPath, order, 2, & channels) ||
1550 !ReadBin4(fp, src->mPath, order, 4, & rate) ||
1551 !ReadBin4(fp, src->mPath, order, 4, & dummy) ||
1552 !ReadBin4(fp, src->mPath, order, 2, & block))
1553 return (0);
1554 block /= channels;
1555 if(chunkSize > 14)
1557 if(!ReadBin4(fp, src->mPath, order, 2, &size))
1558 return 0;
1559 size /= 8;
1560 if(block > size)
1561 size = block;
1563 else
1564 size = block;
1565 if(format == WAVE_FORMAT_EXTENSIBLE)
1567 fseek(fp, 2, SEEK_CUR);
1568 if(!ReadBin4(fp, src->mPath, order, 2, &bits))
1569 return 0;
1570 if(bits == 0)
1571 bits = 8 * size;
1572 fseek(fp, 4, SEEK_CUR);
1573 if(!ReadBin4(fp, src->mPath, order, 2, &format))
1574 return 0;
1575 fseek(fp, (long)(chunkSize - 26), SEEK_CUR);
1577 else
1579 bits = 8 * size;
1580 if(chunkSize > 14)
1581 fseek(fp, (long)(chunkSize - 16), SEEK_CUR);
1582 else
1583 fseek(fp, (long)(chunkSize - 14), SEEK_CUR);
1585 if(format != WAVE_FORMAT_PCM && format != WAVE_FORMAT_IEEE_FLOAT)
1587 fprintf(stderr, "Error: Unsupported WAVE format in file '%s'.\n", src->mPath);
1588 return 0;
1590 if(src->mChannel >= channels)
1592 fprintf(stderr, "Error: Missing source channel in WAVE file '%s'.\n", src->mPath);
1593 return 0;
1595 if(rate != hrirRate)
1597 fprintf(stderr, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src->mPath);
1598 return 0;
1600 if(format == WAVE_FORMAT_PCM)
1602 if(size < 2 || size > 4)
1604 fprintf(stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src->mPath);
1605 return 0;
1607 if(bits < 16 || bits > (8*size))
1609 fprintf (stderr, "Error: Bad significant bits in WAVE file '%s'.\n", src->mPath);
1610 return 0;
1612 src->mType = ET_INT;
1614 else
1616 if(size != 4 && size != 8)
1618 fprintf(stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src->mPath);
1619 return 0;
1621 src->mType = ET_FP;
1623 src->mSize = size;
1624 src->mBits = (int)bits;
1625 src->mSkip = channels;
1626 return 1;
1629 // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
1630 static int ReadWaveData(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
1632 int pre, post, skip;
1633 uint i;
1635 pre = (int)(src->mSize * src->mChannel);
1636 post = (int)(src->mSize * (src->mSkip - src->mChannel - 1));
1637 skip = 0;
1638 for(i = 0;i < n;i++)
1640 skip += pre;
1641 if(skip > 0)
1642 fseek(fp, skip, SEEK_CUR);
1643 if(!ReadBinAsDouble(fp, src->mPath, order, src->mType, src->mSize, src->mBits, &hrir[i]))
1644 return 0;
1645 skip = post;
1647 if(skip > 0)
1648 fseek(fp, skip, SEEK_CUR);
1649 return 1;
1652 // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
1653 // doubles.
1654 static int ReadWaveList(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
1656 uint32 fourCC, chunkSize, listSize, count;
1657 uint block, skip, offset, i;
1658 double lastSample;
1660 for (;;) {
1661 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, & fourCC) ||
1662 !ReadBin4(fp, src->mPath, order, 4, & chunkSize))
1663 return (0);
1665 if(fourCC == FOURCC_DATA)
1667 block = src->mSize * src->mSkip;
1668 count = chunkSize / block;
1669 if(count < (src->mOffset + n))
1671 fprintf(stderr, "Error: Bad read from file '%s'.\n", src->mPath);
1672 return 0;
1674 fseek(fp, (long)(src->mOffset * block), SEEK_CUR);
1675 if(!ReadWaveData(fp, src, order, n, &hrir[0]))
1676 return 0;
1677 return 1;
1679 else if(fourCC == FOURCC_LIST)
1681 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC))
1682 return 0;
1683 chunkSize -= 4;
1684 if(fourCC == FOURCC_WAVL)
1685 break;
1687 if(chunkSize > 0)
1688 fseek(fp, (long)chunkSize, SEEK_CUR);
1690 listSize = chunkSize;
1691 block = src->mSize * src->mSkip;
1692 skip = src->mOffset;
1693 offset = 0;
1694 lastSample = 0.0;
1695 while(offset < n && listSize > 8)
1697 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
1698 !ReadBin4(fp, src->mPath, order, 4, &chunkSize))
1699 return 0;
1700 listSize -= 8 + chunkSize;
1701 if(fourCC == FOURCC_DATA)
1703 count = chunkSize / block;
1704 if(count > skip)
1706 fseek(fp, (long)(skip * block), SEEK_CUR);
1707 chunkSize -= skip * block;
1708 count -= skip;
1709 skip = 0;
1710 if(count > (n - offset))
1711 count = n - offset;
1712 if(!ReadWaveData(fp, src, order, count, &hrir[offset]))
1713 return 0;
1714 chunkSize -= count * block;
1715 offset += count;
1716 lastSample = hrir [offset - 1];
1718 else
1720 skip -= count;
1721 count = 0;
1724 else if(fourCC == FOURCC_SLNT)
1726 if(!ReadBin4(fp, src->mPath, order, 4, &count))
1727 return 0;
1728 chunkSize -= 4;
1729 if(count > skip)
1731 count -= skip;
1732 skip = 0;
1733 if(count > (n - offset))
1734 count = n - offset;
1735 for(i = 0; i < count; i ++)
1736 hrir[offset + i] = lastSample;
1737 offset += count;
1739 else
1741 skip -= count;
1742 count = 0;
1745 if(chunkSize > 0)
1746 fseek(fp, (long)chunkSize, SEEK_CUR);
1748 if(offset < n)
1750 fprintf(stderr, "Error: Bad read from file '%s'.\n", src->mPath);
1751 return 0;
1753 return 1;
1756 // Load a source HRIR from a RIFF/RIFX WAVE file.
1757 static int LoadWaveSource(FILE *fp, SourceRefT *src, const uint hrirRate, const uint n, double *hrir)
1759 uint32 fourCC, dummy;
1760 ByteOrderT order;
1762 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
1763 !ReadBin4(fp, src->mPath, BO_LITTLE, 4, &dummy))
1764 return 0;
1765 if(fourCC == FOURCC_RIFF)
1766 order = BO_LITTLE;
1767 else if(fourCC == FOURCC_RIFX)
1768 order = BO_BIG;
1769 else
1771 fprintf(stderr, "Error: No RIFF/RIFX chunk in file '%s'.\n", src->mPath);
1772 return 0;
1775 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC))
1776 return 0;
1777 if(fourCC != FOURCC_WAVE)
1779 fprintf(stderr, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src->mPath);
1780 return 0;
1782 if(!ReadWaveFormat(fp, order, hrirRate, src))
1783 return 0;
1784 if(!ReadWaveList(fp, src, order, n, hrir))
1785 return 0;
1786 return 1;
1789 // Load a source HRIR from a binary file.
1790 static int LoadBinarySource(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
1792 uint i;
1794 fseek(fp, (long)src->mOffset, SEEK_SET);
1795 for(i = 0;i < n;i++)
1797 if(!ReadBinAsDouble(fp, src->mPath, order, src->mType, src->mSize, src->mBits, &hrir[i]))
1798 return 0;
1799 if(src->mSkip > 0)
1800 fseek(fp, (long)src->mSkip, SEEK_CUR);
1802 return 1;
1805 // Load a source HRIR from an ASCII text file containing a list of elements
1806 // separated by whitespace or common list operators (',', ';', ':', '|').
1807 static int LoadAsciiSource(FILE *fp, const SourceRefT *src, const uint n, double *hrir)
1809 TokenReaderT tr;
1810 uint i, j;
1811 double dummy;
1813 TrSetup(fp, NULL, &tr);
1814 for(i = 0;i < src->mOffset;i++)
1816 if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &dummy))
1817 return (0);
1819 for(i = 0;i < n;i++)
1821 if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &hrir[i]))
1822 return 0;
1823 for(j = 0;j < src->mSkip;j++)
1825 if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &dummy))
1826 return 0;
1829 return 1;
1832 // Load a source HRIR from a supported file type.
1833 static int LoadSource(SourceRefT *src, const uint hrirRate, const uint n, double *hrir)
1835 int result;
1836 FILE *fp;
1838 if (src->mFormat == SF_ASCII)
1839 fp = fopen(src->mPath, "r");
1840 else
1841 fp = fopen(src->mPath, "rb");
1842 if(fp == NULL)
1844 fprintf(stderr, "Error: Could not open source file '%s'.\n", src->mPath);
1845 return 0;
1847 if(src->mFormat == SF_WAVE)
1848 result = LoadWaveSource(fp, src, hrirRate, n, hrir);
1849 else if(src->mFormat == SF_BIN_LE)
1850 result = LoadBinarySource(fp, src, BO_LITTLE, n, hrir);
1851 else if(src->mFormat == SF_BIN_BE)
1852 result = LoadBinarySource(fp, src, BO_BIG, n, hrir);
1853 else
1854 result = LoadAsciiSource(fp, src, n, hrir);
1855 fclose(fp);
1856 return result;
1859 // Calculate the onset time of an HRIR and average it with any existing
1860 // timing for its elevation and azimuth.
1861 static void AverageHrirOnset(const double *hrir, const double f, const uint ei, const uint ai, const HrirDataT *hData)
1863 double mag;
1864 uint n, i, j;
1866 mag = 0.0;
1867 n = hData->mIrPoints;
1868 for(i = 0;i < n;i++)
1869 mag = fmax(fabs(hrir[i]), mag);
1870 mag *= 0.15;
1871 for(i = 0;i < n;i++)
1873 if(fabs(hrir[i]) >= mag)
1874 break;
1876 j = hData->mEvOffset[ei] + ai;
1877 hData->mHrtds[j] = Lerp(hData->mHrtds[j], ((double)i) / hData->mIrRate, f);
1880 // Calculate the magnitude response of an HRIR and average it with any
1881 // existing responses for its elevation and azimuth.
1882 static void AverageHrirMagnitude(const double *hrir, const double f, const uint ei, const uint ai, const HrirDataT *hData)
1884 double *re, *im;
1885 uint n, m, i, j;
1887 n = hData->mFftSize;
1888 re = CreateArray(n);
1889 im = CreateArray(n);
1890 for(i = 0;i < hData->mIrPoints;i++)
1892 re[i] = hrir[i];
1893 im[i] = 0.0;
1895 for(;i < n;i++)
1897 re[i] = 0.0;
1898 im[i] = 0.0;
1900 FftForward(n, re, im, re, im);
1901 MagnitudeResponse(n, re, im, re);
1902 m = 1 + (n / 2);
1903 j = (hData->mEvOffset[ei] + ai) * hData->mIrSize;
1904 for(i = 0;i < m;i++)
1905 hData->mHrirs[j+i] = Lerp(hData->mHrirs[j+i], re[i], f);
1906 DestroyArray(im);
1907 DestroyArray(re);
1910 /* Calculate the contribution of each HRIR to the diffuse-field average based
1911 * on the area of its surface patch. All patches are centered at the HRIR
1912 * coordinates on the unit sphere and are measured by solid angle.
1914 static void CalculateDfWeights(const HrirDataT *hData, double *weights)
1916 double evs, sum, ev, up_ev, down_ev, solidAngle;
1917 uint ei;
1919 evs = 90.0 / (hData->mEvCount - 1);
1920 sum = 0.0;
1921 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
1923 // For each elevation, calculate the upper and lower limits of the
1924 // patch band.
1925 ev = -90.0 + (ei * 2.0 * evs);
1926 if(ei < (hData->mEvCount - 1))
1927 up_ev = (ev + evs) * M_PI / 180.0;
1928 else
1929 up_ev = M_PI / 2.0;
1930 if(ei > 0)
1931 down_ev = (ev - evs) * M_PI / 180.0;
1932 else
1933 down_ev = -M_PI / 2.0;
1934 // Calculate the area of the patch band.
1935 solidAngle = 2.0 * M_PI * (sin(up_ev) - sin(down_ev));
1936 // Each weight is the area of one patch.
1937 weights[ei] = solidAngle / hData->mAzCount [ei];
1938 // Sum the total surface area covered by the HRIRs.
1939 sum += solidAngle;
1941 // Normalize the weights given the total surface coverage.
1942 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
1943 weights[ei] /= sum;
1946 /* Calculate the diffuse-field average from the given magnitude responses of
1947 * the HRIR set. Weighting can be applied to compensate for the varying
1948 * surface area covered by each HRIR. The final average can then be limited
1949 * by the specified magnitude range (in positive dB; 0.0 to skip).
1951 static void CalculateDiffuseFieldAverage(const HrirDataT *hData, const int weighted, const double limit, double *dfa)
1953 uint ei, ai, count, step, start, end, m, j, i;
1954 double *weights;
1956 weights = CreateArray(hData->mEvCount);
1957 if(weighted)
1959 // Use coverage weighting to calculate the average.
1960 CalculateDfWeights(hData, weights);
1962 else
1964 // If coverage weighting is not used, the weights still need to be
1965 // averaged by the number of HRIRs.
1966 count = 0;
1967 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
1968 count += hData->mAzCount [ei];
1969 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
1970 weights[ei] = 1.0 / count;
1972 ei = hData->mEvStart;
1973 ai = 0;
1974 step = hData->mIrSize;
1975 start = hData->mEvOffset[ei] * step;
1976 end = hData->mIrCount * step;
1977 m = 1 + (hData->mFftSize / 2);
1978 for(i = 0;i < m;i++)
1979 dfa[i] = 0.0;
1980 for(j = start;j < end;j += step)
1982 // Get the weight for this HRIR's contribution.
1983 double weight = weights[ei];
1984 // Add this HRIR's weighted power average to the total.
1985 for(i = 0;i < m;i++)
1986 dfa[i] += weight * hData->mHrirs[j+i] * hData->mHrirs[j+i];
1987 // Determine the next weight to use.
1988 ai++;
1989 if(ai >= hData->mAzCount[ei])
1991 ei++;
1992 ai = 0;
1995 // Finish the average calculation and keep it from being too small.
1996 for(i = 0;i < m;i++)
1997 dfa[i] = fmax(sqrt(dfa[i]), EPSILON);
1998 // Apply a limit to the magnitude range of the diffuse-field average if
1999 // desired.
2000 if(limit > 0.0)
2001 LimitMagnitudeResponse(hData->mFftSize, limit, dfa, dfa);
2002 DestroyArray(weights);
2005 // Perform diffuse-field equalization on the magnitude responses of the HRIR
2006 // set using the given average response.
2007 static void DiffuseFieldEqualize(const double *dfa, const HrirDataT *hData)
2009 uint step, start, end, m, j, i;
2011 step = hData->mIrSize;
2012 start = hData->mEvOffset[hData->mEvStart] * step;
2013 end = hData->mIrCount * step;
2014 m = 1 + (hData->mFftSize / 2);
2015 for(j = start;j < end;j += step)
2017 for(i = 0;i < m;i++)
2018 hData->mHrirs[j+i] /= dfa[i];
2022 // Perform minimum-phase reconstruction using the magnitude responses of the
2023 // HRIR set.
2024 static void ReconstructHrirs(const HrirDataT *hData)
2026 uint step, start, end, n, j, i;
2027 double *re, *im;
2029 step = hData->mIrSize;
2030 start = hData->mEvOffset[hData->mEvStart] * step;
2031 end = hData->mIrCount * step;
2032 n = hData->mFftSize;
2033 re = CreateArray(n);
2034 im = CreateArray(n);
2035 for(j = start;j < end;j += step)
2037 MinimumPhase(n, &hData->mHrirs[j], re, im);
2038 FftInverse(n, re, im, re, im);
2039 for(i = 0;i < hData->mIrPoints;i++)
2040 hData->mHrirs[j+i] = re[i];
2042 DestroyArray (im);
2043 DestroyArray (re);
2046 // Resamples the HRIRs for use at the given sampling rate.
2047 static void ResampleHrirs(const uint rate, HrirDataT *hData)
2049 uint n, step, start, end, j;
2050 ResamplerT rs;
2052 ResamplerSetup(&rs, hData->mIrRate, rate);
2053 n = hData->mIrPoints;
2054 step = hData->mIrSize;
2055 start = hData->mEvOffset[hData->mEvStart] * step;
2056 end = hData->mIrCount * step;
2057 for(j = start;j < end;j += step)
2058 ResamplerRun(&rs, n, &hData->mHrirs[j], n, &hData->mHrirs[j]);
2059 ResamplerClear(&rs);
2060 hData->mIrRate = rate;
2063 /* Given an elevation index and an azimuth, calculate the indices of the two
2064 * HRIRs that bound the coordinate along with a factor for calculating the
2065 * continous HRIR using interpolation.
2067 static void CalcAzIndices(const HrirDataT *hData, const uint ei, const double az, uint *j0, uint *j1, double *jf)
2069 double af;
2070 uint ai;
2072 af = ((2.0*M_PI) + az) * hData->mAzCount[ei] / (2.0*M_PI);
2073 ai = ((uint)af) % hData->mAzCount[ei];
2074 af -= floor(af);
2076 *j0 = hData->mEvOffset[ei] + ai;
2077 *j1 = hData->mEvOffset[ei] + ((ai+1) % hData->mAzCount [ei]);
2078 *jf = af;
2081 // Synthesize any missing onset timings at the bottom elevations. This just
2082 // blends between slightly exaggerated known onsets. Not an accurate model.
2083 static void SynthesizeOnsets(HrirDataT *hData)
2085 uint oi, e, a, j0, j1;
2086 double t, of, jf;
2088 oi = hData->mEvStart;
2089 t = 0.0;
2090 for(a = 0;a < hData->mAzCount[oi];a++)
2091 t += hData->mHrtds[hData->mEvOffset[oi] + a];
2092 hData->mHrtds[0] = 1.32e-4 + (t / hData->mAzCount[oi]);
2093 for(e = 1;e < hData->mEvStart;e++)
2095 of = ((double)e) / hData->mEvStart;
2096 for(a = 0;a < hData->mAzCount[e];a++)
2098 CalcAzIndices(hData, oi, a * 2.0 * M_PI / hData->mAzCount[e], &j0, &j1, &jf);
2099 hData->mHrtds[hData->mEvOffset[e] + a] = Lerp(hData->mHrtds[0], Lerp(hData->mHrtds[j0], hData->mHrtds[j1], jf), of);
2104 /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
2105 * now this just blends the lowest elevation HRIRs together and applies some
2106 * attenuation and high frequency damping. It is a simple, if inaccurate
2107 * model.
2109 static void SynthesizeHrirs (HrirDataT *hData)
2111 uint oi, a, e, step, n, i, j;
2112 double lp[4], s0, s1;
2113 double of, b;
2114 uint j0, j1;
2115 double jf;
2117 if(hData->mEvStart <= 0)
2118 return;
2119 step = hData->mIrSize;
2120 oi = hData->mEvStart;
2121 n = hData->mIrPoints;
2122 for(i = 0;i < n;i++)
2123 hData->mHrirs[i] = 0.0;
2124 for(a = 0;a < hData->mAzCount[oi];a++)
2126 j = (hData->mEvOffset[oi] + a) * step;
2127 for(i = 0;i < n;i++)
2128 hData->mHrirs[i] += hData->mHrirs[j+i] / hData->mAzCount[oi];
2130 for(e = 1;e < hData->mEvStart;e++)
2132 of = ((double)e) / hData->mEvStart;
2133 b = (1.0 - of) * (3.5e-6 * hData->mIrRate);
2134 for(a = 0;a < hData->mAzCount[e];a++)
2136 j = (hData->mEvOffset[e] + a) * step;
2137 CalcAzIndices(hData, oi, a * 2.0 * M_PI / hData->mAzCount[e], &j0, &j1, &jf);
2138 j0 *= step;
2139 j1 *= step;
2140 lp[0] = 0.0;
2141 lp[1] = 0.0;
2142 lp[2] = 0.0;
2143 lp[3] = 0.0;
2144 for(i = 0;i < n;i++)
2146 s0 = hData->mHrirs[i];
2147 s1 = Lerp(hData->mHrirs[j0+i], hData->mHrirs[j1+i], jf);
2148 s0 = Lerp(s0, s1, of);
2149 lp[0] = Lerp(s0, lp[0], b);
2150 lp[1] = Lerp(lp[0], lp[1], b);
2151 lp[2] = Lerp(lp[1], lp[2], b);
2152 lp[3] = Lerp(lp[2], lp[3], b);
2153 hData->mHrirs[j+i] = lp[3];
2157 b = 3.5e-6 * hData->mIrRate;
2158 lp[0] = 0.0;
2159 lp[1] = 0.0;
2160 lp[2] = 0.0;
2161 lp[3] = 0.0;
2162 for(i = 0;i < n;i++)
2164 s0 = hData->mHrirs[i];
2165 lp[0] = Lerp(s0, lp[0], b);
2166 lp[1] = Lerp(lp[0], lp[1], b);
2167 lp[2] = Lerp(lp[1], lp[2], b);
2168 lp[3] = Lerp(lp[2], lp[3], b);
2169 hData->mHrirs[i] = lp[3];
2171 hData->mEvStart = 0;
2174 // The following routines assume a full set of HRIRs for all elevations.
2176 // Normalize the HRIR set and slightly attenuate the result.
2177 static void NormalizeHrirs (const HrirDataT *hData)
2179 uint step, end, n, j, i;
2180 double maxLevel;
2182 step = hData->mIrSize;
2183 end = hData->mIrCount * step;
2184 n = hData->mIrPoints;
2185 maxLevel = 0.0;
2186 for(j = 0;j < end;j += step)
2188 for(i = 0;i < n;i++)
2189 maxLevel = fmax(fabs(hData->mHrirs[j+i]), maxLevel);
2191 maxLevel = 1.01 * maxLevel;
2192 for(j = 0;j < end;j += step)
2194 for(i = 0;i < n;i++)
2195 hData->mHrirs[j+i] /= maxLevel;
2199 // Calculate the left-ear time delay using a spherical head model.
2200 static double CalcLTD(const double ev, const double az, const double rad, const double dist)
2202 double azp, dlp, l, al;
2204 azp = asin(cos(ev) * sin(az));
2205 dlp = sqrt((dist*dist) + (rad*rad) + (2.0*dist*rad*sin(azp)));
2206 l = sqrt((dist*dist) - (rad*rad));
2207 al = (0.5 * M_PI) + azp;
2208 if(dlp > l)
2209 dlp = l + (rad * (al - acos(rad / dist)));
2210 return (dlp / 343.3);
2213 // Calculate the effective head-related time delays for each minimum-phase
2214 // HRIR.
2215 static void CalculateHrtds (const HeadModelT model, const double radius, HrirDataT *hData)
2217 double minHrtd, maxHrtd;
2218 uint e, a, j;
2219 double t;
2221 minHrtd = 1000.0;
2222 maxHrtd = -1000.0;
2223 for(e = 0;e < hData->mEvCount;e++)
2225 for(a = 0;a < hData->mAzCount[e];a++)
2227 j = hData->mEvOffset[e] + a;
2228 if(model == HM_DATASET)
2229 t = hData->mHrtds[j] * radius / hData->mRadius;
2230 else
2231 t = CalcLTD((-90.0 + (e * 180.0 / (hData->mEvCount - 1))) * M_PI / 180.0,
2232 (a * 360.0 / hData->mAzCount [e]) * M_PI / 180.0,
2233 radius, hData->mDistance);
2234 hData->mHrtds[j] = t;
2235 maxHrtd = fmax(t, maxHrtd);
2236 minHrtd = fmin(t, minHrtd);
2239 maxHrtd -= minHrtd;
2240 for(j = 0;j < hData->mIrCount;j++)
2241 hData->mHrtds[j] -= minHrtd;
2242 hData->mMaxHrtd = maxHrtd;
2245 // Store the OpenAL Soft HRTF data set.
2246 static int StoreMhr(const HrirDataT *hData, const char *filename)
2248 uint e, step, end, n, j, i;
2249 int hpHist, v;
2250 FILE *fp;
2252 if((fp=fopen(filename, "wb")) == NULL)
2254 fprintf(stderr, "Error: Could not open MHR file '%s'.\n", filename);
2255 return 0;
2257 if(!WriteAscii(MHR_FORMAT, fp, filename))
2258 return 0;
2259 if(!WriteBin4(BO_LITTLE, 4, (uint32)hData->mIrRate, fp, filename))
2260 return 0;
2261 if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mIrPoints, fp, filename))
2262 return 0;
2263 if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mEvCount, fp, filename))
2264 return 0;
2265 for(e = 0;e < hData->mEvCount;e++)
2267 if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mAzCount[e], fp, filename))
2268 return 0;
2270 step = hData->mIrSize;
2271 end = hData->mIrCount * step;
2272 n = hData->mIrPoints;
2273 srand(0x31DF840C);
2274 for(j = 0;j < end;j += step)
2276 hpHist = 0;
2277 for(i = 0;i < n;i++)
2279 v = HpTpdfDither(32767.0 * hData->mHrirs[j+i], &hpHist);
2280 if(!WriteBin4(BO_LITTLE, 2, (uint32)v, fp, filename))
2281 return 0;
2284 for(j = 0;j < hData->mIrCount;j++)
2286 v = (int)fmin(round(hData->mIrRate * hData->mHrtds[j]), MAX_HRTD);
2287 if(!WriteBin4(BO_LITTLE, 1, (uint32)v, fp, filename))
2288 return 0;
2290 fclose(fp);
2291 return 1;
2294 // Process the data set definition to read and validate the data set metrics.
2295 static int ProcessMetrics(TokenReaderT *tr, const uint fftSize, const uint truncSize, HrirDataT *hData)
2297 int hasRate = 0, hasPoints = 0, hasAzimuths = 0;
2298 int hasRadius = 0, hasDistance = 0;
2299 char ident[MAX_IDENT_LEN+1];
2300 uint line, col;
2301 double fpVal;
2302 uint points;
2303 int intVal;
2305 while(!(hasRate && hasPoints && hasAzimuths && hasRadius && hasDistance))
2307 TrIndication(tr, & line, & col);
2308 if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
2309 return 0;
2310 if(strcasecmp(ident, "rate") == 0)
2312 if(hasRate)
2314 TrErrorAt(tr, line, col, "Redefinition of 'rate'.\n");
2315 return 0;
2317 if(!TrReadOperator(tr, "="))
2318 return 0;
2319 if(!TrReadInt(tr, MIN_RATE, MAX_RATE, &intVal))
2320 return 0;
2321 hData->mIrRate = (uint)intVal;
2322 hasRate = 1;
2324 else if(strcasecmp(ident, "points") == 0)
2326 if (hasPoints) {
2327 TrErrorAt(tr, line, col, "Redefinition of 'points'.\n");
2328 return 0;
2330 if(!TrReadOperator(tr, "="))
2331 return 0;
2332 TrIndication(tr, &line, &col);
2333 if(!TrReadInt(tr, MIN_POINTS, MAX_POINTS, &intVal))
2334 return 0;
2335 points = (uint)intVal;
2336 if(fftSize > 0 && points > fftSize)
2338 TrErrorAt(tr, line, col, "Value exceeds the overridden FFT size.\n");
2339 return 0;
2341 if(points < truncSize)
2343 TrErrorAt(tr, line, col, "Value is below the truncation size.\n");
2344 return 0;
2346 hData->mIrPoints = points;
2347 hData->mFftSize = fftSize;
2348 if(fftSize <= 0)
2350 points = 1;
2351 while(points < (4 * hData->mIrPoints))
2352 points <<= 1;
2353 hData->mFftSize = points;
2354 hData->mIrSize = 1 + (points / 2);
2356 else
2358 hData->mFftSize = fftSize;
2359 hData->mIrSize = 1 + (fftSize / 2);
2360 if(points > hData->mIrSize)
2361 hData->mIrSize = points;
2363 hasPoints = 1;
2365 else if(strcasecmp(ident, "azimuths") == 0)
2367 if(hasAzimuths)
2369 TrErrorAt(tr, line, col, "Redefinition of 'azimuths'.\n");
2370 return 0;
2372 if(!TrReadOperator(tr, "="))
2373 return 0;
2374 hData->mIrCount = 0;
2375 hData->mEvCount = 0;
2376 hData->mEvOffset[0] = 0;
2377 for(;;)
2379 if(!TrReadInt(tr, MIN_AZ_COUNT, MAX_AZ_COUNT, &intVal))
2380 return 0;
2381 hData->mAzCount[hData->mEvCount] = (uint)intVal;
2382 hData->mIrCount += (uint)intVal;
2383 hData->mEvCount ++;
2384 if(!TrIsOperator(tr, ","))
2385 break;
2386 if(hData->mEvCount >= MAX_EV_COUNT)
2388 TrError(tr, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT);
2389 return 0;
2391 hData->mEvOffset[hData->mEvCount] = hData->mEvOffset[hData->mEvCount - 1] + ((uint)intVal);
2392 TrReadOperator(tr, ",");
2394 if(hData->mEvCount < MIN_EV_COUNT)
2396 TrErrorAt(tr, line, col, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT);
2397 return 0;
2399 hasAzimuths = 1;
2401 else if(strcasecmp(ident, "radius") == 0)
2403 if(hasRadius)
2405 TrErrorAt(tr, line, col, "Redefinition of 'radius'.\n");
2406 return 0;
2408 if(!TrReadOperator(tr, "="))
2409 return 0;
2410 if(!TrReadFloat(tr, MIN_RADIUS, MAX_RADIUS, &fpVal))
2411 return 0;
2412 hData->mRadius = fpVal;
2413 hasRadius = 1;
2415 else if(strcasecmp(ident, "distance") == 0)
2417 if(hasDistance)
2419 TrErrorAt(tr, line, col, "Redefinition of 'distance'.\n");
2420 return 0;
2422 if(!TrReadOperator(tr, "="))
2423 return 0;
2424 if(!TrReadFloat(tr, MIN_DISTANCE, MAX_DISTANCE, & fpVal))
2425 return 0;
2426 hData->mDistance = fpVal;
2427 hasDistance = 1;
2429 else
2431 TrErrorAt(tr, line, col, "Expected a metric name.\n");
2432 return 0;
2434 TrSkipWhitespace (tr);
2436 return 1;
2439 // Parse an index pair from the data set definition.
2440 static int ReadIndexPair(TokenReaderT *tr, const HrirDataT *hData, uint *ei, uint *ai)
2442 int intVal;
2443 if(!TrReadInt(tr, 0, (int)hData->mEvCount, &intVal))
2444 return 0;
2445 *ei = (uint)intVal;
2446 if(!TrReadOperator(tr, ","))
2447 return 0;
2448 if(!TrReadInt(tr, 0, (int)hData->mAzCount[*ei], &intVal))
2449 return 0;
2450 *ai = (uint)intVal;
2451 return 1;
2454 // Match the source format from a given identifier.
2455 static SourceFormatT MatchSourceFormat(const char *ident)
2457 if(strcasecmp(ident, "wave") == 0)
2458 return SF_WAVE;
2459 if(strcasecmp(ident, "bin_le") == 0)
2460 return SF_BIN_LE;
2461 if(strcasecmp(ident, "bin_be") == 0)
2462 return SF_BIN_BE;
2463 if(strcasecmp(ident, "ascii") == 0)
2464 return SF_ASCII;
2465 return SF_NONE;
2468 // Match the source element type from a given identifier.
2469 static ElementTypeT MatchElementType(const char *ident)
2471 if(strcasecmp(ident, "int") == 0)
2472 return ET_INT;
2473 if(strcasecmp(ident, "fp") == 0)
2474 return ET_FP;
2475 return ET_NONE;
2478 // Parse and validate a source reference from the data set definition.
2479 static int ReadSourceRef(TokenReaderT *tr, SourceRefT *src)
2481 char ident[MAX_IDENT_LEN+1];
2482 uint line, col;
2483 int intVal;
2485 TrIndication(tr, &line, &col);
2486 if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
2487 return 0;
2488 src->mFormat = MatchSourceFormat(ident);
2489 if(src->mFormat == SF_NONE)
2491 TrErrorAt(tr, line, col, "Expected a source format.\n");
2492 return 0;
2494 if(!TrReadOperator(tr, "("))
2495 return 0;
2496 if(src->mFormat == SF_WAVE)
2498 if(!TrReadInt(tr, 0, MAX_WAVE_CHANNELS, &intVal))
2499 return 0;
2500 src->mType = ET_NONE;
2501 src->mSize = 0;
2502 src->mBits = 0;
2503 src->mChannel = (uint)intVal;
2504 src->mSkip = 0;
2506 else
2508 TrIndication(tr, &line, &col);
2509 if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
2510 return 0;
2511 src->mType = MatchElementType(ident);
2512 if(src->mType == ET_NONE)
2514 TrErrorAt(tr, line, col, "Expected a source element type.\n");
2515 return 0;
2517 if(src->mFormat == SF_BIN_LE || src->mFormat == SF_BIN_BE)
2519 if(!TrReadOperator(tr, ","))
2520 return 0;
2521 if(src->mType == ET_INT)
2523 if(!TrReadInt(tr, MIN_BIN_SIZE, MAX_BIN_SIZE, &intVal))
2524 return 0;
2525 src->mSize = (uint)intVal;
2526 if(!TrIsOperator(tr, ","))
2527 src->mBits = (int)(8*src->mSize);
2528 else
2530 TrReadOperator(tr, ",");
2531 TrIndication(tr, &line, &col);
2532 if(!TrReadInt(tr, -2147483647-1, 2147483647, &intVal))
2533 return 0;
2534 if(abs(intVal) < MIN_BIN_BITS || ((uint)abs(intVal)) > (8*src->mSize))
2536 TrErrorAt(tr, line, col, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS, 8*src->mSize);
2537 return 0;
2539 src->mBits = intVal;
2542 else
2544 TrIndication(tr, &line, &col);
2545 if(!TrReadInt(tr, -2147483647-1, 2147483647, &intVal))
2546 return 0;
2547 if(intVal != 4 && intVal != 8)
2549 TrErrorAt(tr, line, col, "Expected a value of 4 or 8.\n");
2550 return 0;
2552 src->mSize = (uint)intVal;
2553 src->mBits = 0;
2556 else if(src->mFormat == SF_ASCII && src->mType == ET_INT)
2558 if(!TrReadOperator(tr, ","))
2559 return 0;
2560 if(!TrReadInt(tr, MIN_ASCII_BITS, MAX_ASCII_BITS, &intVal))
2561 return 0;
2562 src->mSize = 0;
2563 src->mBits = intVal;
2565 else
2567 src->mSize = 0;
2568 src->mBits = 0;
2571 if(!TrIsOperator(tr, ";"))
2572 src->mSkip = 0;
2573 else
2575 TrReadOperator(tr, ";");
2576 if(!TrReadInt (tr, 0, 0x7FFFFFFF, &intVal))
2577 return 0;
2578 src->mSkip = (uint)intVal;
2581 if(!TrReadOperator(tr, ")"))
2582 return 0;
2583 if(TrIsOperator(tr, "@"))
2585 TrReadOperator(tr, "@");
2586 if(!TrReadInt(tr, 0, 0x7FFFFFFF, &intVal))
2587 return 0;
2588 src->mOffset = (uint)intVal;
2590 else
2591 src->mOffset = 0;
2592 if(!TrReadOperator(tr, ":"))
2593 return 0;
2594 if(!TrReadString(tr, MAX_PATH_LEN, src->mPath))
2595 return 0;
2596 return 1;
2599 // Process the list of sources in the data set definition.
2600 static int ProcessSources(const HeadModelT model, TokenReaderT *tr, HrirDataT *hData)
2602 uint *setCount, *setFlag;
2603 uint line, col, ei, ai;
2604 SourceRefT src;
2605 double factor;
2606 double *hrir;
2608 setCount = (uint*)calloc(hData->mEvCount, sizeof(uint));
2609 setFlag = (uint*)calloc(hData->mIrCount, sizeof(uint));
2610 hrir = CreateArray(hData->mIrPoints);
2611 while(TrIsOperator(tr, "["))
2613 TrIndication(tr, & line, & col);
2614 TrReadOperator(tr, "[");
2615 if(!ReadIndexPair(tr, hData, &ei, &ai))
2616 goto error;
2617 if(!TrReadOperator(tr, "]"))
2618 goto error;
2619 if(setFlag[hData->mEvOffset[ei] + ai])
2621 TrErrorAt(tr, line, col, "Redefinition of source.\n");
2622 goto error;
2624 if(!TrReadOperator(tr, "="))
2625 goto error;
2627 factor = 1.0;
2628 for(;;)
2630 if(!ReadSourceRef(tr, &src))
2631 goto error;
2632 if(!LoadSource(&src, hData->mIrRate, hData->mIrPoints, hrir))
2633 goto error;
2635 if(model == HM_DATASET)
2636 AverageHrirOnset(hrir, 1.0 / factor, ei, ai, hData);
2637 AverageHrirMagnitude(hrir, 1.0 / factor, ei, ai, hData);
2638 factor += 1.0;
2639 if(!TrIsOperator(tr, "+"))
2640 break;
2641 TrReadOperator(tr, "+");
2643 setFlag[hData->mEvOffset[ei] + ai] = 1;
2644 setCount[ei]++;
2647 ei = 0;
2648 while(ei < hData->mEvCount && setCount[ei] < 1)
2649 ei++;
2650 if(ei < hData->mEvCount)
2652 hData->mEvStart = ei;
2653 while(ei < hData->mEvCount && setCount[ei] == hData->mAzCount[ei])
2654 ei++;
2655 if(ei >= hData->mEvCount)
2657 if(!TrLoad(tr))
2659 DestroyArray(hrir);
2660 free(setFlag);
2661 free(setCount);
2662 return 1;
2664 TrError(tr, "Errant data at end of source list.\n");
2666 else
2667 TrError(tr, "Missing sources for elevation index %d.\n", ei);
2669 else
2670 TrError(tr, "Missing source references.\n");
2672 error:
2673 DestroyArray(hrir);
2674 free(setFlag);
2675 free(setCount);
2676 return 0;
2679 /* Parse the data set definition and process the source data, storing the
2680 * resulting data set as desired. If the input name is NULL it will read
2681 * from standard input.
2683 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)
2685 char rateStr[8+1], expName[MAX_PATH_LEN];
2686 TokenReaderT tr;
2687 HrirDataT hData;
2688 double *dfa;
2689 FILE *fp;
2691 hData.mIrRate = 0;
2692 hData.mIrPoints = 0;
2693 hData.mFftSize = 0;
2694 hData.mIrSize = 0;
2695 hData.mIrCount = 0;
2696 hData.mEvCount = 0;
2697 hData.mRadius = 0;
2698 hData.mDistance = 0;
2699 fprintf(stdout, "Reading HRIR definition...\n");
2700 if(inName != NULL)
2702 fp = fopen(inName, "r");
2703 if(fp == NULL)
2705 fprintf(stderr, "Error: Could not open definition file '%s'\n", inName);
2706 return 0;
2708 TrSetup(fp, inName, &tr);
2710 else
2712 fp = stdin;
2713 TrSetup(fp, "<stdin>", &tr);
2715 if(!ProcessMetrics(&tr, fftSize, truncSize, &hData))
2717 if(inName != NULL)
2718 fclose(fp);
2719 return 0;
2721 hData.mHrirs = CreateArray(hData.mIrCount * hData . mIrSize);
2722 hData.mHrtds = CreateArray(hData.mIrCount);
2723 if(!ProcessSources(model, &tr, &hData))
2725 DestroyArray(hData.mHrtds);
2726 DestroyArray(hData.mHrirs);
2727 if(inName != NULL)
2728 fclose(fp);
2729 return 0;
2731 if(inName != NULL)
2732 fclose(fp);
2733 if(equalize)
2735 dfa = CreateArray(1 + (hData.mFftSize/2));
2736 fprintf(stdout, "Calculating diffuse-field average...\n");
2737 CalculateDiffuseFieldAverage(&hData, surface, limit, dfa);
2738 fprintf(stdout, "Performing diffuse-field equalization...\n");
2739 DiffuseFieldEqualize(dfa, &hData);
2740 DestroyArray(dfa);
2742 fprintf(stdout, "Performing minimum phase reconstruction...\n");
2743 ReconstructHrirs(&hData);
2744 if(outRate != 0 && outRate != hData.mIrRate)
2746 fprintf(stdout, "Resampling HRIRs...\n");
2747 ResampleHrirs(outRate, &hData);
2749 fprintf(stdout, "Truncating minimum-phase HRIRs...\n");
2750 hData.mIrPoints = truncSize;
2751 fprintf(stdout, "Synthesizing missing elevations...\n");
2752 if(model == HM_DATASET)
2753 SynthesizeOnsets(&hData);
2754 SynthesizeHrirs(&hData);
2755 fprintf(stdout, "Normalizing final HRIRs...\n");
2756 NormalizeHrirs(&hData);
2757 fprintf(stdout, "Calculating impulse delays...\n");
2758 CalculateHrtds(model, (radius > DEFAULT_CUSTOM_RADIUS) ? radius : hData.mRadius, &hData);
2759 snprintf(rateStr, 8, "%u", hData.mIrRate);
2760 StrSubst(outName, "%r", rateStr, MAX_PATH_LEN, expName);
2761 switch(outFormat)
2763 case OF_MHR:
2764 fprintf(stdout, "Creating MHR data set file...\n");
2765 if(!StoreMhr(&hData, expName))
2767 DestroyArray(hData.mHrtds);
2768 DestroyArray(hData.mHrirs);
2769 return 0;
2771 break;
2772 default:
2773 break;
2775 DestroyArray(hData.mHrtds);
2776 DestroyArray(hData.mHrirs);
2777 return 1;
2780 static void PrintHelp(const char *argv0, FILE *ofile)
2782 fprintf(ofile, "Usage: %s <command> [<option>...]\n\n", argv0);
2783 fprintf(ofile, "Commands:\n");
2784 fprintf(ofile, " -m, --make-mhr Makes an OpenAL Soft compatible HRTF data set.\n");
2785 fprintf(ofile, " Defaults output to: ./oalsoft_hrtf_%%r.mhr\n");
2786 fprintf(ofile, " -h, --help Displays this help information.\n\n");
2787 fprintf(ofile, "Options:\n");
2788 fprintf(ofile, " -r=<rate> Change the data set sample rate to the specified value and\n");
2789 fprintf(ofile, " resample the HRIRs accordingly.\n");
2790 fprintf(ofile, " -f=<points> Override the FFT window size (defaults to the first power-\n");
2791 fprintf(ofile, " of-two that fits four times the number of HRIR points).\n");
2792 fprintf(ofile, " -e={on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE ? "on" : "off"));
2793 fprintf(ofile, " -s={on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE ? "on" : "off"));
2794 fprintf(ofile, " -l={<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
2795 fprintf(ofile, " average (default: %.2f).\n", DEFAULT_LIMIT);
2796 fprintf(ofile, " -w=<points> Specify the size of the truncation window that's applied\n");
2797 fprintf(ofile, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE);
2798 fprintf(ofile, " -d={dataset| Specify the model used for calculating the head-delay timing\n");
2799 fprintf(ofile, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL == HM_DATASET) ? "dataset" : "sphere"));
2800 fprintf(ofile, " -c=<size> Use a customized head radius measured ear-to-ear in meters.\n");
2801 fprintf(ofile, " -i=<filename> Specify an HRIR definition file to use (defaults to stdin).\n");
2802 fprintf(ofile, " -o=<filename> Specify an output file. Overrides command-selected default.\n");
2803 fprintf(ofile, " Use of '%%r' will be substituted with the data set sample rate.\n");
2806 // Standard command line dispatch.
2807 int main(const int argc, const char *argv[])
2809 const char *inName = NULL, *outName = NULL;
2810 OutputFormatT outFormat;
2811 uint outRate, fftSize;
2812 int equalize, surface;
2813 char *end = NULL;
2814 HeadModelT model;
2815 uint truncSize;
2816 double radius;
2817 double limit;
2818 int argi;
2820 if(argc < 2 || strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0)
2822 fprintf(stdout, "HRTF Processing and Composition Utility\n\n");
2823 PrintHelp(argv[0], stdout);
2824 return 0;
2827 if(strcmp(argv[1], "--make-mhr") == 0 || strcmp(argv[1], "-m") == 0)
2829 outName = "./oalsoft_hrtf_%r.mhr";
2830 outFormat = OF_MHR;
2832 else
2834 fprintf(stderr, "Error: Invalid command '%s'.\n\n", argv[1]);
2835 PrintHelp(argv[0], stderr);
2836 return -1;
2839 outRate = 0;
2840 fftSize = 0;
2841 equalize = DEFAULT_EQUALIZE;
2842 surface = DEFAULT_SURFACE;
2843 limit = DEFAULT_LIMIT;
2844 truncSize = DEFAULT_TRUNCSIZE;
2845 model = DEFAULT_HEAD_MODEL;
2846 radius = DEFAULT_CUSTOM_RADIUS;
2848 argi = 2;
2849 while(argi < argc)
2851 if(strncmp(argv[argi], "-r=", 3) == 0)
2853 outRate = strtoul(&argv[argi][3], &end, 10);
2854 if(end[0] != '\0' || outRate < MIN_RATE || outRate > MAX_RATE)
2856 fprintf(stderr, "Error: Expected a value from %u to %u for '-r'.\n", MIN_RATE, MAX_RATE);
2857 return -1;
2860 else if(strncmp(argv[argi], "-f=", 3) == 0)
2862 fftSize = strtoul(&argv[argi][3], &end, 10);
2863 if(end[0] != '\0' || (fftSize&(fftSize-1)) || fftSize < MIN_FFTSIZE || fftSize > MAX_FFTSIZE)
2865 fprintf(stderr, "Error: Expected a power-of-two value from %u to %u for '-f'.\n", MIN_FFTSIZE, MAX_FFTSIZE);
2866 return -1;
2869 else if(strncmp(argv[argi], "-e=", 3) == 0)
2871 if(strcmp(&argv[argi][3], "on") == 0)
2872 equalize = 1;
2873 else if(strcmp(&argv[argi][3], "off") == 0)
2874 equalize = 0;
2875 else
2877 fprintf(stderr, "Error: Expected 'on' or 'off' for '-e'.\n");
2878 return -1;
2881 else if(strncmp(argv[argi], "-s=", 3) == 0)
2883 if(strcmp(&argv[argi][3], "on") == 0)
2884 surface = 1;
2885 else if(strcmp(&argv[argi][3], "off") == 0)
2886 surface = 0;
2887 else
2889 fprintf(stderr, "Error: Expected 'on' or 'off' for '-s'.\n");
2890 return -1;
2893 else if(strncmp(argv[argi], "-l=", 3) == 0)
2895 if(strcmp(&argv[argi][3], "none") == 0)
2896 limit = 0.0;
2897 else
2899 limit = strtod(&argv[argi] [3], &end);
2900 if(end[0] != '\0' || limit < MIN_LIMIT || limit > MAX_LIMIT)
2902 fprintf(stderr, "Error: Expected 'none' or a value from %.2f to %.2f for '-l'.\n", MIN_LIMIT, MAX_LIMIT);
2903 return -1;
2907 else if(strncmp(argv[argi], "-w=", 3) == 0)
2909 truncSize = strtoul(&argv[argi][3], &end, 10);
2910 if(end[0] != '\0' || truncSize < MIN_TRUNCSIZE || truncSize > MAX_TRUNCSIZE || (truncSize%MOD_TRUNCSIZE))
2912 fprintf(stderr, "Error: Expected a value from %u to %u in multiples of %u for '-w'.\n", MIN_TRUNCSIZE, MAX_TRUNCSIZE, MOD_TRUNCSIZE);
2913 return -1;
2916 else if(strncmp(argv[argi], "-d=", 3) == 0)
2918 if(strcmp(&argv[argi][3], "dataset") == 0)
2919 model = HM_DATASET;
2920 else if(strcmp(&argv[argi][3], "sphere") == 0)
2921 model = HM_SPHERE;
2922 else
2924 fprintf(stderr, "Error: Expected 'dataset' or 'sphere' for '-d'.\n");
2925 return -1;
2928 else if(strncmp(argv[argi], "-c=", 3) == 0)
2930 radius = strtod(&argv[argi][3], &end);
2931 if(end[0] != '\0' || radius < MIN_CUSTOM_RADIUS || radius > MAX_CUSTOM_RADIUS)
2933 fprintf(stderr, "Error: Expected a value from %.2f to %.2f for '-c'.\n", MIN_CUSTOM_RADIUS, MAX_CUSTOM_RADIUS);
2934 return -1;
2937 else if(strncmp(argv[argi], "-i=", 3) == 0)
2938 inName = &argv[argi][3];
2939 else if(strncmp(argv[argi], "-o=", 3) == 0)
2940 outName = &argv[argi][3];
2941 else
2943 fprintf(stderr, "Error: Invalid option '%s'.\n", argv[argi]);
2944 return -1;
2946 argi++;
2948 if(!ProcessDefinition(inName, outRate, fftSize, equalize, surface, limit, truncSize, model, radius, outFormat, outName))
2949 return -1;
2950 fprintf(stdout, "Operation completed.\n");
2951 return 0;