Add 'restrict' to another parameter
[openal-soft.git] / utils / makehrtf.c
blob177e48c537b284a7b43fcc68706c48ea13a61c12
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_NONE,
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;
291 /*****************************
292 *** Token reader routines ***
293 *****************************/
295 /* Whitespace is not significant. It can process tokens as identifiers, numbers
296 * (integer and floating-point), strings, and operators. Strings must be
297 * encapsulated by double-quotes and cannot span multiple lines.
300 // Setup the reader on the given file. The filename can be NULL if no error
301 // output is desired.
302 static void TrSetup(FILE *fp, const char *filename, TokenReaderT *tr)
304 const char *name = NULL;
306 if(filename)
308 const char *slash = strrchr(filename, '/');
309 if(slash)
311 const char *bslash = strrchr(slash+1, '\\');
312 if(bslash) name = bslash+1;
313 else name = slash+1;
315 else
317 const char *bslash = strrchr(filename, '\\');
318 if(bslash) name = bslash+1;
319 else name = filename;
323 tr->mFile = fp;
324 tr->mName = name;
325 tr->mLine = 1;
326 tr->mColumn = 1;
327 tr->mIn = 0;
328 tr->mOut = 0;
331 // Prime the reader's ring buffer, and return a result indicating that there
332 // is text to process.
333 static int TrLoad(TokenReaderT *tr)
335 size_t toLoad, in, count;
337 toLoad = TR_RING_SIZE - (tr->mIn - tr->mOut);
338 if(toLoad >= TR_LOAD_SIZE && !feof(tr->mFile))
340 // Load TR_LOAD_SIZE (or less if at the end of the file) per read.
341 toLoad = TR_LOAD_SIZE;
342 in = tr->mIn&TR_RING_MASK;
343 count = TR_RING_SIZE - in;
344 if(count < toLoad)
346 tr->mIn += fread(&tr->mRing[in], 1, count, tr->mFile);
347 tr->mIn += fread(&tr->mRing[0], 1, toLoad-count, tr->mFile);
349 else
350 tr->mIn += fread(&tr->mRing[in], 1, toLoad, tr->mFile);
352 if(tr->mOut >= TR_RING_SIZE)
354 tr->mOut -= TR_RING_SIZE;
355 tr->mIn -= TR_RING_SIZE;
358 if(tr->mIn > tr->mOut)
359 return 1;
360 return 0;
363 // Error display routine. Only displays when the base name is not NULL.
364 static void TrErrorVA(const TokenReaderT *tr, uint line, uint column, const char *format, va_list argPtr)
366 if(!tr->mName)
367 return;
368 fprintf(stderr, "Error (%s:%u:%u): ", tr->mName, line, column);
369 vfprintf(stderr, format, argPtr);
372 // Used to display an error at a saved line/column.
373 static void TrErrorAt(const TokenReaderT *tr, uint line, uint column, const char *format, ...)
375 va_list argPtr;
377 va_start(argPtr, format);
378 TrErrorVA(tr, line, column, format, argPtr);
379 va_end(argPtr);
382 // Used to display an error at the current line/column.
383 static void TrError(const TokenReaderT *tr, const char *format, ...)
385 va_list argPtr;
387 va_start(argPtr, format);
388 TrErrorVA(tr, tr->mLine, tr->mColumn, format, argPtr);
389 va_end(argPtr);
392 // Skips to the next line.
393 static void TrSkipLine(TokenReaderT *tr)
395 char ch;
397 while(TrLoad(tr))
399 ch = tr->mRing[tr->mOut&TR_RING_MASK];
400 tr->mOut++;
401 if(ch == '\n')
403 tr->mLine++;
404 tr->mColumn = 1;
405 break;
407 tr->mColumn ++;
411 // Skips to the next token.
412 static int TrSkipWhitespace(TokenReaderT *tr)
414 char ch;
416 while(TrLoad(tr))
418 ch = tr->mRing[tr->mOut&TR_RING_MASK];
419 if(isspace(ch))
421 tr->mOut++;
422 if(ch == '\n')
424 tr->mLine++;
425 tr->mColumn = 1;
427 else
428 tr->mColumn++;
430 else if(ch == '#')
431 TrSkipLine(tr);
432 else
433 return 1;
435 return 0;
438 // Get the line and/or column of the next token (or the end of input).
439 static void TrIndication(TokenReaderT *tr, uint *line, uint *column)
441 TrSkipWhitespace(tr);
442 if(line) *line = tr->mLine;
443 if(column) *column = tr->mColumn;
446 // Checks to see if a token is the given operator. It does not display any
447 // errors and will not proceed to the next token.
448 static int TrIsOperator(TokenReaderT *tr, const char *op)
450 size_t out, len;
451 char ch;
453 if(!TrSkipWhitespace(tr))
454 return 0;
455 out = tr->mOut;
456 len = 0;
457 while(op[len] != '\0' && out < tr->mIn)
459 ch = tr->mRing[out&TR_RING_MASK];
460 if(ch != op[len]) break;
461 len++;
462 out++;
464 if(op[len] == '\0')
465 return 1;
466 return 0;
469 /* The TrRead*() routines obtain the value of a matching token type. They
470 * display type, form, and boundary errors and will proceed to the next
471 * token.
474 // Reads and validates an identifier token.
475 static int TrReadIdent(TokenReaderT *tr, const uint maxLen, char *ident)
477 uint col, len;
478 char ch;
480 col = tr->mColumn;
481 if(TrSkipWhitespace(tr))
483 col = tr->mColumn;
484 ch = tr->mRing[tr->mOut&TR_RING_MASK];
485 if(ch == '_' || isalpha(ch))
487 len = 0;
488 do {
489 if(len < maxLen)
490 ident[len] = ch;
491 len++;
492 tr->mOut++;
493 if(!TrLoad(tr))
494 break;
495 ch = tr->mRing[tr->mOut&TR_RING_MASK];
496 } while(ch == '_' || isdigit(ch) || isalpha(ch));
498 tr->mColumn += len;
499 if(len < maxLen)
501 ident[len] = '\0';
502 return 1;
504 TrErrorAt(tr, tr->mLine, col, "Identifier is too long.\n");
505 return 0;
508 TrErrorAt(tr, tr->mLine, col, "Expected an identifier.\n");
509 return 0;
512 // Reads and validates (including bounds) an integer token.
513 static int TrReadInt(TokenReaderT *tr, const int loBound, const int hiBound, int *value)
515 uint col, digis, len;
516 char ch, temp[64+1];
518 col = tr->mColumn;
519 if(TrSkipWhitespace(tr))
521 col = tr->mColumn;
522 len = 0;
523 ch = tr->mRing[tr->mOut&TR_RING_MASK];
524 if(ch == '+' || ch == '-')
526 temp[len] = ch;
527 len++;
528 tr->mOut++;
530 digis = 0;
531 while(TrLoad(tr))
533 ch = tr->mRing[tr->mOut&TR_RING_MASK];
534 if(!isdigit(ch)) break;
535 if(len < 64)
536 temp[len] = ch;
537 len++;
538 digis++;
539 tr->mOut++;
541 tr->mColumn += len;
542 if(digis > 0 && ch != '.' && !isalpha(ch))
544 if(len > 64)
546 TrErrorAt(tr, tr->mLine, col, "Integer is too long.");
547 return 0;
549 temp[len] = '\0';
550 *value = strtol(temp, NULL, 10);
551 if(*value < loBound || *value > hiBound)
553 TrErrorAt(tr, tr->mLine, col, "Expected a value from %d to %d.\n", loBound, hiBound);
554 return (0);
556 return (1);
559 TrErrorAt(tr, tr->mLine, col, "Expected an integer.\n");
560 return 0;
563 // Reads and validates (including bounds) a float token.
564 static int TrReadFloat(TokenReaderT *tr, const double loBound, const double hiBound, double *value)
566 uint col, digis, len;
567 char ch, temp[64+1];
569 col = tr->mColumn;
570 if(TrSkipWhitespace(tr))
572 col = tr->mColumn;
573 len = 0;
574 ch = tr->mRing[tr->mOut&TR_RING_MASK];
575 if(ch == '+' || ch == '-')
577 temp[len] = ch;
578 len++;
579 tr->mOut++;
582 digis = 0;
583 while(TrLoad(tr))
585 ch = tr->mRing[tr->mOut&TR_RING_MASK];
586 if(!isdigit(ch)) break;
587 if(len < 64)
588 temp[len] = ch;
589 len++;
590 digis++;
591 tr->mOut++;
593 if(ch == '.')
595 if(len < 64)
596 temp[len] = ch;
597 len++;
598 tr->mOut++;
600 while(TrLoad(tr))
602 ch = tr->mRing[tr->mOut&TR_RING_MASK];
603 if(!isdigit(ch)) break;
604 if(len < 64)
605 temp[len] = ch;
606 len++;
607 digis++;
608 tr->mOut++;
610 if(digis > 0)
612 if(ch == 'E' || ch == 'e')
614 if(len < 64)
615 temp[len] = ch;
616 len++;
617 digis = 0;
618 tr->mOut++;
619 if(ch == '+' || ch == '-')
621 if(len < 64)
622 temp[len] = ch;
623 len++;
624 tr->mOut++;
626 while(TrLoad(tr))
628 ch = tr->mRing[tr->mOut&TR_RING_MASK];
629 if(!isdigit(ch)) break;
630 if(len < 64)
631 temp[len] = ch;
632 len++;
633 digis++;
634 tr->mOut++;
637 tr->mColumn += len;
638 if(digis > 0 && ch != '.' && !isalpha(ch))
640 if(len > 64)
642 TrErrorAt(tr, tr->mLine, col, "Float is too long.");
643 return 0;
645 temp[len] = '\0';
646 *value = strtod(temp, NULL);
647 if(*value < loBound || *value > hiBound)
649 TrErrorAt (tr, tr->mLine, col, "Expected a value from %f to %f.\n", loBound, hiBound);
650 return 0;
652 return 1;
655 else
656 tr->mColumn += len;
658 TrErrorAt(tr, tr->mLine, col, "Expected a float.\n");
659 return 0;
662 // Reads and validates a string token.
663 static int TrReadString(TokenReaderT *tr, const uint maxLen, char *text)
665 uint col, len;
666 char ch;
668 col = tr->mColumn;
669 if(TrSkipWhitespace(tr))
671 col = tr->mColumn;
672 ch = tr->mRing[tr->mOut&TR_RING_MASK];
673 if(ch == '\"')
675 tr->mOut++;
676 len = 0;
677 while(TrLoad(tr))
679 ch = tr->mRing[tr->mOut&TR_RING_MASK];
680 tr->mOut++;
681 if(ch == '\"')
682 break;
683 if(ch == '\n')
685 TrErrorAt (tr, tr->mLine, col, "Unterminated string at end of line.\n");
686 return 0;
688 if(len < maxLen)
689 text[len] = ch;
690 len++;
692 if(ch != '\"')
694 tr->mColumn += 1 + len;
695 TrErrorAt(tr, tr->mLine, col, "Unterminated string at end of input.\n");
696 return 0;
698 tr->mColumn += 2 + len;
699 if(len > maxLen)
701 TrErrorAt (tr, tr->mLine, col, "String is too long.\n");
702 return 0;
704 text[len] = '\0';
705 return 1;
708 TrErrorAt(tr, tr->mLine, col, "Expected a string.\n");
709 return 0;
712 // Reads and validates the given operator.
713 static int TrReadOperator(TokenReaderT *tr, const char *op)
715 uint col, len;
716 char ch;
718 col = tr->mColumn;
719 if(TrSkipWhitespace(tr))
721 col = tr->mColumn;
722 len = 0;
723 while(op[len] != '\0' && TrLoad(tr))
725 ch = tr->mRing[tr->mOut&TR_RING_MASK];
726 if(ch != op[len]) break;
727 len++;
728 tr->mOut++;
730 tr->mColumn += len;
731 if(op[len] == '\0')
732 return 1;
734 TrErrorAt(tr, tr->mLine, col, "Expected '%s' operator.\n", op);
735 return 0;
738 /* Performs a string substitution. Any case-insensitive occurrences of the
739 * pattern string are replaced with the replacement string. The result is
740 * truncated if necessary.
742 static int StrSubst(const char *in, const char *pat, const char *rep, const size_t maxLen, char *out)
744 size_t inLen, patLen, repLen;
745 size_t si, di;
746 int truncated;
748 inLen = strlen(in);
749 patLen = strlen(pat);
750 repLen = strlen(rep);
751 si = 0;
752 di = 0;
753 truncated = 0;
754 while(si < inLen && di < maxLen)
756 if(patLen <= inLen-si)
758 if(strncasecmp(&in[si], pat, patLen) == 0)
760 if(repLen > maxLen-di)
762 repLen = maxLen - di;
763 truncated = 1;
765 strncpy(&out[di], rep, repLen);
766 si += patLen;
767 di += repLen;
770 out[di] = in[si];
771 si++;
772 di++;
774 if(si < inLen)
775 truncated = 1;
776 out[di] = '\0';
777 return !truncated;
781 /*********************
782 *** Math routines ***
783 *********************/
785 // Provide missing math routines for MSVC versions < 1800 (Visual Studio 2013).
786 #if defined(_MSC_VER) && _MSC_VER < 1800
787 static double round(double val)
789 if(val < 0.0)
790 return ceil(val-0.5);
791 return floor(val+0.5);
794 static double fmin(double a, double b)
796 return (a<b) ? a : b;
799 static double fmax(double a, double b)
801 return (a>b) ? a : b;
803 #endif
805 // Simple clamp routine.
806 static double Clamp(const double val, const double lower, const double upper)
808 return fmin(fmax(val, lower), upper);
811 // Performs linear interpolation.
812 static double Lerp(const double a, const double b, const double f)
814 return a + (f * (b - a));
817 // Performs a high-passed triangular probability density function dither from
818 // a double to an integer. It assumes the input sample is already scaled.
819 static int HpTpdfDither(const double in, int *hpHist)
821 static const double PRNG_SCALE = 1.0 / (RAND_MAX+1.0);
822 int prn;
823 double out;
825 prn = rand();
826 out = round(in + (PRNG_SCALE * (prn - *hpHist)));
827 *hpHist = prn;
828 return (int)out;
831 // Allocates an array of doubles.
832 static double *CreateArray(size_t n)
834 double *a;
836 if(n == 0) n = 1;
837 a = calloc(n, sizeof(double));
838 if(a == NULL)
840 fprintf(stderr, "Error: Out of memory.\n");
841 exit(-1);
843 return a;
846 // Frees an array of doubles.
847 static void DestroyArray(double *a)
848 { free(a); }
850 // Complex number routines. All outputs must be non-NULL.
852 // Magnitude/absolute value.
853 static double ComplexAbs(const double r, const double i)
855 return sqrt(r*r + i*i);
858 // Multiply.
859 static void ComplexMul(const double aR, const double aI, const double bR, const double bI, double *outR, double *outI)
861 *outR = (aR * bR) - (aI * bI);
862 *outI = (aI * bR) + (aR * bI);
865 // Base-e exponent.
866 static void ComplexExp(const double inR, const double inI, double *outR, double *outI)
868 double e = exp(inR);
869 *outR = e * cos(inI);
870 *outI = e * sin(inI);
873 /* Fast Fourier transform routines. The number of points must be a power of
874 * two. In-place operation is possible only if both the real and imaginary
875 * parts are in-place together.
878 // Performs bit-reversal ordering.
879 static void FftArrange(const uint n, const double *inR, const double *inI, double *outR, double *outI)
881 uint rk, k, m;
882 double tempR, tempI;
884 if(inR == outR && inI == outI)
886 // Handle in-place arrangement.
887 rk = 0;
888 for(k = 0;k < n;k++)
890 if(rk > k)
892 tempR = inR[rk];
893 tempI = inI[rk];
894 outR[rk] = inR[k];
895 outI[rk] = inI[k];
896 outR[k] = tempR;
897 outI[k] = tempI;
899 m = n;
900 while(rk&(m >>= 1))
901 rk &= ~m;
902 rk |= m;
905 else
907 // Handle copy arrangement.
908 rk = 0;
909 for(k = 0;k < n;k++)
911 outR[rk] = inR[k];
912 outI[rk] = inI[k];
913 m = n;
914 while(rk&(m >>= 1))
915 rk &= ~m;
916 rk |= m;
921 // Performs the summation.
922 static void FftSummation(const uint n, const double s, double *re, double *im)
924 double pi;
925 uint m, m2;
926 double vR, vI, wR, wI;
927 uint i, k, mk;
928 double tR, tI;
930 pi = s * M_PI;
931 for(m = 1, m2 = 2;m < n; m <<= 1, m2 <<= 1)
933 // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
934 vR = sin(0.5 * pi / m);
935 vR = -2.0 * vR * vR;
936 vI = -sin(pi / m);
937 // w = Complex (1.0, 0.0)
938 wR = 1.0;
939 wI = 0.0;
940 for(i = 0;i < m;i++)
942 for(k = i;k < n;k += m2)
944 mk = k + m;
945 // t = ComplexMul(w, out[km2])
946 tR = (wR * re[mk]) - (wI * im[mk]);
947 tI = (wR * im[mk]) + (wI * re[mk]);
948 // out[mk] = ComplexSub (out [k], t)
949 re[mk] = re[k] - tR;
950 im[mk] = im[k] - tI;
951 // out[k] = ComplexAdd (out [k], t)
952 re[k] += tR;
953 im[k] += tI;
955 // t = ComplexMul (v, w)
956 tR = (vR * wR) - (vI * wI);
957 tI = (vR * wI) + (vI * wR);
958 // w = ComplexAdd (w, t)
959 wR += tR;
960 wI += tI;
965 // Performs a forward FFT.
966 static void FftForward(const uint n, const double *inR, const double *inI, double *outR, double *outI)
968 FftArrange(n, inR, inI, outR, outI);
969 FftSummation(n, 1.0, outR, outI);
972 // Performs an inverse FFT.
973 static void FftInverse(const uint n, const double *inR, const double *inI, double *outR, double *outI)
975 double f;
976 uint i;
978 FftArrange(n, inR, inI, outR, outI);
979 FftSummation(n, -1.0, outR, outI);
980 f = 1.0 / n;
981 for(i = 0;i < n;i++)
983 outR[i] *= f;
984 outI[i] *= f;
988 /* Calculate the complex helical sequence (or discrete-time analytical
989 * signal) of the given input using the Hilbert transform. Given the
990 * negative natural logarithm of a signal's magnitude response, the imaginary
991 * components can be used as the angles for minimum-phase reconstruction.
993 static void Hilbert(const uint n, const double *in, double *outR, double *outI)
995 uint i;
997 if(in == outR)
999 // Handle in-place operation.
1000 for(i = 0;i < n;i++)
1001 outI[i] = 0.0;
1003 else
1005 // Handle copy operation.
1006 for(i = 0;i < n;i++)
1008 outR[i] = in[i];
1009 outI[i] = 0.0;
1012 FftForward(n, outR, outI, outR, outI);
1013 /* Currently the Fourier routines operate only on point counts that are
1014 * powers of two. If that changes and n is odd, the following conditional
1015 * should be: i < (n + 1) / 2.
1017 for(i = 1;i < (n/2);i++)
1019 outR[i] *= 2.0;
1020 outI[i] *= 2.0;
1022 // If n is odd, the following increment should be skipped.
1023 i++;
1024 for(;i < n;i++)
1026 outR[i] = 0.0;
1027 outI[i] = 0.0;
1029 FftInverse(n, outR, outI, outR, outI);
1032 /* Calculate the magnitude response of the given input. This is used in
1033 * place of phase decomposition, since the phase residuals are discarded for
1034 * minimum phase reconstruction. The mirrored half of the response is also
1035 * discarded.
1037 static void MagnitudeResponse(const uint n, const double *inR, const double *inI, double *out)
1039 const uint m = 1 + (n / 2);
1040 uint i;
1041 for(i = 0;i < m;i++)
1042 out[i] = fmax(ComplexAbs(inR[i], inI[i]), EPSILON);
1045 /* Apply a range limit (in dB) to the given magnitude response. This is used
1046 * to adjust the effects of the diffuse-field average on the equalization
1047 * process.
1049 static void LimitMagnitudeResponse(const uint n, const double limit, const double *in, double *out)
1051 const uint m = 1 + (n / 2);
1052 double halfLim;
1053 uint i, lower, upper;
1054 double ave;
1056 halfLim = limit / 2.0;
1057 // Convert the response to dB.
1058 for(i = 0;i < m;i++)
1059 out[i] = 20.0 * log10(in[i]);
1060 // Use six octaves to calculate the average magnitude of the signal.
1061 lower = ((uint)ceil(n / pow(2.0, 8.0))) - 1;
1062 upper = ((uint)floor(n / pow(2.0, 2.0))) - 1;
1063 ave = 0.0;
1064 for(i = lower;i <= upper;i++)
1065 ave += out[i];
1066 ave /= upper - lower + 1;
1067 // Keep the response within range of the average magnitude.
1068 for(i = 0;i < m;i++)
1069 out[i] = Clamp(out[i], ave - halfLim, ave + halfLim);
1070 // Convert the response back to linear magnitude.
1071 for(i = 0;i < m;i++)
1072 out[i] = pow(10.0, out[i] / 20.0);
1075 /* Reconstructs the minimum-phase component for the given magnitude response
1076 * of a signal. This is equivalent to phase recomposition, sans the missing
1077 * residuals (which were discarded). The mirrored half of the response is
1078 * reconstructed.
1080 static void MinimumPhase(const uint n, const double *in, double *outR, double *outI)
1082 const uint m = 1 + (n / 2);
1083 double aR, aI;
1084 double *mags;
1085 uint i;
1087 mags = CreateArray(n);
1088 for(i = 0;i < m;i++)
1090 mags[i] = fmax(in[i], EPSILON);
1091 outR[i] = -log(mags[i]);
1093 for(;i < n;i++)
1095 mags[i] = mags[n - i];
1096 outR[i] = outR[n - i];
1098 Hilbert(n, outR, outR, outI);
1099 // Remove any DC offset the filter has.
1100 outR[0] = 0.0;
1101 outI[0] = 0.0;
1102 for(i = 1;i < n;i++)
1104 ComplexExp(0.0, outI[i], &aR, &aI);
1105 ComplexMul(mags[i], 0.0, aR, aI, &outR[i], &outI[i]);
1107 DestroyArray(mags);
1111 /***************************
1112 *** Resampler functions ***
1113 ***************************/
1115 /* This is the normalized cardinal sine (sinc) function.
1117 * sinc(x) = { 1, x = 0
1118 * { sin(pi x) / (pi x), otherwise.
1120 static double Sinc(const double x)
1122 if(fabs(x) < EPSILON)
1123 return 1.0;
1124 return sin(M_PI * x) / (M_PI * x);
1127 /* The zero-order modified Bessel function of the first kind, used for the
1128 * Kaiser window.
1130 * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
1131 * = sum_{k=0}^inf ((x / 2)^k / k!)^2
1133 static double BesselI_0(const double x)
1135 double term, sum, x2, y, last_sum;
1136 int k;
1138 // Start at k=1 since k=0 is trivial.
1139 term = 1.0;
1140 sum = 1.0;
1141 x2 = x/2.0;
1142 k = 1;
1144 // Let the integration converge until the term of the sum is no longer
1145 // significant.
1146 do {
1147 y = x2 / k;
1148 k++;
1149 last_sum = sum;
1150 term *= y * y;
1151 sum += term;
1152 } while(sum != last_sum);
1153 return sum;
1156 /* Calculate a Kaiser window from the given beta value and a normalized k
1157 * [-1, 1].
1159 * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
1160 * { 0, elsewhere.
1162 * Where k can be calculated as:
1164 * k = i / l, where -l <= i <= l.
1166 * or:
1168 * k = 2 i / M - 1, where 0 <= i <= M.
1170 static double Kaiser(const double b, const double k)
1172 if(!(k >= -1.0 && k <= 1.0))
1173 return 0.0;
1174 return BesselI_0(b * sqrt(1.0 - k*k)) / BesselI_0(b);
1177 // Calculates the greatest common divisor of a and b.
1178 static uint Gcd(uint x, uint y)
1180 while(y > 0)
1182 uint z = y;
1183 y = x % y;
1184 x = z;
1186 return x;
1189 /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
1190 * the transition width is normalized frequency (0.5 is nyquist).
1192 * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
1193 * { ceil(5.79 / 2 pi f_t), r <= 21.
1196 static uint CalcKaiserOrder(const double rejection, const double transition)
1198 double w_t = 2.0 * M_PI * transition;
1199 if(rejection > 21.0)
1200 return (uint)ceil((rejection - 7.95) / (2.285 * w_t));
1201 return (uint)ceil(5.79 / w_t);
1204 // Calculates the beta value of the Kaiser window. Rejection is in dB.
1205 static double CalcKaiserBeta(const double rejection)
1207 if(rejection > 50.0)
1208 return 0.1102 * (rejection - 8.7);
1209 if(rejection >= 21.0)
1210 return (0.5842 * pow(rejection - 21.0, 0.4)) +
1211 (0.07886 * (rejection - 21.0));
1212 return 0.0;
1215 /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
1216 * width, beta, gain, and cutoff. The point is specified in non-normalized
1217 * samples, from 0 to M, where M = (2 l + 1).
1219 * w(k) 2 p f_t sinc(2 f_t x)
1221 * x -- centered sample index (i - l)
1222 * k -- normalized and centered window index (x / l)
1223 * w(k) -- window function (Kaiser)
1224 * p -- gain compensation factor when sampling
1225 * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
1227 static double SincFilter(const int l, const double b, const double gain, const double cutoff, const int i)
1229 return Kaiser(b, (double)(i - l) / l) * 2.0 * gain * cutoff * Sinc(2.0 * cutoff * (i - l));
1232 /* This is a polyphase sinc-filtered resampler.
1234 * Upsample Downsample
1236 * p/q = 3/2 p/q = 3/5
1238 * M-+-+-+-> M-+-+-+->
1239 * -------------------+ ---------------------+
1240 * p s * f f f f|f| | p s * f f f f f |
1241 * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
1242 * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
1243 * s * f|f|f f f | s * f f|f|f f |
1244 * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
1245 * --------+=+--------+ 0 * |0|0 0 0 0 |
1246 * d . d .|d|. d . d ----------+=+--------+
1247 * d . . . .|d|. . . .
1248 * q->
1249 * q-+-+-+->
1251 * P_f(i,j) = q i mod p + pj
1252 * P_s(i,j) = floor(q i / p) - j
1253 * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
1254 * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
1255 * { 0, P_f(i,j) >= M. }
1258 // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
1259 // that's used to cut frequencies above the destination nyquist.
1260 static void ResamplerSetup(ResamplerT *rs, const uint srcRate, const uint dstRate)
1262 double cutoff, width, beta;
1263 uint gcd, l;
1264 int i;
1266 gcd = Gcd(srcRate, dstRate);
1267 rs->mP = dstRate / gcd;
1268 rs->mQ = srcRate / gcd;
1269 /* The cutoff is adjusted by half the transition width, so the transition
1270 * ends before the nyquist (0.5). Both are scaled by the downsampling
1271 * factor.
1273 if(rs->mP > rs->mQ)
1275 cutoff = 0.45 / rs->mP;
1276 width = 0.1 / rs->mP;
1278 else
1280 cutoff = 0.45 / rs->mQ;
1281 width = 0.1 / rs->mQ;
1283 // A rejection of -180 dB is used for the stop band.
1284 l = CalcKaiserOrder(180.0, width) / 2;
1285 beta = CalcKaiserBeta(180.0);
1286 rs->mM = (2 * l) + 1;
1287 rs->mL = l;
1288 rs->mF = CreateArray(rs->mM);
1289 for(i = 0;i < ((int)rs->mM);i++)
1290 rs->mF[i] = SincFilter((int)l, beta, rs->mP, cutoff, i);
1293 // Clean up after the resampler.
1294 static void ResamplerClear(ResamplerT *rs)
1296 DestroyArray(rs->mF);
1297 rs->mF = NULL;
1300 // Perform the upsample-filter-downsample resampling operation using a
1301 // polyphase filter implementation.
1302 static void ResamplerRun(ResamplerT *rs, const uint inN, const double *in, const uint outN, double *out)
1304 const uint p = rs->mP, q = rs->mQ, m = rs->mM, l = rs->mL;
1305 const double *f = rs->mF;
1306 uint j_f, j_s;
1307 double *work;
1308 uint i;
1310 if(outN == 0)
1311 return;
1313 // Handle in-place operation.
1314 if(in == out)
1315 work = CreateArray(outN);
1316 else
1317 work = out;
1318 // Resample the input.
1319 for(i = 0;i < outN;i++)
1321 double r = 0.0;
1322 // Input starts at l to compensate for the filter delay. This will
1323 // drop any build-up from the first half of the filter.
1324 j_f = (l + (q * i)) % p;
1325 j_s = (l + (q * i)) / p;
1326 while(j_f < m)
1328 // Only take input when 0 <= j_s < inN. This single unsigned
1329 // comparison catches both cases.
1330 if(j_s < inN)
1331 r += f[j_f] * in[j_s];
1332 j_f += p;
1333 j_s--;
1335 work[i] = r;
1337 // Clean up after in-place operation.
1338 if(in == out)
1340 for(i = 0;i < outN;i++)
1341 out[i] = work[i];
1342 DestroyArray(work);
1346 /*************************
1347 *** File source input ***
1348 *************************/
1350 // Read a binary value of the specified byte order and byte size from a file,
1351 // storing it as a 32-bit unsigned integer.
1352 static int ReadBin4(FILE *fp, const char *filename, const ByteOrderT order, const uint bytes, uint32 *out)
1354 uint8 in[4];
1355 uint32 accum;
1356 uint i;
1358 if(fread(in, 1, bytes, fp) != bytes)
1360 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1361 return 0;
1363 accum = 0;
1364 switch(order)
1366 case BO_LITTLE:
1367 for(i = 0;i < bytes;i++)
1368 accum = (accum<<8) | in[bytes - i - 1];
1369 break;
1370 case BO_BIG:
1371 for(i = 0;i < bytes;i++)
1372 accum = (accum<<8) | in[i];
1373 break;
1374 default:
1375 break;
1377 *out = accum;
1378 return 1;
1381 // Read a binary value of the specified byte order from a file, storing it as
1382 // a 64-bit unsigned integer.
1383 static int ReadBin8(FILE *fp, const char *filename, const ByteOrderT order, uint64 *out)
1385 uint8 in [8];
1386 uint64 accum;
1387 uint i;
1389 if(fread(in, 1, 8, fp) != 8)
1391 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1392 return 0;
1394 accum = 0ULL;
1395 switch(order)
1397 case BO_LITTLE:
1398 for(i = 0;i < 8;i++)
1399 accum = (accum<<8) | in[8 - i - 1];
1400 break;
1401 case BO_BIG:
1402 for(i = 0;i < 8;i++)
1403 accum = (accum<<8) | in[i];
1404 break;
1405 default:
1406 break;
1408 *out = accum;
1409 return 1;
1412 /* Read a binary value of the specified type, byte order, and byte size from
1413 * a file, converting it to a double. For integer types, the significant
1414 * bits are used to normalize the result. The sign of bits determines
1415 * whether they are padded toward the MSB (negative) or LSB (positive).
1416 * Floating-point types are not normalized.
1418 static int ReadBinAsDouble(FILE *fp, const char *filename, const ByteOrderT order, const ElementTypeT type, const uint bytes, const int bits, double *out)
1420 union {
1421 uint32 ui;
1422 int32 i;
1423 float f;
1424 } v4;
1425 union {
1426 uint64 ui;
1427 double f;
1428 } v8;
1430 *out = 0.0;
1431 if(bytes > 4)
1433 if(!ReadBin8(fp, filename, order, &v8.ui))
1434 return 0;
1435 if(type == ET_FP)
1436 *out = v8.f;
1438 else
1440 if(!ReadBin4(fp, filename, order, bytes, &v4.ui))
1441 return 0;
1442 if(type == ET_FP)
1443 *out = v4.f;
1444 else
1446 if(bits > 0)
1447 v4.ui >>= (8*bytes) - ((uint)bits);
1448 else
1449 v4.ui &= (0xFFFFFFFF >> (32+bits));
1451 if(v4.ui&(uint)(1<<(abs(bits)-1)))
1452 v4.ui |= (0xFFFFFFFF << abs (bits));
1453 *out = v4.i / (double)(1<<(abs(bits)-1));
1456 return 1;
1459 /* Read an ascii value of the specified type from a file, converting it to a
1460 * double. For integer types, the significant bits are used to normalize the
1461 * result. The sign of the bits should always be positive. This also skips
1462 * up to one separator character before the element itself.
1464 static int ReadAsciiAsDouble(TokenReaderT *tr, const char *filename, const ElementTypeT type, const uint bits, double *out)
1466 if(TrIsOperator(tr, ","))
1467 TrReadOperator(tr, ",");
1468 else if(TrIsOperator(tr, ":"))
1469 TrReadOperator(tr, ":");
1470 else if(TrIsOperator(tr, ";"))
1471 TrReadOperator(tr, ";");
1472 else if(TrIsOperator(tr, "|"))
1473 TrReadOperator(tr, "|");
1475 if(type == ET_FP)
1477 if(!TrReadFloat(tr, -HUGE_VAL, HUGE_VAL, out))
1479 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1480 return 0;
1483 else
1485 int v;
1486 if(!TrReadInt(tr, -(1<<(bits-1)), (1<<(bits-1))-1, &v))
1488 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1489 return 0;
1491 *out = v / (double)((1<<(bits-1))-1);
1493 return 1;
1496 // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
1497 // the source parameters and data set metrics.
1498 static int ReadWaveFormat(FILE *fp, const ByteOrderT order, const uint hrirRate, SourceRefT *src)
1500 uint32 fourCC, chunkSize;
1501 uint32 format, channels, rate, dummy, block, size, bits;
1503 chunkSize = 0;
1504 do {
1505 if (chunkSize > 0)
1506 fseek (fp, (long) chunkSize, SEEK_CUR);
1507 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
1508 !ReadBin4(fp, src->mPath, order, 4, &chunkSize))
1509 return 0;
1510 } while(fourCC != FOURCC_FMT);
1511 if(!ReadBin4(fp, src->mPath, order, 2, & format) ||
1512 !ReadBin4(fp, src->mPath, order, 2, & channels) ||
1513 !ReadBin4(fp, src->mPath, order, 4, & rate) ||
1514 !ReadBin4(fp, src->mPath, order, 4, & dummy) ||
1515 !ReadBin4(fp, src->mPath, order, 2, & block))
1516 return (0);
1517 block /= channels;
1518 if(chunkSize > 14)
1520 if(!ReadBin4(fp, src->mPath, order, 2, &size))
1521 return 0;
1522 size /= 8;
1523 if(block > size)
1524 size = block;
1526 else
1527 size = block;
1528 if(format == WAVE_FORMAT_EXTENSIBLE)
1530 fseek(fp, 2, SEEK_CUR);
1531 if(!ReadBin4(fp, src->mPath, order, 2, &bits))
1532 return 0;
1533 if(bits == 0)
1534 bits = 8 * size;
1535 fseek(fp, 4, SEEK_CUR);
1536 if(!ReadBin4(fp, src->mPath, order, 2, &format))
1537 return 0;
1538 fseek(fp, (long)(chunkSize - 26), SEEK_CUR);
1540 else
1542 bits = 8 * size;
1543 if(chunkSize > 14)
1544 fseek(fp, (long)(chunkSize - 16), SEEK_CUR);
1545 else
1546 fseek(fp, (long)(chunkSize - 14), SEEK_CUR);
1548 if(format != WAVE_FORMAT_PCM && format != WAVE_FORMAT_IEEE_FLOAT)
1550 fprintf(stderr, "Error: Unsupported WAVE format in file '%s'.\n", src->mPath);
1551 return 0;
1553 if(src->mChannel >= channels)
1555 fprintf(stderr, "Error: Missing source channel in WAVE file '%s'.\n", src->mPath);
1556 return 0;
1558 if(rate != hrirRate)
1560 fprintf(stderr, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src->mPath);
1561 return 0;
1563 if(format == WAVE_FORMAT_PCM)
1565 if(size < 2 || size > 4)
1567 fprintf(stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src->mPath);
1568 return 0;
1570 if(bits < 16 || bits > (8*size))
1572 fprintf (stderr, "Error: Bad significant bits in WAVE file '%s'.\n", src->mPath);
1573 return 0;
1575 src->mType = ET_INT;
1577 else
1579 if(size != 4 && size != 8)
1581 fprintf(stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src->mPath);
1582 return 0;
1584 src->mType = ET_FP;
1586 src->mSize = size;
1587 src->mBits = (int)bits;
1588 src->mSkip = channels;
1589 return 1;
1592 // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
1593 static int ReadWaveData(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
1595 int pre, post, skip;
1596 uint i;
1598 pre = (int)(src->mSize * src->mChannel);
1599 post = (int)(src->mSize * (src->mSkip - src->mChannel - 1));
1600 skip = 0;
1601 for(i = 0;i < n;i++)
1603 skip += pre;
1604 if(skip > 0)
1605 fseek(fp, skip, SEEK_CUR);
1606 if(!ReadBinAsDouble(fp, src->mPath, order, src->mType, src->mSize, src->mBits, &hrir[i]))
1607 return 0;
1608 skip = post;
1610 if(skip > 0)
1611 fseek(fp, skip, SEEK_CUR);
1612 return 1;
1615 // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
1616 // doubles.
1617 static int ReadWaveList(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
1619 uint32 fourCC, chunkSize, listSize, count;
1620 uint block, skip, offset, i;
1621 double lastSample;
1623 for (;;) {
1624 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, & fourCC) ||
1625 !ReadBin4(fp, src->mPath, order, 4, & chunkSize))
1626 return (0);
1628 if(fourCC == FOURCC_DATA)
1630 block = src->mSize * src->mSkip;
1631 count = chunkSize / block;
1632 if(count < (src->mOffset + n))
1634 fprintf(stderr, "Error: Bad read from file '%s'.\n", src->mPath);
1635 return 0;
1637 fseek(fp, (long)(src->mOffset * block), SEEK_CUR);
1638 if(!ReadWaveData(fp, src, order, n, &hrir[0]))
1639 return 0;
1640 return 1;
1642 else if(fourCC == FOURCC_LIST)
1644 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC))
1645 return 0;
1646 chunkSize -= 4;
1647 if(fourCC == FOURCC_WAVL)
1648 break;
1650 if(chunkSize > 0)
1651 fseek(fp, (long)chunkSize, SEEK_CUR);
1653 listSize = chunkSize;
1654 block = src->mSize * src->mSkip;
1655 skip = src->mOffset;
1656 offset = 0;
1657 lastSample = 0.0;
1658 while(offset < n && listSize > 8)
1660 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
1661 !ReadBin4(fp, src->mPath, order, 4, &chunkSize))
1662 return 0;
1663 listSize -= 8 + chunkSize;
1664 if(fourCC == FOURCC_DATA)
1666 count = chunkSize / block;
1667 if(count > skip)
1669 fseek(fp, (long)(skip * block), SEEK_CUR);
1670 chunkSize -= skip * block;
1671 count -= skip;
1672 skip = 0;
1673 if(count > (n - offset))
1674 count = n - offset;
1675 if(!ReadWaveData(fp, src, order, count, &hrir[offset]))
1676 return 0;
1677 chunkSize -= count * block;
1678 offset += count;
1679 lastSample = hrir [offset - 1];
1681 else
1683 skip -= count;
1684 count = 0;
1687 else if(fourCC == FOURCC_SLNT)
1689 if(!ReadBin4(fp, src->mPath, order, 4, &count))
1690 return 0;
1691 chunkSize -= 4;
1692 if(count > skip)
1694 count -= skip;
1695 skip = 0;
1696 if(count > (n - offset))
1697 count = n - offset;
1698 for(i = 0; i < count; i ++)
1699 hrir[offset + i] = lastSample;
1700 offset += count;
1702 else
1704 skip -= count;
1705 count = 0;
1708 if(chunkSize > 0)
1709 fseek(fp, (long)chunkSize, SEEK_CUR);
1711 if(offset < n)
1713 fprintf(stderr, "Error: Bad read from file '%s'.\n", src->mPath);
1714 return 0;
1716 return 1;
1719 // Load a source HRIR from a RIFF/RIFX WAVE file.
1720 static int LoadWaveSource(FILE *fp, SourceRefT *src, const uint hrirRate, const uint n, double *hrir)
1722 uint32 fourCC, dummy;
1723 ByteOrderT order;
1725 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
1726 !ReadBin4(fp, src->mPath, BO_LITTLE, 4, &dummy))
1727 return 0;
1728 if(fourCC == FOURCC_RIFF)
1729 order = BO_LITTLE;
1730 else if(fourCC == FOURCC_RIFX)
1731 order = BO_BIG;
1732 else
1734 fprintf(stderr, "Error: No RIFF/RIFX chunk in file '%s'.\n", src->mPath);
1735 return 0;
1738 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC))
1739 return 0;
1740 if(fourCC != FOURCC_WAVE)
1742 fprintf(stderr, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src->mPath);
1743 return 0;
1745 if(!ReadWaveFormat(fp, order, hrirRate, src))
1746 return 0;
1747 if(!ReadWaveList(fp, src, order, n, hrir))
1748 return 0;
1749 return 1;
1752 // Load a source HRIR from a binary file.
1753 static int LoadBinarySource(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
1755 uint i;
1757 fseek(fp, (long)src->mOffset, SEEK_SET);
1758 for(i = 0;i < n;i++)
1760 if(!ReadBinAsDouble(fp, src->mPath, order, src->mType, src->mSize, src->mBits, &hrir[i]))
1761 return 0;
1762 if(src->mSkip > 0)
1763 fseek(fp, (long)src->mSkip, SEEK_CUR);
1765 return 1;
1768 // Load a source HRIR from an ASCII text file containing a list of elements
1769 // separated by whitespace or common list operators (',', ';', ':', '|').
1770 static int LoadAsciiSource(FILE *fp, const SourceRefT *src, const uint n, double *hrir)
1772 TokenReaderT tr;
1773 uint i, j;
1774 double dummy;
1776 TrSetup(fp, NULL, &tr);
1777 for(i = 0;i < src->mOffset;i++)
1779 if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &dummy))
1780 return (0);
1782 for(i = 0;i < n;i++)
1784 if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &hrir[i]))
1785 return 0;
1786 for(j = 0;j < src->mSkip;j++)
1788 if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &dummy))
1789 return 0;
1792 return 1;
1795 // Load a source HRIR from a supported file type.
1796 static int LoadSource(SourceRefT *src, const uint hrirRate, const uint n, double *hrir)
1798 int result;
1799 FILE *fp;
1801 if (src->mFormat == SF_ASCII)
1802 fp = fopen(src->mPath, "r");
1803 else
1804 fp = fopen(src->mPath, "rb");
1805 if(fp == NULL)
1807 fprintf(stderr, "Error: Could not open source file '%s'.\n", src->mPath);
1808 return 0;
1810 if(src->mFormat == SF_WAVE)
1811 result = LoadWaveSource(fp, src, hrirRate, n, hrir);
1812 else if(src->mFormat == SF_BIN_LE)
1813 result = LoadBinarySource(fp, src, BO_LITTLE, n, hrir);
1814 else if(src->mFormat == SF_BIN_BE)
1815 result = LoadBinarySource(fp, src, BO_BIG, n, hrir);
1816 else
1817 result = LoadAsciiSource(fp, src, n, hrir);
1818 fclose(fp);
1819 return result;
1823 /***************************
1824 *** File storage output ***
1825 ***************************/
1827 // Write an ASCII string to a file.
1828 static int WriteAscii(const char *out, FILE *fp, const char *filename)
1830 size_t len;
1832 len = strlen(out);
1833 if(fwrite(out, 1, len, fp) != len)
1835 fclose(fp);
1836 fprintf(stderr, "Error: Bad write to file '%s'.\n", filename);
1837 return 0;
1839 return 1;
1842 // Write a binary value of the given byte order and byte size to a file,
1843 // loading it from a 32-bit unsigned integer.
1844 static int WriteBin4(const ByteOrderT order, const uint bytes, const uint32 in, FILE *fp, const char *filename)
1846 uint8 out[4];
1847 uint i;
1849 switch(order)
1851 case BO_LITTLE:
1852 for(i = 0;i < bytes;i++)
1853 out[i] = (in>>(i*8)) & 0x000000FF;
1854 break;
1855 case BO_BIG:
1856 for(i = 0;i < bytes;i++)
1857 out[bytes - i - 1] = (in>>(i*8)) & 0x000000FF;
1858 break;
1859 default:
1860 break;
1862 if(fwrite(out, 1, bytes, fp) != bytes)
1864 fprintf(stderr, "Error: Bad write to file '%s'.\n", filename);
1865 return 0;
1867 return 1;
1870 // Store the OpenAL Soft HRTF data set.
1871 static int StoreMhr(const HrirDataT *hData, const char *filename)
1873 uint e, step, end, n, j, i;
1874 int hpHist, v;
1875 FILE *fp;
1877 if((fp=fopen(filename, "wb")) == NULL)
1879 fprintf(stderr, "Error: Could not open MHR file '%s'.\n", filename);
1880 return 0;
1882 if(!WriteAscii(MHR_FORMAT, fp, filename))
1883 return 0;
1884 if(!WriteBin4(BO_LITTLE, 4, (uint32)hData->mIrRate, fp, filename))
1885 return 0;
1886 if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mIrPoints, fp, filename))
1887 return 0;
1888 if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mEvCount, fp, filename))
1889 return 0;
1890 for(e = 0;e < hData->mEvCount;e++)
1892 if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mAzCount[e], fp, filename))
1893 return 0;
1895 step = hData->mIrSize;
1896 end = hData->mIrCount * step;
1897 n = hData->mIrPoints;
1898 srand(0x31DF840C);
1899 for(j = 0;j < end;j += step)
1901 hpHist = 0;
1902 for(i = 0;i < n;i++)
1904 v = HpTpdfDither(32767.0 * hData->mHrirs[j+i], &hpHist);
1905 if(!WriteBin4(BO_LITTLE, 2, (uint32)v, fp, filename))
1906 return 0;
1909 for(j = 0;j < hData->mIrCount;j++)
1911 v = (int)fmin(round(hData->mIrRate * hData->mHrtds[j]), MAX_HRTD);
1912 if(!WriteBin4(BO_LITTLE, 1, (uint32)v, fp, filename))
1913 return 0;
1915 fclose(fp);
1916 return 1;
1920 /***********************
1921 *** HRTF processing ***
1922 ***********************/
1924 // Calculate the onset time of an HRIR and average it with any existing
1925 // timing for its elevation and azimuth.
1926 static void AverageHrirOnset(const double *hrir, const double f, const uint ei, const uint ai, const HrirDataT *hData)
1928 double mag;
1929 uint n, i, j;
1931 mag = 0.0;
1932 n = hData->mIrPoints;
1933 for(i = 0;i < n;i++)
1934 mag = fmax(fabs(hrir[i]), mag);
1935 mag *= 0.15;
1936 for(i = 0;i < n;i++)
1938 if(fabs(hrir[i]) >= mag)
1939 break;
1941 j = hData->mEvOffset[ei] + ai;
1942 hData->mHrtds[j] = Lerp(hData->mHrtds[j], ((double)i) / hData->mIrRate, f);
1945 // Calculate the magnitude response of an HRIR and average it with any
1946 // existing responses for its elevation and azimuth.
1947 static void AverageHrirMagnitude(const double *hrir, const double f, const uint ei, const uint ai, const HrirDataT *hData)
1949 double *re, *im;
1950 uint n, m, i, j;
1952 n = hData->mFftSize;
1953 re = CreateArray(n);
1954 im = CreateArray(n);
1955 for(i = 0;i < hData->mIrPoints;i++)
1957 re[i] = hrir[i];
1958 im[i] = 0.0;
1960 for(;i < n;i++)
1962 re[i] = 0.0;
1963 im[i] = 0.0;
1965 FftForward(n, re, im, re, im);
1966 MagnitudeResponse(n, re, im, re);
1967 m = 1 + (n / 2);
1968 j = (hData->mEvOffset[ei] + ai) * hData->mIrSize;
1969 for(i = 0;i < m;i++)
1970 hData->mHrirs[j+i] = Lerp(hData->mHrirs[j+i], re[i], f);
1971 DestroyArray(im);
1972 DestroyArray(re);
1975 /* Calculate the contribution of each HRIR to the diffuse-field average based
1976 * on the area of its surface patch. All patches are centered at the HRIR
1977 * coordinates on the unit sphere and are measured by solid angle.
1979 static void CalculateDfWeights(const HrirDataT *hData, double *weights)
1981 double evs, sum, ev, up_ev, down_ev, solidAngle;
1982 uint ei;
1984 evs = 90.0 / (hData->mEvCount - 1);
1985 sum = 0.0;
1986 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
1988 // For each elevation, calculate the upper and lower limits of the
1989 // patch band.
1990 ev = -90.0 + (ei * 2.0 * evs);
1991 if(ei < (hData->mEvCount - 1))
1992 up_ev = (ev + evs) * M_PI / 180.0;
1993 else
1994 up_ev = M_PI / 2.0;
1995 if(ei > 0)
1996 down_ev = (ev - evs) * M_PI / 180.0;
1997 else
1998 down_ev = -M_PI / 2.0;
1999 // Calculate the area of the patch band.
2000 solidAngle = 2.0 * M_PI * (sin(up_ev) - sin(down_ev));
2001 // Each weight is the area of one patch.
2002 weights[ei] = solidAngle / hData->mAzCount [ei];
2003 // Sum the total surface area covered by the HRIRs.
2004 sum += solidAngle;
2006 // Normalize the weights given the total surface coverage.
2007 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
2008 weights[ei] /= sum;
2011 /* Calculate the diffuse-field average from the given magnitude responses of
2012 * the HRIR set. Weighting can be applied to compensate for the varying
2013 * surface area covered by each HRIR. The final average can then be limited
2014 * by the specified magnitude range (in positive dB; 0.0 to skip).
2016 static void CalculateDiffuseFieldAverage(const HrirDataT *hData, const int weighted, const double limit, double *dfa)
2018 uint ei, ai, count, step, start, end, m, j, i;
2019 double *weights;
2021 weights = CreateArray(hData->mEvCount);
2022 if(weighted)
2024 // Use coverage weighting to calculate the average.
2025 CalculateDfWeights(hData, weights);
2027 else
2029 // If coverage weighting is not used, the weights still need to be
2030 // averaged by the number of HRIRs.
2031 count = 0;
2032 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
2033 count += hData->mAzCount [ei];
2034 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
2035 weights[ei] = 1.0 / count;
2037 ei = hData->mEvStart;
2038 ai = 0;
2039 step = hData->mIrSize;
2040 start = hData->mEvOffset[ei] * step;
2041 end = hData->mIrCount * step;
2042 m = 1 + (hData->mFftSize / 2);
2043 for(i = 0;i < m;i++)
2044 dfa[i] = 0.0;
2045 for(j = start;j < end;j += step)
2047 // Get the weight for this HRIR's contribution.
2048 double weight = weights[ei];
2049 // Add this HRIR's weighted power average to the total.
2050 for(i = 0;i < m;i++)
2051 dfa[i] += weight * hData->mHrirs[j+i] * hData->mHrirs[j+i];
2052 // Determine the next weight to use.
2053 ai++;
2054 if(ai >= hData->mAzCount[ei])
2056 ei++;
2057 ai = 0;
2060 // Finish the average calculation and keep it from being too small.
2061 for(i = 0;i < m;i++)
2062 dfa[i] = fmax(sqrt(dfa[i]), EPSILON);
2063 // Apply a limit to the magnitude range of the diffuse-field average if
2064 // desired.
2065 if(limit > 0.0)
2066 LimitMagnitudeResponse(hData->mFftSize, limit, dfa, dfa);
2067 DestroyArray(weights);
2070 // Perform diffuse-field equalization on the magnitude responses of the HRIR
2071 // set using the given average response.
2072 static void DiffuseFieldEqualize(const double *dfa, const HrirDataT *hData)
2074 uint step, start, end, m, j, i;
2076 step = hData->mIrSize;
2077 start = hData->mEvOffset[hData->mEvStart] * step;
2078 end = hData->mIrCount * step;
2079 m = 1 + (hData->mFftSize / 2);
2080 for(j = start;j < end;j += step)
2082 for(i = 0;i < m;i++)
2083 hData->mHrirs[j+i] /= dfa[i];
2087 // Perform minimum-phase reconstruction using the magnitude responses of the
2088 // HRIR set.
2089 static void ReconstructHrirs(const HrirDataT *hData)
2091 uint step, start, end, n, j, i;
2092 double *re, *im;
2094 step = hData->mIrSize;
2095 start = hData->mEvOffset[hData->mEvStart] * step;
2096 end = hData->mIrCount * step;
2097 n = hData->mFftSize;
2098 re = CreateArray(n);
2099 im = CreateArray(n);
2100 for(j = start;j < end;j += step)
2102 MinimumPhase(n, &hData->mHrirs[j], re, im);
2103 FftInverse(n, re, im, re, im);
2104 for(i = 0;i < hData->mIrPoints;i++)
2105 hData->mHrirs[j+i] = re[i];
2107 DestroyArray (im);
2108 DestroyArray (re);
2111 // Resamples the HRIRs for use at the given sampling rate.
2112 static void ResampleHrirs(const uint rate, HrirDataT *hData)
2114 uint n, step, start, end, j;
2115 ResamplerT rs;
2117 ResamplerSetup(&rs, hData->mIrRate, rate);
2118 n = hData->mIrPoints;
2119 step = hData->mIrSize;
2120 start = hData->mEvOffset[hData->mEvStart] * step;
2121 end = hData->mIrCount * step;
2122 for(j = start;j < end;j += step)
2123 ResamplerRun(&rs, n, &hData->mHrirs[j], n, &hData->mHrirs[j]);
2124 ResamplerClear(&rs);
2125 hData->mIrRate = rate;
2128 /* Given an elevation index and an azimuth, calculate the indices of the two
2129 * HRIRs that bound the coordinate along with a factor for calculating the
2130 * continous HRIR using interpolation.
2132 static void CalcAzIndices(const HrirDataT *hData, const uint ei, const double az, uint *j0, uint *j1, double *jf)
2134 double af;
2135 uint ai;
2137 af = ((2.0*M_PI) + az) * hData->mAzCount[ei] / (2.0*M_PI);
2138 ai = ((uint)af) % hData->mAzCount[ei];
2139 af -= floor(af);
2141 *j0 = hData->mEvOffset[ei] + ai;
2142 *j1 = hData->mEvOffset[ei] + ((ai+1) % hData->mAzCount [ei]);
2143 *jf = af;
2146 // Synthesize any missing onset timings at the bottom elevations. This just
2147 // blends between slightly exaggerated known onsets. Not an accurate model.
2148 static void SynthesizeOnsets(HrirDataT *hData)
2150 uint oi, e, a, j0, j1;
2151 double t, of, jf;
2153 oi = hData->mEvStart;
2154 t = 0.0;
2155 for(a = 0;a < hData->mAzCount[oi];a++)
2156 t += hData->mHrtds[hData->mEvOffset[oi] + a];
2157 hData->mHrtds[0] = 1.32e-4 + (t / hData->mAzCount[oi]);
2158 for(e = 1;e < hData->mEvStart;e++)
2160 of = ((double)e) / hData->mEvStart;
2161 for(a = 0;a < hData->mAzCount[e];a++)
2163 CalcAzIndices(hData, oi, a * 2.0 * M_PI / hData->mAzCount[e], &j0, &j1, &jf);
2164 hData->mHrtds[hData->mEvOffset[e] + a] = Lerp(hData->mHrtds[0], Lerp(hData->mHrtds[j0], hData->mHrtds[j1], jf), of);
2169 /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
2170 * now this just blends the lowest elevation HRIRs together and applies some
2171 * attenuation and high frequency damping. It is a simple, if inaccurate
2172 * model.
2174 static void SynthesizeHrirs (HrirDataT *hData)
2176 uint oi, a, e, step, n, i, j;
2177 double lp[4], s0, s1;
2178 double of, b;
2179 uint j0, j1;
2180 double jf;
2182 if(hData->mEvStart <= 0)
2183 return;
2184 step = hData->mIrSize;
2185 oi = hData->mEvStart;
2186 n = hData->mIrPoints;
2187 for(i = 0;i < n;i++)
2188 hData->mHrirs[i] = 0.0;
2189 for(a = 0;a < hData->mAzCount[oi];a++)
2191 j = (hData->mEvOffset[oi] + a) * step;
2192 for(i = 0;i < n;i++)
2193 hData->mHrirs[i] += hData->mHrirs[j+i] / hData->mAzCount[oi];
2195 for(e = 1;e < hData->mEvStart;e++)
2197 of = ((double)e) / hData->mEvStart;
2198 b = (1.0 - of) * (3.5e-6 * hData->mIrRate);
2199 for(a = 0;a < hData->mAzCount[e];a++)
2201 j = (hData->mEvOffset[e] + a) * step;
2202 CalcAzIndices(hData, oi, a * 2.0 * M_PI / hData->mAzCount[e], &j0, &j1, &jf);
2203 j0 *= step;
2204 j1 *= step;
2205 lp[0] = 0.0;
2206 lp[1] = 0.0;
2207 lp[2] = 0.0;
2208 lp[3] = 0.0;
2209 for(i = 0;i < n;i++)
2211 s0 = hData->mHrirs[i];
2212 s1 = Lerp(hData->mHrirs[j0+i], hData->mHrirs[j1+i], jf);
2213 s0 = Lerp(s0, s1, of);
2214 lp[0] = Lerp(s0, lp[0], b);
2215 lp[1] = Lerp(lp[0], lp[1], b);
2216 lp[2] = Lerp(lp[1], lp[2], b);
2217 lp[3] = Lerp(lp[2], lp[3], b);
2218 hData->mHrirs[j+i] = lp[3];
2222 b = 3.5e-6 * hData->mIrRate;
2223 lp[0] = 0.0;
2224 lp[1] = 0.0;
2225 lp[2] = 0.0;
2226 lp[3] = 0.0;
2227 for(i = 0;i < n;i++)
2229 s0 = hData->mHrirs[i];
2230 lp[0] = Lerp(s0, lp[0], b);
2231 lp[1] = Lerp(lp[0], lp[1], b);
2232 lp[2] = Lerp(lp[1], lp[2], b);
2233 lp[3] = Lerp(lp[2], lp[3], b);
2234 hData->mHrirs[i] = lp[3];
2236 hData->mEvStart = 0;
2239 // The following routines assume a full set of HRIRs for all elevations.
2241 // Normalize the HRIR set and slightly attenuate the result.
2242 static void NormalizeHrirs (const HrirDataT *hData)
2244 uint step, end, n, j, i;
2245 double maxLevel;
2247 step = hData->mIrSize;
2248 end = hData->mIrCount * step;
2249 n = hData->mIrPoints;
2250 maxLevel = 0.0;
2251 for(j = 0;j < end;j += step)
2253 for(i = 0;i < n;i++)
2254 maxLevel = fmax(fabs(hData->mHrirs[j+i]), maxLevel);
2256 maxLevel = 1.01 * maxLevel;
2257 for(j = 0;j < end;j += step)
2259 for(i = 0;i < n;i++)
2260 hData->mHrirs[j+i] /= maxLevel;
2264 // Calculate the left-ear time delay using a spherical head model.
2265 static double CalcLTD(const double ev, const double az, const double rad, const double dist)
2267 double azp, dlp, l, al;
2269 azp = asin(cos(ev) * sin(az));
2270 dlp = sqrt((dist*dist) + (rad*rad) + (2.0*dist*rad*sin(azp)));
2271 l = sqrt((dist*dist) - (rad*rad));
2272 al = (0.5 * M_PI) + azp;
2273 if(dlp > l)
2274 dlp = l + (rad * (al - acos(rad / dist)));
2275 return (dlp / 343.3);
2278 // Calculate the effective head-related time delays for each minimum-phase
2279 // HRIR.
2280 static void CalculateHrtds (const HeadModelT model, const double radius, HrirDataT *hData)
2282 double minHrtd, maxHrtd;
2283 uint e, a, j;
2284 double t;
2286 minHrtd = 1000.0;
2287 maxHrtd = -1000.0;
2288 for(e = 0;e < hData->mEvCount;e++)
2290 for(a = 0;a < hData->mAzCount[e];a++)
2292 j = hData->mEvOffset[e] + a;
2293 if(model == HM_DATASET)
2294 t = hData->mHrtds[j] * radius / hData->mRadius;
2295 else
2296 t = CalcLTD((-90.0 + (e * 180.0 / (hData->mEvCount - 1))) * M_PI / 180.0,
2297 (a * 360.0 / hData->mAzCount [e]) * M_PI / 180.0,
2298 radius, hData->mDistance);
2299 hData->mHrtds[j] = t;
2300 maxHrtd = fmax(t, maxHrtd);
2301 minHrtd = fmin(t, minHrtd);
2304 maxHrtd -= minHrtd;
2305 for(j = 0;j < hData->mIrCount;j++)
2306 hData->mHrtds[j] -= minHrtd;
2307 hData->mMaxHrtd = maxHrtd;
2311 // Process the data set definition to read and validate the data set metrics.
2312 static int ProcessMetrics(TokenReaderT *tr, const uint fftSize, const uint truncSize, HrirDataT *hData)
2314 int hasRate = 0, hasPoints = 0, hasAzimuths = 0;
2315 int hasRadius = 0, hasDistance = 0;
2316 char ident[MAX_IDENT_LEN+1];
2317 uint line, col;
2318 double fpVal;
2319 uint points;
2320 int intVal;
2322 while(!(hasRate && hasPoints && hasAzimuths && hasRadius && hasDistance))
2324 TrIndication(tr, & line, & col);
2325 if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
2326 return 0;
2327 if(strcasecmp(ident, "rate") == 0)
2329 if(hasRate)
2331 TrErrorAt(tr, line, col, "Redefinition of 'rate'.\n");
2332 return 0;
2334 if(!TrReadOperator(tr, "="))
2335 return 0;
2336 if(!TrReadInt(tr, MIN_RATE, MAX_RATE, &intVal))
2337 return 0;
2338 hData->mIrRate = (uint)intVal;
2339 hasRate = 1;
2341 else if(strcasecmp(ident, "points") == 0)
2343 if (hasPoints) {
2344 TrErrorAt(tr, line, col, "Redefinition of 'points'.\n");
2345 return 0;
2347 if(!TrReadOperator(tr, "="))
2348 return 0;
2349 TrIndication(tr, &line, &col);
2350 if(!TrReadInt(tr, MIN_POINTS, MAX_POINTS, &intVal))
2351 return 0;
2352 points = (uint)intVal;
2353 if(fftSize > 0 && points > fftSize)
2355 TrErrorAt(tr, line, col, "Value exceeds the overridden FFT size.\n");
2356 return 0;
2358 if(points < truncSize)
2360 TrErrorAt(tr, line, col, "Value is below the truncation size.\n");
2361 return 0;
2363 hData->mIrPoints = points;
2364 hData->mFftSize = fftSize;
2365 if(fftSize <= 0)
2367 points = 1;
2368 while(points < (4 * hData->mIrPoints))
2369 points <<= 1;
2370 hData->mFftSize = points;
2371 hData->mIrSize = 1 + (points / 2);
2373 else
2375 hData->mFftSize = fftSize;
2376 hData->mIrSize = 1 + (fftSize / 2);
2377 if(points > hData->mIrSize)
2378 hData->mIrSize = points;
2380 hasPoints = 1;
2382 else if(strcasecmp(ident, "azimuths") == 0)
2384 if(hasAzimuths)
2386 TrErrorAt(tr, line, col, "Redefinition of 'azimuths'.\n");
2387 return 0;
2389 if(!TrReadOperator(tr, "="))
2390 return 0;
2391 hData->mIrCount = 0;
2392 hData->mEvCount = 0;
2393 hData->mEvOffset[0] = 0;
2394 for(;;)
2396 if(!TrReadInt(tr, MIN_AZ_COUNT, MAX_AZ_COUNT, &intVal))
2397 return 0;
2398 hData->mAzCount[hData->mEvCount] = (uint)intVal;
2399 hData->mIrCount += (uint)intVal;
2400 hData->mEvCount ++;
2401 if(!TrIsOperator(tr, ","))
2402 break;
2403 if(hData->mEvCount >= MAX_EV_COUNT)
2405 TrError(tr, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT);
2406 return 0;
2408 hData->mEvOffset[hData->mEvCount] = hData->mEvOffset[hData->mEvCount - 1] + ((uint)intVal);
2409 TrReadOperator(tr, ",");
2411 if(hData->mEvCount < MIN_EV_COUNT)
2413 TrErrorAt(tr, line, col, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT);
2414 return 0;
2416 hasAzimuths = 1;
2418 else if(strcasecmp(ident, "radius") == 0)
2420 if(hasRadius)
2422 TrErrorAt(tr, line, col, "Redefinition of 'radius'.\n");
2423 return 0;
2425 if(!TrReadOperator(tr, "="))
2426 return 0;
2427 if(!TrReadFloat(tr, MIN_RADIUS, MAX_RADIUS, &fpVal))
2428 return 0;
2429 hData->mRadius = fpVal;
2430 hasRadius = 1;
2432 else if(strcasecmp(ident, "distance") == 0)
2434 if(hasDistance)
2436 TrErrorAt(tr, line, col, "Redefinition of 'distance'.\n");
2437 return 0;
2439 if(!TrReadOperator(tr, "="))
2440 return 0;
2441 if(!TrReadFloat(tr, MIN_DISTANCE, MAX_DISTANCE, & fpVal))
2442 return 0;
2443 hData->mDistance = fpVal;
2444 hasDistance = 1;
2446 else
2448 TrErrorAt(tr, line, col, "Expected a metric name.\n");
2449 return 0;
2451 TrSkipWhitespace (tr);
2453 return 1;
2456 // Parse an index pair from the data set definition.
2457 static int ReadIndexPair(TokenReaderT *tr, const HrirDataT *hData, uint *ei, uint *ai)
2459 int intVal;
2460 if(!TrReadInt(tr, 0, (int)hData->mEvCount, &intVal))
2461 return 0;
2462 *ei = (uint)intVal;
2463 if(!TrReadOperator(tr, ","))
2464 return 0;
2465 if(!TrReadInt(tr, 0, (int)hData->mAzCount[*ei], &intVal))
2466 return 0;
2467 *ai = (uint)intVal;
2468 return 1;
2471 // Match the source format from a given identifier.
2472 static SourceFormatT MatchSourceFormat(const char *ident)
2474 if(strcasecmp(ident, "wave") == 0)
2475 return SF_WAVE;
2476 if(strcasecmp(ident, "bin_le") == 0)
2477 return SF_BIN_LE;
2478 if(strcasecmp(ident, "bin_be") == 0)
2479 return SF_BIN_BE;
2480 if(strcasecmp(ident, "ascii") == 0)
2481 return SF_ASCII;
2482 return SF_NONE;
2485 // Match the source element type from a given identifier.
2486 static ElementTypeT MatchElementType(const char *ident)
2488 if(strcasecmp(ident, "int") == 0)
2489 return ET_INT;
2490 if(strcasecmp(ident, "fp") == 0)
2491 return ET_FP;
2492 return ET_NONE;
2495 // Parse and validate a source reference from the data set definition.
2496 static int ReadSourceRef(TokenReaderT *tr, SourceRefT *src)
2498 char ident[MAX_IDENT_LEN+1];
2499 uint line, col;
2500 int intVal;
2502 TrIndication(tr, &line, &col);
2503 if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
2504 return 0;
2505 src->mFormat = MatchSourceFormat(ident);
2506 if(src->mFormat == SF_NONE)
2508 TrErrorAt(tr, line, col, "Expected a source format.\n");
2509 return 0;
2511 if(!TrReadOperator(tr, "("))
2512 return 0;
2513 if(src->mFormat == SF_WAVE)
2515 if(!TrReadInt(tr, 0, MAX_WAVE_CHANNELS, &intVal))
2516 return 0;
2517 src->mType = ET_NONE;
2518 src->mSize = 0;
2519 src->mBits = 0;
2520 src->mChannel = (uint)intVal;
2521 src->mSkip = 0;
2523 else
2525 TrIndication(tr, &line, &col);
2526 if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
2527 return 0;
2528 src->mType = MatchElementType(ident);
2529 if(src->mType == ET_NONE)
2531 TrErrorAt(tr, line, col, "Expected a source element type.\n");
2532 return 0;
2534 if(src->mFormat == SF_BIN_LE || src->mFormat == SF_BIN_BE)
2536 if(!TrReadOperator(tr, ","))
2537 return 0;
2538 if(src->mType == ET_INT)
2540 if(!TrReadInt(tr, MIN_BIN_SIZE, MAX_BIN_SIZE, &intVal))
2541 return 0;
2542 src->mSize = (uint)intVal;
2543 if(!TrIsOperator(tr, ","))
2544 src->mBits = (int)(8*src->mSize);
2545 else
2547 TrReadOperator(tr, ",");
2548 TrIndication(tr, &line, &col);
2549 if(!TrReadInt(tr, -2147483647-1, 2147483647, &intVal))
2550 return 0;
2551 if(abs(intVal) < MIN_BIN_BITS || ((uint)abs(intVal)) > (8*src->mSize))
2553 TrErrorAt(tr, line, col, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS, 8*src->mSize);
2554 return 0;
2556 src->mBits = intVal;
2559 else
2561 TrIndication(tr, &line, &col);
2562 if(!TrReadInt(tr, -2147483647-1, 2147483647, &intVal))
2563 return 0;
2564 if(intVal != 4 && intVal != 8)
2566 TrErrorAt(tr, line, col, "Expected a value of 4 or 8.\n");
2567 return 0;
2569 src->mSize = (uint)intVal;
2570 src->mBits = 0;
2573 else if(src->mFormat == SF_ASCII && src->mType == ET_INT)
2575 if(!TrReadOperator(tr, ","))
2576 return 0;
2577 if(!TrReadInt(tr, MIN_ASCII_BITS, MAX_ASCII_BITS, &intVal))
2578 return 0;
2579 src->mSize = 0;
2580 src->mBits = intVal;
2582 else
2584 src->mSize = 0;
2585 src->mBits = 0;
2588 if(!TrIsOperator(tr, ";"))
2589 src->mSkip = 0;
2590 else
2592 TrReadOperator(tr, ";");
2593 if(!TrReadInt (tr, 0, 0x7FFFFFFF, &intVal))
2594 return 0;
2595 src->mSkip = (uint)intVal;
2598 if(!TrReadOperator(tr, ")"))
2599 return 0;
2600 if(TrIsOperator(tr, "@"))
2602 TrReadOperator(tr, "@");
2603 if(!TrReadInt(tr, 0, 0x7FFFFFFF, &intVal))
2604 return 0;
2605 src->mOffset = (uint)intVal;
2607 else
2608 src->mOffset = 0;
2609 if(!TrReadOperator(tr, ":"))
2610 return 0;
2611 if(!TrReadString(tr, MAX_PATH_LEN, src->mPath))
2612 return 0;
2613 return 1;
2616 // Process the list of sources in the data set definition.
2617 static int ProcessSources(const HeadModelT model, TokenReaderT *tr, HrirDataT *hData)
2619 uint *setCount, *setFlag;
2620 uint line, col, ei, ai;
2621 SourceRefT src;
2622 double factor;
2623 double *hrir;
2625 setCount = (uint*)calloc(hData->mEvCount, sizeof(uint));
2626 setFlag = (uint*)calloc(hData->mIrCount, sizeof(uint));
2627 hrir = CreateArray(hData->mIrPoints);
2628 while(TrIsOperator(tr, "["))
2630 TrIndication(tr, & line, & col);
2631 TrReadOperator(tr, "[");
2632 if(!ReadIndexPair(tr, hData, &ei, &ai))
2633 goto error;
2634 if(!TrReadOperator(tr, "]"))
2635 goto error;
2636 if(setFlag[hData->mEvOffset[ei] + ai])
2638 TrErrorAt(tr, line, col, "Redefinition of source.\n");
2639 goto error;
2641 if(!TrReadOperator(tr, "="))
2642 goto error;
2644 factor = 1.0;
2645 for(;;)
2647 if(!ReadSourceRef(tr, &src))
2648 goto error;
2649 if(!LoadSource(&src, hData->mIrRate, hData->mIrPoints, hrir))
2650 goto error;
2652 if(model == HM_DATASET)
2653 AverageHrirOnset(hrir, 1.0 / factor, ei, ai, hData);
2654 AverageHrirMagnitude(hrir, 1.0 / factor, ei, ai, hData);
2655 factor += 1.0;
2656 if(!TrIsOperator(tr, "+"))
2657 break;
2658 TrReadOperator(tr, "+");
2660 setFlag[hData->mEvOffset[ei] + ai] = 1;
2661 setCount[ei]++;
2664 ei = 0;
2665 while(ei < hData->mEvCount && setCount[ei] < 1)
2666 ei++;
2667 if(ei < hData->mEvCount)
2669 hData->mEvStart = ei;
2670 while(ei < hData->mEvCount && setCount[ei] == hData->mAzCount[ei])
2671 ei++;
2672 if(ei >= hData->mEvCount)
2674 if(!TrLoad(tr))
2676 DestroyArray(hrir);
2677 free(setFlag);
2678 free(setCount);
2679 return 1;
2681 TrError(tr, "Errant data at end of source list.\n");
2683 else
2684 TrError(tr, "Missing sources for elevation index %d.\n", ei);
2686 else
2687 TrError(tr, "Missing source references.\n");
2689 error:
2690 DestroyArray(hrir);
2691 free(setFlag);
2692 free(setCount);
2693 return 0;
2696 /* Parse the data set definition and process the source data, storing the
2697 * resulting data set as desired. If the input name is NULL it will read
2698 * from standard input.
2700 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)
2702 char rateStr[8+1], expName[MAX_PATH_LEN];
2703 TokenReaderT tr;
2704 HrirDataT hData;
2705 double *dfa;
2706 FILE *fp;
2708 hData.mIrRate = 0;
2709 hData.mIrPoints = 0;
2710 hData.mFftSize = 0;
2711 hData.mIrSize = 0;
2712 hData.mIrCount = 0;
2713 hData.mEvCount = 0;
2714 hData.mRadius = 0;
2715 hData.mDistance = 0;
2716 fprintf(stdout, "Reading HRIR definition...\n");
2717 if(inName != NULL)
2719 fp = fopen(inName, "r");
2720 if(fp == NULL)
2722 fprintf(stderr, "Error: Could not open definition file '%s'\n", inName);
2723 return 0;
2725 TrSetup(fp, inName, &tr);
2727 else
2729 fp = stdin;
2730 TrSetup(fp, "<stdin>", &tr);
2732 if(!ProcessMetrics(&tr, fftSize, truncSize, &hData))
2734 if(inName != NULL)
2735 fclose(fp);
2736 return 0;
2738 hData.mHrirs = CreateArray(hData.mIrCount * hData . mIrSize);
2739 hData.mHrtds = CreateArray(hData.mIrCount);
2740 if(!ProcessSources(model, &tr, &hData))
2742 DestroyArray(hData.mHrtds);
2743 DestroyArray(hData.mHrirs);
2744 if(inName != NULL)
2745 fclose(fp);
2746 return 0;
2748 if(inName != NULL)
2749 fclose(fp);
2750 if(equalize)
2752 dfa = CreateArray(1 + (hData.mFftSize/2));
2753 fprintf(stdout, "Calculating diffuse-field average...\n");
2754 CalculateDiffuseFieldAverage(&hData, surface, limit, dfa);
2755 fprintf(stdout, "Performing diffuse-field equalization...\n");
2756 DiffuseFieldEqualize(dfa, &hData);
2757 DestroyArray(dfa);
2759 fprintf(stdout, "Performing minimum phase reconstruction...\n");
2760 ReconstructHrirs(&hData);
2761 if(outRate != 0 && outRate != hData.mIrRate)
2763 fprintf(stdout, "Resampling HRIRs...\n");
2764 ResampleHrirs(outRate, &hData);
2766 fprintf(stdout, "Truncating minimum-phase HRIRs...\n");
2767 hData.mIrPoints = truncSize;
2768 fprintf(stdout, "Synthesizing missing elevations...\n");
2769 if(model == HM_DATASET)
2770 SynthesizeOnsets(&hData);
2771 SynthesizeHrirs(&hData);
2772 fprintf(stdout, "Normalizing final HRIRs...\n");
2773 NormalizeHrirs(&hData);
2774 fprintf(stdout, "Calculating impulse delays...\n");
2775 CalculateHrtds(model, (radius > DEFAULT_CUSTOM_RADIUS) ? radius : hData.mRadius, &hData);
2776 snprintf(rateStr, 8, "%u", hData.mIrRate);
2777 StrSubst(outName, "%r", rateStr, MAX_PATH_LEN, expName);
2778 switch(outFormat)
2780 case OF_MHR:
2781 fprintf(stdout, "Creating MHR data set file...\n");
2782 if(!StoreMhr(&hData, expName))
2784 DestroyArray(hData.mHrtds);
2785 DestroyArray(hData.mHrirs);
2786 return 0;
2788 break;
2789 default:
2790 break;
2792 DestroyArray(hData.mHrtds);
2793 DestroyArray(hData.mHrirs);
2794 return 1;
2797 static void PrintHelp(const char *argv0, FILE *ofile)
2799 fprintf(ofile, "Usage: %s <command> [<option>...]\n\n", argv0);
2800 fprintf(ofile, "Commands:\n");
2801 fprintf(ofile, " -m, --make-mhr Makes an OpenAL Soft compatible HRTF data set.\n");
2802 fprintf(ofile, " Defaults output to: ./oalsoft_hrtf_%%r.mhr\n");
2803 fprintf(ofile, " -h, --help Displays this help information.\n\n");
2804 fprintf(ofile, "Options:\n");
2805 fprintf(ofile, " -r=<rate> Change the data set sample rate to the specified value and\n");
2806 fprintf(ofile, " resample the HRIRs accordingly.\n");
2807 fprintf(ofile, " -f=<points> Override the FFT window size (defaults to the first power-\n");
2808 fprintf(ofile, " of-two that fits four times the number of HRIR points).\n");
2809 fprintf(ofile, " -e={on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE ? "on" : "off"));
2810 fprintf(ofile, " -s={on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE ? "on" : "off"));
2811 fprintf(ofile, " -l={<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
2812 fprintf(ofile, " average (default: %.2f).\n", DEFAULT_LIMIT);
2813 fprintf(ofile, " -w=<points> Specify the size of the truncation window that's applied\n");
2814 fprintf(ofile, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE);
2815 fprintf(ofile, " -d={dataset| Specify the model used for calculating the head-delay timing\n");
2816 fprintf(ofile, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL == HM_DATASET) ? "dataset" : "sphere"));
2817 fprintf(ofile, " -c=<size> Use a customized head radius measured ear-to-ear in meters.\n");
2818 fprintf(ofile, " -i=<filename> Specify an HRIR definition file to use (defaults to stdin).\n");
2819 fprintf(ofile, " -o=<filename> Specify an output file. Overrides command-selected default.\n");
2820 fprintf(ofile, " Use of '%%r' will be substituted with the data set sample rate.\n");
2823 // Standard command line dispatch.
2824 int main(const int argc, const char *argv[])
2826 const char *inName = NULL, *outName = NULL;
2827 OutputFormatT outFormat;
2828 uint outRate, fftSize;
2829 int equalize, surface;
2830 char *end = NULL;
2831 HeadModelT model;
2832 uint truncSize;
2833 double radius;
2834 double limit;
2835 int argi;
2837 if(argc < 2 || strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0)
2839 fprintf(stdout, "HRTF Processing and Composition Utility\n\n");
2840 PrintHelp(argv[0], stdout);
2841 return 0;
2844 if(strcmp(argv[1], "--make-mhr") == 0 || strcmp(argv[1], "-m") == 0)
2846 outName = "./oalsoft_hrtf_%r.mhr";
2847 outFormat = OF_MHR;
2849 else
2851 fprintf(stderr, "Error: Invalid command '%s'.\n\n", argv[1]);
2852 PrintHelp(argv[0], stderr);
2853 return -1;
2856 outRate = 0;
2857 fftSize = 0;
2858 equalize = DEFAULT_EQUALIZE;
2859 surface = DEFAULT_SURFACE;
2860 limit = DEFAULT_LIMIT;
2861 truncSize = DEFAULT_TRUNCSIZE;
2862 model = DEFAULT_HEAD_MODEL;
2863 radius = DEFAULT_CUSTOM_RADIUS;
2865 argi = 2;
2866 while(argi < argc)
2868 if(strncmp(argv[argi], "-r=", 3) == 0)
2870 outRate = strtoul(&argv[argi][3], &end, 10);
2871 if(end[0] != '\0' || outRate < MIN_RATE || outRate > MAX_RATE)
2873 fprintf(stderr, "Error: Expected a value from %u to %u for '-r'.\n", MIN_RATE, MAX_RATE);
2874 return -1;
2877 else if(strncmp(argv[argi], "-f=", 3) == 0)
2879 fftSize = strtoul(&argv[argi][3], &end, 10);
2880 if(end[0] != '\0' || (fftSize&(fftSize-1)) || fftSize < MIN_FFTSIZE || fftSize > MAX_FFTSIZE)
2882 fprintf(stderr, "Error: Expected a power-of-two value from %u to %u for '-f'.\n", MIN_FFTSIZE, MAX_FFTSIZE);
2883 return -1;
2886 else if(strncmp(argv[argi], "-e=", 3) == 0)
2888 if(strcmp(&argv[argi][3], "on") == 0)
2889 equalize = 1;
2890 else if(strcmp(&argv[argi][3], "off") == 0)
2891 equalize = 0;
2892 else
2894 fprintf(stderr, "Error: Expected 'on' or 'off' for '-e'.\n");
2895 return -1;
2898 else if(strncmp(argv[argi], "-s=", 3) == 0)
2900 if(strcmp(&argv[argi][3], "on") == 0)
2901 surface = 1;
2902 else if(strcmp(&argv[argi][3], "off") == 0)
2903 surface = 0;
2904 else
2906 fprintf(stderr, "Error: Expected 'on' or 'off' for '-s'.\n");
2907 return -1;
2910 else if(strncmp(argv[argi], "-l=", 3) == 0)
2912 if(strcmp(&argv[argi][3], "none") == 0)
2913 limit = 0.0;
2914 else
2916 limit = strtod(&argv[argi] [3], &end);
2917 if(end[0] != '\0' || limit < MIN_LIMIT || limit > MAX_LIMIT)
2919 fprintf(stderr, "Error: Expected 'none' or a value from %.2f to %.2f for '-l'.\n", MIN_LIMIT, MAX_LIMIT);
2920 return -1;
2924 else if(strncmp(argv[argi], "-w=", 3) == 0)
2926 truncSize = strtoul(&argv[argi][3], &end, 10);
2927 if(end[0] != '\0' || truncSize < MIN_TRUNCSIZE || truncSize > MAX_TRUNCSIZE || (truncSize%MOD_TRUNCSIZE))
2929 fprintf(stderr, "Error: Expected a value from %u to %u in multiples of %u for '-w'.\n", MIN_TRUNCSIZE, MAX_TRUNCSIZE, MOD_TRUNCSIZE);
2930 return -1;
2933 else if(strncmp(argv[argi], "-d=", 3) == 0)
2935 if(strcmp(&argv[argi][3], "dataset") == 0)
2936 model = HM_DATASET;
2937 else if(strcmp(&argv[argi][3], "sphere") == 0)
2938 model = HM_SPHERE;
2939 else
2941 fprintf(stderr, "Error: Expected 'dataset' or 'sphere' for '-d'.\n");
2942 return -1;
2945 else if(strncmp(argv[argi], "-c=", 3) == 0)
2947 radius = strtod(&argv[argi][3], &end);
2948 if(end[0] != '\0' || radius < MIN_CUSTOM_RADIUS || radius > MAX_CUSTOM_RADIUS)
2950 fprintf(stderr, "Error: Expected a value from %.2f to %.2f for '-c'.\n", MIN_CUSTOM_RADIUS, MAX_CUSTOM_RADIUS);
2951 return -1;
2954 else if(strncmp(argv[argi], "-i=", 3) == 0)
2955 inName = &argv[argi][3];
2956 else if(strncmp(argv[argi], "-o=", 3) == 0)
2957 outName = &argv[argi][3];
2958 else
2960 fprintf(stderr, "Error: Invalid option '%s'.\n", argv[argi]);
2961 return -1;
2963 argi++;
2965 if(!ProcessDefinition(inName, outRate, fftSize, equalize, surface, limit, truncSize, model, radius, outFormat, outName))
2966 return -1;
2967 fprintf(stdout, "Operation completed.\n");
2968 return 0;