Improve the OSS enumeration code
[openal-soft.git] / utils / makehrtf.c
blob57d8a91a28bd0b531c6699c91caba7c8d38d61b7
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 enum ByteOrderT {
199 BO_NONE = 0,
200 BO_LITTLE ,
201 BO_BIG
204 // Source format for the references listed in the data set definition.
205 enum SourceFormatT {
206 SF_NONE = 0,
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.
213 // Element types for the references listed in the data set definition.
214 enum ElementTypeT {
215 ET_NONE = 0,
216 ET_INT , // Integer elements.
217 ET_FP // Floating-point elements.
220 // Head model used for calculating the impulse delays.
221 enum HeadModelT {
222 HM_NONE = 0,
223 HM_DATASET , // Measure the onset from the dataset.
224 HM_SPHERE // Calculate the onset using a spherical head model.
227 // Desired output format from the command line.
228 enum OutputFormatT {
229 OF_NONE = 0,
230 OF_MHR // OpenAL Soft MHR data set file.
233 // Unsigned integer type.
234 typedef unsigned int uint;
236 // Serialization types. The trailing digit indicates the number of bits.
237 typedef ALubyte uint8;
239 typedef ALint int32;
240 typedef ALuint uint32;
241 typedef ALuint64SOFT uint64;
243 typedef enum ByteOrderT ByteOrderT;
244 typedef enum SourceFormatT SourceFormatT;
245 typedef enum ElementTypeT ElementTypeT;
246 typedef enum HeadModelT HeadModelT;
247 typedef enum OutputFormatT OutputFormatT;
249 typedef struct TokenReaderT TokenReaderT;
250 typedef struct SourceRefT SourceRefT;
251 typedef struct HrirDataT HrirDataT;
252 typedef struct ResamplerT ResamplerT;
254 // Token reader state for parsing the data set definition.
255 struct TokenReaderT {
256 FILE * mFile;
257 const char * mName;
258 uint mLine,
259 mColumn;
260 char mRing [TR_RING_SIZE];
261 size_t mIn,
262 mOut;
265 // Source reference state used when loading sources.
266 struct SourceRefT {
267 SourceFormatT mFormat;
268 ElementTypeT mType;
269 uint mSize;
270 int mBits;
271 uint mChannel,
272 mSkip,
273 mOffset;
274 char mPath [MAX_PATH_LEN + 1];
277 // The HRIR metrics and data set used when loading, processing, and storing
278 // the resulting HRTF.
279 struct HrirDataT {
280 uint mIrRate,
281 mIrCount,
282 mIrSize,
283 mIrPoints,
284 mFftSize,
285 mEvCount,
286 mEvStart,
287 mAzCount [MAX_EV_COUNT],
288 mEvOffset [MAX_EV_COUNT];
289 double mRadius,
290 mDistance,
291 * mHrirs,
292 * mHrtds,
293 mMaxHrtd;
296 // The resampler metrics and FIR filter.
297 struct ResamplerT {
298 uint mP,
302 double * mF;
305 /* Token reader routines for parsing text files. Whitespace is not
306 * significant. It can process tokens as identifiers, numbers (integer and
307 * floating-point), strings, and operators. Strings must be encapsulated by
308 * double-quotes and cannot span multiple lines.
311 // Setup the reader on the given file. The filename can be NULL if no error
312 // output is desired.
313 static void TrSetup (FILE * fp, const char * filename, TokenReaderT * tr) {
314 const char * name = NULL;
315 char ch;
317 tr -> mFile = fp;
318 name = filename;
319 // If a filename was given, store a pointer to the base name.
320 if (filename != NULL) {
321 while ((ch = (* filename)) != '\0') {
322 if ((ch == '/') || (ch == '\\'))
323 name = filename + 1;
324 filename ++;
327 tr -> mName = name;
328 tr -> mLine = 1;
329 tr -> mColumn = 1;
330 tr -> mIn = 0;
331 tr -> mOut = 0;
334 // Prime the reader's ring buffer, and return a result indicating that there
335 // is text to process.
336 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))) {
341 // Load TR_LOAD_SIZE (or less if at the end of the file) per read.
342 toLoad = TR_LOAD_SIZE;
343 in = tr -> mIn & TR_RING_MASK;
344 count = TR_RING_SIZE - in;
345 if (count < toLoad) {
346 tr -> mIn += fread (& tr -> mRing [in], 1, count, tr -> mFile);
347 tr -> mIn += fread (& tr -> mRing [0], 1, toLoad - count, tr -> mFile);
348 } else {
349 tr -> mIn += fread (& tr -> mRing [in], 1, toLoad, tr -> mFile);
351 if (tr -> mOut >= TR_RING_SIZE) {
352 tr -> mOut -= TR_RING_SIZE;
353 tr -> mIn -= TR_RING_SIZE;
356 if (tr -> mIn > tr -> mOut)
357 return (1);
358 return (0);
361 // Error display routine. Only displays when the base name is not NULL.
362 static void TrErrorVA (const TokenReaderT * tr, uint line, uint column, const char * format, va_list argPtr) {
363 if (tr -> mName != NULL) {
364 fprintf (stderr, "Error (%s:%u:%u): ", tr -> mName, line, column);
365 vfprintf (stderr, format, argPtr);
369 // Used to display an error at a saved line/column.
370 static void TrErrorAt (const TokenReaderT * tr, uint line, uint column, const char * format, ...) {
371 va_list argPtr;
373 va_start (argPtr, format);
374 TrErrorVA (tr, line, column, format, argPtr);
375 va_end (argPtr);
378 // Used to display an error at the current line/column.
379 static void TrError (const TokenReaderT * tr, const char * format, ...) {
380 va_list argPtr;
382 va_start (argPtr, format);
383 TrErrorVA (tr, tr -> mLine, tr -> mColumn, format, argPtr);
384 va_end (argPtr);
387 // Skips to the next line.
388 static void TrSkipLine (TokenReaderT * tr) {
389 char ch;
391 while (TrLoad (tr)) {
392 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
393 tr -> mOut ++;
394 if (ch == '\n') {
395 tr -> mLine ++;
396 tr -> mColumn = 1;
397 break;
399 tr -> mColumn ++;
403 // Skips to the next token.
404 static int TrSkipWhitespace (TokenReaderT * tr) {
405 char ch;
407 while (TrLoad (tr)) {
408 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
409 if (isspace (ch)) {
410 tr -> mOut ++;
411 if (ch == '\n') {
412 tr -> mLine ++;
413 tr -> mColumn = 1;
414 } else {
415 tr -> mColumn ++;
417 } else if (ch == '#') {
418 TrSkipLine (tr);
419 } else {
420 return (1);
423 return (0);
426 // Get the line and/or column of the next token (or the end of input).
427 static void TrIndication (TokenReaderT * tr, uint * line, uint * column) {
428 TrSkipWhitespace (tr);
429 if (line != NULL)
430 (* line) = tr -> mLine;
431 if (column != NULL)
432 (* column) = tr -> mColumn;
435 // Checks to see if a token is the given operator. It does not display any
436 // errors and will not proceed to the next token.
437 static int TrIsOperator (TokenReaderT * tr, const char * op) {
438 size_t out, len;
439 char ch;
441 if (! TrSkipWhitespace (tr))
442 return (0);
443 out = tr -> mOut;
444 len = 0;
445 while ((op [len] != '\0') && (out < tr -> mIn)) {
446 ch = tr -> mRing [out & TR_RING_MASK];
447 if (ch != op [len])
448 break;
449 len ++;
450 out ++;
452 if (op [len] == '\0')
453 return (1);
454 return (0);
457 /* The TrRead*() routines obtain the value of a matching token type. They
458 * display type, form, and boundary errors and will proceed to the next
459 * token.
462 // Reads and validates an identifier token.
463 static int TrReadIdent (TokenReaderT * tr, const uint maxLen, char * ident) {
464 uint col, len;
465 char ch;
467 col = tr -> mColumn;
468 if (TrSkipWhitespace (tr)) {
469 col = tr -> mColumn;
470 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
471 if ((ch == '_') || isalpha (ch)) {
472 len = 0;
473 do {
474 if (len < maxLen)
475 ident [len] = ch;
476 len ++;
477 tr -> mOut ++;
478 if (! TrLoad (tr))
479 break;
480 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
481 } while ((ch == '_') || isdigit (ch) || isalpha (ch));
482 tr -> mColumn += len;
483 if (len > maxLen) {
484 TrErrorAt (tr, tr -> mLine, col, "Identifier is too long.\n");
485 return (0);
487 ident [len] = '\0';
488 return (1);
491 TrErrorAt (tr, tr -> mLine, col, "Expected an identifier.\n");
492 return (0);
495 // Reads and validates (including bounds) an integer token.
496 static int TrReadInt (TokenReaderT * tr, const int loBound, const int hiBound, int * value) {
497 uint col, digis, len;
498 char ch, temp [64 + 1];
500 col = tr -> mColumn;
501 if (TrSkipWhitespace (tr)) {
502 col = tr -> mColumn;
503 len = 0;
504 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
505 if ((ch == '+') || (ch == '-')) {
506 temp [len] = ch;
507 len ++;
508 tr -> mOut ++;
510 digis = 0;
511 while (TrLoad (tr)) {
512 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
513 if (! isdigit (ch))
514 break;
515 if (len < 64)
516 temp [len] = ch;
517 len ++;
518 digis ++;
519 tr -> mOut ++;
521 tr -> mColumn += len;
522 if ((digis > 0) && (ch != '.') && (! isalpha (ch))) {
523 if (len > 64) {
524 TrErrorAt (tr, tr -> mLine, col, "Integer is too long.");
525 return (0);
527 temp [len] = '\0';
528 (* value) = strtol (temp, NULL, 10);
529 if (((* value) < loBound) || ((* value) > hiBound)) {
530 TrErrorAt (tr, tr -> mLine, col, "Expected a value from %d to %d.\n", loBound, hiBound);
531 return (0);
533 return (1);
536 TrErrorAt (tr, tr -> mLine, col, "Expected an integer.\n");
537 return (0);
540 // Reads and validates (including bounds) a float token.
541 static int TrReadFloat (TokenReaderT * tr, const double loBound, const double hiBound, double * value) {
542 uint col, digis, len;
543 char ch, temp [64 + 1];
545 col = tr -> mColumn;
546 if (TrSkipWhitespace (tr)) {
547 col = tr -> mColumn;
548 len = 0;
549 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
550 if ((ch == '+') || (ch == '-')) {
551 temp [len] = ch;
552 len ++;
553 tr -> mOut ++;
555 digis = 0;
556 while (TrLoad (tr)) {
557 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
558 if (! isdigit (ch))
559 break;
560 if (len < 64)
561 temp [len] = ch;
562 len ++;
563 digis ++;
564 tr -> mOut ++;
566 if (ch == '.') {
567 if (len < 64)
568 temp [len] = ch;
569 len ++;
570 tr -> mOut ++;
572 while (TrLoad (tr)) {
573 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
574 if (! isdigit (ch))
575 break;
576 if (len < 64)
577 temp [len] = ch;
578 len ++;
579 digis ++;
580 tr -> mOut ++;
582 if (digis > 0) {
583 if ((ch == 'E') || (ch == 'e')) {
584 if (len < 64)
585 temp [len] = ch;
586 len ++;
587 digis = 0;
588 tr -> mOut ++;
589 if ((ch == '+') || (ch == '-')) {
590 if (len < 64)
591 temp [len] = ch;
592 len ++;
593 tr -> mOut ++;
595 while (TrLoad (tr)) {
596 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
597 if (! isdigit (ch))
598 break;
599 if (len < 64)
600 temp [len] = ch;
601 len ++;
602 digis ++;
603 tr -> mOut ++;
606 tr -> mColumn += len;
607 if ((digis > 0) && (ch != '.') && (! isalpha (ch))) {
608 if (len > 64) {
609 TrErrorAt (tr, tr -> mLine, col, "Float is too long.");
610 return (0);
612 temp [len] = '\0';
613 (* value) = strtod (temp, NULL);
614 if (((* value) < loBound) || ((* value) > hiBound)) {
615 TrErrorAt (tr, tr -> mLine, col, "Expected a value from %f to %f.\n", loBound, hiBound);
616 return (0);
618 return (1);
620 } else {
621 tr -> mColumn += len;
624 TrErrorAt (tr, tr -> mLine, col, "Expected a float.\n");
625 return (0);
628 // Reads and validates a string token.
629 static int TrReadString (TokenReaderT * tr, const uint maxLen, char * text) {
630 uint col, len;
631 char ch;
633 col = tr -> mColumn;
634 if (TrSkipWhitespace (tr)) {
635 col = tr -> mColumn;
636 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
637 if (ch == '\"') {
638 tr -> mOut ++;
639 len = 0;
640 while (TrLoad (tr)) {
641 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
642 tr -> mOut ++;
643 if (ch == '\"')
644 break;
645 if (ch == '\n') {
646 TrErrorAt (tr, tr -> mLine, col, "Unterminated string at end of line.\n");
647 return (0);
649 if (len < maxLen)
650 text [len] = ch;
651 len ++;
653 if (ch != '\"') {
654 tr -> mColumn += 1 + len;
655 TrErrorAt (tr, tr -> mLine, col, "Unterminated string at end of input.\n");
656 return (0);
658 tr -> mColumn += 2 + len;
659 if (len > maxLen) {
660 TrErrorAt (tr, tr -> mLine, col, "String is too long.\n");
661 return (0);
663 text [len] = '\0';
664 return (1);
667 TrErrorAt (tr, tr -> mLine, col, "Expected a string.\n");
668 return (0);
671 // Reads and validates the given operator.
672 static int TrReadOperator (TokenReaderT * tr, const char * op) {
673 uint col, len;
674 char ch;
676 col = tr -> mColumn;
677 if (TrSkipWhitespace (tr)) {
678 col = tr -> mColumn;
679 len = 0;
680 while ((op [len] != '\0') && TrLoad (tr)) {
681 ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
682 if (ch != op [len])
683 break;
684 len ++;
685 tr -> mOut ++;
687 tr -> mColumn += len;
688 if (op [len] == '\0')
689 return (1);
691 TrErrorAt (tr, tr -> mLine, col, "Expected '%s' operator.\n", op);
692 return (0);
695 /* Performs a string substitution. Any case-insensitive occurrences of the
696 * pattern string are replaced with the replacement string. The result is
697 * truncated if necessary.
699 static int StrSubst (const char * in, const char * pat, const char * rep, const size_t maxLen, char * out) {
700 size_t inLen, patLen, repLen;
701 size_t si, di;
702 int truncated;
704 inLen = strlen (in);
705 patLen = strlen (pat);
706 repLen = strlen (rep);
707 si = 0;
708 di = 0;
709 truncated = 0;
710 while ((si < inLen) && (di < maxLen)) {
711 if (patLen <= (inLen - si)) {
712 if (strncasecmp (& in [si], pat, patLen) == 0) {
713 if (repLen > (maxLen - di)) {
714 repLen = maxLen - di;
715 truncated = 1;
717 strncpy (& out [di], rep, repLen);
718 si += patLen;
719 di += repLen;
722 out [di] = in [si];
723 si ++;
724 di ++;
726 if (si < inLen)
727 truncated = 1;
728 out [di] = '\0';
729 return (! truncated);
732 // Provide missing math routines for MSVC versions < 1800 (Visual Studio 2013).
733 #if defined(_MSC_VER) && _MSC_VER < 1800
734 static double round (double val) {
735 if (val < 0.0)
736 return (ceil (val - 0.5));
737 return (floor (val + 0.5));
740 static double fmin (double a, double b) {
741 return ((a < b) ? a : b);
744 static double fmax (double a, double b) {
745 return ((a > b) ? a : b);
747 #endif
749 // Simple clamp routine.
750 static double Clamp (const double val, const double lower, const double upper) {
751 return (fmin (fmax (val, lower), upper));
754 // Performs linear interpolation.
755 static double Lerp (const double a, const double b, const double f) {
756 return (a + (f * (b - a)));
759 // Performs a high-passed triangular probability density function dither from
760 // a double to an integer. It assumes the input sample is already scaled.
761 static int HpTpdfDither (const double in, int * hpHist) {
762 const double PRNG_SCALE = 1.0 / (RAND_MAX + 1.0);
763 int prn;
764 double out;
766 prn = rand ();
767 out = round (in + (PRNG_SCALE * (prn - (* hpHist))));
768 (* hpHist) = prn;
769 return ((int) out);
772 // Allocates an array of doubles.
773 static double *CreateArray(size_t n)
775 double *a;
777 if(n == 0) n = 1;
778 a = calloc(n, sizeof(double));
779 if(a == NULL)
781 fprintf(stderr, "Error: Out of memory.\n");
782 exit(-1);
784 return a;
787 // Frees an array of doubles.
788 static void DestroyArray(double *a)
789 { free(a); }
791 // Complex number routines. All outputs must be non-NULL.
793 // Magnitude/absolute value.
794 static double ComplexAbs (const double r, const double i) {
795 return (sqrt ((r * r) + (i * i)));
798 // Multiply.
799 static void ComplexMul (const double aR, const double aI, const double bR, const double bI, double * outR, double * outI) {
800 (* outR) = (aR * bR) - (aI * bI);
801 (* outI) = (aI * bR) + (aR * bI);
804 // Base-e exponent.
805 static void ComplexExp (const double inR, const double inI, double * outR, double * outI) {
806 double e;
808 e = exp (inR);
809 (* outR) = e * cos (inI);
810 (* outI) = e * sin (inI);
813 /* Fast Fourier transform routines. The number of points must be a power of
814 * two. In-place operation is possible only if both the real and imaginary
815 * parts are in-place together.
818 // Performs bit-reversal ordering.
819 static void FftArrange (const uint n, const double * inR, const double * inI, double * outR, double * outI) {
820 uint rk, k, m;
821 double tempR, tempI;
823 if ((inR == outR) && (inI == outI)) {
824 // Handle in-place arrangement.
825 rk = 0;
826 for (k = 0; k < n; k ++) {
827 if (rk > k) {
828 tempR = inR [rk];
829 tempI = inI [rk];
830 outR [rk] = inR [k];
831 outI [rk] = inI [k];
832 outR [k] = tempR;
833 outI [k] = tempI;
835 m = n;
836 while (rk & (m >>= 1))
837 rk &= ~m;
838 rk |= m;
840 } else {
841 // Handle copy arrangement.
842 rk = 0;
843 for (k = 0; k < n; k ++) {
844 outR [rk] = inR [k];
845 outI [rk] = inI [k];
846 m = n;
847 while (rk & (m >>= 1))
848 rk &= ~m;
849 rk |= m;
854 // Performs the summation.
855 static void FftSummation (const uint n, const double s, double * re, double * im) {
856 double pi;
857 uint m, m2;
858 double vR, vI, wR, wI;
859 uint i, k, mk;
860 double tR, tI;
862 pi = s * M_PI;
863 for (m = 1, m2 = 2; m < n; m <<= 1, m2 <<= 1) {
864 // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
865 vR = sin (0.5 * pi / m);
866 vR = -2.0 * vR * vR;
867 vI = -sin (pi / m);
868 // w = Complex (1.0, 0.0)
869 wR = 1.0;
870 wI = 0.0;
871 for (i = 0; i < m; i ++) {
872 for (k = i; k < n; k += m2) {
873 mk = k + m;
874 // t = ComplexMul (w, out [km2])
875 tR = (wR * re [mk]) - (wI * im [mk]);
876 tI = (wR * im [mk]) + (wI * re [mk]);
877 // out [mk] = ComplexSub (out [k], t)
878 re [mk] = re [k] - tR;
879 im [mk] = im [k] - tI;
880 // out [k] = ComplexAdd (out [k], t)
881 re [k] += tR;
882 im [k] += tI;
884 // t = ComplexMul (v, w)
885 tR = (vR * wR) - (vI * wI);
886 tI = (vR * wI) + (vI * wR);
887 // w = ComplexAdd (w, t)
888 wR += tR;
889 wI += tI;
894 // Performs a forward FFT.
895 static void FftForward (const uint n, const double * inR, const double * inI, double * outR, double * outI) {
896 FftArrange (n, inR, inI, outR, outI);
897 FftSummation (n, 1.0, outR, outI);
900 // Performs an inverse FFT.
901 static void FftInverse (const uint n, const double * inR, const double * inI, double * outR, double * outI) {
902 double f;
903 uint i;
905 FftArrange (n, inR, inI, outR, outI);
906 FftSummation (n, -1.0, outR, outI);
907 f = 1.0 / n;
908 for (i = 0; i < n; i ++) {
909 outR [i] *= f;
910 outI [i] *= f;
914 /* Calculate the complex helical sequence (or discrete-time analytical
915 * signal) of the given input using the Hilbert transform. Given the
916 * negative natural logarithm of a signal's magnitude response, the imaginary
917 * components can be used as the angles for minimum-phase reconstruction.
919 static void Hilbert (const uint n, const double * in, double * outR, double * outI) {
920 uint i;
922 if (in == outR) {
923 // Handle in-place operation.
924 for (i = 0; i < n; i ++)
925 outI [i] = 0.0;
926 } else {
927 // Handle copy operation.
928 for (i = 0; i < n; i ++) {
929 outR [i] = in [i];
930 outI [i] = 0.0;
933 FftForward (n, outR, outI, outR, outI);
934 /* Currently the Fourier routines operate only on point counts that are
935 * powers of two. If that changes and n is odd, the following conditional
936 * should be: i < (n + 1) / 2.
938 for (i = 1; i < (n / 2); i ++) {
939 outR [i] *= 2.0;
940 outI [i] *= 2.0;
942 // If n is odd, the following increment should be skipped.
943 i ++;
944 for (; i < n; i ++) {
945 outR [i] = 0.0;
946 outI [i] = 0.0;
948 FftInverse (n, outR, outI, outR, outI);
951 /* Calculate the magnitude response of the given input. This is used in
952 * place of phase decomposition, since the phase residuals are discarded for
953 * minimum phase reconstruction. The mirrored half of the response is also
954 * discarded.
956 static void MagnitudeResponse (const uint n, const double * inR, const double * inI, double * out) {
957 const uint m = 1 + (n / 2);
958 uint i;
960 for (i = 0; i < m; i ++)
961 out [i] = fmax (ComplexAbs (inR [i], inI [i]), EPSILON);
964 /* Apply a range limit (in dB) to the given magnitude response. This is used
965 * to adjust the effects of the diffuse-field average on the equalization
966 * process.
968 static void LimitMagnitudeResponse (const uint n, const double limit, const double * in, double * out) {
969 const uint m = 1 + (n / 2);
970 double halfLim;
971 uint i, lower, upper;
972 double ave;
974 halfLim = limit / 2.0;
975 // Convert the response to dB.
976 for (i = 0; i < m; i ++)
977 out [i] = 20.0 * log10 (in [i]);
978 // Use six octaves to calculate the average magnitude of the signal.
979 lower = ((uint) ceil (n / pow (2.0, 8.0))) - 1;
980 upper = ((uint) floor (n / pow (2.0, 2.0))) - 1;
981 ave = 0.0;
982 for (i = lower; i <= upper; i ++)
983 ave += out [i];
984 ave /= upper - lower + 1;
985 // Keep the response within range of the average magnitude.
986 for (i = 0; i < m; i ++)
987 out [i] = Clamp (out [i], ave - halfLim, ave + halfLim);
988 // Convert the response back to linear magnitude.
989 for (i = 0; i < m; i ++)
990 out [i] = pow (10.0, out [i] / 20.0);
993 /* Reconstructs the minimum-phase component for the given magnitude response
994 * of a signal. This is equivalent to phase recomposition, sans the missing
995 * residuals (which were discarded). The mirrored half of the response is
996 * reconstructed.
998 static void MinimumPhase (const uint n, const double * in, double * outR, double * outI) {
999 const uint m = 1 + (n / 2);
1000 double * mags = NULL;
1001 uint i;
1002 double aR, aI;
1004 mags = CreateArray (n);
1005 for (i = 0; i < m; i ++) {
1006 mags [i] = fmax (in [i], EPSILON);
1007 outR [i] = -log (mags [i]);
1009 for (; i < n; i ++) {
1010 mags [i] = mags [n - i];
1011 outR [i] = outR [n - i];
1013 Hilbert (n, outR, outR, outI);
1014 // Remove any DC offset the filter has.
1015 outR [0] = 0.0;
1016 outI [0] = 0.0;
1017 for (i = 1; i < n; i ++) {
1018 ComplexExp (0.0, outI [i], & aR, & aI);
1019 ComplexMul (mags [i], 0.0, aR, aI, & outR [i], & outI [i]);
1021 DestroyArray (mags);
1024 /* This is the normalized cardinal sine (sinc) function.
1026 * sinc(x) = { 1, x = 0
1027 * { sin(pi x) / (pi x), otherwise.
1029 static double Sinc (const double x) {
1030 if (fabs (x) < EPSILON)
1031 return (1.0);
1032 return (sin (M_PI * x) / (M_PI * x));
1035 /* The zero-order modified Bessel function of the first kind, used for the
1036 * Kaiser window.
1038 * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
1039 * = sum_{k=0}^inf ((x / 2)^k / k!)^2
1041 static double BesselI_0 (const double x) {
1042 double term, sum, x2, y, last_sum;
1043 int k;
1045 // Start at k=1 since k=0 is trivial.
1046 term = 1.0;
1047 sum = 1.0;
1048 x2 = x / 2.0;
1049 k = 1;
1050 // Let the integration converge until the term of the sum is no longer
1051 // significant.
1052 do {
1053 y = x2 / k;
1054 k ++;
1055 last_sum = sum;
1056 term *= y * y;
1057 sum += term;
1058 } while (sum != last_sum);
1059 return (sum);
1062 /* Calculate a Kaiser window from the given beta value and a normalized k
1063 * [-1, 1].
1065 * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
1066 * { 0, elsewhere.
1068 * Where k can be calculated as:
1070 * k = i / l, where -l <= i <= l.
1072 * or:
1074 * k = 2 i / M - 1, where 0 <= i <= M.
1076 static double Kaiser (const double b, const double k) {
1077 double k2;
1079 k2 = Clamp (k, -1.0, 1.0);
1080 if ((k < -1.0) || (k > 1.0))
1081 return (0.0);
1082 k2 *= k2;
1083 return (BesselI_0 (b * sqrt (1.0 - k2)) / BesselI_0 (b));
1086 // Calculates the greatest common divisor of a and b.
1087 static uint Gcd (const uint a, const uint b) {
1088 uint x, y, z;
1090 x = a;
1091 y = b;
1092 while (y > 0) {
1093 z = y;
1094 y = x % y;
1095 x = z;
1097 return (x);
1100 /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
1101 * the transition width is normalized frequency (0.5 is nyquist).
1103 * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
1104 * { ceil(5.79 / 2 pi f_t), r <= 21.
1107 static uint CalcKaiserOrder (const double rejection, const double transition) {
1108 double w_t;
1110 w_t = 2.0 * M_PI * transition;
1111 if (rejection > 21.0)
1112 return ((uint) ceil ((rejection - 7.95) / (2.285 * w_t)));
1113 return ((uint) ceil (5.79 / w_t));
1116 // Calculates the beta value of the Kaiser window. Rejection is in dB.
1117 static double CalcKaiserBeta (const double rejection) {
1118 if (rejection > 50.0)
1119 return (0.1102 * (rejection - 8.7));
1120 else if (rejection >= 21.0)
1121 return ((0.5842 * pow (rejection - 21.0, 0.4)) +
1122 (0.07886 * (rejection - 21.0)));
1123 else
1124 return (0.0);
1127 /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
1128 * width, beta, gain, and cutoff. The point is specified in non-normalized
1129 * samples, from 0 to M, where M = (2 l + 1).
1131 * w(k) 2 p f_t sinc(2 f_t x)
1133 * x -- centered sample index (i - l)
1134 * k -- normalized and centered window index (x / l)
1135 * w(k) -- window function (Kaiser)
1136 * p -- gain compensation factor when sampling
1137 * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
1139 static double SincFilter (const int l, const double b, const double gain, const double cutoff, const int i) {
1140 return (Kaiser (b, ((double) (i - l)) / l) * 2.0 * gain * cutoff * Sinc (2.0 * cutoff * (i - l)));
1143 /* This is a polyphase sinc-filtered resampler.
1145 * Upsample Downsample
1147 * p/q = 3/2 p/q = 3/5
1149 * M-+-+-+-> M-+-+-+->
1150 * -------------------+ ---------------------+
1151 * p s * f f f f|f| | p s * f f f f f |
1152 * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
1153 * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
1154 * s * f|f|f f f | s * f f|f|f f |
1155 * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
1156 * --------+=+--------+ 0 * |0|0 0 0 0 |
1157 * d . d .|d|. d . d ----------+=+--------+
1158 * d . . . .|d|. . . .
1159 * q->
1160 * q-+-+-+->
1162 * P_f(i,j) = q i mod p + pj
1163 * P_s(i,j) = floor(q i / p) - j
1164 * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
1165 * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
1166 * { 0, P_f(i,j) >= M. }
1169 // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
1170 // that's used to cut frequencies above the destination nyquist.
1171 static void ResamplerSetup (ResamplerT * rs, const uint srcRate, const uint dstRate) {
1172 uint gcd, l;
1173 double cutoff, width, beta;
1174 int i;
1176 gcd = Gcd (srcRate, dstRate);
1177 rs -> mP = dstRate / gcd;
1178 rs -> mQ = srcRate / gcd;
1179 /* The cutoff is adjusted by half the transition width, so the transition
1180 * ends before the nyquist (0.5). Both are scaled by the downsampling
1181 * factor.
1183 if (rs -> mP > rs -> mQ) {
1184 cutoff = 0.45 / rs -> mP;
1185 width = 0.1 / rs -> mP;
1186 } else {
1187 cutoff = 0.45 / rs -> mQ;
1188 width = 0.1 / rs -> mQ;
1190 // A rejection of -180 dB is used for the stop band.
1191 l = CalcKaiserOrder (180.0, width) / 2;
1192 beta = CalcKaiserBeta (180.0);
1193 rs -> mM = (2 * l) + 1;
1194 rs -> mL = l;
1195 rs -> mF = CreateArray (rs -> mM);
1196 for (i = 0; i < ((int) rs -> mM); i ++)
1197 rs -> mF [i] = SincFilter ((int) l, beta, rs -> mP, cutoff, i);
1200 // Clean up after the resampler.
1201 static void ResamplerClear (ResamplerT * rs) {
1202 DestroyArray (rs -> mF);
1203 rs -> mF = NULL;
1206 // Perform the upsample-filter-downsample resampling operation using a
1207 // polyphase filter implementation.
1208 static void ResamplerRun (ResamplerT * rs, const uint inN, const double * in, const uint outN, double * out) {
1209 const uint p = rs -> mP, q = rs -> mQ, m = rs -> mM, l = rs -> mL;
1210 const double * f = rs -> mF;
1211 double * work = NULL;
1212 uint i;
1213 double r;
1214 uint j_f, j_s;
1216 if (outN == 0)
1217 return;
1219 // Handle in-place operation.
1220 if (in == out)
1221 work = CreateArray (outN);
1222 else
1223 work = out;
1224 // Resample the input.
1225 for (i = 0; i < outN; i ++) {
1226 r = 0.0;
1227 // Input starts at l to compensate for the filter delay. This will
1228 // drop any build-up from the first half of the filter.
1229 j_f = (l + (q * i)) % p;
1230 j_s = (l + (q * i)) / p;
1231 while (j_f < m) {
1232 // Only take input when 0 <= j_s < inN. This single unsigned
1233 // comparison catches both cases.
1234 if (j_s < inN)
1235 r += f [j_f] * in [j_s];
1236 j_f += p;
1237 j_s --;
1239 work [i] = r;
1241 // Clean up after in-place operation.
1242 if (in == out) {
1243 for (i = 0; i < outN; i ++)
1244 out [i] = work [i];
1245 DestroyArray (work);
1249 // Read a binary value of the specified byte order and byte size from a file,
1250 // storing it as a 32-bit unsigned integer.
1251 static int ReadBin4 (FILE * fp, const char * filename, const ByteOrderT order, const uint bytes, uint32 * out) {
1252 uint8 in [4];
1253 uint32 accum;
1254 uint i;
1256 if (fread (in, 1, bytes, fp) != bytes) {
1257 fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
1258 return (0);
1260 accum = 0;
1261 switch (order) {
1262 case BO_LITTLE :
1263 for (i = 0; i < bytes; i ++)
1264 accum = (accum << 8) | in [bytes - i - 1];
1265 break;
1266 case BO_BIG :
1267 for (i = 0; i < bytes; i ++)
1268 accum = (accum << 8) | in [i];
1269 break;
1270 default :
1271 break;
1273 (* out) = accum;
1274 return (1);
1277 // Read a binary value of the specified byte order from a file, storing it as
1278 // a 64-bit unsigned integer.
1279 static int ReadBin8 (FILE * fp, const char * filename, const ByteOrderT order, uint64 * out) {
1280 uint8 in [8];
1281 uint64 accum;
1282 uint i;
1284 if (fread (in, 1, 8, fp) != 8) {
1285 fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
1286 return (0);
1288 accum = 0ULL;
1289 switch (order) {
1290 case BO_LITTLE :
1291 for (i = 0; i < 8; i ++)
1292 accum = (accum << 8) | in [8 - i - 1];
1293 break;
1294 case BO_BIG :
1295 for (i = 0; i < 8; i ++)
1296 accum = (accum << 8) | in [i];
1297 break;
1298 default :
1299 break;
1301 (* out) = accum;
1302 return (1);
1305 // Write an ASCII string to a file.
1306 static int WriteAscii (const char * out, FILE * fp, const char * filename) {
1307 size_t len;
1309 len = strlen (out);
1310 if (fwrite (out, 1, len, fp) != len) {
1311 fclose (fp);
1312 fprintf (stderr, "Error: Bad write to file '%s'.\n", filename);
1313 return (0);
1315 return (1);
1318 // Write a binary value of the given byte order and byte size to a file,
1319 // loading it from a 32-bit unsigned integer.
1320 static int WriteBin4 (const ByteOrderT order, const uint bytes, const uint32 in, FILE * fp, const char * filename) {
1321 uint8 out [4];
1322 uint i;
1324 switch (order) {
1325 case BO_LITTLE :
1326 for (i = 0; i < bytes; i ++)
1327 out [i] = (in >> (i * 8)) & 0x000000FF;
1328 break;
1329 case BO_BIG :
1330 for (i = 0; i < bytes; i ++)
1331 out [bytes - i - 1] = (in >> (i * 8)) & 0x000000FF;
1332 break;
1333 default :
1334 break;
1336 if (fwrite (out, 1, bytes, fp) != bytes) {
1337 fprintf (stderr, "Error: Bad write to file '%s'.\n", filename);
1338 return (0);
1340 return (1);
1343 /* Read a binary value of the specified type, byte order, and byte size from
1344 * a file, converting it to a double. For integer types, the significant
1345 * bits are used to normalize the result. The sign of bits determines
1346 * whether they are padded toward the MSB (negative) or LSB (positive).
1347 * Floating-point types are not normalized.
1349 static int ReadBinAsDouble (FILE * fp, const char * filename, const ByteOrderT order, const ElementTypeT type, const uint bytes, const int bits, double * out) {
1350 union {
1351 uint32 ui;
1352 int32 i;
1353 float f;
1354 } v4;
1355 union {
1356 uint64 ui;
1357 double f;
1358 } v8;
1360 (* out) = 0.0;
1361 if (bytes > 4) {
1362 if (! ReadBin8 (fp, filename, order, & v8 . ui))
1363 return (0);
1364 if (type == ET_FP)
1365 (* out) = v8 . f;
1366 } else {
1367 if (! ReadBin4 (fp, filename, order, bytes, & v4 . ui))
1368 return (0);
1369 if (type == ET_FP) {
1370 (* out) = (double) v4 . f;
1371 } else {
1372 if (bits > 0)
1373 v4 . ui >>= (8 * bytes) - ((uint) bits);
1374 else
1375 v4 . ui &= (0xFFFFFFFF >> (32 + bits));
1376 if (v4 . ui & ((uint) (1 << (abs (bits) - 1))))
1377 v4 . ui |= (0xFFFFFFFF << abs (bits));
1378 (* out) = v4 . i / ((double) (1 << (abs (bits) - 1)));
1381 return (1);
1384 /* Read an ascii value of the specified type from a file, converting it to a
1385 * double. For integer types, the significant bits are used to normalize the
1386 * result. The sign of the bits should always be positive. This also skips
1387 * up to one separator character before the element itself.
1389 static int ReadAsciiAsDouble (TokenReaderT * tr, const char * filename, const ElementTypeT type, const uint bits, double * out) {
1390 int v;
1392 if (TrIsOperator (tr, ","))
1393 TrReadOperator (tr, ",");
1394 else if (TrIsOperator (tr, ":"))
1395 TrReadOperator (tr, ":");
1396 else if (TrIsOperator (tr, ";"))
1397 TrReadOperator (tr, ";");
1398 else if (TrIsOperator (tr, "|"))
1399 TrReadOperator (tr, "|");
1400 if (type == ET_FP) {
1401 if (! TrReadFloat (tr, -HUGE_VAL, HUGE_VAL, out)) {
1402 fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
1403 return (0);
1405 } else {
1406 if (! TrReadInt (tr, -(1 << (bits - 1)), (1 << (bits - 1)) - 1, & v)) {
1407 fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
1408 return (0);
1410 (* out) = v / ((double) ((1 << (bits - 1)) - 1));
1412 return (1);
1415 // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
1416 // the source parameters and data set metrics.
1417 static int ReadWaveFormat (FILE * fp, const ByteOrderT order, const uint hrirRate, SourceRefT * src) {
1418 uint32 fourCC, chunkSize;
1419 uint32 format, channels, rate, dummy, block, size, bits;
1421 chunkSize = 0;
1422 do {
1423 if (chunkSize > 0)
1424 fseek (fp, (long) chunkSize, SEEK_CUR);
1425 if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
1426 (! ReadBin4 (fp, src -> mPath, order, 4, & chunkSize)))
1427 return (0);
1428 } while (fourCC != FOURCC_FMT);
1429 if ((! ReadBin4 (fp, src -> mPath, order, 2, & format)) ||
1430 (! ReadBin4 (fp, src -> mPath, order, 2, & channels)) ||
1431 (! ReadBin4 (fp, src -> mPath, order, 4, & rate)) ||
1432 (! ReadBin4 (fp, src -> mPath, order, 4, & dummy)) ||
1433 (! ReadBin4 (fp, src -> mPath, order, 2, & block)))
1434 return (0);
1435 block /= channels;
1436 if (chunkSize > 14) {
1437 if (! ReadBin4 (fp, src -> mPath, order, 2, & size))
1438 return (0);
1439 size /= 8;
1440 if (block > size)
1441 size = block;
1442 } else {
1443 size = block;
1445 if (format == WAVE_FORMAT_EXTENSIBLE) {
1446 fseek (fp, 2, SEEK_CUR);
1447 if (! ReadBin4 (fp, src -> mPath, order, 2, & bits))
1448 return (0);
1449 if (bits == 0)
1450 bits = 8 * size;
1451 fseek (fp, 4, SEEK_CUR);
1452 if (! ReadBin4 (fp, src -> mPath, order, 2, & format))
1453 return (0);
1454 fseek (fp, (long) (chunkSize - 26), SEEK_CUR);
1455 } else {
1456 bits = 8 * size;
1457 if (chunkSize > 14)
1458 fseek (fp, (long) (chunkSize - 16), SEEK_CUR);
1459 else
1460 fseek (fp, (long) (chunkSize - 14), SEEK_CUR);
1462 if ((format != WAVE_FORMAT_PCM) && (format != WAVE_FORMAT_IEEE_FLOAT)) {
1463 fprintf (stderr, "Error: Unsupported WAVE format in file '%s'.\n", src -> mPath);
1464 return (0);
1466 if (src -> mChannel >= channels) {
1467 fprintf (stderr, "Error: Missing source channel in WAVE file '%s'.\n", src -> mPath);
1468 return (0);
1470 if (rate != hrirRate) {
1471 fprintf (stderr, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src -> mPath);
1472 return (0);
1474 if (format == WAVE_FORMAT_PCM) {
1475 if ((size < 2) || (size > 4)) {
1476 fprintf (stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src -> mPath);
1477 return (0);
1479 if ((bits < 16) || (bits > (8 * size))) {
1480 fprintf (stderr, "Error: Bad significant bits in WAVE file '%s'.\n", src -> mPath);
1481 return (0);
1483 src -> mType = ET_INT;
1484 } else {
1485 if ((size != 4) && (size != 8)) {
1486 fprintf (stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src -> mPath);
1487 return (0);
1489 src -> mType = ET_FP;
1491 src -> mSize = size;
1492 src -> mBits = (int) bits;
1493 src -> mSkip = channels;
1494 return (1);
1497 // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
1498 static int ReadWaveData (FILE * fp, const SourceRefT * src, const ByteOrderT order, const uint n, double * hrir) {
1499 int pre, post, skip;
1500 uint i;
1502 pre = (int) (src -> mSize * src -> mChannel);
1503 post = (int) (src -> mSize * (src -> mSkip - src -> mChannel - 1));
1504 skip = 0;
1505 for (i = 0; i < n; i ++) {
1506 skip += pre;
1507 if (skip > 0)
1508 fseek (fp, skip, SEEK_CUR);
1509 if (! ReadBinAsDouble (fp, src -> mPath, order, src -> mType, src -> mSize, src -> mBits, & hrir [i]))
1510 return (0);
1511 skip = post;
1513 if (skip > 0)
1514 fseek (fp, skip, SEEK_CUR);
1515 return (1);
1518 // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
1519 // doubles.
1520 static int ReadWaveList (FILE * fp, const SourceRefT * src, const ByteOrderT order, const uint n, double * hrir) {
1521 uint32 fourCC, chunkSize, listSize, count;
1522 uint block, skip, offset, i;
1523 double lastSample;
1525 for (;;) {
1526 if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
1527 (! ReadBin4 (fp, src -> mPath, order, 4, & chunkSize)))
1528 return (0);
1529 if (fourCC == FOURCC_DATA) {
1530 block = src -> mSize * src -> mSkip;
1531 count = chunkSize / block;
1532 if (count < (src -> mOffset + n)) {
1533 fprintf (stderr, "Error: Bad read from file '%s'.\n", src -> mPath);
1534 return (0);
1536 fseek (fp, (long) (src -> mOffset * block), SEEK_CUR);
1537 if (! ReadWaveData (fp, src, order, n, & hrir [0]))
1538 return (0);
1539 return (1);
1540 } else if (fourCC == FOURCC_LIST) {
1541 if (! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC))
1542 return (0);
1543 chunkSize -= 4;
1544 if (fourCC == FOURCC_WAVL)
1545 break;
1547 if (chunkSize > 0)
1548 fseek (fp, (long) chunkSize, SEEK_CUR);
1550 listSize = chunkSize;
1551 block = src -> mSize * src -> mSkip;
1552 skip = src -> mOffset;
1553 offset = 0;
1554 lastSample = 0.0;
1555 while ((offset < n) && (listSize > 8)) {
1556 if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
1557 (! ReadBin4 (fp, src -> mPath, order, 4, & chunkSize)))
1558 return (0);
1559 listSize -= 8 + chunkSize;
1560 if (fourCC == FOURCC_DATA) {
1561 count = chunkSize / block;
1562 if (count > skip) {
1563 fseek (fp, (long) (skip * block), SEEK_CUR);
1564 chunkSize -= skip * block;
1565 count -= skip;
1566 skip = 0;
1567 if (count > (n - offset))
1568 count = n - offset;
1569 if (! ReadWaveData (fp, src, order, count, & hrir [offset]))
1570 return (0);
1571 chunkSize -= count * block;
1572 offset += count;
1573 lastSample = hrir [offset - 1];
1574 } else {
1575 skip -= count;
1576 count = 0;
1578 } else if (fourCC == FOURCC_SLNT) {
1579 if (! ReadBin4 (fp, src -> mPath, order, 4, & count))
1580 return (0);
1581 chunkSize -= 4;
1582 if (count > skip) {
1583 count -= skip;
1584 skip = 0;
1585 if (count > (n - offset))
1586 count = n - offset;
1587 for (i = 0; i < count; i ++)
1588 hrir [offset + i] = lastSample;
1589 offset += count;
1590 } else {
1591 skip -= count;
1592 count = 0;
1595 if (chunkSize > 0)
1596 fseek (fp, (long) chunkSize, SEEK_CUR);
1598 if (offset < n) {
1599 fprintf (stderr, "Error: Bad read from file '%s'.\n", src -> mPath);
1600 return (0);
1602 return (1);
1605 // Load a source HRIR from a RIFF/RIFX WAVE file.
1606 static int LoadWaveSource (FILE * fp, SourceRefT * src, const uint hrirRate, const uint n, double * hrir) {
1607 uint32 fourCC, dummy;
1608 ByteOrderT order;
1610 if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
1611 (! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & dummy)))
1612 return (0);
1613 if (fourCC == FOURCC_RIFF) {
1614 order = BO_LITTLE;
1615 } else if (fourCC == FOURCC_RIFX) {
1616 order = BO_BIG;
1617 } else {
1618 fprintf (stderr, "Error: No RIFF/RIFX chunk in file '%s'.\n", src -> mPath);
1619 return (0);
1621 if (! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC))
1622 return (0);
1623 if (fourCC != FOURCC_WAVE) {
1624 fprintf (stderr, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src -> mPath);
1625 return (0);
1627 if (! ReadWaveFormat (fp, order, hrirRate, src))
1628 return (0);
1629 if (! ReadWaveList (fp, src, order, n, hrir))
1630 return (0);
1631 return (1);
1634 // Load a source HRIR from a binary file.
1635 static int LoadBinarySource (FILE * fp, const SourceRefT * src, const ByteOrderT order, const uint n, double * hrir) {
1636 uint i;
1638 fseek (fp, (long) src -> mOffset, SEEK_SET);
1639 for (i = 0; i < n; i ++) {
1640 if (! ReadBinAsDouble (fp, src -> mPath, order, src -> mType, src -> mSize, src -> mBits, & hrir [i]))
1641 return (0);
1642 if (src -> mSkip > 0)
1643 fseek (fp, (long) src -> mSkip, SEEK_CUR);
1645 return (1);
1648 // Load a source HRIR from an ASCII text file containing a list of elements
1649 // separated by whitespace or common list operators (',', ';', ':', '|').
1650 static int LoadAsciiSource (FILE * fp, const SourceRefT * src, const uint n, double * hrir) {
1651 TokenReaderT tr;
1652 uint i, j;
1653 double dummy;
1655 TrSetup (fp, NULL, & tr);
1656 for (i = 0; i < src -> mOffset; i ++) {
1657 if (! ReadAsciiAsDouble (& tr, src -> mPath, src -> mType, (uint) src -> mBits, & dummy))
1658 return (0);
1660 for (i = 0; i < n; i ++) {
1661 if (! ReadAsciiAsDouble (& tr, src -> mPath, src -> mType, (uint) src -> mBits, & hrir [i]))
1662 return (0);
1663 for (j = 0; j < src -> mSkip; j ++) {
1664 if (! ReadAsciiAsDouble (& tr, src -> mPath, src -> mType, (uint) src -> mBits, & dummy))
1665 return (0);
1668 return (1);
1671 // Load a source HRIR from a supported file type.
1672 static int LoadSource (SourceRefT * src, const uint hrirRate, const uint n, double * hrir) {
1673 FILE * fp = NULL;
1674 int result;
1676 if (src -> mFormat == SF_ASCII)
1677 fp = fopen (src -> mPath, "r");
1678 else
1679 fp = fopen (src -> mPath, "rb");
1680 if (fp == NULL) {
1681 fprintf (stderr, "Error: Could not open source file '%s'.\n", src -> mPath);
1682 return (0);
1684 if (src -> mFormat == SF_WAVE)
1685 result = LoadWaveSource (fp, src, hrirRate, n, hrir);
1686 else if (src -> mFormat == SF_BIN_LE)
1687 result = LoadBinarySource (fp, src, BO_LITTLE, n, hrir);
1688 else if (src -> mFormat == SF_BIN_BE)
1689 result = LoadBinarySource (fp, src, BO_BIG, n, hrir);
1690 else
1691 result = LoadAsciiSource (fp, src, n, hrir);
1692 fclose (fp);
1693 return (result);
1696 // Calculate the onset time of an HRIR and average it with any existing
1697 // timing for its elevation and azimuth.
1698 static void AverageHrirOnset (const double * hrir, const double f, const uint ei, const uint ai, const HrirDataT * hData) {
1699 double mag;
1700 uint n, i, j;
1702 mag = 0.0;
1703 n = hData -> mIrPoints;
1704 for (i = 0; i < n; i ++)
1705 mag = fmax (fabs (hrir [i]), mag);
1706 mag *= 0.15;
1707 for (i = 0; i < n; i ++) {
1708 if (fabs (hrir [i]) >= mag)
1709 break;
1711 j = hData -> mEvOffset [ei] + ai;
1712 hData -> mHrtds [j] = Lerp (hData -> mHrtds [j], ((double) i) / hData -> mIrRate, f);
1715 // Calculate the magnitude response of an HRIR and average it with any
1716 // existing responses for its elevation and azimuth.
1717 static void AverageHrirMagnitude (const double * hrir, const double f, const uint ei, const uint ai, const HrirDataT * hData) {
1718 double * re = NULL, * im = NULL;
1719 uint n, m, i, j;
1721 n = hData -> mFftSize;
1722 re = CreateArray (n);
1723 im = CreateArray (n);
1724 for (i = 0; i < hData -> mIrPoints; i ++) {
1725 re [i] = hrir [i];
1726 im [i] = 0.0;
1728 for (; i < n; i ++) {
1729 re [i] = 0.0;
1730 im [i] = 0.0;
1732 FftForward (n, re, im, re, im);
1733 MagnitudeResponse (n, re, im, re);
1734 m = 1 + (n / 2);
1735 j = (hData -> mEvOffset [ei] + ai) * hData -> mIrSize;
1736 for (i = 0; i < m; i ++)
1737 hData -> mHrirs [j + i] = Lerp (hData -> mHrirs [j + i], re [i], f);
1738 DestroyArray (im);
1739 DestroyArray (re);
1742 /* Calculate the contribution of each HRIR to the diffuse-field average based
1743 * on the area of its surface patch. All patches are centered at the HRIR
1744 * coordinates on the unit sphere and are measured by solid angle.
1746 static void CalculateDfWeights (const HrirDataT * hData, double * weights) {
1747 uint ei;
1748 double evs, sum, ev, up_ev, down_ev, solidAngle;
1750 evs = 90.0 / (hData -> mEvCount - 1);
1751 sum = 0.0;
1752 for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++) {
1753 // For each elevation, calculate the upper and lower limits of the
1754 // patch band.
1755 ev = -90.0 + (ei * 2.0 * evs);
1756 if (ei < (hData -> mEvCount - 1))
1757 up_ev = (ev + evs) * M_PI / 180.0;
1758 else
1759 up_ev = M_PI / 2.0;
1760 if (ei > 0)
1761 down_ev = (ev - evs) * M_PI / 180.0;
1762 else
1763 down_ev = -M_PI / 2.0;
1764 // Calculate the area of the patch band.
1765 solidAngle = 2.0 * M_PI * (sin (up_ev) - sin (down_ev));
1766 // Each weight is the area of one patch.
1767 weights [ei] = solidAngle / hData -> mAzCount [ei];
1768 // Sum the total surface area covered by the HRIRs.
1769 sum += solidAngle;
1771 // Normalize the weights given the total surface coverage.
1772 for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++)
1773 weights [ei] /= sum;
1776 /* Calculate the diffuse-field average from the given magnitude responses of
1777 * the HRIR set. Weighting can be applied to compensate for the varying
1778 * surface area covered by each HRIR. The final average can then be limited
1779 * by the specified magnitude range (in positive dB; 0.0 to skip).
1781 static void CalculateDiffuseFieldAverage (const HrirDataT * hData, const int weighted, const double limit, double * dfa) {
1782 double * weights = NULL;
1783 uint ei, ai, count, step, start, end, m, j, i;
1784 double weight;
1786 weights = CreateArray (hData -> mEvCount);
1787 if (weighted) {
1788 // Use coverage weighting to calculate the average.
1789 CalculateDfWeights (hData, weights);
1790 } else {
1791 // If coverage weighting is not used, the weights still need to be
1792 // averaged by the number of HRIRs.
1793 count = 0;
1794 for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++)
1795 count += hData -> mAzCount [ei];
1796 for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++)
1797 weights [ei] = 1.0 / count;
1799 ei = hData -> mEvStart;
1800 ai = 0;
1801 step = hData -> mIrSize;
1802 start = hData -> mEvOffset [ei] * step;
1803 end = hData -> mIrCount * step;
1804 m = 1 + (hData -> mFftSize / 2);
1805 for (i = 0; i < m; i ++)
1806 dfa [i] = 0.0;
1807 for (j = start; j < end; j += step) {
1808 // Get the weight for this HRIR's contribution.
1809 weight = weights [ei];
1810 // Add this HRIR's weighted power average to the total.
1811 for (i = 0; i < m; i ++)
1812 dfa [i] += weight * hData -> mHrirs [j + i] * hData -> mHrirs [j + i];
1813 // Determine the next weight to use.
1814 ai ++;
1815 if (ai >= hData -> mAzCount [ei]) {
1816 ei ++;
1817 ai = 0;
1820 // Finish the average calculation and keep it from being too small.
1821 for (i = 0; i < m; i ++)
1822 dfa [i] = fmax (sqrt (dfa [i]), EPSILON);
1823 // Apply a limit to the magnitude range of the diffuse-field average if
1824 // desired.
1825 if (limit > 0.0)
1826 LimitMagnitudeResponse (hData -> mFftSize, limit, dfa, dfa);
1827 DestroyArray (weights);
1830 // Perform diffuse-field equalization on the magnitude responses of the HRIR
1831 // set using the given average response.
1832 static void DiffuseFieldEqualize (const double * dfa, const HrirDataT * hData) {
1833 uint step, start, end, m, j, i;
1835 step = hData -> mIrSize;
1836 start = hData -> mEvOffset [hData -> mEvStart] * step;
1837 end = hData -> mIrCount * step;
1838 m = 1 + (hData -> mFftSize / 2);
1839 for (j = start; j < end; j += step) {
1840 for (i = 0; i < m; i ++)
1841 hData -> mHrirs [j + i] /= dfa [i];
1845 // Perform minimum-phase reconstruction using the magnitude responses of the
1846 // HRIR set.
1847 static void ReconstructHrirs (const HrirDataT * hData) {
1848 double * re = NULL, * im = NULL;
1849 uint step, start, end, n, j, i;
1851 step = hData -> mIrSize;
1852 start = hData -> mEvOffset [hData -> mEvStart] * step;
1853 end = hData -> mIrCount * step;
1854 n = hData -> mFftSize;
1855 re = CreateArray (n);
1856 im = CreateArray (n);
1857 for (j = start; j < end; j += step) {
1858 MinimumPhase (n, & hData -> mHrirs [j], re, im);
1859 FftInverse (n, re, im, re, im);
1860 for (i = 0; i < hData -> mIrPoints; i ++)
1861 hData -> mHrirs [j + i] = re [i];
1863 DestroyArray (im);
1864 DestroyArray (re);
1867 // Resamples the HRIRs for use at the given sampling rate.
1868 static void ResampleHrirs (const uint rate, HrirDataT * hData) {
1869 ResamplerT rs;
1870 uint n, step, start, end, j;
1872 ResamplerSetup (& rs, hData -> mIrRate, rate);
1873 n = hData -> mIrPoints;
1874 step = hData -> mIrSize;
1875 start = hData -> mEvOffset [hData -> mEvStart] * step;
1876 end = hData -> mIrCount * step;
1877 for (j = start; j < end; j += step)
1878 ResamplerRun (& rs, n, & hData -> mHrirs [j], n, & hData -> mHrirs [j]);
1879 ResamplerClear (& rs);
1880 hData -> mIrRate = rate;
1883 /* Given an elevation index and an azimuth, calculate the indices of the two
1884 * HRIRs that bound the coordinate along with a factor for calculating the
1885 * continous HRIR using interpolation.
1887 static void CalcAzIndices (const HrirDataT * hData, const uint ei, const double az, uint * j0, uint * j1, double * jf) {
1888 double af;
1889 uint ai;
1891 af = ((2.0 * M_PI) + az) * hData -> mAzCount [ei] / (2.0 * M_PI);
1892 ai = ((uint) af) % hData -> mAzCount [ei];
1893 af -= floor (af);
1894 (* j0) = hData -> mEvOffset [ei] + ai;
1895 (* j1) = hData -> mEvOffset [ei] + ((ai + 1) % hData -> mAzCount [ei]);
1896 (* jf) = af;
1899 // Synthesize any missing onset timings at the bottom elevations. This just
1900 // blends between slightly exaggerated known onsets. Not an accurate model.
1901 static void SynthesizeOnsets (HrirDataT * hData) {
1902 uint oi, e, a, j0, j1;
1903 double t, of, jf;
1905 oi = hData -> mEvStart;
1906 t = 0.0;
1907 for (a = 0; a < hData -> mAzCount [oi]; a ++)
1908 t += hData -> mHrtds [hData -> mEvOffset [oi] + a];
1909 hData -> mHrtds [0] = 1.32e-4 + (t / hData -> mAzCount [oi]);
1910 for (e = 1; e < hData -> mEvStart; e ++) {
1911 of = ((double) e) / hData -> mEvStart;
1912 for (a = 0; a < hData -> mAzCount [e]; a ++) {
1913 CalcAzIndices (hData, oi, a * 2.0 * M_PI / hData -> mAzCount [e], & j0, & j1, & jf);
1914 hData -> mHrtds [hData -> mEvOffset [e] + a] = Lerp (hData -> mHrtds [0], Lerp (hData -> mHrtds [j0], hData -> mHrtds [j1], jf), of);
1919 /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
1920 * now this just blends the lowest elevation HRIRs together and applies some
1921 * attenuation and high frequency damping. It is a simple, if inaccurate
1922 * model.
1924 static void SynthesizeHrirs (HrirDataT * hData) {
1925 uint oi, a, e, step, n, i, j;
1926 double of, b;
1927 uint j0, j1;
1928 double jf;
1929 double lp [4], s0, s1;
1931 if (hData -> mEvStart <= 0)
1932 return;
1933 step = hData -> mIrSize;
1934 oi = hData -> mEvStart;
1935 n = hData -> mIrPoints;
1936 for (i = 0; i < n; i ++)
1937 hData -> mHrirs [i] = 0.0;
1938 for (a = 0; a < hData -> mAzCount [oi]; a ++) {
1939 j = (hData -> mEvOffset [oi] + a) * step;
1940 for (i = 0; i < n; i ++)
1941 hData -> mHrirs [i] += hData -> mHrirs [j + i] / hData -> mAzCount [oi];
1943 for (e = 1; e < hData -> mEvStart; e ++) {
1944 of = ((double) e) / hData -> mEvStart;
1945 b = (1.0 - of) * (3.5e-6 * hData -> mIrRate);
1946 for (a = 0; a < hData -> mAzCount [e]; a ++) {
1947 j = (hData -> mEvOffset [e] + a) * step;
1948 CalcAzIndices (hData, oi, a * 2.0 * M_PI / hData -> mAzCount [e], & j0, & j1, & jf);
1949 j0 *= step;
1950 j1 *= step;
1951 lp [0] = 0.0;
1952 lp [1] = 0.0;
1953 lp [2] = 0.0;
1954 lp [3] = 0.0;
1955 for (i = 0; i < n; i ++) {
1956 s0 = hData -> mHrirs [i];
1957 s1 = Lerp (hData -> mHrirs [j0 + i], hData -> mHrirs [j1 + i], jf);
1958 s0 = Lerp (s0, s1, of);
1959 lp [0] = Lerp (s0, lp [0], b);
1960 lp [1] = Lerp (lp [0], lp [1], b);
1961 lp [2] = Lerp (lp [1], lp [2], b);
1962 lp [3] = Lerp (lp [2], lp [3], b);
1963 hData -> mHrirs [j + i] = lp [3];
1967 b = 3.5e-6 * hData -> mIrRate;
1968 lp [0] = 0.0;
1969 lp [1] = 0.0;
1970 lp [2] = 0.0;
1971 lp [3] = 0.0;
1972 for (i = 0; i < n; i ++) {
1973 s0 = hData -> mHrirs [i];
1974 lp [0] = Lerp (s0, lp [0], b);
1975 lp [1] = Lerp (lp [0], lp [1], b);
1976 lp [2] = Lerp (lp [1], lp [2], b);
1977 lp [3] = Lerp (lp [2], lp [3], b);
1978 hData -> mHrirs [i] = lp [3];
1980 hData -> mEvStart = 0;
1983 // The following routines assume a full set of HRIRs for all elevations.
1985 // Normalize the HRIR set and slightly attenuate the result.
1986 static void NormalizeHrirs (const HrirDataT * hData) {
1987 uint step, end, n, j, i;
1988 double maxLevel;
1990 step = hData -> mIrSize;
1991 end = hData -> mIrCount * step;
1992 n = hData -> mIrPoints;
1993 maxLevel = 0.0;
1994 for (j = 0; j < end; j += step) {
1995 for (i = 0; i < n; i ++)
1996 maxLevel = fmax (fabs (hData -> mHrirs [j + i]), maxLevel);
1998 maxLevel = 1.01 * maxLevel;
1999 for (j = 0; j < end; j += step) {
2000 for (i = 0; i < n; i ++)
2001 hData -> mHrirs [j + i] /= maxLevel;
2005 // Calculate the left-ear time delay using a spherical head model.
2006 static double CalcLTD (const double ev, const double az, const double rad, const double dist) {
2007 double azp, dlp, l, al;
2009 azp = asin (cos (ev) * sin (az));
2010 dlp = sqrt ((dist * dist) + (rad * rad) + (2.0 * dist * rad * sin (azp)));
2011 l = sqrt ((dist * dist) - (rad * rad));
2012 al = (0.5 * M_PI) + azp;
2013 if (dlp > l)
2014 dlp = l + (rad * (al - acos (rad / dist)));
2015 return (dlp / 343.3);
2018 // Calculate the effective head-related time delays for each minimum-phase
2019 // HRIR.
2020 static void CalculateHrtds (const HeadModelT model, const double radius, HrirDataT * hData) {
2021 double minHrtd, maxHrtd;
2022 uint e, a, j;
2023 double t;
2025 minHrtd = 1000.0;
2026 maxHrtd = -1000.0;
2027 for (e = 0; e < hData -> mEvCount; e ++) {
2028 for (a = 0; a < hData -> mAzCount [e]; a ++) {
2029 j = hData -> mEvOffset [e] + a;
2030 if (model == HM_DATASET) {
2031 t = hData -> mHrtds [j] * radius / hData -> mRadius;
2032 } else {
2033 t = CalcLTD ((-90.0 + (e * 180.0 / (hData -> mEvCount - 1))) * M_PI / 180.0,
2034 (a * 360.0 / hData -> mAzCount [e]) * M_PI / 180.0,
2035 radius, hData -> mDistance);
2037 hData -> mHrtds [j] = t;
2038 maxHrtd = fmax (t, maxHrtd);
2039 minHrtd = fmin (t, minHrtd);
2042 maxHrtd -= minHrtd;
2043 for (j = 0; j < hData -> mIrCount; j ++)
2044 hData -> mHrtds [j] -= minHrtd;
2045 hData -> mMaxHrtd = maxHrtd;
2048 // Store the OpenAL Soft HRTF data set.
2049 static int StoreMhr (const HrirDataT * hData, const char * filename) {
2050 FILE * fp = NULL;
2051 uint e, step, end, n, j, i;
2052 int hpHist, v;
2054 if ((fp = fopen (filename, "wb")) == NULL) {
2055 fprintf (stderr, "Error: Could not open MHR file '%s'.\n", filename);
2056 return (0);
2058 if (! WriteAscii (MHR_FORMAT, fp, filename))
2059 return (0);
2060 if (! WriteBin4 (BO_LITTLE, 4, (uint32) hData -> mIrRate, fp, filename))
2061 return (0);
2062 if (! WriteBin4 (BO_LITTLE, 1, (uint32) hData -> mIrPoints, fp, filename))
2063 return (0);
2064 if (! WriteBin4 (BO_LITTLE, 1, (uint32) hData -> mEvCount, fp, filename))
2065 return (0);
2066 for (e = 0; e < hData -> mEvCount; e ++) {
2067 if (! WriteBin4 (BO_LITTLE, 1, (uint32) hData -> mAzCount [e], fp, filename))
2068 return (0);
2070 step = hData -> mIrSize;
2071 end = hData -> mIrCount * step;
2072 n = hData -> mIrPoints;
2073 srand (0x31DF840C);
2074 for (j = 0; j < end; j += step) {
2075 hpHist = 0;
2076 for (i = 0; i < n; i ++) {
2077 v = HpTpdfDither (32767.0 * hData -> mHrirs [j + i], & hpHist);
2078 if (! WriteBin4 (BO_LITTLE, 2, (uint32) v, fp, filename))
2079 return (0);
2082 for (j = 0; j < hData -> mIrCount; j ++) {
2083 v = (int) fmin (round (hData -> mIrRate * hData -> mHrtds [j]), MAX_HRTD);
2084 if (! WriteBin4 (BO_LITTLE, 1, (uint32) v, fp, filename))
2085 return (0);
2087 fclose (fp);
2088 return (1);
2091 // Process the data set definition to read and validate the data set metrics.
2092 static int ProcessMetrics (TokenReaderT * tr, const uint fftSize, const uint truncSize, HrirDataT * hData) {
2093 char ident [MAX_IDENT_LEN + 1];
2094 uint line, col;
2095 int intVal;
2096 uint points;
2097 double fpVal;
2098 int hasRate = 0, hasPoints = 0, hasAzimuths = 0;
2099 int hasRadius = 0, hasDistance = 0;
2101 while (! (hasRate && hasPoints && hasAzimuths && hasRadius && hasDistance)) {
2102 TrIndication (tr, & line, & col);
2103 if (! TrReadIdent (tr, MAX_IDENT_LEN, ident))
2104 return (0);
2105 if (strcasecmp (ident, "rate") == 0) {
2106 if (hasRate) {
2107 TrErrorAt (tr, line, col, "Redefinition of 'rate'.\n");
2108 return (0);
2110 if (! TrReadOperator (tr, "="))
2111 return (0);
2112 if (! TrReadInt (tr, MIN_RATE, MAX_RATE, & intVal))
2113 return (0);
2114 hData -> mIrRate = (uint) intVal;
2115 hasRate = 1;
2116 } else if (strcasecmp (ident, "points") == 0) {
2117 if (hasPoints) {
2118 TrErrorAt (tr, line, col, "Redefinition of 'points'.\n");
2119 return (0);
2121 if (! TrReadOperator (tr, "="))
2122 return (0);
2123 TrIndication (tr, & line, & col);
2124 if (! TrReadInt (tr, MIN_POINTS, MAX_POINTS, & intVal))
2125 return (0);
2126 points = (uint) intVal;
2127 if ((fftSize > 0) && (points > fftSize)) {
2128 TrErrorAt (tr, line, col, "Value exceeds the overridden FFT size.\n");
2129 return (0);
2131 if (points < truncSize) {
2132 TrErrorAt (tr, line, col, "Value is below the truncation size.\n");
2133 return (0);
2135 hData -> mIrPoints = points;
2136 hData -> mFftSize = fftSize;
2137 if (fftSize <= 0) {
2138 points = 1;
2139 while (points < (4 * hData -> mIrPoints))
2140 points <<= 1;
2141 hData -> mFftSize = points;
2142 hData -> mIrSize = 1 + (points / 2);
2143 } else {
2144 hData -> mFftSize = fftSize;
2145 hData -> mIrSize = 1 + (fftSize / 2);
2146 if (points > hData -> mIrSize)
2147 hData -> mIrSize = points;
2149 hasPoints = 1;
2150 } else if (strcasecmp (ident, "azimuths") == 0) {
2151 if (hasAzimuths) {
2152 TrErrorAt (tr, line, col, "Redefinition of 'azimuths'.\n");
2153 return (0);
2155 if (! TrReadOperator (tr, "="))
2156 return (0);
2157 hData -> mIrCount = 0;
2158 hData -> mEvCount = 0;
2159 hData -> mEvOffset [0] = 0;
2160 for (;;) {
2161 if (! TrReadInt (tr, MIN_AZ_COUNT, MAX_AZ_COUNT, & intVal))
2162 return (0);
2163 hData -> mAzCount [hData -> mEvCount] = (uint) intVal;
2164 hData -> mIrCount += (uint) intVal;
2165 hData -> mEvCount ++;
2166 if (! TrIsOperator (tr, ","))
2167 break;
2168 if (hData -> mEvCount >= MAX_EV_COUNT) {
2169 TrError (tr, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT);
2170 return (0);
2172 hData -> mEvOffset [hData -> mEvCount] = hData -> mEvOffset [hData -> mEvCount - 1] + ((uint) intVal);
2173 TrReadOperator (tr, ",");
2175 if (hData -> mEvCount < MIN_EV_COUNT) {
2176 TrErrorAt (tr, line, col, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT);
2177 return (0);
2179 hasAzimuths = 1;
2180 } else if (strcasecmp (ident, "radius") == 0) {
2181 if (hasRadius) {
2182 TrErrorAt (tr, line, col, "Redefinition of 'radius'.\n");
2183 return (0);
2185 if (! TrReadOperator (tr, "="))
2186 return (0);
2187 if (! TrReadFloat (tr, MIN_RADIUS, MAX_RADIUS, & fpVal))
2188 return (0);
2189 hData -> mRadius = fpVal;
2190 hasRadius = 1;
2191 } else if (strcasecmp (ident, "distance") == 0) {
2192 if (hasDistance) {
2193 TrErrorAt (tr, line, col, "Redefinition of 'distance'.\n");
2194 return (0);
2196 if (! TrReadOperator (tr, "="))
2197 return (0);
2198 if (! TrReadFloat (tr, MIN_DISTANCE, MAX_DISTANCE, & fpVal))
2199 return (0);
2200 hData -> mDistance = fpVal;
2201 hasDistance = 1;
2202 } else {
2203 TrErrorAt (tr, line, col, "Expected a metric name.\n");
2204 return (0);
2206 TrSkipWhitespace (tr);
2208 return (1);
2211 // Parse an index pair from the data set definition.
2212 static int ReadIndexPair (TokenReaderT * tr, const HrirDataT * hData, uint * ei, uint * ai) {
2213 int intVal;
2215 if (! TrReadInt (tr, 0, (int) hData -> mEvCount, & intVal))
2216 return (0);
2217 (* ei) = (uint) intVal;
2218 if (! TrReadOperator (tr, ","))
2219 return (0);
2220 if (! TrReadInt (tr, 0, (int) hData -> mAzCount [(* ei)], & intVal))
2221 return (0);
2222 (* ai) = (uint) intVal;
2223 return (1);
2226 // Match the source format from a given identifier.
2227 static SourceFormatT MatchSourceFormat (const char * ident) {
2228 if (strcasecmp (ident, "wave") == 0)
2229 return (SF_WAVE);
2230 else if (strcasecmp (ident, "bin_le") == 0)
2231 return (SF_BIN_LE);
2232 else if (strcasecmp (ident, "bin_be") == 0)
2233 return (SF_BIN_BE);
2234 else if (strcasecmp (ident, "ascii") == 0)
2235 return (SF_ASCII);
2236 return (SF_NONE);
2239 // Match the source element type from a given identifier.
2240 static ElementTypeT MatchElementType (const char * ident) {
2241 if (strcasecmp (ident, "int") == 0)
2242 return (ET_INT);
2243 else if (strcasecmp (ident, "fp") == 0)
2244 return (ET_FP);
2245 return (ET_NONE);
2248 // Parse and validate a source reference from the data set definition.
2249 static int ReadSourceRef (TokenReaderT * tr, SourceRefT * src) {
2250 uint line, col;
2251 char ident [MAX_IDENT_LEN + 1];
2252 int intVal;
2254 TrIndication (tr, & line, & col);
2255 if (! TrReadIdent (tr, MAX_IDENT_LEN, ident))
2256 return (0);
2257 src -> mFormat = MatchSourceFormat (ident);
2258 if (src -> mFormat == SF_NONE) {
2259 TrErrorAt (tr, line, col, "Expected a source format.\n");
2260 return (0);
2262 if (! TrReadOperator (tr, "("))
2263 return (0);
2264 if (src -> mFormat == SF_WAVE) {
2265 if (! TrReadInt (tr, 0, MAX_WAVE_CHANNELS, & intVal))
2266 return (0);
2267 src -> mType = ET_NONE;
2268 src -> mSize = 0;
2269 src -> mBits = 0;
2270 src -> mChannel = (uint) intVal;
2271 src -> mSkip = 0;
2272 } else {
2273 TrIndication (tr, & line, & col);
2274 if (! TrReadIdent (tr, MAX_IDENT_LEN, ident))
2275 return (0);
2276 src -> mType = MatchElementType (ident);
2277 if (src -> mType == ET_NONE) {
2278 TrErrorAt (tr, line, col, "Expected a source element type.\n");
2279 return (0);
2281 if ((src -> mFormat == SF_BIN_LE) || (src -> mFormat == SF_BIN_BE)) {
2282 if (! TrReadOperator (tr, ","))
2283 return (0);
2284 if (src -> mType == ET_INT) {
2285 if (! TrReadInt (tr, MIN_BIN_SIZE, MAX_BIN_SIZE, & intVal))
2286 return (0);
2287 src -> mSize = (uint) intVal;
2288 if (TrIsOperator (tr, ",")) {
2289 TrReadOperator (tr, ",");
2290 TrIndication (tr, & line, & col);
2291 if (! TrReadInt (tr, -2147483647 - 1, 2147483647, & intVal))
2292 return (0);
2293 if ((abs (intVal) < MIN_BIN_BITS) || (((uint) abs (intVal)) > (8 * src -> mSize))) {
2294 TrErrorAt (tr, line, col, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS, 8 * src -> mSize);
2295 return (0);
2297 src -> mBits = intVal;
2298 } else {
2299 src -> mBits = (int) (8 * src -> mSize);
2301 } else {
2302 TrIndication (tr, & line, & col);
2303 if (! TrReadInt (tr, -2147483647 - 1, 2147483647, & intVal))
2304 return (0);
2305 if ((intVal != 4) && (intVal != 8)) {
2306 TrErrorAt (tr, line, col, "Expected a value of 4 or 8.\n");
2307 return (0);
2309 src -> mSize = (uint) intVal;
2310 src -> mBits = 0;
2312 } else if ((src -> mFormat == SF_ASCII) && (src -> mType == ET_INT)) {
2313 if (! TrReadOperator (tr, ","))
2314 return (0);
2315 if (! TrReadInt (tr, MIN_ASCII_BITS, MAX_ASCII_BITS, & intVal))
2316 return (0);
2317 src -> mSize = 0;
2318 src -> mBits = intVal;
2319 } else {
2320 src -> mSize = 0;
2321 src -> mBits = 0;
2323 if (TrIsOperator (tr, ";")) {
2324 TrReadOperator (tr, ";");
2325 if (! TrReadInt (tr, 0, 0x7FFFFFFF, & intVal))
2326 return (0);
2327 src -> mSkip = (uint) intVal;
2328 } else {
2329 src -> mSkip = 0;
2332 if (! TrReadOperator (tr, ")"))
2333 return (0);
2334 if (TrIsOperator (tr, "@")) {
2335 TrReadOperator (tr, "@");
2336 if (! TrReadInt (tr, 0, 0x7FFFFFFF, & intVal))
2337 return (0);
2338 src -> mOffset = (uint) intVal;
2339 } else {
2340 src -> mOffset = 0;
2342 if (! TrReadOperator (tr, ":"))
2343 return (0);
2344 if (! TrReadString (tr, MAX_PATH_LEN, src -> mPath))
2345 return (0);
2346 return (1);
2349 // Process the list of sources in the data set definition.
2350 static int ProcessSources (const HeadModelT model, TokenReaderT * tr, HrirDataT * hData) {
2351 uint * setCount = NULL, * setFlag = NULL;
2352 double * hrir = NULL;
2353 uint line, col, ei, ai;
2354 SourceRefT src;
2355 double factor;
2357 setCount = (uint *) calloc (hData -> mEvCount, sizeof (uint));
2358 setFlag = (uint *) calloc (hData -> mIrCount, sizeof (uint));
2359 hrir = CreateArray (hData -> mIrPoints);
2360 while (TrIsOperator (tr, "[")) {
2361 TrIndication (tr, & line, & col);
2362 TrReadOperator (tr, "[");
2363 if (ReadIndexPair (tr, hData, & ei, & ai)) {
2364 if (TrReadOperator (tr, "]")) {
2365 if (! setFlag [hData -> mEvOffset [ei] + ai]) {
2366 if (TrReadOperator (tr, "=")) {
2367 factor = 1.0;
2368 for (;;) {
2369 if (ReadSourceRef (tr, & src)) {
2370 if (LoadSource (& src, hData -> mIrRate, hData -> mIrPoints, hrir)) {
2371 if (model == HM_DATASET)
2372 AverageHrirOnset (hrir, 1.0 / factor, ei, ai, hData);
2373 AverageHrirMagnitude (hrir, 1.0 / factor, ei, ai, hData);
2374 factor += 1.0;
2375 if (! TrIsOperator (tr, "+"))
2376 break;
2377 TrReadOperator (tr, "+");
2378 continue;
2381 DestroyArray (hrir);
2382 free (setFlag);
2383 free (setCount);
2384 return (0);
2386 setFlag [hData -> mEvOffset [ei] + ai] = 1;
2387 setCount [ei] ++;
2388 continue;
2390 } else {
2391 TrErrorAt (tr, line, col, "Redefinition of source.\n");
2395 DestroyArray (hrir);
2396 free (setFlag);
2397 free (setCount);
2398 return (0);
2400 ei = 0;
2401 while ((ei < hData -> mEvCount) && (setCount [ei] < 1))
2402 ei ++;
2403 if (ei < hData -> mEvCount) {
2404 hData -> mEvStart = ei;
2405 while ((ei < hData -> mEvCount) && (setCount [ei] == hData -> mAzCount [ei]))
2406 ei ++;
2407 if (ei >= hData -> mEvCount) {
2408 if (! TrLoad (tr)) {
2409 DestroyArray (hrir);
2410 free (setFlag);
2411 free (setCount);
2412 return (1);
2413 } else {
2414 TrError (tr, "Errant data at end of source list.\n");
2416 } else {
2417 TrError (tr, "Missing sources for elevation index %d.\n", ei);
2419 } else {
2420 TrError (tr, "Missing source references.\n");
2422 DestroyArray (hrir);
2423 free (setFlag);
2424 free (setCount);
2425 return (0);
2428 /* Parse the data set definition and process the source data, storing the
2429 * resulting data set as desired. If the input name is NULL it will read
2430 * from standard input.
2432 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) {
2433 FILE * fp = NULL;
2434 TokenReaderT tr;
2435 HrirDataT hData;
2436 double * dfa = NULL;
2437 char rateStr [8 + 1], expName [MAX_PATH_LEN];
2439 hData . mIrRate = 0;
2440 hData . mIrPoints = 0;
2441 hData . mFftSize = 0;
2442 hData . mIrSize = 0;
2443 hData . mIrCount = 0;
2444 hData . mEvCount = 0;
2445 hData . mRadius = 0;
2446 hData . mDistance = 0;
2447 fprintf (stdout, "Reading HRIR definition...\n");
2448 if (inName != NULL) {
2449 fp = fopen (inName, "r");
2450 if (fp == NULL) {
2451 fprintf (stderr, "Error: Could not open definition file '%s'\n", inName);
2452 return (0);
2454 TrSetup (fp, inName, & tr);
2455 } else {
2456 fp = stdin;
2457 TrSetup (fp, "<stdin>", & tr);
2459 if (! ProcessMetrics (& tr, fftSize, truncSize, & hData)) {
2460 if (inName != NULL)
2461 fclose (fp);
2462 return (0);
2464 hData . mHrirs = CreateArray (hData . mIrCount * hData . mIrSize);
2465 hData . mHrtds = CreateArray (hData . mIrCount);
2466 if (! ProcessSources (model, & tr, & hData)) {
2467 DestroyArray (hData . mHrtds);
2468 DestroyArray (hData . mHrirs);
2469 if (inName != NULL)
2470 fclose (fp);
2471 return (0);
2473 if (inName != NULL)
2474 fclose (fp);
2475 if (equalize) {
2476 dfa = CreateArray (1 + (hData . mFftSize / 2));
2477 fprintf (stdout, "Calculating diffuse-field average...\n");
2478 CalculateDiffuseFieldAverage (& hData, surface, limit, dfa);
2479 fprintf (stdout, "Performing diffuse-field equalization...\n");
2480 DiffuseFieldEqualize (dfa, & hData);
2481 DestroyArray (dfa);
2483 fprintf (stdout, "Performing minimum phase reconstruction...\n");
2484 ReconstructHrirs (& hData);
2485 if ((outRate != 0) && (outRate != hData . mIrRate)) {
2486 fprintf (stdout, "Resampling HRIRs...\n");
2487 ResampleHrirs (outRate, & hData);
2489 fprintf (stdout, "Truncating minimum-phase HRIRs...\n");
2490 hData . mIrPoints = truncSize;
2491 fprintf (stdout, "Synthesizing missing elevations...\n");
2492 if (model == HM_DATASET)
2493 SynthesizeOnsets (& hData);
2494 SynthesizeHrirs (& hData);
2495 fprintf (stdout, "Normalizing final HRIRs...\n");
2496 NormalizeHrirs (& hData);
2497 fprintf (stdout, "Calculating impulse delays...\n");
2498 CalculateHrtds (model, (radius > DEFAULT_CUSTOM_RADIUS) ? radius : hData . mRadius, & hData);
2499 snprintf (rateStr, 8, "%u", hData . mIrRate);
2500 StrSubst (outName, "%r", rateStr, MAX_PATH_LEN, expName);
2501 switch (outFormat) {
2502 case OF_MHR :
2503 fprintf (stdout, "Creating MHR data set file...\n");
2504 if (! StoreMhr (& hData, expName))
2505 return (0);
2506 break;
2507 default :
2508 break;
2510 DestroyArray (hData . mHrtds);
2511 DestroyArray (hData . mHrirs);
2512 return (1);
2515 // Standard command line dispatch.
2516 int main (const int argc, const char * argv []) {
2517 const char * inName = NULL, * outName = NULL;
2518 OutputFormatT outFormat;
2519 int argi;
2520 uint outRate, fftSize;
2521 int equalize, surface;
2522 double limit;
2523 uint truncSize;
2524 HeadModelT model;
2525 double radius;
2526 char * end = NULL;
2528 if (argc < 2) {
2529 fprintf (stderr, "Error: No command specified. See '%s -h' for help.\n", argv [0]);
2530 return (-1);
2532 if ((strcmp (argv [1], "--help") == 0) || (strcmp (argv [1], "-h") == 0)) {
2533 fprintf (stdout, "HRTF Processing and Composition Utility\n\n");
2534 fprintf (stdout, "Usage: %s <command> [<option>...]\n\n", argv [0]);
2535 fprintf (stdout, "Commands:\n");
2536 fprintf (stdout, " -m, --make-mhr Makes an OpenAL Soft compatible HRTF data set.\n");
2537 fprintf (stdout, " Defaults output to: ./oalsoft_hrtf_%%r.mhr\n");
2538 fprintf (stdout, " -h, --help Displays this help information.\n\n");
2539 fprintf (stdout, "Options:\n");
2540 fprintf (stdout, " -r=<rate> Change the data set sample rate to the specified value and\n");
2541 fprintf (stdout, " resample the HRIRs accordingly.\n");
2542 fprintf (stdout, " -f=<points> Override the FFT window size (defaults to the first power-\n");
2543 fprintf (stdout, " of-two that fits four times the number of HRIR points).\n");
2544 fprintf (stdout, " -e={on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE ? "on" : "off"));
2545 fprintf (stdout, " -s={on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE ? "on" : "off"));
2546 fprintf (stdout, " -l={<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
2547 fprintf (stdout, " average (default: %.2f).\n", DEFAULT_LIMIT);
2548 fprintf (stdout, " -w=<points> Specify the size of the truncation window that's applied\n");
2549 fprintf (stdout, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE);
2550 fprintf (stdout, " -d={dataset| Specify the model used for calculating the head-delay timing\n");
2551 fprintf (stdout, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL == HM_DATASET) ? "dataset" : "sphere"));
2552 fprintf (stdout, " -c=<size> Use a customized head radius measured ear-to-ear in meters.\n");
2553 fprintf (stdout, " -i=<filename> Specify an HRIR definition file to use (defaults to stdin).\n");
2554 fprintf (stdout, " -o=<filename> Specify an output file. Overrides command-selected default.\n");
2555 fprintf (stdout, " Use of '%%r' will be substituted with the data set sample rate.\n");
2556 return (0);
2558 if ((strcmp (argv [1], "--make-mhr") == 0) || (strcmp (argv [1], "-m") == 0)) {
2559 if (argc > 3)
2560 outName = argv [3];
2561 else
2562 outName = "./oalsoft_hrtf_%r.mhr";
2563 outFormat = OF_MHR;
2564 } else {
2565 fprintf (stderr, "Error: Invalid command '%s'.\n", argv [1]);
2566 return (-1);
2568 argi = 2;
2569 outRate = 0;
2570 fftSize = 0;
2571 equalize = DEFAULT_EQUALIZE;
2572 surface = DEFAULT_SURFACE;
2573 limit = DEFAULT_LIMIT;
2574 truncSize = DEFAULT_TRUNCSIZE;
2575 model = DEFAULT_HEAD_MODEL;
2576 radius = DEFAULT_CUSTOM_RADIUS;
2577 while (argi < argc) {
2578 if (strncmp (argv [argi], "-r=", 3) == 0) {
2579 outRate = strtoul (& argv [argi] [3], & end, 10);
2580 if ((end [0] != '\0') || (outRate < MIN_RATE) || (outRate > MAX_RATE)) {
2581 fprintf (stderr, "Error: Expected a value from %u to %u for '-r'.\n", MIN_RATE, MAX_RATE);
2582 return (-1);
2584 } else if (strncmp (argv [argi], "-f=", 3) == 0) {
2585 fftSize = strtoul (& argv [argi] [3], & end, 10);
2586 if ((end [0] != '\0') || (fftSize & (fftSize - 1)) || (fftSize < MIN_FFTSIZE) || (fftSize > MAX_FFTSIZE)) {
2587 fprintf (stderr, "Error: Expected a power-of-two value from %u to %u for '-f'.\n", MIN_FFTSIZE, MAX_FFTSIZE);
2588 return (-1);
2590 } else if (strncmp (argv [argi], "-e=", 3) == 0) {
2591 if (strcmp (& argv [argi] [3], "on") == 0) {
2592 equalize = 1;
2593 } else if (strcmp (& argv [argi] [3], "off") == 0) {
2594 equalize = 0;
2595 } else {
2596 fprintf (stderr, "Error: Expected 'on' or 'off' for '-e'.\n");
2597 return (-1);
2599 } else if (strncmp (argv [argi], "-s=", 3) == 0) {
2600 if (strcmp (& argv [argi] [3], "on") == 0) {
2601 surface = 1;
2602 } else if (strcmp (& argv [argi] [3], "off") == 0) {
2603 surface = 0;
2604 } else {
2605 fprintf (stderr, "Error: Expected 'on' or 'off' for '-s'.\n");
2606 return (-1);
2608 } else if (strncmp (argv [argi], "-l=", 3) == 0) {
2609 if (strcmp (& argv [argi] [3], "none") == 0) {
2610 limit = 0.0;
2611 } else {
2612 limit = strtod (& argv [argi] [3], & end);
2613 if ((end [0] != '\0') || (limit < MIN_LIMIT) || (limit > MAX_LIMIT)) {
2614 fprintf (stderr, "Error: Expected 'none' or a value from %.2f to %.2f for '-l'.\n", MIN_LIMIT, MAX_LIMIT);
2615 return (-1);
2618 } else if (strncmp (argv [argi], "-w=", 3) == 0) {
2619 truncSize = strtoul (& argv [argi] [3], & end, 10);
2620 if ((end [0] != '\0') || (truncSize < MIN_TRUNCSIZE) || (truncSize > MAX_TRUNCSIZE) || (truncSize % MOD_TRUNCSIZE)) {
2621 fprintf (stderr, "Error: Expected a value from %u to %u in multiples of %u for '-w'.\n", MIN_TRUNCSIZE, MAX_TRUNCSIZE, MOD_TRUNCSIZE);
2622 return (-1);
2624 } else if (strncmp (argv [argi], "-d=", 3) == 0) {
2625 if (strcmp (& argv [argi] [3], "dataset") == 0) {
2626 model = HM_DATASET;
2627 } else if (strcmp (& argv [argi] [3], "sphere") == 0) {
2628 model = HM_SPHERE;
2629 } else {
2630 fprintf (stderr, "Error: Expected 'dataset' or 'sphere' for '-d'.\n");
2631 return (-1);
2633 } else if (strncmp (argv [argi], "-c=", 3) == 0) {
2634 radius = strtod (& argv [argi] [3], & end);
2635 if ((end [0] != '\0') || (radius < MIN_CUSTOM_RADIUS) || (radius > MAX_CUSTOM_RADIUS)) {
2636 fprintf (stderr, "Error: Expected a value from %.2f to %.2f for '-c'.\n", MIN_CUSTOM_RADIUS, MAX_CUSTOM_RADIUS);
2637 return (-1);
2639 } else if (strncmp (argv [argi], "-i=", 3) == 0) {
2640 inName = & argv [argi] [3];
2641 } else if (strncmp (argv [argi], "-o=", 3) == 0) {
2642 outName = & argv [argi] [3];
2643 } else {
2644 fprintf (stderr, "Error: Invalid option '%s'.\n", argv [argi]);
2645 return (-1);
2647 argi ++;
2649 if (! ProcessDefinition (inName, outRate, fftSize, equalize, surface, limit, truncSize, model, radius, outFormat, outName))
2650 return (-1);
2651 fprintf (stdout, "Operation completed.\n");
2652 return (0);