Open a device only when a driver index is found
[openal-soft.git] / utils / makehrtf.c
blob704bf622fb31e509d56edbb51143d4cde4744988
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 uint n, const double f, const uint ei, const uint ai, const HrirDataT *hData)
1928 double mag;
1929 uint i, j;
1931 mag = 0.0;
1932 for(i = 0;i < n;i++)
1933 mag = fmax(fabs(hrir[i]), mag);
1934 mag *= 0.15;
1935 for(i = 0;i < n;i++)
1937 if(fabs(hrir[i]) >= mag)
1938 break;
1940 j = hData->mEvOffset[ei] + ai;
1941 hData->mHrtds[j] = Lerp(hData->mHrtds[j], ((double)i) / hData->mIrRate, f);
1944 // Calculate the magnitude response of an HRIR and average it with any
1945 // existing responses for its elevation and azimuth.
1946 static void AverageHrirMagnitude(const double *hrir, const uint npoints, const double f, const uint ei, const uint ai, const HrirDataT *hData)
1948 double *re, *im;
1949 uint n, m, i, j;
1951 n = hData->mFftSize;
1952 re = CreateArray(n);
1953 im = CreateArray(n);
1954 for(i = 0;i < npoints;i++)
1956 re[i] = hrir[i];
1957 im[i] = 0.0;
1959 for(;i < n;i++)
1961 re[i] = 0.0;
1962 im[i] = 0.0;
1964 FftForward(n, re, im, re, im);
1965 MagnitudeResponse(n, re, im, re);
1966 m = 1 + (n / 2);
1967 j = (hData->mEvOffset[ei] + ai) * hData->mIrSize;
1968 for(i = 0;i < m;i++)
1969 hData->mHrirs[j+i] = Lerp(hData->mHrirs[j+i], re[i], f);
1970 DestroyArray(im);
1971 DestroyArray(re);
1974 /* Calculate the contribution of each HRIR to the diffuse-field average based
1975 * on the area of its surface patch. All patches are centered at the HRIR
1976 * coordinates on the unit sphere and are measured by solid angle.
1978 static void CalculateDfWeights(const HrirDataT *hData, double *weights)
1980 double evs, sum, ev, up_ev, down_ev, solidAngle;
1981 uint ei;
1983 evs = 90.0 / (hData->mEvCount - 1);
1984 sum = 0.0;
1985 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
1987 // For each elevation, calculate the upper and lower limits of the
1988 // patch band.
1989 ev = -90.0 + (ei * 2.0 * evs);
1990 if(ei < (hData->mEvCount - 1))
1991 up_ev = (ev + evs) * M_PI / 180.0;
1992 else
1993 up_ev = M_PI / 2.0;
1994 if(ei > 0)
1995 down_ev = (ev - evs) * M_PI / 180.0;
1996 else
1997 down_ev = -M_PI / 2.0;
1998 // Calculate the area of the patch band.
1999 solidAngle = 2.0 * M_PI * (sin(up_ev) - sin(down_ev));
2000 // Each weight is the area of one patch.
2001 weights[ei] = solidAngle / hData->mAzCount [ei];
2002 // Sum the total surface area covered by the HRIRs.
2003 sum += solidAngle;
2005 // Normalize the weights given the total surface coverage.
2006 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
2007 weights[ei] /= sum;
2010 /* Calculate the diffuse-field average from the given magnitude responses of
2011 * the HRIR set. Weighting can be applied to compensate for the varying
2012 * surface area covered by each HRIR. The final average can then be limited
2013 * by the specified magnitude range (in positive dB; 0.0 to skip).
2015 static void CalculateDiffuseFieldAverage(const HrirDataT *hData, const int weighted, const double limit, double *dfa)
2017 uint ei, ai, count, step, start, end, m, j, i;
2018 double *weights;
2020 weights = CreateArray(hData->mEvCount);
2021 if(weighted)
2023 // Use coverage weighting to calculate the average.
2024 CalculateDfWeights(hData, weights);
2026 else
2028 // If coverage weighting is not used, the weights still need to be
2029 // averaged by the number of HRIRs.
2030 count = 0;
2031 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
2032 count += hData->mAzCount [ei];
2033 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
2034 weights[ei] = 1.0 / count;
2036 ei = hData->mEvStart;
2037 ai = 0;
2038 step = hData->mIrSize;
2039 start = hData->mEvOffset[ei] * step;
2040 end = hData->mIrCount * step;
2041 m = 1 + (hData->mFftSize / 2);
2042 for(i = 0;i < m;i++)
2043 dfa[i] = 0.0;
2044 for(j = start;j < end;j += step)
2046 // Get the weight for this HRIR's contribution.
2047 double weight = weights[ei];
2048 // Add this HRIR's weighted power average to the total.
2049 for(i = 0;i < m;i++)
2050 dfa[i] += weight * hData->mHrirs[j+i] * hData->mHrirs[j+i];
2051 // Determine the next weight to use.
2052 ai++;
2053 if(ai >= hData->mAzCount[ei])
2055 ei++;
2056 ai = 0;
2059 // Finish the average calculation and keep it from being too small.
2060 for(i = 0;i < m;i++)
2061 dfa[i] = fmax(sqrt(dfa[i]), EPSILON);
2062 // Apply a limit to the magnitude range of the diffuse-field average if
2063 // desired.
2064 if(limit > 0.0)
2065 LimitMagnitudeResponse(hData->mFftSize, limit, dfa, dfa);
2066 DestroyArray(weights);
2069 // Perform diffuse-field equalization on the magnitude responses of the HRIR
2070 // set using the given average response.
2071 static void DiffuseFieldEqualize(const double *dfa, const HrirDataT *hData)
2073 uint step, start, end, m, j, i;
2075 step = hData->mIrSize;
2076 start = hData->mEvOffset[hData->mEvStart] * step;
2077 end = hData->mIrCount * step;
2078 m = 1 + (hData->mFftSize / 2);
2079 for(j = start;j < end;j += step)
2081 for(i = 0;i < m;i++)
2082 hData->mHrirs[j+i] /= dfa[i];
2086 // Perform minimum-phase reconstruction using the magnitude responses of the
2087 // HRIR set.
2088 static void ReconstructHrirs(const HrirDataT *hData)
2090 uint step, start, end, n, j, i;
2091 double *re, *im;
2093 step = hData->mIrSize;
2094 start = hData->mEvOffset[hData->mEvStart] * step;
2095 end = hData->mIrCount * step;
2096 n = hData->mFftSize;
2097 re = CreateArray(n);
2098 im = CreateArray(n);
2099 for(j = start;j < end;j += step)
2101 MinimumPhase(n, &hData->mHrirs[j], re, im);
2102 FftInverse(n, re, im, re, im);
2103 for(i = 0;i < hData->mIrPoints;i++)
2104 hData->mHrirs[j+i] = re[i];
2106 DestroyArray (im);
2107 DestroyArray (re);
2110 /* Given an elevation index and an azimuth, calculate the indices of the two
2111 * HRIRs that bound the coordinate along with a factor for calculating the
2112 * continous HRIR using interpolation.
2114 static void CalcAzIndices(const HrirDataT *hData, const uint ei, const double az, uint *j0, uint *j1, double *jf)
2116 double af;
2117 uint ai;
2119 af = ((2.0*M_PI) + az) * hData->mAzCount[ei] / (2.0*M_PI);
2120 ai = ((uint)af) % hData->mAzCount[ei];
2121 af -= floor(af);
2123 *j0 = hData->mEvOffset[ei] + ai;
2124 *j1 = hData->mEvOffset[ei] + ((ai+1) % hData->mAzCount [ei]);
2125 *jf = af;
2128 // Synthesize any missing onset timings at the bottom elevations. This just
2129 // blends between slightly exaggerated known onsets. Not an accurate model.
2130 static void SynthesizeOnsets(HrirDataT *hData)
2132 uint oi, e, a, j0, j1;
2133 double t, of, jf;
2135 oi = hData->mEvStart;
2136 t = 0.0;
2137 for(a = 0;a < hData->mAzCount[oi];a++)
2138 t += hData->mHrtds[hData->mEvOffset[oi] + a];
2139 hData->mHrtds[0] = 1.32e-4 + (t / hData->mAzCount[oi]);
2140 for(e = 1;e < hData->mEvStart;e++)
2142 of = ((double)e) / hData->mEvStart;
2143 for(a = 0;a < hData->mAzCount[e];a++)
2145 CalcAzIndices(hData, oi, a * 2.0 * M_PI / hData->mAzCount[e], &j0, &j1, &jf);
2146 hData->mHrtds[hData->mEvOffset[e] + a] = Lerp(hData->mHrtds[0], Lerp(hData->mHrtds[j0], hData->mHrtds[j1], jf), of);
2151 /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
2152 * now this just blends the lowest elevation HRIRs together and applies some
2153 * attenuation and high frequency damping. It is a simple, if inaccurate
2154 * model.
2156 static void SynthesizeHrirs (HrirDataT *hData)
2158 uint oi, a, e, step, n, i, j;
2159 double lp[4], s0, s1;
2160 double of, b;
2161 uint j0, j1;
2162 double jf;
2164 if(hData->mEvStart <= 0)
2165 return;
2166 step = hData->mIrSize;
2167 oi = hData->mEvStart;
2168 n = hData->mIrPoints;
2169 for(i = 0;i < n;i++)
2170 hData->mHrirs[i] = 0.0;
2171 for(a = 0;a < hData->mAzCount[oi];a++)
2173 j = (hData->mEvOffset[oi] + a) * step;
2174 for(i = 0;i < n;i++)
2175 hData->mHrirs[i] += hData->mHrirs[j+i] / hData->mAzCount[oi];
2177 for(e = 1;e < hData->mEvStart;e++)
2179 of = ((double)e) / hData->mEvStart;
2180 b = (1.0 - of) * (3.5e-6 * hData->mIrRate);
2181 for(a = 0;a < hData->mAzCount[e];a++)
2183 j = (hData->mEvOffset[e] + a) * step;
2184 CalcAzIndices(hData, oi, a * 2.0 * M_PI / hData->mAzCount[e], &j0, &j1, &jf);
2185 j0 *= step;
2186 j1 *= step;
2187 lp[0] = 0.0;
2188 lp[1] = 0.0;
2189 lp[2] = 0.0;
2190 lp[3] = 0.0;
2191 for(i = 0;i < n;i++)
2193 s0 = hData->mHrirs[i];
2194 s1 = Lerp(hData->mHrirs[j0+i], hData->mHrirs[j1+i], jf);
2195 s0 = Lerp(s0, s1, of);
2196 lp[0] = Lerp(s0, lp[0], b);
2197 lp[1] = Lerp(lp[0], lp[1], b);
2198 lp[2] = Lerp(lp[1], lp[2], b);
2199 lp[3] = Lerp(lp[2], lp[3], b);
2200 hData->mHrirs[j+i] = lp[3];
2204 b = 3.5e-6 * hData->mIrRate;
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 lp[0] = Lerp(s0, lp[0], b);
2213 lp[1] = Lerp(lp[0], lp[1], b);
2214 lp[2] = Lerp(lp[1], lp[2], b);
2215 lp[3] = Lerp(lp[2], lp[3], b);
2216 hData->mHrirs[i] = lp[3];
2218 hData->mEvStart = 0;
2221 // The following routines assume a full set of HRIRs for all elevations.
2223 // Normalize the HRIR set and slightly attenuate the result.
2224 static void NormalizeHrirs (const HrirDataT *hData)
2226 uint step, end, n, j, i;
2227 double maxLevel;
2229 step = hData->mIrSize;
2230 end = hData->mIrCount * step;
2231 n = hData->mIrPoints;
2232 maxLevel = 0.0;
2233 for(j = 0;j < end;j += step)
2235 for(i = 0;i < n;i++)
2236 maxLevel = fmax(fabs(hData->mHrirs[j+i]), maxLevel);
2238 maxLevel = 1.01 * maxLevel;
2239 for(j = 0;j < end;j += step)
2241 for(i = 0;i < n;i++)
2242 hData->mHrirs[j+i] /= maxLevel;
2246 // Calculate the left-ear time delay using a spherical head model.
2247 static double CalcLTD(const double ev, const double az, const double rad, const double dist)
2249 double azp, dlp, l, al;
2251 azp = asin(cos(ev) * sin(az));
2252 dlp = sqrt((dist*dist) + (rad*rad) + (2.0*dist*rad*sin(azp)));
2253 l = sqrt((dist*dist) - (rad*rad));
2254 al = (0.5 * M_PI) + azp;
2255 if(dlp > l)
2256 dlp = l + (rad * (al - acos(rad / dist)));
2257 return (dlp / 343.3);
2260 // Calculate the effective head-related time delays for each minimum-phase
2261 // HRIR.
2262 static void CalculateHrtds (const HeadModelT model, const double radius, HrirDataT *hData)
2264 double minHrtd, maxHrtd;
2265 uint e, a, j;
2266 double t;
2268 minHrtd = 1000.0;
2269 maxHrtd = -1000.0;
2270 for(e = 0;e < hData->mEvCount;e++)
2272 for(a = 0;a < hData->mAzCount[e];a++)
2274 j = hData->mEvOffset[e] + a;
2275 if(model == HM_DATASET)
2276 t = hData->mHrtds[j] * radius / hData->mRadius;
2277 else
2278 t = CalcLTD((-90.0 + (e * 180.0 / (hData->mEvCount - 1))) * M_PI / 180.0,
2279 (a * 360.0 / hData->mAzCount [e]) * M_PI / 180.0,
2280 radius, hData->mDistance);
2281 hData->mHrtds[j] = t;
2282 maxHrtd = fmax(t, maxHrtd);
2283 minHrtd = fmin(t, minHrtd);
2286 maxHrtd -= minHrtd;
2287 for(j = 0;j < hData->mIrCount;j++)
2288 hData->mHrtds[j] -= minHrtd;
2289 hData->mMaxHrtd = maxHrtd;
2293 // Process the data set definition to read and validate the data set metrics.
2294 static int ProcessMetrics(TokenReaderT *tr, const uint fftSize, const uint truncSize, HrirDataT *hData)
2296 int hasRate = 0, hasPoints = 0, hasAzimuths = 0;
2297 int hasRadius = 0, hasDistance = 0;
2298 char ident[MAX_IDENT_LEN+1];
2299 uint line, col;
2300 double fpVal;
2301 uint points;
2302 int intVal;
2304 while(!(hasRate && hasPoints && hasAzimuths && hasRadius && hasDistance))
2306 TrIndication(tr, & line, & col);
2307 if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
2308 return 0;
2309 if(strcasecmp(ident, "rate") == 0)
2311 if(hasRate)
2313 TrErrorAt(tr, line, col, "Redefinition of 'rate'.\n");
2314 return 0;
2316 if(!TrReadOperator(tr, "="))
2317 return 0;
2318 if(!TrReadInt(tr, MIN_RATE, MAX_RATE, &intVal))
2319 return 0;
2320 hData->mIrRate = (uint)intVal;
2321 hasRate = 1;
2323 else if(strcasecmp(ident, "points") == 0)
2325 if (hasPoints) {
2326 TrErrorAt(tr, line, col, "Redefinition of 'points'.\n");
2327 return 0;
2329 if(!TrReadOperator(tr, "="))
2330 return 0;
2331 TrIndication(tr, &line, &col);
2332 if(!TrReadInt(tr, MIN_POINTS, MAX_POINTS, &intVal))
2333 return 0;
2334 points = (uint)intVal;
2335 if(fftSize > 0 && points > fftSize)
2337 TrErrorAt(tr, line, col, "Value exceeds the overridden FFT size.\n");
2338 return 0;
2340 if(points < truncSize)
2342 TrErrorAt(tr, line, col, "Value is below the truncation size.\n");
2343 return 0;
2345 hData->mIrPoints = points;
2346 hData->mFftSize = fftSize;
2347 if(fftSize <= 0)
2349 points = 1;
2350 while(points < (4 * hData->mIrPoints))
2351 points <<= 1;
2352 hData->mFftSize = points;
2353 hData->mIrSize = 1 + (points / 2);
2355 else
2357 hData->mFftSize = fftSize;
2358 hData->mIrSize = 1 + (fftSize / 2);
2359 if(points > hData->mIrSize)
2360 hData->mIrSize = points;
2362 hasPoints = 1;
2364 else if(strcasecmp(ident, "azimuths") == 0)
2366 if(hasAzimuths)
2368 TrErrorAt(tr, line, col, "Redefinition of 'azimuths'.\n");
2369 return 0;
2371 if(!TrReadOperator(tr, "="))
2372 return 0;
2373 hData->mIrCount = 0;
2374 hData->mEvCount = 0;
2375 hData->mEvOffset[0] = 0;
2376 for(;;)
2378 if(!TrReadInt(tr, MIN_AZ_COUNT, MAX_AZ_COUNT, &intVal))
2379 return 0;
2380 hData->mAzCount[hData->mEvCount] = (uint)intVal;
2381 hData->mIrCount += (uint)intVal;
2382 hData->mEvCount ++;
2383 if(!TrIsOperator(tr, ","))
2384 break;
2385 if(hData->mEvCount >= MAX_EV_COUNT)
2387 TrError(tr, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT);
2388 return 0;
2390 hData->mEvOffset[hData->mEvCount] = hData->mEvOffset[hData->mEvCount - 1] + ((uint)intVal);
2391 TrReadOperator(tr, ",");
2393 if(hData->mEvCount < MIN_EV_COUNT)
2395 TrErrorAt(tr, line, col, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT);
2396 return 0;
2398 hasAzimuths = 1;
2400 else if(strcasecmp(ident, "radius") == 0)
2402 if(hasRadius)
2404 TrErrorAt(tr, line, col, "Redefinition of 'radius'.\n");
2405 return 0;
2407 if(!TrReadOperator(tr, "="))
2408 return 0;
2409 if(!TrReadFloat(tr, MIN_RADIUS, MAX_RADIUS, &fpVal))
2410 return 0;
2411 hData->mRadius = fpVal;
2412 hasRadius = 1;
2414 else if(strcasecmp(ident, "distance") == 0)
2416 if(hasDistance)
2418 TrErrorAt(tr, line, col, "Redefinition of 'distance'.\n");
2419 return 0;
2421 if(!TrReadOperator(tr, "="))
2422 return 0;
2423 if(!TrReadFloat(tr, MIN_DISTANCE, MAX_DISTANCE, & fpVal))
2424 return 0;
2425 hData->mDistance = fpVal;
2426 hasDistance = 1;
2428 else
2430 TrErrorAt(tr, line, col, "Expected a metric name.\n");
2431 return 0;
2433 TrSkipWhitespace (tr);
2435 return 1;
2438 // Parse an index pair from the data set definition.
2439 static int ReadIndexPair(TokenReaderT *tr, const HrirDataT *hData, uint *ei, uint *ai)
2441 int intVal;
2442 if(!TrReadInt(tr, 0, (int)hData->mEvCount, &intVal))
2443 return 0;
2444 *ei = (uint)intVal;
2445 if(!TrReadOperator(tr, ","))
2446 return 0;
2447 if(!TrReadInt(tr, 0, (int)hData->mAzCount[*ei], &intVal))
2448 return 0;
2449 *ai = (uint)intVal;
2450 return 1;
2453 // Match the source format from a given identifier.
2454 static SourceFormatT MatchSourceFormat(const char *ident)
2456 if(strcasecmp(ident, "wave") == 0)
2457 return SF_WAVE;
2458 if(strcasecmp(ident, "bin_le") == 0)
2459 return SF_BIN_LE;
2460 if(strcasecmp(ident, "bin_be") == 0)
2461 return SF_BIN_BE;
2462 if(strcasecmp(ident, "ascii") == 0)
2463 return SF_ASCII;
2464 return SF_NONE;
2467 // Match the source element type from a given identifier.
2468 static ElementTypeT MatchElementType(const char *ident)
2470 if(strcasecmp(ident, "int") == 0)
2471 return ET_INT;
2472 if(strcasecmp(ident, "fp") == 0)
2473 return ET_FP;
2474 return ET_NONE;
2477 // Parse and validate a source reference from the data set definition.
2478 static int ReadSourceRef(TokenReaderT *tr, SourceRefT *src)
2480 char ident[MAX_IDENT_LEN+1];
2481 uint line, col;
2482 int intVal;
2484 TrIndication(tr, &line, &col);
2485 if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
2486 return 0;
2487 src->mFormat = MatchSourceFormat(ident);
2488 if(src->mFormat == SF_NONE)
2490 TrErrorAt(tr, line, col, "Expected a source format.\n");
2491 return 0;
2493 if(!TrReadOperator(tr, "("))
2494 return 0;
2495 if(src->mFormat == SF_WAVE)
2497 if(!TrReadInt(tr, 0, MAX_WAVE_CHANNELS, &intVal))
2498 return 0;
2499 src->mType = ET_NONE;
2500 src->mSize = 0;
2501 src->mBits = 0;
2502 src->mChannel = (uint)intVal;
2503 src->mSkip = 0;
2505 else
2507 TrIndication(tr, &line, &col);
2508 if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
2509 return 0;
2510 src->mType = MatchElementType(ident);
2511 if(src->mType == ET_NONE)
2513 TrErrorAt(tr, line, col, "Expected a source element type.\n");
2514 return 0;
2516 if(src->mFormat == SF_BIN_LE || src->mFormat == SF_BIN_BE)
2518 if(!TrReadOperator(tr, ","))
2519 return 0;
2520 if(src->mType == ET_INT)
2522 if(!TrReadInt(tr, MIN_BIN_SIZE, MAX_BIN_SIZE, &intVal))
2523 return 0;
2524 src->mSize = (uint)intVal;
2525 if(!TrIsOperator(tr, ","))
2526 src->mBits = (int)(8*src->mSize);
2527 else
2529 TrReadOperator(tr, ",");
2530 TrIndication(tr, &line, &col);
2531 if(!TrReadInt(tr, -2147483647-1, 2147483647, &intVal))
2532 return 0;
2533 if(abs(intVal) < MIN_BIN_BITS || ((uint)abs(intVal)) > (8*src->mSize))
2535 TrErrorAt(tr, line, col, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS, 8*src->mSize);
2536 return 0;
2538 src->mBits = intVal;
2541 else
2543 TrIndication(tr, &line, &col);
2544 if(!TrReadInt(tr, -2147483647-1, 2147483647, &intVal))
2545 return 0;
2546 if(intVal != 4 && intVal != 8)
2548 TrErrorAt(tr, line, col, "Expected a value of 4 or 8.\n");
2549 return 0;
2551 src->mSize = (uint)intVal;
2552 src->mBits = 0;
2555 else if(src->mFormat == SF_ASCII && src->mType == ET_INT)
2557 if(!TrReadOperator(tr, ","))
2558 return 0;
2559 if(!TrReadInt(tr, MIN_ASCII_BITS, MAX_ASCII_BITS, &intVal))
2560 return 0;
2561 src->mSize = 0;
2562 src->mBits = intVal;
2564 else
2566 src->mSize = 0;
2567 src->mBits = 0;
2570 if(!TrIsOperator(tr, ";"))
2571 src->mSkip = 0;
2572 else
2574 TrReadOperator(tr, ";");
2575 if(!TrReadInt (tr, 0, 0x7FFFFFFF, &intVal))
2576 return 0;
2577 src->mSkip = (uint)intVal;
2580 if(!TrReadOperator(tr, ")"))
2581 return 0;
2582 if(TrIsOperator(tr, "@"))
2584 TrReadOperator(tr, "@");
2585 if(!TrReadInt(tr, 0, 0x7FFFFFFF, &intVal))
2586 return 0;
2587 src->mOffset = (uint)intVal;
2589 else
2590 src->mOffset = 0;
2591 if(!TrReadOperator(tr, ":"))
2592 return 0;
2593 if(!TrReadString(tr, MAX_PATH_LEN, src->mPath))
2594 return 0;
2595 return 1;
2598 // Process the list of sources in the data set definition.
2599 static int ProcessSources(const HeadModelT model, const uint dstRate, TokenReaderT *tr, HrirDataT *hData)
2601 uint *setCount, *setFlag;
2602 uint line, col, ei, ai;
2603 uint res_points;
2604 SourceRefT src;
2605 double factor;
2606 double *hrir;
2607 ResamplerT rs;
2609 ResamplerSetup(&rs, hData->mIrRate, dstRate);
2610 /* Scale the number of IR points for resampling. This could be improved by
2611 * also including space for the resampler build-up and fall-off (rs.mL*2),
2612 * instead of clipping them off, but that could affect the HRTDs. It's not
2613 * a big deal to exclude them for sources that aren't already minimum-
2614 * phase).
2616 res_points = (uint)(((uint64)hData->mIrPoints*dstRate + hData->mIrRate-1) /
2617 hData->mIrRate);
2618 /* Clamp to the IR size to prevent overflow, and don't go less than the
2619 * original point count.
2621 if(res_points > hData->mIrSize)
2622 res_points = hData->mIrSize;
2623 else if(res_points < hData->mIrPoints)
2624 res_points = hData->mIrPoints;
2626 setCount = (uint*)calloc(hData->mEvCount, sizeof(uint));
2627 setFlag = (uint*)calloc(hData->mIrCount, sizeof(uint));
2628 hrir = CreateArray(res_points);
2630 while(TrIsOperator(tr, "["))
2632 TrIndication(tr, & line, & col);
2633 TrReadOperator(tr, "[");
2634 if(!ReadIndexPair(tr, hData, &ei, &ai))
2635 goto error;
2636 if(!TrReadOperator(tr, "]"))
2637 goto error;
2638 if(setFlag[hData->mEvOffset[ei] + ai])
2640 TrErrorAt(tr, line, col, "Redefinition of source.\n");
2641 goto error;
2643 if(!TrReadOperator(tr, "="))
2644 goto error;
2646 factor = 1.0;
2647 for(;;)
2649 if(!ReadSourceRef(tr, &src))
2650 goto error;
2651 if(!LoadSource(&src, hData->mIrRate, hData->mIrPoints, hrir))
2652 goto error;
2654 if(hData->mIrRate != dstRate)
2655 ResamplerRun(&rs, hData->mIrPoints, hrir,
2656 res_points, hrir);
2658 if(model == HM_DATASET)
2659 AverageHrirOnset(hrir, res_points, 1.0 / factor, ei, ai, hData);
2660 AverageHrirMagnitude(hrir, res_points, 1.0 / factor, ei, ai, hData);
2661 factor += 1.0;
2662 if(!TrIsOperator(tr, "+"))
2663 break;
2664 TrReadOperator(tr, "+");
2666 setFlag[hData->mEvOffset[ei] + ai] = 1;
2667 setCount[ei]++;
2669 hData->mIrPoints = res_points;
2670 hData->mIrRate = dstRate;
2672 ei = 0;
2673 while(ei < hData->mEvCount && setCount[ei] < 1)
2674 ei++;
2675 if(ei < hData->mEvCount)
2677 hData->mEvStart = ei;
2678 while(ei < hData->mEvCount && setCount[ei] == hData->mAzCount[ei])
2679 ei++;
2680 if(ei >= hData->mEvCount)
2682 if(!TrLoad(tr))
2684 ResamplerClear(&rs);
2685 DestroyArray(hrir);
2686 free(setFlag);
2687 free(setCount);
2688 return 1;
2690 TrError(tr, "Errant data at end of source list.\n");
2692 else
2693 TrError(tr, "Missing sources for elevation index %d.\n", ei);
2695 else
2696 TrError(tr, "Missing source references.\n");
2698 error:
2699 ResamplerClear(&rs);
2700 DestroyArray(hrir);
2701 free(setFlag);
2702 free(setCount);
2703 return 0;
2706 /* Parse the data set definition and process the source data, storing the
2707 * resulting data set as desired. If the input name is NULL it will read
2708 * from standard input.
2710 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)
2712 char rateStr[8+1], expName[MAX_PATH_LEN];
2713 TokenReaderT tr;
2714 HrirDataT hData;
2715 double *dfa;
2716 FILE *fp;
2718 hData.mIrRate = 0;
2719 hData.mIrPoints = 0;
2720 hData.mFftSize = 0;
2721 hData.mIrSize = 0;
2722 hData.mIrCount = 0;
2723 hData.mEvCount = 0;
2724 hData.mRadius = 0;
2725 hData.mDistance = 0;
2726 fprintf(stdout, "Reading HRIR definition...\n");
2727 if(inName != NULL)
2729 fp = fopen(inName, "r");
2730 if(fp == NULL)
2732 fprintf(stderr, "Error: Could not open definition file '%s'\n", inName);
2733 return 0;
2735 TrSetup(fp, inName, &tr);
2737 else
2739 fp = stdin;
2740 TrSetup(fp, "<stdin>", &tr);
2742 if(!ProcessMetrics(&tr, fftSize, truncSize, &hData))
2744 if(inName != NULL)
2745 fclose(fp);
2746 return 0;
2748 hData.mHrirs = CreateArray(hData.mIrCount * hData.mIrSize);
2749 hData.mHrtds = CreateArray(hData.mIrCount);
2750 if(!ProcessSources(model, outRate ? outRate : hData.mIrRate, &tr, &hData))
2752 DestroyArray(hData.mHrtds);
2753 DestroyArray(hData.mHrirs);
2754 if(inName != NULL)
2755 fclose(fp);
2756 return 0;
2758 if(inName != NULL)
2759 fclose(fp);
2760 if(equalize)
2762 dfa = CreateArray(1 + (hData.mFftSize/2));
2763 fprintf(stdout, "Calculating diffuse-field average...\n");
2764 CalculateDiffuseFieldAverage(&hData, surface, limit, dfa);
2765 fprintf(stdout, "Performing diffuse-field equalization...\n");
2766 DiffuseFieldEqualize(dfa, &hData);
2767 DestroyArray(dfa);
2769 fprintf(stdout, "Performing minimum phase reconstruction...\n");
2770 ReconstructHrirs(&hData);
2771 fprintf(stdout, "Truncating minimum-phase HRIRs...\n");
2772 hData.mIrPoints = truncSize;
2773 fprintf(stdout, "Synthesizing missing elevations...\n");
2774 if(model == HM_DATASET)
2775 SynthesizeOnsets(&hData);
2776 SynthesizeHrirs(&hData);
2777 fprintf(stdout, "Normalizing final HRIRs...\n");
2778 NormalizeHrirs(&hData);
2779 fprintf(stdout, "Calculating impulse delays...\n");
2780 CalculateHrtds(model, (radius > DEFAULT_CUSTOM_RADIUS) ? radius : hData.mRadius, &hData);
2781 snprintf(rateStr, 8, "%u", hData.mIrRate);
2782 StrSubst(outName, "%r", rateStr, MAX_PATH_LEN, expName);
2783 switch(outFormat)
2785 case OF_MHR:
2786 fprintf(stdout, "Creating MHR data set file...\n");
2787 if(!StoreMhr(&hData, expName))
2789 DestroyArray(hData.mHrtds);
2790 DestroyArray(hData.mHrirs);
2791 return 0;
2793 break;
2794 default:
2795 break;
2797 DestroyArray(hData.mHrtds);
2798 DestroyArray(hData.mHrirs);
2799 return 1;
2802 static void PrintHelp(const char *argv0, FILE *ofile)
2804 fprintf(ofile, "Usage: %s <command> [<option>...]\n\n", argv0);
2805 fprintf(ofile, "Commands:\n");
2806 fprintf(ofile, " -m, --make-mhr Makes an OpenAL Soft compatible HRTF data set.\n");
2807 fprintf(ofile, " Defaults output to: ./oalsoft_hrtf_%%r.mhr\n");
2808 fprintf(ofile, " -h, --help Displays this help information.\n\n");
2809 fprintf(ofile, "Options:\n");
2810 fprintf(ofile, " -r=<rate> Change the data set sample rate to the specified value and\n");
2811 fprintf(ofile, " resample the HRIRs accordingly.\n");
2812 fprintf(ofile, " -f=<points> Override the FFT window size (defaults to the first power-\n");
2813 fprintf(ofile, " of-two that fits four times the number of HRIR points).\n");
2814 fprintf(ofile, " -e={on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE ? "on" : "off"));
2815 fprintf(ofile, " -s={on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE ? "on" : "off"));
2816 fprintf(ofile, " -l={<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
2817 fprintf(ofile, " average (default: %.2f).\n", DEFAULT_LIMIT);
2818 fprintf(ofile, " -w=<points> Specify the size of the truncation window that's applied\n");
2819 fprintf(ofile, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE);
2820 fprintf(ofile, " -d={dataset| Specify the model used for calculating the head-delay timing\n");
2821 fprintf(ofile, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL == HM_DATASET) ? "dataset" : "sphere"));
2822 fprintf(ofile, " -c=<size> Use a customized head radius measured ear-to-ear in meters.\n");
2823 fprintf(ofile, " -i=<filename> Specify an HRIR definition file to use (defaults to stdin).\n");
2824 fprintf(ofile, " -o=<filename> Specify an output file. Overrides command-selected default.\n");
2825 fprintf(ofile, " Use of '%%r' will be substituted with the data set sample rate.\n");
2828 // Standard command line dispatch.
2829 int main(const int argc, const char *argv[])
2831 const char *inName = NULL, *outName = NULL;
2832 OutputFormatT outFormat;
2833 uint outRate, fftSize;
2834 int equalize, surface;
2835 char *end = NULL;
2836 HeadModelT model;
2837 uint truncSize;
2838 double radius;
2839 double limit;
2840 int argi;
2842 if(argc < 2 || strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0)
2844 fprintf(stdout, "HRTF Processing and Composition Utility\n\n");
2845 PrintHelp(argv[0], stdout);
2846 return 0;
2849 if(strcmp(argv[1], "--make-mhr") == 0 || strcmp(argv[1], "-m") == 0)
2851 outName = "./oalsoft_hrtf_%r.mhr";
2852 outFormat = OF_MHR;
2854 else
2856 fprintf(stderr, "Error: Invalid command '%s'.\n\n", argv[1]);
2857 PrintHelp(argv[0], stderr);
2858 return -1;
2861 outRate = 0;
2862 fftSize = 0;
2863 equalize = DEFAULT_EQUALIZE;
2864 surface = DEFAULT_SURFACE;
2865 limit = DEFAULT_LIMIT;
2866 truncSize = DEFAULT_TRUNCSIZE;
2867 model = DEFAULT_HEAD_MODEL;
2868 radius = DEFAULT_CUSTOM_RADIUS;
2870 argi = 2;
2871 while(argi < argc)
2873 if(strncmp(argv[argi], "-r=", 3) == 0)
2875 outRate = strtoul(&argv[argi][3], &end, 10);
2876 if(end[0] != '\0' || outRate < MIN_RATE || outRate > MAX_RATE)
2878 fprintf(stderr, "Error: Expected a value from %u to %u for '-r'.\n", MIN_RATE, MAX_RATE);
2879 return -1;
2882 else if(strncmp(argv[argi], "-f=", 3) == 0)
2884 fftSize = strtoul(&argv[argi][3], &end, 10);
2885 if(end[0] != '\0' || (fftSize&(fftSize-1)) || fftSize < MIN_FFTSIZE || fftSize > MAX_FFTSIZE)
2887 fprintf(stderr, "Error: Expected a power-of-two value from %u to %u for '-f'.\n", MIN_FFTSIZE, MAX_FFTSIZE);
2888 return -1;
2891 else if(strncmp(argv[argi], "-e=", 3) == 0)
2893 if(strcmp(&argv[argi][3], "on") == 0)
2894 equalize = 1;
2895 else if(strcmp(&argv[argi][3], "off") == 0)
2896 equalize = 0;
2897 else
2899 fprintf(stderr, "Error: Expected 'on' or 'off' for '-e'.\n");
2900 return -1;
2903 else if(strncmp(argv[argi], "-s=", 3) == 0)
2905 if(strcmp(&argv[argi][3], "on") == 0)
2906 surface = 1;
2907 else if(strcmp(&argv[argi][3], "off") == 0)
2908 surface = 0;
2909 else
2911 fprintf(stderr, "Error: Expected 'on' or 'off' for '-s'.\n");
2912 return -1;
2915 else if(strncmp(argv[argi], "-l=", 3) == 0)
2917 if(strcmp(&argv[argi][3], "none") == 0)
2918 limit = 0.0;
2919 else
2921 limit = strtod(&argv[argi] [3], &end);
2922 if(end[0] != '\0' || limit < MIN_LIMIT || limit > MAX_LIMIT)
2924 fprintf(stderr, "Error: Expected 'none' or a value from %.2f to %.2f for '-l'.\n", MIN_LIMIT, MAX_LIMIT);
2925 return -1;
2929 else if(strncmp(argv[argi], "-w=", 3) == 0)
2931 truncSize = strtoul(&argv[argi][3], &end, 10);
2932 if(end[0] != '\0' || truncSize < MIN_TRUNCSIZE || truncSize > MAX_TRUNCSIZE || (truncSize%MOD_TRUNCSIZE))
2934 fprintf(stderr, "Error: Expected a value from %u to %u in multiples of %u for '-w'.\n", MIN_TRUNCSIZE, MAX_TRUNCSIZE, MOD_TRUNCSIZE);
2935 return -1;
2938 else if(strncmp(argv[argi], "-d=", 3) == 0)
2940 if(strcmp(&argv[argi][3], "dataset") == 0)
2941 model = HM_DATASET;
2942 else if(strcmp(&argv[argi][3], "sphere") == 0)
2943 model = HM_SPHERE;
2944 else
2946 fprintf(stderr, "Error: Expected 'dataset' or 'sphere' for '-d'.\n");
2947 return -1;
2950 else if(strncmp(argv[argi], "-c=", 3) == 0)
2952 radius = strtod(&argv[argi][3], &end);
2953 if(end[0] != '\0' || radius < MIN_CUSTOM_RADIUS || radius > MAX_CUSTOM_RADIUS)
2955 fprintf(stderr, "Error: Expected a value from %.2f to %.2f for '-c'.\n", MIN_CUSTOM_RADIUS, MAX_CUSTOM_RADIUS);
2956 return -1;
2959 else if(strncmp(argv[argi], "-i=", 3) == 0)
2960 inName = &argv[argi][3];
2961 else if(strncmp(argv[argi], "-o=", 3) == 0)
2962 outName = &argv[argi][3];
2963 else
2965 fprintf(stderr, "Error: Invalid option '%s'.\n", argv[argi]);
2966 return -1;
2968 argi++;
2970 if(!ProcessDefinition(inName, outRate, fftSize, equalize, surface, limit, truncSize, model, radius, outFormat, outName))
2971 return -1;
2972 fprintf(stdout, "Operation completed.\n");
2973 return 0;