Replace makehrtf's dither
[openal-soft.git] / utils / makehrtf.c
blob259b717fb4abdba08fbcef3ed6c36536205e9923
1 /*
2 * HRTF utility for producing and demonstrating the process of creating an
3 * OpenAL Soft compatible HRIR data set.
5 * Copyright (C) 2011-2017 Christopher Fitzgerald
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Or visit: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
23 * --------------------------------------------------------------------------
25 * A big thanks goes out to all those whose work done in the field of
26 * binaural sound synthesis using measured HRTFs makes this utility and the
27 * OpenAL Soft implementation possible.
29 * The algorithm for diffuse-field equalization was adapted from the work
30 * done by Rio Emmanuel and Larcher Veronique of IRCAM and Bill Gardner of
31 * MIT Media Laboratory. It operates as follows:
33 * 1. Take the FFT of each HRIR and only keep the magnitude responses.
34 * 2. Calculate the diffuse-field power-average of all HRIRs weighted by
35 * their contribution to the total surface area covered by their
36 * measurement.
37 * 3. Take the diffuse-field average and limit its magnitude range.
38 * 4. Equalize the responses by using the inverse of the diffuse-field
39 * average.
40 * 5. Reconstruct the minimum-phase responses.
41 * 5. Zero the DC component.
42 * 6. IFFT the result and truncate to the desired-length minimum-phase FIR.
44 * The spherical head algorithm for calculating propagation delay was adapted
45 * from the paper:
47 * Modeling Interaural Time Difference Assuming a Spherical Head
48 * Joel David Miller
49 * Music 150, Musical Acoustics, Stanford University
50 * December 2, 2001
52 * The formulae for calculating the Kaiser window metrics are from the
53 * the textbook:
55 * Discrete-Time Signal Processing
56 * Alan V. Oppenheim and Ronald W. Schafer
57 * Prentice-Hall Signal Processing Series
58 * 1999
61 #include "config.h"
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <stdarg.h>
66 #include <string.h>
67 #include <limits.h>
68 #include <ctype.h>
69 #include <math.h>
70 #ifdef HAVE_STRINGS_H
71 #include <strings.h>
72 #endif
74 // Rely (if naively) on OpenAL's header for the types used for serialization.
75 #include "AL/al.h"
76 #include "AL/alext.h"
78 #ifndef M_PI
79 #define M_PI (3.14159265358979323846)
80 #endif
82 #ifndef HUGE_VAL
83 #define HUGE_VAL (1.0 / 0.0)
84 #endif
86 // The epsilon used to maintain signal stability.
87 #define EPSILON (1e-9)
89 // Constants for accessing the token reader's ring buffer.
90 #define TR_RING_BITS (16)
91 #define TR_RING_SIZE (1 << TR_RING_BITS)
92 #define TR_RING_MASK (TR_RING_SIZE - 1)
94 // The token reader's load interval in bytes.
95 #define TR_LOAD_SIZE (TR_RING_SIZE >> 2)
97 // The maximum identifier length used when processing the data set
98 // definition.
99 #define MAX_IDENT_LEN (16)
101 // The maximum path length used when processing filenames.
102 #define MAX_PATH_LEN (256)
104 // The limits for the sample 'rate' metric in the data set definition and for
105 // resampling.
106 #define MIN_RATE (32000)
107 #define MAX_RATE (96000)
109 // The limits for the HRIR 'points' metric in the data set definition.
110 #define MIN_POINTS (16)
111 #define MAX_POINTS (8192)
113 // The limits to the number of 'azimuths' listed in the data set definition.
114 #define MIN_EV_COUNT (5)
115 #define MAX_EV_COUNT (128)
117 // The limits for each of the 'azimuths' listed in the data set definition.
118 #define MIN_AZ_COUNT (1)
119 #define MAX_AZ_COUNT (128)
121 // The limits for the listener's head 'radius' in the data set definition.
122 #define MIN_RADIUS (0.05)
123 #define MAX_RADIUS (0.15)
125 // The limits for the 'distance' from source to listener in the definition
126 // file.
127 #define MIN_DISTANCE (0.5)
128 #define MAX_DISTANCE (2.5)
130 // The maximum number of channels that can be addressed for a WAVE file
131 // source listed in the data set definition.
132 #define MAX_WAVE_CHANNELS (65535)
134 // The limits to the byte size for a binary source listed in the definition
135 // file.
136 #define MIN_BIN_SIZE (2)
137 #define MAX_BIN_SIZE (4)
139 // The minimum number of significant bits for binary sources listed in the
140 // data set definition. The maximum is calculated from the byte size.
141 #define MIN_BIN_BITS (16)
143 // The limits to the number of significant bits for an ASCII source listed in
144 // the data set definition.
145 #define MIN_ASCII_BITS (16)
146 #define MAX_ASCII_BITS (32)
148 // The limits to the FFT window size override on the command line.
149 #define MIN_FFTSIZE (65536)
150 #define MAX_FFTSIZE (131072)
152 // The limits to the equalization range limit on the command line.
153 #define MIN_LIMIT (2.0)
154 #define MAX_LIMIT (120.0)
156 // The limits to the truncation window size on the command line.
157 #define MIN_TRUNCSIZE (16)
158 #define MAX_TRUNCSIZE (512)
160 // The limits to the custom head radius on the command line.
161 #define MIN_CUSTOM_RADIUS (0.05)
162 #define MAX_CUSTOM_RADIUS (0.15)
164 // The truncation window size must be a multiple of the below value to allow
165 // for vectorized convolution.
166 #define MOD_TRUNCSIZE (8)
168 // The defaults for the command line options.
169 #define DEFAULT_FFTSIZE (65536)
170 #define DEFAULT_EQUALIZE (1)
171 #define DEFAULT_SURFACE (1)
172 #define DEFAULT_LIMIT (24.0)
173 #define DEFAULT_TRUNCSIZE (32)
174 #define DEFAULT_HEAD_MODEL (HM_DATASET)
175 #define DEFAULT_CUSTOM_RADIUS (0.0)
177 // The four-character-codes for RIFF/RIFX WAVE file chunks.
178 #define FOURCC_RIFF (0x46464952) // 'RIFF'
179 #define FOURCC_RIFX (0x58464952) // 'RIFX'
180 #define FOURCC_WAVE (0x45564157) // 'WAVE'
181 #define FOURCC_FMT (0x20746D66) // 'fmt '
182 #define FOURCC_DATA (0x61746164) // 'data'
183 #define FOURCC_LIST (0x5453494C) // 'LIST'
184 #define FOURCC_WAVL (0x6C766177) // 'wavl'
185 #define FOURCC_SLNT (0x746E6C73) // 'slnt'
187 // The supported wave formats.
188 #define WAVE_FORMAT_PCM (0x0001)
189 #define WAVE_FORMAT_IEEE_FLOAT (0x0003)
190 #define WAVE_FORMAT_EXTENSIBLE (0xFFFE)
192 // The maximum propagation delay value supported by OpenAL Soft.
193 #define MAX_HRTD (63.0)
195 // The OpenAL Soft HRTF format marker. It stands for minimum-phase head
196 // response protocol 01.
197 #define MHR_FORMAT ("MinPHR01")
199 // Byte order for the serialization routines.
200 typedef enum ByteOrderT {
201 BO_NONE,
202 BO_LITTLE,
203 BO_BIG
204 } ByteOrderT;
206 // Source format for the references listed in the data set definition.
207 typedef enum SourceFormatT {
208 SF_NONE,
209 SF_WAVE, // RIFF/RIFX WAVE file.
210 SF_BIN_LE, // Little-endian binary file.
211 SF_BIN_BE, // Big-endian binary file.
212 SF_ASCII // ASCII text file.
213 } SourceFormatT;
215 // Element types for the references listed in the data set definition.
216 typedef enum ElementTypeT {
217 ET_NONE,
218 ET_INT, // Integer elements.
219 ET_FP // Floating-point elements.
220 } ElementTypeT;
222 // Head model used for calculating the impulse delays.
223 typedef enum HeadModelT {
224 HM_NONE,
225 HM_DATASET, // Measure the onset from the dataset.
226 HM_SPHERE // Calculate the onset using a spherical head model.
227 } HeadModelT;
229 // Desired output format from the command line.
230 typedef enum OutputFormatT {
231 OF_NONE,
232 OF_MHR // OpenAL Soft MHR data set file.
233 } OutputFormatT;
235 // Unsigned integer type.
236 typedef unsigned int uint;
238 // Serialization types. The trailing digit indicates the number of bits.
239 typedef ALubyte uint8;
240 typedef ALint int32;
241 typedef ALuint uint32;
242 typedef ALuint64SOFT uint64;
244 // Token reader state for parsing the data set definition.
245 typedef struct TokenReaderT {
246 FILE *mFile;
247 const char *mName;
248 uint mLine;
249 uint mColumn;
250 char mRing[TR_RING_SIZE];
251 size_t mIn;
252 size_t mOut;
253 } TokenReaderT;
255 // Source reference state used when loading sources.
256 typedef struct SourceRefT {
257 SourceFormatT mFormat;
258 ElementTypeT mType;
259 uint mSize;
260 int mBits;
261 uint mChannel;
262 uint mSkip;
263 uint mOffset;
264 char mPath[MAX_PATH_LEN+1];
265 } SourceRefT;
267 // The HRIR metrics and data set used when loading, processing, and storing
268 // the resulting HRTF.
269 typedef struct HrirDataT {
270 uint mIrRate;
271 uint mIrCount;
272 uint mIrSize;
273 uint mIrPoints;
274 uint mFftSize;
275 uint mEvCount;
276 uint mEvStart;
277 uint mAzCount[MAX_EV_COUNT];
278 uint mEvOffset[MAX_EV_COUNT];
279 double mRadius;
280 double mDistance;
281 double *mHrirs;
282 double *mHrtds;
283 double mMaxHrtd;
284 } HrirDataT;
286 // The resampler metrics and FIR filter.
287 typedef struct ResamplerT {
288 uint mP, mQ, mM, mL;
289 double *mF;
290 } ResamplerT;
293 /*****************************
294 *** Token reader routines ***
295 *****************************/
297 /* Whitespace is not significant. It can process tokens as identifiers, numbers
298 * (integer and floating-point), strings, and operators. Strings must be
299 * encapsulated by double-quotes and cannot span multiple lines.
302 // Setup the reader on the given file. The filename can be NULL if no error
303 // output is desired.
304 static void TrSetup(FILE *fp, const char *filename, TokenReaderT *tr)
306 const char *name = NULL;
308 if(filename)
310 const char *slash = strrchr(filename, '/');
311 if(slash)
313 const char *bslash = strrchr(slash+1, '\\');
314 if(bslash) name = bslash+1;
315 else name = slash+1;
317 else
319 const char *bslash = strrchr(filename, '\\');
320 if(bslash) name = bslash+1;
321 else name = filename;
325 tr->mFile = fp;
326 tr->mName = name;
327 tr->mLine = 1;
328 tr->mColumn = 1;
329 tr->mIn = 0;
330 tr->mOut = 0;
333 // Prime the reader's ring buffer, and return a result indicating that there
334 // is text to process.
335 static int TrLoad(TokenReaderT *tr)
337 size_t toLoad, in, count;
339 toLoad = TR_RING_SIZE - (tr->mIn - tr->mOut);
340 if(toLoad >= TR_LOAD_SIZE && !feof(tr->mFile))
342 // Load TR_LOAD_SIZE (or less if at the end of the file) per read.
343 toLoad = TR_LOAD_SIZE;
344 in = tr->mIn&TR_RING_MASK;
345 count = TR_RING_SIZE - in;
346 if(count < toLoad)
348 tr->mIn += fread(&tr->mRing[in], 1, count, tr->mFile);
349 tr->mIn += fread(&tr->mRing[0], 1, toLoad-count, tr->mFile);
351 else
352 tr->mIn += fread(&tr->mRing[in], 1, toLoad, tr->mFile);
354 if(tr->mOut >= TR_RING_SIZE)
356 tr->mOut -= TR_RING_SIZE;
357 tr->mIn -= TR_RING_SIZE;
360 if(tr->mIn > tr->mOut)
361 return 1;
362 return 0;
365 // Error display routine. Only displays when the base name is not NULL.
366 static void TrErrorVA(const TokenReaderT *tr, uint line, uint column, const char *format, va_list argPtr)
368 if(!tr->mName)
369 return;
370 fprintf(stderr, "Error (%s:%u:%u): ", tr->mName, line, column);
371 vfprintf(stderr, format, argPtr);
374 // Used to display an error at a saved line/column.
375 static void TrErrorAt(const TokenReaderT *tr, uint line, uint column, const char *format, ...)
377 va_list argPtr;
379 va_start(argPtr, format);
380 TrErrorVA(tr, line, column, format, argPtr);
381 va_end(argPtr);
384 // Used to display an error at the current line/column.
385 static void TrError(const TokenReaderT *tr, const char *format, ...)
387 va_list argPtr;
389 va_start(argPtr, format);
390 TrErrorVA(tr, tr->mLine, tr->mColumn, format, argPtr);
391 va_end(argPtr);
394 // Skips to the next line.
395 static void TrSkipLine(TokenReaderT *tr)
397 char ch;
399 while(TrLoad(tr))
401 ch = tr->mRing[tr->mOut&TR_RING_MASK];
402 tr->mOut++;
403 if(ch == '\n')
405 tr->mLine++;
406 tr->mColumn = 1;
407 break;
409 tr->mColumn ++;
413 // Skips to the next token.
414 static int TrSkipWhitespace(TokenReaderT *tr)
416 char ch;
418 while(TrLoad(tr))
420 ch = tr->mRing[tr->mOut&TR_RING_MASK];
421 if(isspace(ch))
423 tr->mOut++;
424 if(ch == '\n')
426 tr->mLine++;
427 tr->mColumn = 1;
429 else
430 tr->mColumn++;
432 else if(ch == '#')
433 TrSkipLine(tr);
434 else
435 return 1;
437 return 0;
440 // Get the line and/or column of the next token (or the end of input).
441 static void TrIndication(TokenReaderT *tr, uint *line, uint *column)
443 TrSkipWhitespace(tr);
444 if(line) *line = tr->mLine;
445 if(column) *column = tr->mColumn;
448 // Checks to see if a token is the given operator. It does not display any
449 // errors and will not proceed to the next token.
450 static int TrIsOperator(TokenReaderT *tr, const char *op)
452 size_t out, len;
453 char ch;
455 if(!TrSkipWhitespace(tr))
456 return 0;
457 out = tr->mOut;
458 len = 0;
459 while(op[len] != '\0' && out < tr->mIn)
461 ch = tr->mRing[out&TR_RING_MASK];
462 if(ch != op[len]) break;
463 len++;
464 out++;
466 if(op[len] == '\0')
467 return 1;
468 return 0;
471 /* The TrRead*() routines obtain the value of a matching token type. They
472 * display type, form, and boundary errors and will proceed to the next
473 * token.
476 // Reads and validates an identifier token.
477 static int TrReadIdent(TokenReaderT *tr, const uint maxLen, char *ident)
479 uint col, len;
480 char ch;
482 col = tr->mColumn;
483 if(TrSkipWhitespace(tr))
485 col = tr->mColumn;
486 ch = tr->mRing[tr->mOut&TR_RING_MASK];
487 if(ch == '_' || isalpha(ch))
489 len = 0;
490 do {
491 if(len < maxLen)
492 ident[len] = ch;
493 len++;
494 tr->mOut++;
495 if(!TrLoad(tr))
496 break;
497 ch = tr->mRing[tr->mOut&TR_RING_MASK];
498 } while(ch == '_' || isdigit(ch) || isalpha(ch));
500 tr->mColumn += len;
501 if(len < maxLen)
503 ident[len] = '\0';
504 return 1;
506 TrErrorAt(tr, tr->mLine, col, "Identifier is too long.\n");
507 return 0;
510 TrErrorAt(tr, tr->mLine, col, "Expected an identifier.\n");
511 return 0;
514 // Reads and validates (including bounds) an integer token.
515 static int TrReadInt(TokenReaderT *tr, const int loBound, const int hiBound, int *value)
517 uint col, digis, len;
518 char ch, temp[64+1];
520 col = tr->mColumn;
521 if(TrSkipWhitespace(tr))
523 col = tr->mColumn;
524 len = 0;
525 ch = tr->mRing[tr->mOut&TR_RING_MASK];
526 if(ch == '+' || ch == '-')
528 temp[len] = ch;
529 len++;
530 tr->mOut++;
532 digis = 0;
533 while(TrLoad(tr))
535 ch = tr->mRing[tr->mOut&TR_RING_MASK];
536 if(!isdigit(ch)) break;
537 if(len < 64)
538 temp[len] = ch;
539 len++;
540 digis++;
541 tr->mOut++;
543 tr->mColumn += len;
544 if(digis > 0 && ch != '.' && !isalpha(ch))
546 if(len > 64)
548 TrErrorAt(tr, tr->mLine, col, "Integer is too long.");
549 return 0;
551 temp[len] = '\0';
552 *value = strtol(temp, NULL, 10);
553 if(*value < loBound || *value > hiBound)
555 TrErrorAt(tr, tr->mLine, col, "Expected a value from %d to %d.\n", loBound, hiBound);
556 return (0);
558 return (1);
561 TrErrorAt(tr, tr->mLine, col, "Expected an integer.\n");
562 return 0;
565 // Reads and validates (including bounds) a float token.
566 static int TrReadFloat(TokenReaderT *tr, const double loBound, const double hiBound, double *value)
568 uint col, digis, len;
569 char ch, temp[64+1];
571 col = tr->mColumn;
572 if(TrSkipWhitespace(tr))
574 col = tr->mColumn;
575 len = 0;
576 ch = tr->mRing[tr->mOut&TR_RING_MASK];
577 if(ch == '+' || ch == '-')
579 temp[len] = ch;
580 len++;
581 tr->mOut++;
584 digis = 0;
585 while(TrLoad(tr))
587 ch = tr->mRing[tr->mOut&TR_RING_MASK];
588 if(!isdigit(ch)) break;
589 if(len < 64)
590 temp[len] = ch;
591 len++;
592 digis++;
593 tr->mOut++;
595 if(ch == '.')
597 if(len < 64)
598 temp[len] = ch;
599 len++;
600 tr->mOut++;
602 while(TrLoad(tr))
604 ch = tr->mRing[tr->mOut&TR_RING_MASK];
605 if(!isdigit(ch)) break;
606 if(len < 64)
607 temp[len] = ch;
608 len++;
609 digis++;
610 tr->mOut++;
612 if(digis > 0)
614 if(ch == 'E' || ch == 'e')
616 if(len < 64)
617 temp[len] = ch;
618 len++;
619 digis = 0;
620 tr->mOut++;
621 if(ch == '+' || ch == '-')
623 if(len < 64)
624 temp[len] = ch;
625 len++;
626 tr->mOut++;
628 while(TrLoad(tr))
630 ch = tr->mRing[tr->mOut&TR_RING_MASK];
631 if(!isdigit(ch)) break;
632 if(len < 64)
633 temp[len] = ch;
634 len++;
635 digis++;
636 tr->mOut++;
639 tr->mColumn += len;
640 if(digis > 0 && ch != '.' && !isalpha(ch))
642 if(len > 64)
644 TrErrorAt(tr, tr->mLine, col, "Float is too long.");
645 return 0;
647 temp[len] = '\0';
648 *value = strtod(temp, NULL);
649 if(*value < loBound || *value > hiBound)
651 TrErrorAt (tr, tr->mLine, col, "Expected a value from %f to %f.\n", loBound, hiBound);
652 return 0;
654 return 1;
657 else
658 tr->mColumn += len;
660 TrErrorAt(tr, tr->mLine, col, "Expected a float.\n");
661 return 0;
664 // Reads and validates a string token.
665 static int TrReadString(TokenReaderT *tr, const uint maxLen, char *text)
667 uint col, len;
668 char ch;
670 col = tr->mColumn;
671 if(TrSkipWhitespace(tr))
673 col = tr->mColumn;
674 ch = tr->mRing[tr->mOut&TR_RING_MASK];
675 if(ch == '\"')
677 tr->mOut++;
678 len = 0;
679 while(TrLoad(tr))
681 ch = tr->mRing[tr->mOut&TR_RING_MASK];
682 tr->mOut++;
683 if(ch == '\"')
684 break;
685 if(ch == '\n')
687 TrErrorAt (tr, tr->mLine, col, "Unterminated string at end of line.\n");
688 return 0;
690 if(len < maxLen)
691 text[len] = ch;
692 len++;
694 if(ch != '\"')
696 tr->mColumn += 1 + len;
697 TrErrorAt(tr, tr->mLine, col, "Unterminated string at end of input.\n");
698 return 0;
700 tr->mColumn += 2 + len;
701 if(len > maxLen)
703 TrErrorAt (tr, tr->mLine, col, "String is too long.\n");
704 return 0;
706 text[len] = '\0';
707 return 1;
710 TrErrorAt(tr, tr->mLine, col, "Expected a string.\n");
711 return 0;
714 // Reads and validates the given operator.
715 static int TrReadOperator(TokenReaderT *tr, const char *op)
717 uint col, len;
718 char ch;
720 col = tr->mColumn;
721 if(TrSkipWhitespace(tr))
723 col = tr->mColumn;
724 len = 0;
725 while(op[len] != '\0' && TrLoad(tr))
727 ch = tr->mRing[tr->mOut&TR_RING_MASK];
728 if(ch != op[len]) break;
729 len++;
730 tr->mOut++;
732 tr->mColumn += len;
733 if(op[len] == '\0')
734 return 1;
736 TrErrorAt(tr, tr->mLine, col, "Expected '%s' operator.\n", op);
737 return 0;
740 /* Performs a string substitution. Any case-insensitive occurrences of the
741 * pattern string are replaced with the replacement string. The result is
742 * truncated if necessary.
744 static int StrSubst(const char *in, const char *pat, const char *rep, const size_t maxLen, char *out)
746 size_t inLen, patLen, repLen;
747 size_t si, di;
748 int truncated;
750 inLen = strlen(in);
751 patLen = strlen(pat);
752 repLen = strlen(rep);
753 si = 0;
754 di = 0;
755 truncated = 0;
756 while(si < inLen && di < maxLen)
758 if(patLen <= inLen-si)
760 if(strncasecmp(&in[si], pat, patLen) == 0)
762 if(repLen > maxLen-di)
764 repLen = maxLen - di;
765 truncated = 1;
767 strncpy(&out[di], rep, repLen);
768 si += patLen;
769 di += repLen;
772 out[di] = in[si];
773 si++;
774 di++;
776 if(si < inLen)
777 truncated = 1;
778 out[di] = '\0';
779 return !truncated;
783 /*********************
784 *** Math routines ***
785 *********************/
787 // Provide missing math routines for MSVC versions < 1800 (Visual Studio 2013).
788 #if defined(_MSC_VER) && _MSC_VER < 1800
789 static double round(double val)
791 if(val < 0.0)
792 return ceil(val-0.5);
793 return floor(val+0.5);
796 static double fmin(double a, double b)
798 return (a<b) ? a : b;
801 static double fmax(double a, double b)
803 return (a>b) ? a : b;
805 #endif
807 // Simple clamp routine.
808 static double Clamp(const double val, const double lower, const double upper)
810 return fmin(fmax(val, lower), upper);
813 // Performs linear interpolation.
814 static double Lerp(const double a, const double b, const double f)
816 return a + (f * (b - a));
819 static inline uint dither_rng(uint *seed)
821 *seed = (*seed * 96314165) + 907633515;
822 return *seed;
825 // Performs a triangular probability density function dither. It assumes the
826 // input sample is already scaled.
827 static inline double TpdfDither(const double in, uint *seed)
829 static const double PRNG_SCALE = 1.0 / UINT_MAX;
830 uint prn0, prn1;
832 prn0 = dither_rng(seed);
833 prn1 = dither_rng(seed);
834 return round(in + (prn0*PRNG_SCALE - prn1*PRNG_SCALE));
837 // Allocates an array of doubles.
838 static double *CreateArray(size_t n)
840 double *a;
842 if(n == 0) n = 1;
843 a = calloc(n, sizeof(double));
844 if(a == NULL)
846 fprintf(stderr, "Error: Out of memory.\n");
847 exit(-1);
849 return a;
852 // Frees an array of doubles.
853 static void DestroyArray(double *a)
854 { free(a); }
856 // Complex number routines. All outputs must be non-NULL.
858 // Magnitude/absolute value.
859 static double ComplexAbs(const double r, const double i)
861 return sqrt(r*r + i*i);
864 // Multiply.
865 static void ComplexMul(const double aR, const double aI, const double bR, const double bI, double *outR, double *outI)
867 *outR = (aR * bR) - (aI * bI);
868 *outI = (aI * bR) + (aR * bI);
871 // Base-e exponent.
872 static void ComplexExp(const double inR, const double inI, double *outR, double *outI)
874 double e = exp(inR);
875 *outR = e * cos(inI);
876 *outI = e * sin(inI);
879 /* Fast Fourier transform routines. The number of points must be a power of
880 * two. In-place operation is possible only if both the real and imaginary
881 * parts are in-place together.
884 // Performs bit-reversal ordering.
885 static void FftArrange(const uint n, const double *inR, const double *inI, double *outR, double *outI)
887 uint rk, k, m;
888 double tempR, tempI;
890 if(inR == outR && inI == outI)
892 // Handle in-place arrangement.
893 rk = 0;
894 for(k = 0;k < n;k++)
896 if(rk > k)
898 tempR = inR[rk];
899 tempI = inI[rk];
900 outR[rk] = inR[k];
901 outI[rk] = inI[k];
902 outR[k] = tempR;
903 outI[k] = tempI;
905 m = n;
906 while(rk&(m >>= 1))
907 rk &= ~m;
908 rk |= m;
911 else
913 // Handle copy arrangement.
914 rk = 0;
915 for(k = 0;k < n;k++)
917 outR[rk] = inR[k];
918 outI[rk] = inI[k];
919 m = n;
920 while(rk&(m >>= 1))
921 rk &= ~m;
922 rk |= m;
927 // Performs the summation.
928 static void FftSummation(const uint n, const double s, double *re, double *im)
930 double pi;
931 uint m, m2;
932 double vR, vI, wR, wI;
933 uint i, k, mk;
934 double tR, tI;
936 pi = s * M_PI;
937 for(m = 1, m2 = 2;m < n; m <<= 1, m2 <<= 1)
939 // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
940 vR = sin(0.5 * pi / m);
941 vR = -2.0 * vR * vR;
942 vI = -sin(pi / m);
943 // w = Complex (1.0, 0.0)
944 wR = 1.0;
945 wI = 0.0;
946 for(i = 0;i < m;i++)
948 for(k = i;k < n;k += m2)
950 mk = k + m;
951 // t = ComplexMul(w, out[km2])
952 tR = (wR * re[mk]) - (wI * im[mk]);
953 tI = (wR * im[mk]) + (wI * re[mk]);
954 // out[mk] = ComplexSub (out [k], t)
955 re[mk] = re[k] - tR;
956 im[mk] = im[k] - tI;
957 // out[k] = ComplexAdd (out [k], t)
958 re[k] += tR;
959 im[k] += tI;
961 // t = ComplexMul (v, w)
962 tR = (vR * wR) - (vI * wI);
963 tI = (vR * wI) + (vI * wR);
964 // w = ComplexAdd (w, t)
965 wR += tR;
966 wI += tI;
971 // Performs a forward FFT.
972 static void FftForward(const uint n, const double *inR, const double *inI, double *outR, double *outI)
974 FftArrange(n, inR, inI, outR, outI);
975 FftSummation(n, 1.0, outR, outI);
978 // Performs an inverse FFT.
979 static void FftInverse(const uint n, const double *inR, const double *inI, double *outR, double *outI)
981 double f;
982 uint i;
984 FftArrange(n, inR, inI, outR, outI);
985 FftSummation(n, -1.0, outR, outI);
986 f = 1.0 / n;
987 for(i = 0;i < n;i++)
989 outR[i] *= f;
990 outI[i] *= f;
994 /* Calculate the complex helical sequence (or discrete-time analytical signal)
995 * of the given input using the Hilbert transform. Given the natural logarithm
996 * of a signal's magnitude response, the imaginary components can be used as
997 * the angles for minimum-phase reconstruction.
999 static void Hilbert(const uint n, const double *in, double *outR, double *outI)
1001 uint i;
1003 if(in == outR)
1005 // Handle in-place operation.
1006 for(i = 0;i < n;i++)
1007 outI[i] = 0.0;
1009 else
1011 // Handle copy operation.
1012 for(i = 0;i < n;i++)
1014 outR[i] = in[i];
1015 outI[i] = 0.0;
1018 FftInverse(n, outR, outI, outR, outI);
1019 for(i = 1;i < (n+1)/2;i++)
1021 outR[i] *= 2.0;
1022 outI[i] *= 2.0;
1024 /* Increment i if n is even. */
1025 i += (n&1)^1;
1026 for(;i < n;i++)
1028 outR[i] = 0.0;
1029 outI[i] = 0.0;
1031 FftForward(n, outR, outI, outR, outI);
1034 /* Calculate the magnitude response of the given input. This is used in
1035 * place of phase decomposition, since the phase residuals are discarded for
1036 * minimum phase reconstruction. The mirrored half of the response is also
1037 * discarded.
1039 static void MagnitudeResponse(const uint n, const double *inR, const double *inI, double *out)
1041 const uint m = 1 + (n / 2);
1042 uint i;
1043 for(i = 0;i < m;i++)
1044 out[i] = fmax(ComplexAbs(inR[i], inI[i]), EPSILON);
1047 /* Apply a range limit (in dB) to the given magnitude response. This is used
1048 * to adjust the effects of the diffuse-field average on the equalization
1049 * process.
1051 static void LimitMagnitudeResponse(const uint n, const double limit, const double *in, double *out)
1053 const uint m = 1 + (n / 2);
1054 double halfLim;
1055 uint i, lower, upper;
1056 double ave;
1058 halfLim = limit / 2.0;
1059 // Convert the response to dB.
1060 for(i = 0;i < m;i++)
1061 out[i] = 20.0 * log10(in[i]);
1062 // Use six octaves to calculate the average magnitude of the signal.
1063 lower = ((uint)ceil(n / pow(2.0, 8.0))) - 1;
1064 upper = ((uint)floor(n / pow(2.0, 2.0))) - 1;
1065 ave = 0.0;
1066 for(i = lower;i <= upper;i++)
1067 ave += out[i];
1068 ave /= upper - lower + 1;
1069 // Keep the response within range of the average magnitude.
1070 for(i = 0;i < m;i++)
1071 out[i] = Clamp(out[i], ave - halfLim, ave + halfLim);
1072 // Convert the response back to linear magnitude.
1073 for(i = 0;i < m;i++)
1074 out[i] = pow(10.0, out[i] / 20.0);
1077 /* Reconstructs the minimum-phase component for the given magnitude response
1078 * of a signal. This is equivalent to phase recomposition, sans the missing
1079 * residuals (which were discarded). The mirrored half of the response is
1080 * reconstructed.
1082 static void MinimumPhase(const uint n, const double *in, double *outR, double *outI)
1084 const uint m = 1 + (n / 2);
1085 double *mags;
1086 double aR, aI;
1087 uint i;
1089 mags = CreateArray(n);
1090 for(i = 0;i < m;i++)
1092 mags[i] = fmax(EPSILON, in[i]);
1093 outR[i] = log(mags[i]);
1095 for(;i < n;i++)
1097 mags[i] = mags[n - i];
1098 outR[i] = outR[n - i];
1100 Hilbert(n, outR, outR, outI);
1101 // Remove any DC offset the filter has.
1102 mags[0] = EPSILON;
1103 for(i = 0;i < n;i++)
1105 ComplexExp(0.0, outI[i], &aR, &aI);
1106 ComplexMul(mags[i], 0.0, aR, aI, &outR[i], &outI[i]);
1108 DestroyArray(mags);
1112 /***************************
1113 *** Resampler functions ***
1114 ***************************/
1116 /* This is the normalized cardinal sine (sinc) function.
1118 * sinc(x) = { 1, x = 0
1119 * { sin(pi x) / (pi x), otherwise.
1121 static double Sinc(const double x)
1123 if(fabs(x) < EPSILON)
1124 return 1.0;
1125 return sin(M_PI * x) / (M_PI * x);
1128 /* The zero-order modified Bessel function of the first kind, used for the
1129 * Kaiser window.
1131 * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
1132 * = sum_{k=0}^inf ((x / 2)^k / k!)^2
1134 static double BesselI_0(const double x)
1136 double term, sum, x2, y, last_sum;
1137 int k;
1139 // Start at k=1 since k=0 is trivial.
1140 term = 1.0;
1141 sum = 1.0;
1142 x2 = x/2.0;
1143 k = 1;
1145 // Let the integration converge until the term of the sum is no longer
1146 // significant.
1147 do {
1148 y = x2 / k;
1149 k++;
1150 last_sum = sum;
1151 term *= y * y;
1152 sum += term;
1153 } while(sum != last_sum);
1154 return sum;
1157 /* Calculate a Kaiser window from the given beta value and a normalized k
1158 * [-1, 1].
1160 * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
1161 * { 0, elsewhere.
1163 * Where k can be calculated as:
1165 * k = i / l, where -l <= i <= l.
1167 * or:
1169 * k = 2 i / M - 1, where 0 <= i <= M.
1171 static double Kaiser(const double b, const double k)
1173 if(!(k >= -1.0 && k <= 1.0))
1174 return 0.0;
1175 return BesselI_0(b * sqrt(1.0 - k*k)) / BesselI_0(b);
1178 // Calculates the greatest common divisor of a and b.
1179 static uint Gcd(uint x, uint y)
1181 while(y > 0)
1183 uint z = y;
1184 y = x % y;
1185 x = z;
1187 return x;
1190 /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
1191 * the transition width is normalized frequency (0.5 is nyquist).
1193 * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
1194 * { ceil(5.79 / 2 pi f_t), r <= 21.
1197 static uint CalcKaiserOrder(const double rejection, const double transition)
1199 double w_t = 2.0 * M_PI * transition;
1200 if(rejection > 21.0)
1201 return (uint)ceil((rejection - 7.95) / (2.285 * w_t));
1202 return (uint)ceil(5.79 / w_t);
1205 // Calculates the beta value of the Kaiser window. Rejection is in dB.
1206 static double CalcKaiserBeta(const double rejection)
1208 if(rejection > 50.0)
1209 return 0.1102 * (rejection - 8.7);
1210 if(rejection >= 21.0)
1211 return (0.5842 * pow(rejection - 21.0, 0.4)) +
1212 (0.07886 * (rejection - 21.0));
1213 return 0.0;
1216 /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
1217 * width, beta, gain, and cutoff. The point is specified in non-normalized
1218 * samples, from 0 to M, where M = (2 l + 1).
1220 * w(k) 2 p f_t sinc(2 f_t x)
1222 * x -- centered sample index (i - l)
1223 * k -- normalized and centered window index (x / l)
1224 * w(k) -- window function (Kaiser)
1225 * p -- gain compensation factor when sampling
1226 * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
1228 static double SincFilter(const int l, const double b, const double gain, const double cutoff, const int i)
1230 return Kaiser(b, (double)(i - l) / l) * 2.0 * gain * cutoff * Sinc(2.0 * cutoff * (i - l));
1233 /* This is a polyphase sinc-filtered resampler.
1235 * Upsample Downsample
1237 * p/q = 3/2 p/q = 3/5
1239 * M-+-+-+-> M-+-+-+->
1240 * -------------------+ ---------------------+
1241 * p s * f f f f|f| | p s * f f f f f |
1242 * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
1243 * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
1244 * s * f|f|f f f | s * f f|f|f f |
1245 * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
1246 * --------+=+--------+ 0 * |0|0 0 0 0 |
1247 * d . d .|d|. d . d ----------+=+--------+
1248 * d . . . .|d|. . . .
1249 * q->
1250 * q-+-+-+->
1252 * P_f(i,j) = q i mod p + pj
1253 * P_s(i,j) = floor(q i / p) - j
1254 * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
1255 * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
1256 * { 0, P_f(i,j) >= M. }
1259 // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
1260 // that's used to cut frequencies above the destination nyquist.
1261 static void ResamplerSetup(ResamplerT *rs, const uint srcRate, const uint dstRate)
1263 double cutoff, width, beta;
1264 uint gcd, l;
1265 int i;
1267 gcd = Gcd(srcRate, dstRate);
1268 rs->mP = dstRate / gcd;
1269 rs->mQ = srcRate / gcd;
1270 /* The cutoff is adjusted by half the transition width, so the transition
1271 * ends before the nyquist (0.5). Both are scaled by the downsampling
1272 * factor.
1274 if(rs->mP > rs->mQ)
1276 cutoff = 0.475 / rs->mP;
1277 width = 0.05 / rs->mP;
1279 else
1281 cutoff = 0.475 / rs->mQ;
1282 width = 0.05 / rs->mQ;
1284 // A rejection of -180 dB is used for the stop band.
1285 l = CalcKaiserOrder(180.0, width) / 2;
1286 beta = CalcKaiserBeta(180.0);
1287 rs->mM = (2 * l) + 1;
1288 rs->mL = l;
1289 rs->mF = CreateArray(rs->mM);
1290 for(i = 0;i < ((int)rs->mM);i++)
1291 rs->mF[i] = SincFilter((int)l, beta, rs->mP, cutoff, i);
1294 // Clean up after the resampler.
1295 static void ResamplerClear(ResamplerT *rs)
1297 DestroyArray(rs->mF);
1298 rs->mF = NULL;
1301 // Perform the upsample-filter-downsample resampling operation using a
1302 // polyphase filter implementation.
1303 static void ResamplerRun(ResamplerT *rs, const uint inN, const double *in, const uint outN, double *out)
1305 const uint p = rs->mP, q = rs->mQ, m = rs->mM, l = rs->mL;
1306 const double *f = rs->mF;
1307 uint j_f, j_s;
1308 double *work;
1309 uint i;
1311 if(outN == 0)
1312 return;
1314 // Handle in-place operation.
1315 if(in == out)
1316 work = CreateArray(outN);
1317 else
1318 work = out;
1319 // Resample the input.
1320 for(i = 0;i < outN;i++)
1322 double r = 0.0;
1323 // Input starts at l to compensate for the filter delay. This will
1324 // drop any build-up from the first half of the filter.
1325 j_f = (l + (q * i)) % p;
1326 j_s = (l + (q * i)) / p;
1327 while(j_f < m)
1329 // Only take input when 0 <= j_s < inN. This single unsigned
1330 // comparison catches both cases.
1331 if(j_s < inN)
1332 r += f[j_f] * in[j_s];
1333 j_f += p;
1334 j_s--;
1336 work[i] = r;
1338 // Clean up after in-place operation.
1339 if(in == out)
1341 for(i = 0;i < outN;i++)
1342 out[i] = work[i];
1343 DestroyArray(work);
1347 /*************************
1348 *** File source input ***
1349 *************************/
1351 // Read a binary value of the specified byte order and byte size from a file,
1352 // storing it as a 32-bit unsigned integer.
1353 static int ReadBin4(FILE *fp, const char *filename, const ByteOrderT order, const uint bytes, uint32 *out)
1355 uint8 in[4];
1356 uint32 accum;
1357 uint i;
1359 if(fread(in, 1, bytes, fp) != bytes)
1361 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1362 return 0;
1364 accum = 0;
1365 switch(order)
1367 case BO_LITTLE:
1368 for(i = 0;i < bytes;i++)
1369 accum = (accum<<8) | in[bytes - i - 1];
1370 break;
1371 case BO_BIG:
1372 for(i = 0;i < bytes;i++)
1373 accum = (accum<<8) | in[i];
1374 break;
1375 default:
1376 break;
1378 *out = accum;
1379 return 1;
1382 // Read a binary value of the specified byte order from a file, storing it as
1383 // a 64-bit unsigned integer.
1384 static int ReadBin8(FILE *fp, const char *filename, const ByteOrderT order, uint64 *out)
1386 uint8 in [8];
1387 uint64 accum;
1388 uint i;
1390 if(fread(in, 1, 8, fp) != 8)
1392 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1393 return 0;
1395 accum = 0ULL;
1396 switch(order)
1398 case BO_LITTLE:
1399 for(i = 0;i < 8;i++)
1400 accum = (accum<<8) | in[8 - i - 1];
1401 break;
1402 case BO_BIG:
1403 for(i = 0;i < 8;i++)
1404 accum = (accum<<8) | in[i];
1405 break;
1406 default:
1407 break;
1409 *out = accum;
1410 return 1;
1413 /* Read a binary value of the specified type, byte order, and byte size from
1414 * a file, converting it to a double. For integer types, the significant
1415 * bits are used to normalize the result. The sign of bits determines
1416 * whether they are padded toward the MSB (negative) or LSB (positive).
1417 * Floating-point types are not normalized.
1419 static int ReadBinAsDouble(FILE *fp, const char *filename, const ByteOrderT order, const ElementTypeT type, const uint bytes, const int bits, double *out)
1421 union {
1422 uint32 ui;
1423 int32 i;
1424 float f;
1425 } v4;
1426 union {
1427 uint64 ui;
1428 double f;
1429 } v8;
1431 *out = 0.0;
1432 if(bytes > 4)
1434 if(!ReadBin8(fp, filename, order, &v8.ui))
1435 return 0;
1436 if(type == ET_FP)
1437 *out = v8.f;
1439 else
1441 if(!ReadBin4(fp, filename, order, bytes, &v4.ui))
1442 return 0;
1443 if(type == ET_FP)
1444 *out = v4.f;
1445 else
1447 if(bits > 0)
1448 v4.ui >>= (8*bytes) - ((uint)bits);
1449 else
1450 v4.ui &= (0xFFFFFFFF >> (32+bits));
1452 if(v4.ui&(uint)(1<<(abs(bits)-1)))
1453 v4.ui |= (0xFFFFFFFF << abs (bits));
1454 *out = v4.i / (double)(1<<(abs(bits)-1));
1457 return 1;
1460 /* Read an ascii value of the specified type from a file, converting it to a
1461 * double. For integer types, the significant bits are used to normalize the
1462 * result. The sign of the bits should always be positive. This also skips
1463 * up to one separator character before the element itself.
1465 static int ReadAsciiAsDouble(TokenReaderT *tr, const char *filename, const ElementTypeT type, const uint bits, double *out)
1467 if(TrIsOperator(tr, ","))
1468 TrReadOperator(tr, ",");
1469 else if(TrIsOperator(tr, ":"))
1470 TrReadOperator(tr, ":");
1471 else if(TrIsOperator(tr, ";"))
1472 TrReadOperator(tr, ";");
1473 else if(TrIsOperator(tr, "|"))
1474 TrReadOperator(tr, "|");
1476 if(type == ET_FP)
1478 if(!TrReadFloat(tr, -HUGE_VAL, HUGE_VAL, out))
1480 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1481 return 0;
1484 else
1486 int v;
1487 if(!TrReadInt(tr, -(1<<(bits-1)), (1<<(bits-1))-1, &v))
1489 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1490 return 0;
1492 *out = v / (double)((1<<(bits-1))-1);
1494 return 1;
1497 // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
1498 // the source parameters and data set metrics.
1499 static int ReadWaveFormat(FILE *fp, const ByteOrderT order, const uint hrirRate, SourceRefT *src)
1501 uint32 fourCC, chunkSize;
1502 uint32 format, channels, rate, dummy, block, size, bits;
1504 chunkSize = 0;
1505 do {
1506 if (chunkSize > 0)
1507 fseek (fp, (long) chunkSize, SEEK_CUR);
1508 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
1509 !ReadBin4(fp, src->mPath, order, 4, &chunkSize))
1510 return 0;
1511 } while(fourCC != FOURCC_FMT);
1512 if(!ReadBin4(fp, src->mPath, order, 2, & format) ||
1513 !ReadBin4(fp, src->mPath, order, 2, & channels) ||
1514 !ReadBin4(fp, src->mPath, order, 4, & rate) ||
1515 !ReadBin4(fp, src->mPath, order, 4, & dummy) ||
1516 !ReadBin4(fp, src->mPath, order, 2, & block))
1517 return (0);
1518 block /= channels;
1519 if(chunkSize > 14)
1521 if(!ReadBin4(fp, src->mPath, order, 2, &size))
1522 return 0;
1523 size /= 8;
1524 if(block > size)
1525 size = block;
1527 else
1528 size = block;
1529 if(format == WAVE_FORMAT_EXTENSIBLE)
1531 fseek(fp, 2, SEEK_CUR);
1532 if(!ReadBin4(fp, src->mPath, order, 2, &bits))
1533 return 0;
1534 if(bits == 0)
1535 bits = 8 * size;
1536 fseek(fp, 4, SEEK_CUR);
1537 if(!ReadBin4(fp, src->mPath, order, 2, &format))
1538 return 0;
1539 fseek(fp, (long)(chunkSize - 26), SEEK_CUR);
1541 else
1543 bits = 8 * size;
1544 if(chunkSize > 14)
1545 fseek(fp, (long)(chunkSize - 16), SEEK_CUR);
1546 else
1547 fseek(fp, (long)(chunkSize - 14), SEEK_CUR);
1549 if(format != WAVE_FORMAT_PCM && format != WAVE_FORMAT_IEEE_FLOAT)
1551 fprintf(stderr, "Error: Unsupported WAVE format in file '%s'.\n", src->mPath);
1552 return 0;
1554 if(src->mChannel >= channels)
1556 fprintf(stderr, "Error: Missing source channel in WAVE file '%s'.\n", src->mPath);
1557 return 0;
1559 if(rate != hrirRate)
1561 fprintf(stderr, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src->mPath);
1562 return 0;
1564 if(format == WAVE_FORMAT_PCM)
1566 if(size < 2 || size > 4)
1568 fprintf(stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src->mPath);
1569 return 0;
1571 if(bits < 16 || bits > (8*size))
1573 fprintf (stderr, "Error: Bad significant bits in WAVE file '%s'.\n", src->mPath);
1574 return 0;
1576 src->mType = ET_INT;
1578 else
1580 if(size != 4 && size != 8)
1582 fprintf(stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src->mPath);
1583 return 0;
1585 src->mType = ET_FP;
1587 src->mSize = size;
1588 src->mBits = (int)bits;
1589 src->mSkip = channels;
1590 return 1;
1593 // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
1594 static int ReadWaveData(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
1596 int pre, post, skip;
1597 uint i;
1599 pre = (int)(src->mSize * src->mChannel);
1600 post = (int)(src->mSize * (src->mSkip - src->mChannel - 1));
1601 skip = 0;
1602 for(i = 0;i < n;i++)
1604 skip += pre;
1605 if(skip > 0)
1606 fseek(fp, skip, SEEK_CUR);
1607 if(!ReadBinAsDouble(fp, src->mPath, order, src->mType, src->mSize, src->mBits, &hrir[i]))
1608 return 0;
1609 skip = post;
1611 if(skip > 0)
1612 fseek(fp, skip, SEEK_CUR);
1613 return 1;
1616 // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
1617 // doubles.
1618 static int ReadWaveList(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
1620 uint32 fourCC, chunkSize, listSize, count;
1621 uint block, skip, offset, i;
1622 double lastSample;
1624 for (;;) {
1625 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, & fourCC) ||
1626 !ReadBin4(fp, src->mPath, order, 4, & chunkSize))
1627 return (0);
1629 if(fourCC == FOURCC_DATA)
1631 block = src->mSize * src->mSkip;
1632 count = chunkSize / block;
1633 if(count < (src->mOffset + n))
1635 fprintf(stderr, "Error: Bad read from file '%s'.\n", src->mPath);
1636 return 0;
1638 fseek(fp, (long)(src->mOffset * block), SEEK_CUR);
1639 if(!ReadWaveData(fp, src, order, n, &hrir[0]))
1640 return 0;
1641 return 1;
1643 else if(fourCC == FOURCC_LIST)
1645 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC))
1646 return 0;
1647 chunkSize -= 4;
1648 if(fourCC == FOURCC_WAVL)
1649 break;
1651 if(chunkSize > 0)
1652 fseek(fp, (long)chunkSize, SEEK_CUR);
1654 listSize = chunkSize;
1655 block = src->mSize * src->mSkip;
1656 skip = src->mOffset;
1657 offset = 0;
1658 lastSample = 0.0;
1659 while(offset < n && listSize > 8)
1661 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
1662 !ReadBin4(fp, src->mPath, order, 4, &chunkSize))
1663 return 0;
1664 listSize -= 8 + chunkSize;
1665 if(fourCC == FOURCC_DATA)
1667 count = chunkSize / block;
1668 if(count > skip)
1670 fseek(fp, (long)(skip * block), SEEK_CUR);
1671 chunkSize -= skip * block;
1672 count -= skip;
1673 skip = 0;
1674 if(count > (n - offset))
1675 count = n - offset;
1676 if(!ReadWaveData(fp, src, order, count, &hrir[offset]))
1677 return 0;
1678 chunkSize -= count * block;
1679 offset += count;
1680 lastSample = hrir [offset - 1];
1682 else
1684 skip -= count;
1685 count = 0;
1688 else if(fourCC == FOURCC_SLNT)
1690 if(!ReadBin4(fp, src->mPath, order, 4, &count))
1691 return 0;
1692 chunkSize -= 4;
1693 if(count > skip)
1695 count -= skip;
1696 skip = 0;
1697 if(count > (n - offset))
1698 count = n - offset;
1699 for(i = 0; i < count; i ++)
1700 hrir[offset + i] = lastSample;
1701 offset += count;
1703 else
1705 skip -= count;
1706 count = 0;
1709 if(chunkSize > 0)
1710 fseek(fp, (long)chunkSize, SEEK_CUR);
1712 if(offset < n)
1714 fprintf(stderr, "Error: Bad read from file '%s'.\n", src->mPath);
1715 return 0;
1717 return 1;
1720 // Load a source HRIR from a RIFF/RIFX WAVE file.
1721 static int LoadWaveSource(FILE *fp, SourceRefT *src, const uint hrirRate, const uint n, double *hrir)
1723 uint32 fourCC, dummy;
1724 ByteOrderT order;
1726 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
1727 !ReadBin4(fp, src->mPath, BO_LITTLE, 4, &dummy))
1728 return 0;
1729 if(fourCC == FOURCC_RIFF)
1730 order = BO_LITTLE;
1731 else if(fourCC == FOURCC_RIFX)
1732 order = BO_BIG;
1733 else
1735 fprintf(stderr, "Error: No RIFF/RIFX chunk in file '%s'.\n", src->mPath);
1736 return 0;
1739 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC))
1740 return 0;
1741 if(fourCC != FOURCC_WAVE)
1743 fprintf(stderr, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src->mPath);
1744 return 0;
1746 if(!ReadWaveFormat(fp, order, hrirRate, src))
1747 return 0;
1748 if(!ReadWaveList(fp, src, order, n, hrir))
1749 return 0;
1750 return 1;
1753 // Load a source HRIR from a binary file.
1754 static int LoadBinarySource(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
1756 uint i;
1758 fseek(fp, (long)src->mOffset, SEEK_SET);
1759 for(i = 0;i < n;i++)
1761 if(!ReadBinAsDouble(fp, src->mPath, order, src->mType, src->mSize, src->mBits, &hrir[i]))
1762 return 0;
1763 if(src->mSkip > 0)
1764 fseek(fp, (long)src->mSkip, SEEK_CUR);
1766 return 1;
1769 // Load a source HRIR from an ASCII text file containing a list of elements
1770 // separated by whitespace or common list operators (',', ';', ':', '|').
1771 static int LoadAsciiSource(FILE *fp, const SourceRefT *src, const uint n, double *hrir)
1773 TokenReaderT tr;
1774 uint i, j;
1775 double dummy;
1777 TrSetup(fp, NULL, &tr);
1778 for(i = 0;i < src->mOffset;i++)
1780 if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &dummy))
1781 return (0);
1783 for(i = 0;i < n;i++)
1785 if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &hrir[i]))
1786 return 0;
1787 for(j = 0;j < src->mSkip;j++)
1789 if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &dummy))
1790 return 0;
1793 return 1;
1796 // Load a source HRIR from a supported file type.
1797 static int LoadSource(SourceRefT *src, const uint hrirRate, const uint n, double *hrir)
1799 int result;
1800 FILE *fp;
1802 if (src->mFormat == SF_ASCII)
1803 fp = fopen(src->mPath, "r");
1804 else
1805 fp = fopen(src->mPath, "rb");
1806 if(fp == NULL)
1808 fprintf(stderr, "Error: Could not open source file '%s'.\n", src->mPath);
1809 return 0;
1811 if(src->mFormat == SF_WAVE)
1812 result = LoadWaveSource(fp, src, hrirRate, n, hrir);
1813 else if(src->mFormat == SF_BIN_LE)
1814 result = LoadBinarySource(fp, src, BO_LITTLE, n, hrir);
1815 else if(src->mFormat == SF_BIN_BE)
1816 result = LoadBinarySource(fp, src, BO_BIG, n, hrir);
1817 else
1818 result = LoadAsciiSource(fp, src, n, hrir);
1819 fclose(fp);
1820 return result;
1824 /***************************
1825 *** File storage output ***
1826 ***************************/
1828 // Write an ASCII string to a file.
1829 static int WriteAscii(const char *out, FILE *fp, const char *filename)
1831 size_t len;
1833 len = strlen(out);
1834 if(fwrite(out, 1, len, fp) != len)
1836 fclose(fp);
1837 fprintf(stderr, "Error: Bad write to file '%s'.\n", filename);
1838 return 0;
1840 return 1;
1843 // Write a binary value of the given byte order and byte size to a file,
1844 // loading it from a 32-bit unsigned integer.
1845 static int WriteBin4(const ByteOrderT order, const uint bytes, const uint32 in, FILE *fp, const char *filename)
1847 uint8 out[4];
1848 uint i;
1850 switch(order)
1852 case BO_LITTLE:
1853 for(i = 0;i < bytes;i++)
1854 out[i] = (in>>(i*8)) & 0x000000FF;
1855 break;
1856 case BO_BIG:
1857 for(i = 0;i < bytes;i++)
1858 out[bytes - i - 1] = (in>>(i*8)) & 0x000000FF;
1859 break;
1860 default:
1861 break;
1863 if(fwrite(out, 1, bytes, fp) != bytes)
1865 fprintf(stderr, "Error: Bad write to file '%s'.\n", filename);
1866 return 0;
1868 return 1;
1871 // Store the OpenAL Soft HRTF data set.
1872 static int StoreMhr(const HrirDataT *hData, const char *filename)
1874 uint e, step, end, n, j, i;
1875 uint dither_seed;
1876 FILE *fp;
1877 int v;
1879 if((fp=fopen(filename, "wb")) == NULL)
1881 fprintf(stderr, "Error: Could not open MHR file '%s'.\n", filename);
1882 return 0;
1884 if(!WriteAscii(MHR_FORMAT, fp, filename))
1885 return 0;
1886 if(!WriteBin4(BO_LITTLE, 4, (uint32)hData->mIrRate, fp, filename))
1887 return 0;
1888 if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mIrPoints, fp, filename))
1889 return 0;
1890 if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mEvCount, fp, filename))
1891 return 0;
1892 for(e = 0;e < hData->mEvCount;e++)
1894 if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mAzCount[e], fp, filename))
1895 return 0;
1897 step = hData->mIrSize;
1898 end = hData->mIrCount * step;
1899 n = hData->mIrPoints;
1900 dither_seed = 22222;
1901 for(j = 0;j < end;j += step)
1903 double out[MAX_TRUNCSIZE];
1904 for(i = 0;i < n;i++)
1905 out[i] = TpdfDither(32767.0 * hData->mHrirs[j+i], &dither_seed);
1906 for(i = 0;i < n;i++)
1908 v = (int)Clamp(out[i], -32768.0, 32767.0);
1909 if(!WriteBin4(BO_LITTLE, 2, (uint32)v, fp, filename))
1910 return 0;
1913 for(j = 0;j < hData->mIrCount;j++)
1915 v = (int)fmin(round(hData->mIrRate * hData->mHrtds[j]), MAX_HRTD);
1916 if(!WriteBin4(BO_LITTLE, 1, (uint32)v, fp, filename))
1917 return 0;
1919 fclose(fp);
1920 return 1;
1924 /***********************
1925 *** HRTF processing ***
1926 ***********************/
1928 // Calculate the onset time of an HRIR and average it with any existing
1929 // timing for its elevation and azimuth.
1930 static void AverageHrirOnset(const double *hrir, const double f, const uint ei, const uint ai, const HrirDataT *hData)
1932 double mag;
1933 uint n, i, j;
1935 mag = 0.0;
1936 n = hData->mIrPoints;
1937 for(i = 0;i < n;i++)
1938 mag = fmax(fabs(hrir[i]), mag);
1939 mag *= 0.15;
1940 for(i = 0;i < n;i++)
1942 if(fabs(hrir[i]) >= mag)
1943 break;
1945 j = hData->mEvOffset[ei] + ai;
1946 hData->mHrtds[j] = Lerp(hData->mHrtds[j], ((double)i) / hData->mIrRate, f);
1949 // Calculate the magnitude response of an HRIR and average it with any
1950 // existing responses for its elevation and azimuth.
1951 static void AverageHrirMagnitude(const double *hrir, const double f, const uint ei, const uint ai, const HrirDataT *hData)
1953 double *re, *im;
1954 uint n, m, i, j;
1956 n = hData->mFftSize;
1957 re = CreateArray(n);
1958 im = CreateArray(n);
1959 for(i = 0;i < hData->mIrPoints;i++)
1961 re[i] = hrir[i];
1962 im[i] = 0.0;
1964 for(;i < n;i++)
1966 re[i] = 0.0;
1967 im[i] = 0.0;
1969 FftForward(n, re, im, re, im);
1970 MagnitudeResponse(n, re, im, re);
1971 m = 1 + (n / 2);
1972 j = (hData->mEvOffset[ei] + ai) * hData->mIrSize;
1973 for(i = 0;i < m;i++)
1974 hData->mHrirs[j+i] = Lerp(hData->mHrirs[j+i], re[i], f);
1975 DestroyArray(im);
1976 DestroyArray(re);
1979 /* Calculate the contribution of each HRIR to the diffuse-field average based
1980 * on the area of its surface patch. All patches are centered at the HRIR
1981 * coordinates on the unit sphere and are measured by solid angle.
1983 static void CalculateDfWeights(const HrirDataT *hData, double *weights)
1985 double evs, sum, ev, up_ev, down_ev, solidAngle;
1986 uint ei;
1988 evs = 90.0 / (hData->mEvCount - 1);
1989 sum = 0.0;
1990 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
1992 // For each elevation, calculate the upper and lower limits of the
1993 // patch band.
1994 ev = -90.0 + (ei * 2.0 * evs);
1995 if(ei < (hData->mEvCount - 1))
1996 up_ev = (ev + evs) * M_PI / 180.0;
1997 else
1998 up_ev = M_PI / 2.0;
1999 if(ei > 0)
2000 down_ev = (ev - evs) * M_PI / 180.0;
2001 else
2002 down_ev = -M_PI / 2.0;
2003 // Calculate the area of the patch band.
2004 solidAngle = 2.0 * M_PI * (sin(up_ev) - sin(down_ev));
2005 // Each weight is the area of one patch.
2006 weights[ei] = solidAngle / hData->mAzCount [ei];
2007 // Sum the total surface area covered by the HRIRs.
2008 sum += solidAngle;
2010 // Normalize the weights given the total surface coverage.
2011 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
2012 weights[ei] /= sum;
2015 /* Calculate the diffuse-field average from the given magnitude responses of
2016 * the HRIR set. Weighting can be applied to compensate for the varying
2017 * surface area covered by each HRIR. The final average can then be limited
2018 * by the specified magnitude range (in positive dB; 0.0 to skip).
2020 static void CalculateDiffuseFieldAverage(const HrirDataT *hData, const int weighted, const double limit, double *dfa)
2022 uint ei, ai, count, step, start, end, m, j, i;
2023 double *weights;
2025 weights = CreateArray(hData->mEvCount);
2026 if(weighted)
2028 // Use coverage weighting to calculate the average.
2029 CalculateDfWeights(hData, weights);
2031 else
2033 // If coverage weighting is not used, the weights still need to be
2034 // averaged by the number of HRIRs.
2035 count = 0;
2036 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
2037 count += hData->mAzCount [ei];
2038 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
2039 weights[ei] = 1.0 / count;
2041 ei = hData->mEvStart;
2042 ai = 0;
2043 step = hData->mIrSize;
2044 start = hData->mEvOffset[ei] * step;
2045 end = hData->mIrCount * step;
2046 m = 1 + (hData->mFftSize / 2);
2047 for(i = 0;i < m;i++)
2048 dfa[i] = 0.0;
2049 for(j = start;j < end;j += step)
2051 // Get the weight for this HRIR's contribution.
2052 double weight = weights[ei];
2053 // Add this HRIR's weighted power average to the total.
2054 for(i = 0;i < m;i++)
2055 dfa[i] += weight * hData->mHrirs[j+i] * hData->mHrirs[j+i];
2056 // Determine the next weight to use.
2057 ai++;
2058 if(ai >= hData->mAzCount[ei])
2060 ei++;
2061 ai = 0;
2064 // Finish the average calculation and keep it from being too small.
2065 for(i = 0;i < m;i++)
2066 dfa[i] = fmax(sqrt(dfa[i]), EPSILON);
2067 // Apply a limit to the magnitude range of the diffuse-field average if
2068 // desired.
2069 if(limit > 0.0)
2070 LimitMagnitudeResponse(hData->mFftSize, limit, dfa, dfa);
2071 DestroyArray(weights);
2074 // Perform diffuse-field equalization on the magnitude responses of the HRIR
2075 // set using the given average response.
2076 static void DiffuseFieldEqualize(const double *dfa, const HrirDataT *hData)
2078 uint step, start, end, m, j, i;
2080 step = hData->mIrSize;
2081 start = hData->mEvOffset[hData->mEvStart] * step;
2082 end = hData->mIrCount * step;
2083 m = 1 + (hData->mFftSize / 2);
2084 for(j = start;j < end;j += step)
2086 for(i = 0;i < m;i++)
2087 hData->mHrirs[j+i] /= dfa[i];
2091 // Perform minimum-phase reconstruction using the magnitude responses of the
2092 // HRIR set.
2093 static void ReconstructHrirs(const HrirDataT *hData)
2095 uint step, start, end, n, j, i;
2096 double *re, *im;
2098 step = hData->mIrSize;
2099 start = hData->mEvOffset[hData->mEvStart] * step;
2100 end = hData->mIrCount * step;
2101 n = hData->mFftSize;
2102 re = CreateArray(n);
2103 im = CreateArray(n);
2104 for(j = start;j < end;j += step)
2106 MinimumPhase(n, &hData->mHrirs[j], re, im);
2107 FftInverse(n, re, im, re, im);
2108 for(i = 0;i < hData->mIrPoints;i++)
2109 hData->mHrirs[j+i] = re[i];
2111 DestroyArray (im);
2112 DestroyArray (re);
2115 // Resamples the HRIRs for use at the given sampling rate.
2116 static void ResampleHrirs(const uint rate, HrirDataT *hData)
2118 uint n, step, start, end, j;
2119 ResamplerT rs;
2121 ResamplerSetup(&rs, hData->mIrRate, rate);
2122 n = hData->mIrPoints;
2123 step = hData->mIrSize;
2124 start = hData->mEvOffset[hData->mEvStart] * step;
2125 end = hData->mIrCount * step;
2126 for(j = start;j < end;j += step)
2127 ResamplerRun(&rs, n, &hData->mHrirs[j], n, &hData->mHrirs[j]);
2128 ResamplerClear(&rs);
2129 hData->mIrRate = rate;
2132 /* Given an elevation index and an azimuth, calculate the indices of the two
2133 * HRIRs that bound the coordinate along with a factor for calculating the
2134 * continous HRIR using interpolation.
2136 static void CalcAzIndices(const HrirDataT *hData, const uint ei, const double az, uint *j0, uint *j1, double *jf)
2138 double af;
2139 uint ai;
2141 af = ((2.0*M_PI) + az) * hData->mAzCount[ei] / (2.0*M_PI);
2142 ai = ((uint)af) % hData->mAzCount[ei];
2143 af -= floor(af);
2145 *j0 = hData->mEvOffset[ei] + ai;
2146 *j1 = hData->mEvOffset[ei] + ((ai+1) % hData->mAzCount [ei]);
2147 *jf = af;
2150 // Synthesize any missing onset timings at the bottom elevations. This just
2151 // blends between slightly exaggerated known onsets. Not an accurate model.
2152 static void SynthesizeOnsets(HrirDataT *hData)
2154 uint oi, e, a, j0, j1;
2155 double t, of, jf;
2157 oi = hData->mEvStart;
2158 t = 0.0;
2159 for(a = 0;a < hData->mAzCount[oi];a++)
2160 t += hData->mHrtds[hData->mEvOffset[oi] + a];
2161 hData->mHrtds[0] = 1.32e-4 + (t / hData->mAzCount[oi]);
2162 for(e = 1;e < hData->mEvStart;e++)
2164 of = ((double)e) / hData->mEvStart;
2165 for(a = 0;a < hData->mAzCount[e];a++)
2167 CalcAzIndices(hData, oi, a * 2.0 * M_PI / hData->mAzCount[e], &j0, &j1, &jf);
2168 hData->mHrtds[hData->mEvOffset[e] + a] = Lerp(hData->mHrtds[0], Lerp(hData->mHrtds[j0], hData->mHrtds[j1], jf), of);
2173 /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
2174 * now this just blends the lowest elevation HRIRs together and applies some
2175 * attenuation and high frequency damping. It is a simple, if inaccurate
2176 * model.
2178 static void SynthesizeHrirs (HrirDataT *hData)
2180 uint oi, a, e, step, n, i, j;
2181 double lp[4], s0, s1;
2182 double of, b;
2183 uint j0, j1;
2184 double jf;
2186 if(hData->mEvStart <= 0)
2187 return;
2188 step = hData->mIrSize;
2189 oi = hData->mEvStart;
2190 n = hData->mIrPoints;
2191 for(i = 0;i < n;i++)
2192 hData->mHrirs[i] = 0.0;
2193 for(a = 0;a < hData->mAzCount[oi];a++)
2195 j = (hData->mEvOffset[oi] + a) * step;
2196 for(i = 0;i < n;i++)
2197 hData->mHrirs[i] += hData->mHrirs[j+i] / hData->mAzCount[oi];
2199 for(e = 1;e < hData->mEvStart;e++)
2201 of = ((double)e) / hData->mEvStart;
2202 b = (1.0 - of) * (3.5e-6 * hData->mIrRate);
2203 for(a = 0;a < hData->mAzCount[e];a++)
2205 j = (hData->mEvOffset[e] + a) * step;
2206 CalcAzIndices(hData, oi, a * 2.0 * M_PI / hData->mAzCount[e], &j0, &j1, &jf);
2207 j0 *= step;
2208 j1 *= step;
2209 lp[0] = 0.0;
2210 lp[1] = 0.0;
2211 lp[2] = 0.0;
2212 lp[3] = 0.0;
2213 for(i = 0;i < n;i++)
2215 s0 = hData->mHrirs[i];
2216 s1 = Lerp(hData->mHrirs[j0+i], hData->mHrirs[j1+i], jf);
2217 s0 = Lerp(s0, s1, of);
2218 lp[0] = Lerp(s0, lp[0], b);
2219 lp[1] = Lerp(lp[0], lp[1], b);
2220 lp[2] = Lerp(lp[1], lp[2], b);
2221 lp[3] = Lerp(lp[2], lp[3], b);
2222 hData->mHrirs[j+i] = lp[3];
2226 b = 3.5e-6 * hData->mIrRate;
2227 lp[0] = 0.0;
2228 lp[1] = 0.0;
2229 lp[2] = 0.0;
2230 lp[3] = 0.0;
2231 for(i = 0;i < n;i++)
2233 s0 = hData->mHrirs[i];
2234 lp[0] = Lerp(s0, lp[0], b);
2235 lp[1] = Lerp(lp[0], lp[1], b);
2236 lp[2] = Lerp(lp[1], lp[2], b);
2237 lp[3] = Lerp(lp[2], lp[3], b);
2238 hData->mHrirs[i] = lp[3];
2240 hData->mEvStart = 0;
2243 // The following routines assume a full set of HRIRs for all elevations.
2245 // Normalize the HRIR set and slightly attenuate the result.
2246 static void NormalizeHrirs (const HrirDataT *hData)
2248 uint step, end, n, j, i;
2249 double maxLevel;
2251 step = hData->mIrSize;
2252 end = hData->mIrCount * step;
2253 n = hData->mIrPoints;
2254 maxLevel = 0.0;
2255 for(j = 0;j < end;j += step)
2257 for(i = 0;i < n;i++)
2258 maxLevel = fmax(fabs(hData->mHrirs[j+i]), maxLevel);
2260 maxLevel = 1.01 * maxLevel;
2261 for(j = 0;j < end;j += step)
2263 for(i = 0;i < n;i++)
2264 hData->mHrirs[j+i] /= maxLevel;
2268 // Calculate the left-ear time delay using a spherical head model.
2269 static double CalcLTD(const double ev, const double az, const double rad, const double dist)
2271 double azp, dlp, l, al;
2273 azp = asin(cos(ev) * sin(az));
2274 dlp = sqrt((dist*dist) + (rad*rad) + (2.0*dist*rad*sin(azp)));
2275 l = sqrt((dist*dist) - (rad*rad));
2276 al = (0.5 * M_PI) + azp;
2277 if(dlp > l)
2278 dlp = l + (rad * (al - acos(rad / dist)));
2279 return (dlp / 343.3);
2282 // Calculate the effective head-related time delays for each minimum-phase
2283 // HRIR.
2284 static void CalculateHrtds (const HeadModelT model, const double radius, HrirDataT *hData)
2286 double minHrtd, maxHrtd;
2287 uint e, a, j;
2288 double t;
2290 minHrtd = 1000.0;
2291 maxHrtd = -1000.0;
2292 for(e = 0;e < hData->mEvCount;e++)
2294 for(a = 0;a < hData->mAzCount[e];a++)
2296 j = hData->mEvOffset[e] + a;
2297 if(model == HM_DATASET)
2298 t = hData->mHrtds[j] * radius / hData->mRadius;
2299 else
2300 t = CalcLTD((-90.0 + (e * 180.0 / (hData->mEvCount - 1))) * M_PI / 180.0,
2301 (a * 360.0 / hData->mAzCount [e]) * M_PI / 180.0,
2302 radius, hData->mDistance);
2303 hData->mHrtds[j] = t;
2304 maxHrtd = fmax(t, maxHrtd);
2305 minHrtd = fmin(t, minHrtd);
2308 maxHrtd -= minHrtd;
2309 for(j = 0;j < hData->mIrCount;j++)
2310 hData->mHrtds[j] -= minHrtd;
2311 hData->mMaxHrtd = maxHrtd;
2315 // Process the data set definition to read and validate the data set metrics.
2316 static int ProcessMetrics(TokenReaderT *tr, const uint fftSize, const uint truncSize, HrirDataT *hData)
2318 int hasRate = 0, hasPoints = 0, hasAzimuths = 0;
2319 int hasRadius = 0, hasDistance = 0;
2320 char ident[MAX_IDENT_LEN+1];
2321 uint line, col;
2322 double fpVal;
2323 uint points;
2324 int intVal;
2326 while(!(hasRate && hasPoints && hasAzimuths && hasRadius && hasDistance))
2328 TrIndication(tr, & line, & col);
2329 if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
2330 return 0;
2331 if(strcasecmp(ident, "rate") == 0)
2333 if(hasRate)
2335 TrErrorAt(tr, line, col, "Redefinition of 'rate'.\n");
2336 return 0;
2338 if(!TrReadOperator(tr, "="))
2339 return 0;
2340 if(!TrReadInt(tr, MIN_RATE, MAX_RATE, &intVal))
2341 return 0;
2342 hData->mIrRate = (uint)intVal;
2343 hasRate = 1;
2345 else if(strcasecmp(ident, "points") == 0)
2347 if (hasPoints) {
2348 TrErrorAt(tr, line, col, "Redefinition of 'points'.\n");
2349 return 0;
2351 if(!TrReadOperator(tr, "="))
2352 return 0;
2353 TrIndication(tr, &line, &col);
2354 if(!TrReadInt(tr, MIN_POINTS, MAX_POINTS, &intVal))
2355 return 0;
2356 points = (uint)intVal;
2357 if(fftSize > 0 && points > fftSize)
2359 TrErrorAt(tr, line, col, "Value exceeds the overridden FFT size.\n");
2360 return 0;
2362 if(points < truncSize)
2364 TrErrorAt(tr, line, col, "Value is below the truncation size.\n");
2365 return 0;
2367 hData->mIrPoints = points;
2368 if(fftSize <= 0)
2370 hData->mFftSize = DEFAULT_FFTSIZE;
2371 hData->mIrSize = 1 + (DEFAULT_FFTSIZE / 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 (default: %u).\n", DEFAULT_FFTSIZE);
2808 fprintf(ofile, " -e={on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE ? "on" : "off"));
2809 fprintf(ofile, " -s={on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE ? "on" : "off"));
2810 fprintf(ofile, " -l={<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
2811 fprintf(ofile, " average (default: %.2f).\n", DEFAULT_LIMIT);
2812 fprintf(ofile, " -w=<points> Specify the size of the truncation window that's applied\n");
2813 fprintf(ofile, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE);
2814 fprintf(ofile, " -d={dataset| Specify the model used for calculating the head-delay timing\n");
2815 fprintf(ofile, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL == HM_DATASET) ? "dataset" : "sphere"));
2816 fprintf(ofile, " -c=<size> Use a customized head radius measured ear-to-ear in meters.\n");
2817 fprintf(ofile, " -i=<filename> Specify an HRIR definition file to use (defaults to stdin).\n");
2818 fprintf(ofile, " -o=<filename> Specify an output file. Overrides command-selected default.\n");
2819 fprintf(ofile, " Use of '%%r' will be substituted with the data set sample rate.\n");
2822 // Standard command line dispatch.
2823 int main(const int argc, const char *argv[])
2825 const char *inName = NULL, *outName = NULL;
2826 OutputFormatT outFormat;
2827 uint outRate, fftSize;
2828 int equalize, surface;
2829 char *end = NULL;
2830 HeadModelT model;
2831 uint truncSize;
2832 double radius;
2833 double limit;
2834 int argi;
2836 if(argc < 2 || strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0)
2838 fprintf(stdout, "HRTF Processing and Composition Utility\n\n");
2839 PrintHelp(argv[0], stdout);
2840 return 0;
2843 if(strcmp(argv[1], "--make-mhr") == 0 || strcmp(argv[1], "-m") == 0)
2845 outName = "./oalsoft_hrtf_%r.mhr";
2846 outFormat = OF_MHR;
2848 else
2850 fprintf(stderr, "Error: Invalid command '%s'.\n\n", argv[1]);
2851 PrintHelp(argv[0], stderr);
2852 return -1;
2855 outRate = 0;
2856 fftSize = 0;
2857 equalize = DEFAULT_EQUALIZE;
2858 surface = DEFAULT_SURFACE;
2859 limit = DEFAULT_LIMIT;
2860 truncSize = DEFAULT_TRUNCSIZE;
2861 model = DEFAULT_HEAD_MODEL;
2862 radius = DEFAULT_CUSTOM_RADIUS;
2864 argi = 2;
2865 while(argi < argc)
2867 if(strncmp(argv[argi], "-r=", 3) == 0)
2869 outRate = strtoul(&argv[argi][3], &end, 10);
2870 if(end[0] != '\0' || outRate < MIN_RATE || outRate > MAX_RATE)
2872 fprintf(stderr, "Error: Expected a value from %u to %u for '-r'.\n", MIN_RATE, MAX_RATE);
2873 return -1;
2876 else if(strncmp(argv[argi], "-f=", 3) == 0)
2878 fftSize = strtoul(&argv[argi][3], &end, 10);
2879 if(end[0] != '\0' || (fftSize&(fftSize-1)) || fftSize < MIN_FFTSIZE || fftSize > MAX_FFTSIZE)
2881 fprintf(stderr, "Error: Expected a power-of-two value from %u to %u for '-f'.\n", MIN_FFTSIZE, MAX_FFTSIZE);
2882 return -1;
2885 else if(strncmp(argv[argi], "-e=", 3) == 0)
2887 if(strcmp(&argv[argi][3], "on") == 0)
2888 equalize = 1;
2889 else if(strcmp(&argv[argi][3], "off") == 0)
2890 equalize = 0;
2891 else
2893 fprintf(stderr, "Error: Expected 'on' or 'off' for '-e'.\n");
2894 return -1;
2897 else if(strncmp(argv[argi], "-s=", 3) == 0)
2899 if(strcmp(&argv[argi][3], "on") == 0)
2900 surface = 1;
2901 else if(strcmp(&argv[argi][3], "off") == 0)
2902 surface = 0;
2903 else
2905 fprintf(stderr, "Error: Expected 'on' or 'off' for '-s'.\n");
2906 return -1;
2909 else if(strncmp(argv[argi], "-l=", 3) == 0)
2911 if(strcmp(&argv[argi][3], "none") == 0)
2912 limit = 0.0;
2913 else
2915 limit = strtod(&argv[argi] [3], &end);
2916 if(end[0] != '\0' || limit < MIN_LIMIT || limit > MAX_LIMIT)
2918 fprintf(stderr, "Error: Expected 'none' or a value from %.2f to %.2f for '-l'.\n", MIN_LIMIT, MAX_LIMIT);
2919 return -1;
2923 else if(strncmp(argv[argi], "-w=", 3) == 0)
2925 truncSize = strtoul(&argv[argi][3], &end, 10);
2926 if(end[0] != '\0' || truncSize < MIN_TRUNCSIZE || truncSize > MAX_TRUNCSIZE || (truncSize%MOD_TRUNCSIZE))
2928 fprintf(stderr, "Error: Expected a value from %u to %u in multiples of %u for '-w'.\n", MIN_TRUNCSIZE, MAX_TRUNCSIZE, MOD_TRUNCSIZE);
2929 return -1;
2932 else if(strncmp(argv[argi], "-d=", 3) == 0)
2934 if(strcmp(&argv[argi][3], "dataset") == 0)
2935 model = HM_DATASET;
2936 else if(strcmp(&argv[argi][3], "sphere") == 0)
2937 model = HM_SPHERE;
2938 else
2940 fprintf(stderr, "Error: Expected 'dataset' or 'sphere' for '-d'.\n");
2941 return -1;
2944 else if(strncmp(argv[argi], "-c=", 3) == 0)
2946 radius = strtod(&argv[argi][3], &end);
2947 if(end[0] != '\0' || radius < MIN_CUSTOM_RADIUS || radius > MAX_CUSTOM_RADIUS)
2949 fprintf(stderr, "Error: Expected a value from %.2f to %.2f for '-c'.\n", MIN_CUSTOM_RADIUS, MAX_CUSTOM_RADIUS);
2950 return -1;
2953 else if(strncmp(argv[argi], "-i=", 3) == 0)
2954 inName = &argv[argi][3];
2955 else if(strncmp(argv[argi], "-o=", 3) == 0)
2956 outName = &argv[argi][3];
2957 else
2959 fprintf(stderr, "Error: Invalid option '%s'.\n", argv[argi]);
2960 return -1;
2962 argi++;
2964 if(!ProcessDefinition(inName, outRate, fftSize, equalize, surface, limit, truncSize, model, radius, outFormat, outName))
2965 return -1;
2966 fprintf(stdout, "Operation completed.\n");
2967 return 0;