Rename the bsinc resampler to bsinc12
[openal-soft.git] / utils / makehrtf.c
bloba4286ee3e125790a6552179a8362d8e170279bae
1 /*
2 * HRTF utility for producing and demonstrating the process of creating an
3 * OpenAL Soft compatible HRIR data set.
5 * Copyright (C) 2011-2017 Christopher Fitzgerald
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Or visit: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
23 * --------------------------------------------------------------------------
25 * A big thanks goes out to all those whose work done in the field of
26 * binaural sound synthesis using measured HRTFs makes this utility and the
27 * OpenAL Soft implementation possible.
29 * The algorithm for diffuse-field equalization was adapted from the work
30 * done by Rio Emmanuel and Larcher Veronique of IRCAM and Bill Gardner of
31 * MIT Media Laboratory. It operates as follows:
33 * 1. Take the FFT of each HRIR and only keep the magnitude responses.
34 * 2. Calculate the diffuse-field power-average of all HRIRs weighted by
35 * their contribution to the total surface area covered by their
36 * measurement.
37 * 3. Take the diffuse-field average and limit its magnitude range.
38 * 4. Equalize the responses by using the inverse of the diffuse-field
39 * average.
40 * 5. Reconstruct the minimum-phase responses.
41 * 5. Zero the DC component.
42 * 6. IFFT the result and truncate to the desired-length minimum-phase FIR.
44 * The spherical head algorithm for calculating propagation delay was adapted
45 * from the paper:
47 * Modeling Interaural Time Difference Assuming a Spherical Head
48 * Joel David Miller
49 * Music 150, Musical Acoustics, Stanford University
50 * December 2, 2001
52 * The formulae for calculating the Kaiser window metrics are from the
53 * the textbook:
55 * Discrete-Time Signal Processing
56 * Alan V. Oppenheim and Ronald W. Schafer
57 * Prentice-Hall Signal Processing Series
58 * 1999
61 #include "config.h"
63 #define _UNICODE
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <stdarg.h>
67 #include <string.h>
68 #include <limits.h>
69 #include <ctype.h>
70 #include <math.h>
71 #ifdef HAVE_STRINGS_H
72 #include <strings.h>
73 #endif
74 #ifdef HAVE_GETOPT
75 #include <unistd.h>
76 #else
77 #include "getopt.h"
78 #endif
80 // Rely (if naively) on OpenAL's header for the types used for serialization.
81 #include "AL/al.h"
82 #include "AL/alext.h"
84 #ifndef M_PI
85 #define M_PI (3.14159265358979323846)
86 #endif
88 #ifndef HUGE_VAL
89 #define HUGE_VAL (1.0 / 0.0)
90 #endif
93 #ifdef _WIN32
94 #define WIN32_LEAN_AND_MEAN
95 #include <windows.h>
97 static char *ToUTF8(const wchar_t *from)
99 char *out = NULL;
100 int len;
101 if((len=WideCharToMultiByte(CP_UTF8, 0, from, -1, NULL, 0, NULL, NULL)) > 0)
103 out = calloc(sizeof(*out), len);
104 WideCharToMultiByte(CP_UTF8, 0, from, -1, out, len, NULL, NULL);
105 out[len-1] = 0;
107 return out;
110 static WCHAR *FromUTF8(const char *str)
112 WCHAR *out = NULL;
113 int len;
115 if((len=MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0)) > 0)
117 out = calloc(sizeof(WCHAR), len);
118 MultiByteToWideChar(CP_UTF8, 0, str, -1, out, len);
119 out[len-1] = 0;
121 return out;
125 static FILE *my_fopen(const char *fname, const char *mode)
127 WCHAR *wname=NULL, *wmode=NULL;
128 FILE *file = NULL;
130 wname = FromUTF8(fname);
131 wmode = FromUTF8(mode);
132 if(!wname)
133 fprintf(stderr, "Failed to convert UTF-8 filename: \"%s\"\n", fname);
134 else if(!wmode)
135 fprintf(stderr, "Failed to convert UTF-8 mode: \"%s\"\n", mode);
136 else
137 file = _wfopen(wname, wmode);
139 free(wname);
140 free(wmode);
142 return file;
144 #define fopen my_fopen
145 #endif
147 // The epsilon used to maintain signal stability.
148 #define EPSILON (1e-9)
150 // Constants for accessing the token reader's ring buffer.
151 #define TR_RING_BITS (16)
152 #define TR_RING_SIZE (1 << TR_RING_BITS)
153 #define TR_RING_MASK (TR_RING_SIZE - 1)
155 // The token reader's load interval in bytes.
156 #define TR_LOAD_SIZE (TR_RING_SIZE >> 2)
158 // The maximum identifier length used when processing the data set
159 // definition.
160 #define MAX_IDENT_LEN (16)
162 // The maximum path length used when processing filenames.
163 #define MAX_PATH_LEN (256)
165 // The limits for the sample 'rate' metric in the data set definition and for
166 // resampling.
167 #define MIN_RATE (32000)
168 #define MAX_RATE (96000)
170 // The limits for the HRIR 'points' metric in the data set definition.
171 #define MIN_POINTS (16)
172 #define MAX_POINTS (8192)
174 // The limits to the number of 'azimuths' listed in the data set definition.
175 #define MIN_EV_COUNT (5)
176 #define MAX_EV_COUNT (128)
178 // The limits for each of the 'azimuths' listed in the data set definition.
179 #define MIN_AZ_COUNT (1)
180 #define MAX_AZ_COUNT (128)
182 // The limits for the listener's head 'radius' in the data set definition.
183 #define MIN_RADIUS (0.05)
184 #define MAX_RADIUS (0.15)
186 // The limits for the 'distance' from source to listener in the definition
187 // file.
188 #define MIN_DISTANCE (0.5)
189 #define MAX_DISTANCE (2.5)
191 // The maximum number of channels that can be addressed for a WAVE file
192 // source listed in the data set definition.
193 #define MAX_WAVE_CHANNELS (65535)
195 // The limits to the byte size for a binary source listed in the definition
196 // file.
197 #define MIN_BIN_SIZE (2)
198 #define MAX_BIN_SIZE (4)
200 // The minimum number of significant bits for binary sources listed in the
201 // data set definition. The maximum is calculated from the byte size.
202 #define MIN_BIN_BITS (16)
204 // The limits to the number of significant bits for an ASCII source listed in
205 // the data set definition.
206 #define MIN_ASCII_BITS (16)
207 #define MAX_ASCII_BITS (32)
209 // The limits to the FFT window size override on the command line.
210 #define MIN_FFTSIZE (65536)
211 #define MAX_FFTSIZE (131072)
213 // The limits to the equalization range limit on the command line.
214 #define MIN_LIMIT (2.0)
215 #define MAX_LIMIT (120.0)
217 // The limits to the truncation window size on the command line.
218 #define MIN_TRUNCSIZE (16)
219 #define MAX_TRUNCSIZE (512)
221 // The limits to the custom head radius on the command line.
222 #define MIN_CUSTOM_RADIUS (0.05)
223 #define MAX_CUSTOM_RADIUS (0.15)
225 // The truncation window size must be a multiple of the below value to allow
226 // for vectorized convolution.
227 #define MOD_TRUNCSIZE (8)
229 // The defaults for the command line options.
230 #define DEFAULT_FFTSIZE (65536)
231 #define DEFAULT_EQUALIZE (1)
232 #define DEFAULT_SURFACE (1)
233 #define DEFAULT_LIMIT (24.0)
234 #define DEFAULT_TRUNCSIZE (32)
235 #define DEFAULT_HEAD_MODEL (HM_DATASET)
236 #define DEFAULT_CUSTOM_RADIUS (0.0)
238 // The four-character-codes for RIFF/RIFX WAVE file chunks.
239 #define FOURCC_RIFF (0x46464952) // 'RIFF'
240 #define FOURCC_RIFX (0x58464952) // 'RIFX'
241 #define FOURCC_WAVE (0x45564157) // 'WAVE'
242 #define FOURCC_FMT (0x20746D66) // 'fmt '
243 #define FOURCC_DATA (0x61746164) // 'data'
244 #define FOURCC_LIST (0x5453494C) // 'LIST'
245 #define FOURCC_WAVL (0x6C766177) // 'wavl'
246 #define FOURCC_SLNT (0x746E6C73) // 'slnt'
248 // The supported wave formats.
249 #define WAVE_FORMAT_PCM (0x0001)
250 #define WAVE_FORMAT_IEEE_FLOAT (0x0003)
251 #define WAVE_FORMAT_EXTENSIBLE (0xFFFE)
253 // The maximum propagation delay value supported by OpenAL Soft.
254 #define MAX_HRTD (63.0)
256 // The OpenAL Soft HRTF format marker. It stands for minimum-phase head
257 // response protocol 01.
258 #define MHR_FORMAT ("MinPHR01")
260 #define MHR_FORMAT_EXPERIMENTAL ("MinPHRTEMPDONOTUSE")
262 // Sample and channel type enum values
263 typedef enum SampleTypeT {
264 ST_S16 = 0,
265 ST_S24 = 1
266 } SampleTypeT;
268 typedef enum ChannelTypeT {
269 CT_LEFTONLY = 0,
270 CT_LEFTRIGHT = 1
271 } ChannelTypeT;
273 // Byte order for the serialization routines.
274 typedef enum ByteOrderT {
275 BO_NONE,
276 BO_LITTLE,
277 BO_BIG
278 } ByteOrderT;
280 // Source format for the references listed in the data set definition.
281 typedef enum SourceFormatT {
282 SF_NONE,
283 SF_WAVE, // RIFF/RIFX WAVE file.
284 SF_BIN_LE, // Little-endian binary file.
285 SF_BIN_BE, // Big-endian binary file.
286 SF_ASCII // ASCII text file.
287 } SourceFormatT;
289 // Element types for the references listed in the data set definition.
290 typedef enum ElementTypeT {
291 ET_NONE,
292 ET_INT, // Integer elements.
293 ET_FP // Floating-point elements.
294 } ElementTypeT;
296 // Head model used for calculating the impulse delays.
297 typedef enum HeadModelT {
298 HM_NONE,
299 HM_DATASET, // Measure the onset from the dataset.
300 HM_SPHERE // Calculate the onset using a spherical head model.
301 } HeadModelT;
303 // Unsigned integer type.
304 typedef unsigned int uint;
306 // Serialization types. The trailing digit indicates the number of bits.
307 typedef ALubyte uint8;
308 typedef ALint int32;
309 typedef ALuint uint32;
310 typedef ALuint64SOFT uint64;
312 // Token reader state for parsing the data set definition.
313 typedef struct TokenReaderT {
314 FILE *mFile;
315 const char *mName;
316 uint mLine;
317 uint mColumn;
318 char mRing[TR_RING_SIZE];
319 size_t mIn;
320 size_t mOut;
321 } TokenReaderT;
323 // Source reference state used when loading sources.
324 typedef struct SourceRefT {
325 SourceFormatT mFormat;
326 ElementTypeT mType;
327 uint mSize;
328 int mBits;
329 uint mChannel;
330 uint mSkip;
331 uint mOffset;
332 char mPath[MAX_PATH_LEN+1];
333 } SourceRefT;
335 // The HRIR metrics and data set used when loading, processing, and storing
336 // the resulting HRTF.
337 typedef struct HrirDataT {
338 uint mIrRate;
339 SampleTypeT mSampleType;
340 ChannelTypeT mChannelType;
341 uint mIrCount;
342 uint mIrSize;
343 uint mIrPoints;
344 uint mFftSize;
345 uint mEvCount;
346 uint mEvStart;
347 uint mAzCount[MAX_EV_COUNT];
348 uint mEvOffset[MAX_EV_COUNT];
349 double mRadius;
350 double mDistance;
351 double *mHrirs;
352 double *mHrtds;
353 double mMaxHrtd;
354 } HrirDataT;
356 // The resampler metrics and FIR filter.
357 typedef struct ResamplerT {
358 uint mP, mQ, mM, mL;
359 double *mF;
360 } ResamplerT;
363 /****************************************
364 *** Complex number type and routines ***
365 ****************************************/
367 typedef struct {
368 double Real, Imag;
369 } Complex;
371 static Complex MakeComplex(double r, double i)
373 Complex c = { r, i };
374 return c;
377 static Complex c_add(Complex a, Complex b)
379 Complex r;
380 r.Real = a.Real + b.Real;
381 r.Imag = a.Imag + b.Imag;
382 return r;
385 static Complex c_sub(Complex a, Complex b)
387 Complex r;
388 r.Real = a.Real - b.Real;
389 r.Imag = a.Imag - b.Imag;
390 return r;
393 static Complex c_mul(Complex a, Complex b)
395 Complex r;
396 r.Real = a.Real*b.Real - a.Imag*b.Imag;
397 r.Imag = a.Imag*b.Real + a.Real*b.Imag;
398 return r;
401 static Complex c_muls(Complex a, double s)
403 Complex r;
404 r.Real = a.Real * s;
405 r.Imag = a.Imag * s;
406 return r;
409 static double c_abs(Complex a)
411 return sqrt(a.Real*a.Real + a.Imag*a.Imag);
414 static Complex c_exp(Complex a)
416 Complex r;
417 double e = exp(a.Real);
418 r.Real = e * cos(a.Imag);
419 r.Imag = e * sin(a.Imag);
420 return r;
423 /*****************************
424 *** Token reader routines ***
425 *****************************/
427 /* Whitespace is not significant. It can process tokens as identifiers, numbers
428 * (integer and floating-point), strings, and operators. Strings must be
429 * encapsulated by double-quotes and cannot span multiple lines.
432 // Setup the reader on the given file. The filename can be NULL if no error
433 // output is desired.
434 static void TrSetup(FILE *fp, const char *filename, TokenReaderT *tr)
436 const char *name = NULL;
438 if(filename)
440 const char *slash = strrchr(filename, '/');
441 if(slash)
443 const char *bslash = strrchr(slash+1, '\\');
444 if(bslash) name = bslash+1;
445 else name = slash+1;
447 else
449 const char *bslash = strrchr(filename, '\\');
450 if(bslash) name = bslash+1;
451 else name = filename;
455 tr->mFile = fp;
456 tr->mName = name;
457 tr->mLine = 1;
458 tr->mColumn = 1;
459 tr->mIn = 0;
460 tr->mOut = 0;
463 // Prime the reader's ring buffer, and return a result indicating that there
464 // is text to process.
465 static int TrLoad(TokenReaderT *tr)
467 size_t toLoad, in, count;
469 toLoad = TR_RING_SIZE - (tr->mIn - tr->mOut);
470 if(toLoad >= TR_LOAD_SIZE && !feof(tr->mFile))
472 // Load TR_LOAD_SIZE (or less if at the end of the file) per read.
473 toLoad = TR_LOAD_SIZE;
474 in = tr->mIn&TR_RING_MASK;
475 count = TR_RING_SIZE - in;
476 if(count < toLoad)
478 tr->mIn += fread(&tr->mRing[in], 1, count, tr->mFile);
479 tr->mIn += fread(&tr->mRing[0], 1, toLoad-count, tr->mFile);
481 else
482 tr->mIn += fread(&tr->mRing[in], 1, toLoad, tr->mFile);
484 if(tr->mOut >= TR_RING_SIZE)
486 tr->mOut -= TR_RING_SIZE;
487 tr->mIn -= TR_RING_SIZE;
490 if(tr->mIn > tr->mOut)
491 return 1;
492 return 0;
495 // Error display routine. Only displays when the base name is not NULL.
496 static void TrErrorVA(const TokenReaderT *tr, uint line, uint column, const char *format, va_list argPtr)
498 if(!tr->mName)
499 return;
500 fprintf(stderr, "Error (%s:%u:%u): ", tr->mName, line, column);
501 vfprintf(stderr, format, argPtr);
504 // Used to display an error at a saved line/column.
505 static void TrErrorAt(const TokenReaderT *tr, uint line, uint column, const char *format, ...)
507 va_list argPtr;
509 va_start(argPtr, format);
510 TrErrorVA(tr, line, column, format, argPtr);
511 va_end(argPtr);
514 // Used to display an error at the current line/column.
515 static void TrError(const TokenReaderT *tr, const char *format, ...)
517 va_list argPtr;
519 va_start(argPtr, format);
520 TrErrorVA(tr, tr->mLine, tr->mColumn, format, argPtr);
521 va_end(argPtr);
524 // Skips to the next line.
525 static void TrSkipLine(TokenReaderT *tr)
527 char ch;
529 while(TrLoad(tr))
531 ch = tr->mRing[tr->mOut&TR_RING_MASK];
532 tr->mOut++;
533 if(ch == '\n')
535 tr->mLine++;
536 tr->mColumn = 1;
537 break;
539 tr->mColumn ++;
543 // Skips to the next token.
544 static int TrSkipWhitespace(TokenReaderT *tr)
546 char ch;
548 while(TrLoad(tr))
550 ch = tr->mRing[tr->mOut&TR_RING_MASK];
551 if(isspace(ch))
553 tr->mOut++;
554 if(ch == '\n')
556 tr->mLine++;
557 tr->mColumn = 1;
559 else
560 tr->mColumn++;
562 else if(ch == '#')
563 TrSkipLine(tr);
564 else
565 return 1;
567 return 0;
570 // Get the line and/or column of the next token (or the end of input).
571 static void TrIndication(TokenReaderT *tr, uint *line, uint *column)
573 TrSkipWhitespace(tr);
574 if(line) *line = tr->mLine;
575 if(column) *column = tr->mColumn;
578 // Checks to see if a token is the given operator. It does not display any
579 // errors and will not proceed to the next token.
580 static int TrIsOperator(TokenReaderT *tr, const char *op)
582 size_t out, len;
583 char ch;
585 if(!TrSkipWhitespace(tr))
586 return 0;
587 out = tr->mOut;
588 len = 0;
589 while(op[len] != '\0' && out < tr->mIn)
591 ch = tr->mRing[out&TR_RING_MASK];
592 if(ch != op[len]) break;
593 len++;
594 out++;
596 if(op[len] == '\0')
597 return 1;
598 return 0;
601 /* The TrRead*() routines obtain the value of a matching token type. They
602 * display type, form, and boundary errors and will proceed to the next
603 * token.
606 // Reads and validates an identifier token.
607 static int TrReadIdent(TokenReaderT *tr, const uint maxLen, char *ident)
609 uint col, len;
610 char ch;
612 col = tr->mColumn;
613 if(TrSkipWhitespace(tr))
615 col = tr->mColumn;
616 ch = tr->mRing[tr->mOut&TR_RING_MASK];
617 if(ch == '_' || isalpha(ch))
619 len = 0;
620 do {
621 if(len < maxLen)
622 ident[len] = ch;
623 len++;
624 tr->mOut++;
625 if(!TrLoad(tr))
626 break;
627 ch = tr->mRing[tr->mOut&TR_RING_MASK];
628 } while(ch == '_' || isdigit(ch) || isalpha(ch));
630 tr->mColumn += len;
631 if(len < maxLen)
633 ident[len] = '\0';
634 return 1;
636 TrErrorAt(tr, tr->mLine, col, "Identifier is too long.\n");
637 return 0;
640 TrErrorAt(tr, tr->mLine, col, "Expected an identifier.\n");
641 return 0;
644 // Reads and validates (including bounds) an integer token.
645 static int TrReadInt(TokenReaderT *tr, const int loBound, const int hiBound, int *value)
647 uint col, digis, len;
648 char ch, temp[64+1];
650 col = tr->mColumn;
651 if(TrSkipWhitespace(tr))
653 col = tr->mColumn;
654 len = 0;
655 ch = tr->mRing[tr->mOut&TR_RING_MASK];
656 if(ch == '+' || ch == '-')
658 temp[len] = ch;
659 len++;
660 tr->mOut++;
662 digis = 0;
663 while(TrLoad(tr))
665 ch = tr->mRing[tr->mOut&TR_RING_MASK];
666 if(!isdigit(ch)) break;
667 if(len < 64)
668 temp[len] = ch;
669 len++;
670 digis++;
671 tr->mOut++;
673 tr->mColumn += len;
674 if(digis > 0 && ch != '.' && !isalpha(ch))
676 if(len > 64)
678 TrErrorAt(tr, tr->mLine, col, "Integer is too long.");
679 return 0;
681 temp[len] = '\0';
682 *value = strtol(temp, NULL, 10);
683 if(*value < loBound || *value > hiBound)
685 TrErrorAt(tr, tr->mLine, col, "Expected a value from %d to %d.\n", loBound, hiBound);
686 return (0);
688 return (1);
691 TrErrorAt(tr, tr->mLine, col, "Expected an integer.\n");
692 return 0;
695 // Reads and validates (including bounds) a float token.
696 static int TrReadFloat(TokenReaderT *tr, const double loBound, const double hiBound, double *value)
698 uint col, digis, len;
699 char ch, temp[64+1];
701 col = tr->mColumn;
702 if(TrSkipWhitespace(tr))
704 col = tr->mColumn;
705 len = 0;
706 ch = tr->mRing[tr->mOut&TR_RING_MASK];
707 if(ch == '+' || ch == '-')
709 temp[len] = ch;
710 len++;
711 tr->mOut++;
714 digis = 0;
715 while(TrLoad(tr))
717 ch = tr->mRing[tr->mOut&TR_RING_MASK];
718 if(!isdigit(ch)) break;
719 if(len < 64)
720 temp[len] = ch;
721 len++;
722 digis++;
723 tr->mOut++;
725 if(ch == '.')
727 if(len < 64)
728 temp[len] = ch;
729 len++;
730 tr->mOut++;
732 while(TrLoad(tr))
734 ch = tr->mRing[tr->mOut&TR_RING_MASK];
735 if(!isdigit(ch)) break;
736 if(len < 64)
737 temp[len] = ch;
738 len++;
739 digis++;
740 tr->mOut++;
742 if(digis > 0)
744 if(ch == 'E' || ch == 'e')
746 if(len < 64)
747 temp[len] = ch;
748 len++;
749 digis = 0;
750 tr->mOut++;
751 if(ch == '+' || ch == '-')
753 if(len < 64)
754 temp[len] = ch;
755 len++;
756 tr->mOut++;
758 while(TrLoad(tr))
760 ch = tr->mRing[tr->mOut&TR_RING_MASK];
761 if(!isdigit(ch)) break;
762 if(len < 64)
763 temp[len] = ch;
764 len++;
765 digis++;
766 tr->mOut++;
769 tr->mColumn += len;
770 if(digis > 0 && ch != '.' && !isalpha(ch))
772 if(len > 64)
774 TrErrorAt(tr, tr->mLine, col, "Float is too long.");
775 return 0;
777 temp[len] = '\0';
778 *value = strtod(temp, NULL);
779 if(*value < loBound || *value > hiBound)
781 TrErrorAt (tr, tr->mLine, col, "Expected a value from %f to %f.\n", loBound, hiBound);
782 return 0;
784 return 1;
787 else
788 tr->mColumn += len;
790 TrErrorAt(tr, tr->mLine, col, "Expected a float.\n");
791 return 0;
794 // Reads and validates a string token.
795 static int TrReadString(TokenReaderT *tr, const uint maxLen, char *text)
797 uint col, len;
798 char ch;
800 col = tr->mColumn;
801 if(TrSkipWhitespace(tr))
803 col = tr->mColumn;
804 ch = tr->mRing[tr->mOut&TR_RING_MASK];
805 if(ch == '\"')
807 tr->mOut++;
808 len = 0;
809 while(TrLoad(tr))
811 ch = tr->mRing[tr->mOut&TR_RING_MASK];
812 tr->mOut++;
813 if(ch == '\"')
814 break;
815 if(ch == '\n')
817 TrErrorAt (tr, tr->mLine, col, "Unterminated string at end of line.\n");
818 return 0;
820 if(len < maxLen)
821 text[len] = ch;
822 len++;
824 if(ch != '\"')
826 tr->mColumn += 1 + len;
827 TrErrorAt(tr, tr->mLine, col, "Unterminated string at end of input.\n");
828 return 0;
830 tr->mColumn += 2 + len;
831 if(len > maxLen)
833 TrErrorAt (tr, tr->mLine, col, "String is too long.\n");
834 return 0;
836 text[len] = '\0';
837 return 1;
840 TrErrorAt(tr, tr->mLine, col, "Expected a string.\n");
841 return 0;
844 // Reads and validates the given operator.
845 static int TrReadOperator(TokenReaderT *tr, const char *op)
847 uint col, len;
848 char ch;
850 col = tr->mColumn;
851 if(TrSkipWhitespace(tr))
853 col = tr->mColumn;
854 len = 0;
855 while(op[len] != '\0' && TrLoad(tr))
857 ch = tr->mRing[tr->mOut&TR_RING_MASK];
858 if(ch != op[len]) break;
859 len++;
860 tr->mOut++;
862 tr->mColumn += len;
863 if(op[len] == '\0')
864 return 1;
866 TrErrorAt(tr, tr->mLine, col, "Expected '%s' operator.\n", op);
867 return 0;
870 /* Performs a string substitution. Any case-insensitive occurrences of the
871 * pattern string are replaced with the replacement string. The result is
872 * truncated if necessary.
874 static int StrSubst(const char *in, const char *pat, const char *rep, const size_t maxLen, char *out)
876 size_t inLen, patLen, repLen;
877 size_t si, di;
878 int truncated;
880 inLen = strlen(in);
881 patLen = strlen(pat);
882 repLen = strlen(rep);
883 si = 0;
884 di = 0;
885 truncated = 0;
886 while(si < inLen && di < maxLen)
888 if(patLen <= inLen-si)
890 if(strncasecmp(&in[si], pat, patLen) == 0)
892 if(repLen > maxLen-di)
894 repLen = maxLen - di;
895 truncated = 1;
897 strncpy(&out[di], rep, repLen);
898 si += patLen;
899 di += repLen;
902 out[di] = in[si];
903 si++;
904 di++;
906 if(si < inLen)
907 truncated = 1;
908 out[di] = '\0';
909 return !truncated;
913 /*********************
914 *** Math routines ***
915 *********************/
917 // Provide missing math routines for MSVC versions < 1800 (Visual Studio 2013).
918 #if defined(_MSC_VER) && _MSC_VER < 1800
919 static double round(double val)
921 if(val < 0.0)
922 return ceil(val-0.5);
923 return floor(val+0.5);
926 static double fmin(double a, double b)
928 return (a<b) ? a : b;
931 static double fmax(double a, double b)
933 return (a>b) ? a : b;
935 #endif
937 // Simple clamp routine.
938 static double Clamp(const double val, const double lower, const double upper)
940 return fmin(fmax(val, lower), upper);
943 // Performs linear interpolation.
944 static double Lerp(const double a, const double b, const double f)
946 return a + (f * (b - a));
949 static inline uint dither_rng(uint *seed)
951 *seed = (*seed * 96314165) + 907633515;
952 return *seed;
955 // Performs a triangular probability density function dither. It assumes the
956 // input sample is already scaled.
957 static inline double TpdfDither(const double in, uint *seed)
959 static const double PRNG_SCALE = 1.0 / UINT_MAX;
960 uint prn0, prn1;
962 prn0 = dither_rng(seed);
963 prn1 = dither_rng(seed);
964 return round(in + (prn0*PRNG_SCALE - prn1*PRNG_SCALE));
967 // Allocates an array of doubles.
968 static double *CreateArray(size_t n)
970 double *a;
972 if(n == 0) n = 1;
973 a = calloc(n, sizeof(double));
974 if(a == NULL)
976 fprintf(stderr, "Error: Out of memory.\n");
977 exit(-1);
979 return a;
982 // Frees an array of doubles.
983 static void DestroyArray(double *a)
984 { free(a); }
986 /* Fast Fourier transform routines. The number of points must be a power of
987 * two. In-place operation is possible only if both the real and imaginary
988 * parts are in-place together.
991 // Performs bit-reversal ordering.
992 static void FftArrange(const uint n, const Complex *in, Complex *out)
994 uint rk, k, m;
996 if(in == out)
998 // Handle in-place arrangement.
999 rk = 0;
1000 for(k = 0;k < n;k++)
1002 if(rk > k)
1004 Complex temp = in[rk];
1005 out[rk] = in[k];
1006 out[k] = temp;
1008 m = n;
1009 while(rk&(m >>= 1))
1010 rk &= ~m;
1011 rk |= m;
1014 else
1016 // Handle copy arrangement.
1017 rk = 0;
1018 for(k = 0;k < n;k++)
1020 out[rk] = in[k];
1021 m = n;
1022 while(rk&(m >>= 1))
1023 rk &= ~m;
1024 rk |= m;
1029 // Performs the summation.
1030 static void FftSummation(const int n, const double s, Complex *cplx)
1032 double pi;
1033 int m, m2;
1034 int i, k, mk;
1036 pi = s * M_PI;
1037 for(m = 1, m2 = 2;m < n; m <<= 1, m2 <<= 1)
1039 // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
1040 double sm = sin(0.5 * pi / m);
1041 Complex v = MakeComplex(-2.0*sm*sm, -sin(pi / m));
1042 Complex w = MakeComplex(1.0, 0.0);
1043 for(i = 0;i < m;i++)
1045 for(k = i;k < n;k += m2)
1047 Complex t;
1048 mk = k + m;
1049 t = c_mul(w, cplx[mk]);
1050 cplx[mk] = c_sub(cplx[k], t);
1051 cplx[k] = c_add(cplx[k], t);
1053 w = c_add(w, c_mul(v, w));
1058 // Performs a forward FFT.
1059 static void FftForward(const uint n, const Complex *in, Complex *out)
1061 FftArrange(n, in, out);
1062 FftSummation(n, 1.0, out);
1065 // Performs an inverse FFT.
1066 static void FftInverse(const uint n, const Complex *in, Complex *out)
1068 double f;
1069 uint i;
1071 FftArrange(n, in, out);
1072 FftSummation(n, -1.0, out);
1073 f = 1.0 / n;
1074 for(i = 0;i < n;i++)
1075 out[i] = c_muls(out[i], f);
1078 /* Calculate the complex helical sequence (or discrete-time analytical signal)
1079 * of the given input using the Hilbert transform. Given the natural logarithm
1080 * of a signal's magnitude response, the imaginary components can be used as
1081 * the angles for minimum-phase reconstruction.
1083 static void Hilbert(const uint n, const Complex *in, Complex *out)
1085 uint i;
1087 if(in == out)
1089 // Handle in-place operation.
1090 for(i = 0;i < n;i++)
1091 out[i].Imag = 0.0;
1093 else
1095 // Handle copy operation.
1096 for(i = 0;i < n;i++)
1097 out[i] = MakeComplex(in[i].Real, 0.0);
1099 FftInverse(n, out, out);
1100 for(i = 1;i < (n+1)/2;i++)
1101 out[i] = c_muls(out[i], 2.0);
1102 /* Increment i if n is even. */
1103 i += (n&1)^1;
1104 for(;i < n;i++)
1105 out[i] = MakeComplex(0.0, 0.0);
1106 FftForward(n, out, out);
1109 /* Calculate the magnitude response of the given input. This is used in
1110 * place of phase decomposition, since the phase residuals are discarded for
1111 * minimum phase reconstruction. The mirrored half of the response is also
1112 * discarded.
1114 static void MagnitudeResponse(const uint n, const Complex *in, double *out)
1116 const uint m = 1 + (n / 2);
1117 uint i;
1118 for(i = 0;i < m;i++)
1119 out[i] = fmax(c_abs(in[i]), EPSILON);
1122 /* Apply a range limit (in dB) to the given magnitude response. This is used
1123 * to adjust the effects of the diffuse-field average on the equalization
1124 * process.
1126 static void LimitMagnitudeResponse(const uint n, const double limit, const double *in, double *out)
1128 const uint m = 1 + (n / 2);
1129 double halfLim;
1130 uint i, lower, upper;
1131 double ave;
1133 halfLim = limit / 2.0;
1134 // Convert the response to dB.
1135 for(i = 0;i < m;i++)
1136 out[i] = 20.0 * log10(in[i]);
1137 // Use six octaves to calculate the average magnitude of the signal.
1138 lower = ((uint)ceil(n / pow(2.0, 8.0))) - 1;
1139 upper = ((uint)floor(n / pow(2.0, 2.0))) - 1;
1140 ave = 0.0;
1141 for(i = lower;i <= upper;i++)
1142 ave += out[i];
1143 ave /= upper - lower + 1;
1144 // Keep the response within range of the average magnitude.
1145 for(i = 0;i < m;i++)
1146 out[i] = Clamp(out[i], ave - halfLim, ave + halfLim);
1147 // Convert the response back to linear magnitude.
1148 for(i = 0;i < m;i++)
1149 out[i] = pow(10.0, out[i] / 20.0);
1152 /* Reconstructs the minimum-phase component for the given magnitude response
1153 * of a signal. This is equivalent to phase recomposition, sans the missing
1154 * residuals (which were discarded). The mirrored half of the response is
1155 * reconstructed.
1157 static void MinimumPhase(const uint n, const double *in, Complex *out)
1159 const uint m = 1 + (n / 2);
1160 double *mags;
1161 uint i;
1163 mags = CreateArray(n);
1164 for(i = 0;i < m;i++)
1166 mags[i] = fmax(EPSILON, in[i]);
1167 out[i] = MakeComplex(log(mags[i]), 0.0);
1169 for(;i < n;i++)
1171 mags[i] = mags[n - i];
1172 out[i] = out[n - i];
1174 Hilbert(n, out, out);
1175 // Remove any DC offset the filter has.
1176 mags[0] = EPSILON;
1177 for(i = 0;i < n;i++)
1179 Complex a = c_exp(MakeComplex(0.0, out[i].Imag));
1180 out[i] = c_mul(MakeComplex(mags[i], 0.0), a);
1182 DestroyArray(mags);
1186 /***************************
1187 *** Resampler functions ***
1188 ***************************/
1190 /* This is the normalized cardinal sine (sinc) function.
1192 * sinc(x) = { 1, x = 0
1193 * { sin(pi x) / (pi x), otherwise.
1195 static double Sinc(const double x)
1197 if(fabs(x) < EPSILON)
1198 return 1.0;
1199 return sin(M_PI * x) / (M_PI * x);
1202 /* The zero-order modified Bessel function of the first kind, used for the
1203 * Kaiser window.
1205 * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
1206 * = sum_{k=0}^inf ((x / 2)^k / k!)^2
1208 static double BesselI_0(const double x)
1210 double term, sum, x2, y, last_sum;
1211 int k;
1213 // Start at k=1 since k=0 is trivial.
1214 term = 1.0;
1215 sum = 1.0;
1216 x2 = x/2.0;
1217 k = 1;
1219 // Let the integration converge until the term of the sum is no longer
1220 // significant.
1221 do {
1222 y = x2 / k;
1223 k++;
1224 last_sum = sum;
1225 term *= y * y;
1226 sum += term;
1227 } while(sum != last_sum);
1228 return sum;
1231 /* Calculate a Kaiser window from the given beta value and a normalized k
1232 * [-1, 1].
1234 * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
1235 * { 0, elsewhere.
1237 * Where k can be calculated as:
1239 * k = i / l, where -l <= i <= l.
1241 * or:
1243 * k = 2 i / M - 1, where 0 <= i <= M.
1245 static double Kaiser(const double b, const double k)
1247 if(!(k >= -1.0 && k <= 1.0))
1248 return 0.0;
1249 return BesselI_0(b * sqrt(1.0 - k*k)) / BesselI_0(b);
1252 // Calculates the greatest common divisor of a and b.
1253 static uint Gcd(uint x, uint y)
1255 while(y > 0)
1257 uint z = y;
1258 y = x % y;
1259 x = z;
1261 return x;
1264 /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
1265 * the transition width is normalized frequency (0.5 is nyquist).
1267 * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
1268 * { ceil(5.79 / 2 pi f_t), r <= 21.
1271 static uint CalcKaiserOrder(const double rejection, const double transition)
1273 double w_t = 2.0 * M_PI * transition;
1274 if(rejection > 21.0)
1275 return (uint)ceil((rejection - 7.95) / (2.285 * w_t));
1276 return (uint)ceil(5.79 / w_t);
1279 // Calculates the beta value of the Kaiser window. Rejection is in dB.
1280 static double CalcKaiserBeta(const double rejection)
1282 if(rejection > 50.0)
1283 return 0.1102 * (rejection - 8.7);
1284 if(rejection >= 21.0)
1285 return (0.5842 * pow(rejection - 21.0, 0.4)) +
1286 (0.07886 * (rejection - 21.0));
1287 return 0.0;
1290 /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
1291 * width, beta, gain, and cutoff. The point is specified in non-normalized
1292 * samples, from 0 to M, where M = (2 l + 1).
1294 * w(k) 2 p f_t sinc(2 f_t x)
1296 * x -- centered sample index (i - l)
1297 * k -- normalized and centered window index (x / l)
1298 * w(k) -- window function (Kaiser)
1299 * p -- gain compensation factor when sampling
1300 * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
1302 static double SincFilter(const int l, const double b, const double gain, const double cutoff, const int i)
1304 return Kaiser(b, (double)(i - l) / l) * 2.0 * gain * cutoff * Sinc(2.0 * cutoff * (i - l));
1307 /* This is a polyphase sinc-filtered resampler.
1309 * Upsample Downsample
1311 * p/q = 3/2 p/q = 3/5
1313 * M-+-+-+-> M-+-+-+->
1314 * -------------------+ ---------------------+
1315 * p s * f f f f|f| | p s * f f f f f |
1316 * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
1317 * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
1318 * s * f|f|f f f | s * f f|f|f f |
1319 * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
1320 * --------+=+--------+ 0 * |0|0 0 0 0 |
1321 * d . d .|d|. d . d ----------+=+--------+
1322 * d . . . .|d|. . . .
1323 * q->
1324 * q-+-+-+->
1326 * P_f(i,j) = q i mod p + pj
1327 * P_s(i,j) = floor(q i / p) - j
1328 * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
1329 * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
1330 * { 0, P_f(i,j) >= M. }
1333 // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
1334 // that's used to cut frequencies above the destination nyquist.
1335 static void ResamplerSetup(ResamplerT *rs, const uint srcRate, const uint dstRate)
1337 double cutoff, width, beta;
1338 uint gcd, l;
1339 int i;
1341 gcd = Gcd(srcRate, dstRate);
1342 rs->mP = dstRate / gcd;
1343 rs->mQ = srcRate / gcd;
1344 /* The cutoff is adjusted by half the transition width, so the transition
1345 * ends before the nyquist (0.5). Both are scaled by the downsampling
1346 * factor.
1348 if(rs->mP > rs->mQ)
1350 cutoff = 0.475 / rs->mP;
1351 width = 0.05 / rs->mP;
1353 else
1355 cutoff = 0.475 / rs->mQ;
1356 width = 0.05 / rs->mQ;
1358 // A rejection of -180 dB is used for the stop band. Round up when
1359 // calculating the left offset to avoid increasing the transition width.
1360 l = (CalcKaiserOrder(180.0, width)+1) / 2;
1361 beta = CalcKaiserBeta(180.0);
1362 rs->mM = l*2 + 1;
1363 rs->mL = l;
1364 rs->mF = CreateArray(rs->mM);
1365 for(i = 0;i < ((int)rs->mM);i++)
1366 rs->mF[i] = SincFilter((int)l, beta, rs->mP, cutoff, i);
1369 // Clean up after the resampler.
1370 static void ResamplerClear(ResamplerT *rs)
1372 DestroyArray(rs->mF);
1373 rs->mF = NULL;
1376 // Perform the upsample-filter-downsample resampling operation using a
1377 // polyphase filter implementation.
1378 static void ResamplerRun(ResamplerT *rs, const uint inN, const double *in, const uint outN, double *out)
1380 const uint p = rs->mP, q = rs->mQ, m = rs->mM, l = rs->mL;
1381 const double *f = rs->mF;
1382 uint j_f, j_s;
1383 double *work;
1384 uint i;
1386 if(outN == 0)
1387 return;
1389 // Handle in-place operation.
1390 if(in == out)
1391 work = CreateArray(outN);
1392 else
1393 work = out;
1394 // Resample the input.
1395 for(i = 0;i < outN;i++)
1397 double r = 0.0;
1398 // Input starts at l to compensate for the filter delay. This will
1399 // drop any build-up from the first half of the filter.
1400 j_f = (l + (q * i)) % p;
1401 j_s = (l + (q * i)) / p;
1402 while(j_f < m)
1404 // Only take input when 0 <= j_s < inN. This single unsigned
1405 // comparison catches both cases.
1406 if(j_s < inN)
1407 r += f[j_f] * in[j_s];
1408 j_f += p;
1409 j_s--;
1411 work[i] = r;
1413 // Clean up after in-place operation.
1414 if(work != out)
1416 for(i = 0;i < outN;i++)
1417 out[i] = work[i];
1418 DestroyArray(work);
1422 /*************************
1423 *** File source input ***
1424 *************************/
1426 // Read a binary value of the specified byte order and byte size from a file,
1427 // storing it as a 32-bit unsigned integer.
1428 static int ReadBin4(FILE *fp, const char *filename, const ByteOrderT order, const uint bytes, uint32 *out)
1430 uint8 in[4];
1431 uint32 accum;
1432 uint i;
1434 if(fread(in, 1, bytes, fp) != bytes)
1436 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1437 return 0;
1439 accum = 0;
1440 switch(order)
1442 case BO_LITTLE:
1443 for(i = 0;i < bytes;i++)
1444 accum = (accum<<8) | in[bytes - i - 1];
1445 break;
1446 case BO_BIG:
1447 for(i = 0;i < bytes;i++)
1448 accum = (accum<<8) | in[i];
1449 break;
1450 default:
1451 break;
1453 *out = accum;
1454 return 1;
1457 // Read a binary value of the specified byte order from a file, storing it as
1458 // a 64-bit unsigned integer.
1459 static int ReadBin8(FILE *fp, const char *filename, const ByteOrderT order, uint64 *out)
1461 uint8 in [8];
1462 uint64 accum;
1463 uint i;
1465 if(fread(in, 1, 8, fp) != 8)
1467 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1468 return 0;
1470 accum = 0ULL;
1471 switch(order)
1473 case BO_LITTLE:
1474 for(i = 0;i < 8;i++)
1475 accum = (accum<<8) | in[8 - i - 1];
1476 break;
1477 case BO_BIG:
1478 for(i = 0;i < 8;i++)
1479 accum = (accum<<8) | in[i];
1480 break;
1481 default:
1482 break;
1484 *out = accum;
1485 return 1;
1488 /* Read a binary value of the specified type, byte order, and byte size from
1489 * a file, converting it to a double. For integer types, the significant
1490 * bits are used to normalize the result. The sign of bits determines
1491 * whether they are padded toward the MSB (negative) or LSB (positive).
1492 * Floating-point types are not normalized.
1494 static int ReadBinAsDouble(FILE *fp, const char *filename, const ByteOrderT order, const ElementTypeT type, const uint bytes, const int bits, double *out)
1496 union {
1497 uint32 ui;
1498 int32 i;
1499 float f;
1500 } v4;
1501 union {
1502 uint64 ui;
1503 double f;
1504 } v8;
1506 *out = 0.0;
1507 if(bytes > 4)
1509 if(!ReadBin8(fp, filename, order, &v8.ui))
1510 return 0;
1511 if(type == ET_FP)
1512 *out = v8.f;
1514 else
1516 if(!ReadBin4(fp, filename, order, bytes, &v4.ui))
1517 return 0;
1518 if(type == ET_FP)
1519 *out = v4.f;
1520 else
1522 if(bits > 0)
1523 v4.ui >>= (8*bytes) - ((uint)bits);
1524 else
1525 v4.ui &= (0xFFFFFFFF >> (32+bits));
1527 if(v4.ui&(uint)(1<<(abs(bits)-1)))
1528 v4.ui |= (0xFFFFFFFF << abs (bits));
1529 *out = v4.i / (double)(1<<(abs(bits)-1));
1532 return 1;
1535 /* Read an ascii value of the specified type from a file, converting it to a
1536 * double. For integer types, the significant bits are used to normalize the
1537 * result. The sign of the bits should always be positive. This also skips
1538 * up to one separator character before the element itself.
1540 static int ReadAsciiAsDouble(TokenReaderT *tr, const char *filename, const ElementTypeT type, const uint bits, double *out)
1542 if(TrIsOperator(tr, ","))
1543 TrReadOperator(tr, ",");
1544 else if(TrIsOperator(tr, ":"))
1545 TrReadOperator(tr, ":");
1546 else if(TrIsOperator(tr, ";"))
1547 TrReadOperator(tr, ";");
1548 else if(TrIsOperator(tr, "|"))
1549 TrReadOperator(tr, "|");
1551 if(type == ET_FP)
1553 if(!TrReadFloat(tr, -HUGE_VAL, HUGE_VAL, out))
1555 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1556 return 0;
1559 else
1561 int v;
1562 if(!TrReadInt(tr, -(1<<(bits-1)), (1<<(bits-1))-1, &v))
1564 fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
1565 return 0;
1567 *out = v / (double)((1<<(bits-1))-1);
1569 return 1;
1572 // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
1573 // the source parameters and data set metrics.
1574 static int ReadWaveFormat(FILE *fp, const ByteOrderT order, const uint hrirRate, SourceRefT *src)
1576 uint32 fourCC, chunkSize;
1577 uint32 format, channels, rate, dummy, block, size, bits;
1579 chunkSize = 0;
1580 do {
1581 if (chunkSize > 0)
1582 fseek (fp, (long) chunkSize, SEEK_CUR);
1583 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
1584 !ReadBin4(fp, src->mPath, order, 4, &chunkSize))
1585 return 0;
1586 } while(fourCC != FOURCC_FMT);
1587 if(!ReadBin4(fp, src->mPath, order, 2, & format) ||
1588 !ReadBin4(fp, src->mPath, order, 2, & channels) ||
1589 !ReadBin4(fp, src->mPath, order, 4, & rate) ||
1590 !ReadBin4(fp, src->mPath, order, 4, & dummy) ||
1591 !ReadBin4(fp, src->mPath, order, 2, & block))
1592 return (0);
1593 block /= channels;
1594 if(chunkSize > 14)
1596 if(!ReadBin4(fp, src->mPath, order, 2, &size))
1597 return 0;
1598 size /= 8;
1599 if(block > size)
1600 size = block;
1602 else
1603 size = block;
1604 if(format == WAVE_FORMAT_EXTENSIBLE)
1606 fseek(fp, 2, SEEK_CUR);
1607 if(!ReadBin4(fp, src->mPath, order, 2, &bits))
1608 return 0;
1609 if(bits == 0)
1610 bits = 8 * size;
1611 fseek(fp, 4, SEEK_CUR);
1612 if(!ReadBin4(fp, src->mPath, order, 2, &format))
1613 return 0;
1614 fseek(fp, (long)(chunkSize - 26), SEEK_CUR);
1616 else
1618 bits = 8 * size;
1619 if(chunkSize > 14)
1620 fseek(fp, (long)(chunkSize - 16), SEEK_CUR);
1621 else
1622 fseek(fp, (long)(chunkSize - 14), SEEK_CUR);
1624 if(format != WAVE_FORMAT_PCM && format != WAVE_FORMAT_IEEE_FLOAT)
1626 fprintf(stderr, "Error: Unsupported WAVE format in file '%s'.\n", src->mPath);
1627 return 0;
1629 if(src->mChannel >= channels)
1631 fprintf(stderr, "Error: Missing source channel in WAVE file '%s'.\n", src->mPath);
1632 return 0;
1634 if(rate != hrirRate)
1636 fprintf(stderr, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src->mPath);
1637 return 0;
1639 if(format == WAVE_FORMAT_PCM)
1641 if(size < 2 || size > 4)
1643 fprintf(stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src->mPath);
1644 return 0;
1646 if(bits < 16 || bits > (8*size))
1648 fprintf (stderr, "Error: Bad significant bits in WAVE file '%s'.\n", src->mPath);
1649 return 0;
1651 src->mType = ET_INT;
1653 else
1655 if(size != 4 && size != 8)
1657 fprintf(stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src->mPath);
1658 return 0;
1660 src->mType = ET_FP;
1662 src->mSize = size;
1663 src->mBits = (int)bits;
1664 src->mSkip = channels;
1665 return 1;
1668 // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
1669 static int ReadWaveData(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
1671 int pre, post, skip;
1672 uint i;
1674 pre = (int)(src->mSize * src->mChannel);
1675 post = (int)(src->mSize * (src->mSkip - src->mChannel - 1));
1676 skip = 0;
1677 for(i = 0;i < n;i++)
1679 skip += pre;
1680 if(skip > 0)
1681 fseek(fp, skip, SEEK_CUR);
1682 if(!ReadBinAsDouble(fp, src->mPath, order, src->mType, src->mSize, src->mBits, &hrir[i]))
1683 return 0;
1684 skip = post;
1686 if(skip > 0)
1687 fseek(fp, skip, SEEK_CUR);
1688 return 1;
1691 // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
1692 // doubles.
1693 static int ReadWaveList(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
1695 uint32 fourCC, chunkSize, listSize, count;
1696 uint block, skip, offset, i;
1697 double lastSample;
1699 for (;;) {
1700 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, & fourCC) ||
1701 !ReadBin4(fp, src->mPath, order, 4, & chunkSize))
1702 return (0);
1704 if(fourCC == FOURCC_DATA)
1706 block = src->mSize * src->mSkip;
1707 count = chunkSize / block;
1708 if(count < (src->mOffset + n))
1710 fprintf(stderr, "Error: Bad read from file '%s'.\n", src->mPath);
1711 return 0;
1713 fseek(fp, (long)(src->mOffset * block), SEEK_CUR);
1714 if(!ReadWaveData(fp, src, order, n, &hrir[0]))
1715 return 0;
1716 return 1;
1718 else if(fourCC == FOURCC_LIST)
1720 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC))
1721 return 0;
1722 chunkSize -= 4;
1723 if(fourCC == FOURCC_WAVL)
1724 break;
1726 if(chunkSize > 0)
1727 fseek(fp, (long)chunkSize, SEEK_CUR);
1729 listSize = chunkSize;
1730 block = src->mSize * src->mSkip;
1731 skip = src->mOffset;
1732 offset = 0;
1733 lastSample = 0.0;
1734 while(offset < n && listSize > 8)
1736 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
1737 !ReadBin4(fp, src->mPath, order, 4, &chunkSize))
1738 return 0;
1739 listSize -= 8 + chunkSize;
1740 if(fourCC == FOURCC_DATA)
1742 count = chunkSize / block;
1743 if(count > skip)
1745 fseek(fp, (long)(skip * block), SEEK_CUR);
1746 chunkSize -= skip * block;
1747 count -= skip;
1748 skip = 0;
1749 if(count > (n - offset))
1750 count = n - offset;
1751 if(!ReadWaveData(fp, src, order, count, &hrir[offset]))
1752 return 0;
1753 chunkSize -= count * block;
1754 offset += count;
1755 lastSample = hrir [offset - 1];
1757 else
1759 skip -= count;
1760 count = 0;
1763 else if(fourCC == FOURCC_SLNT)
1765 if(!ReadBin4(fp, src->mPath, order, 4, &count))
1766 return 0;
1767 chunkSize -= 4;
1768 if(count > skip)
1770 count -= skip;
1771 skip = 0;
1772 if(count > (n - offset))
1773 count = n - offset;
1774 for(i = 0; i < count; i ++)
1775 hrir[offset + i] = lastSample;
1776 offset += count;
1778 else
1780 skip -= count;
1781 count = 0;
1784 if(chunkSize > 0)
1785 fseek(fp, (long)chunkSize, SEEK_CUR);
1787 if(offset < n)
1789 fprintf(stderr, "Error: Bad read from file '%s'.\n", src->mPath);
1790 return 0;
1792 return 1;
1795 // Load a source HRIR from a RIFF/RIFX WAVE file.
1796 static int LoadWaveSource(FILE *fp, SourceRefT *src, const uint hrirRate, const uint n, double *hrir)
1798 uint32 fourCC, dummy;
1799 ByteOrderT order;
1801 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
1802 !ReadBin4(fp, src->mPath, BO_LITTLE, 4, &dummy))
1803 return 0;
1804 if(fourCC == FOURCC_RIFF)
1805 order = BO_LITTLE;
1806 else if(fourCC == FOURCC_RIFX)
1807 order = BO_BIG;
1808 else
1810 fprintf(stderr, "Error: No RIFF/RIFX chunk in file '%s'.\n", src->mPath);
1811 return 0;
1814 if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC))
1815 return 0;
1816 if(fourCC != FOURCC_WAVE)
1818 fprintf(stderr, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src->mPath);
1819 return 0;
1821 if(!ReadWaveFormat(fp, order, hrirRate, src))
1822 return 0;
1823 if(!ReadWaveList(fp, src, order, n, hrir))
1824 return 0;
1825 return 1;
1828 // Load a source HRIR from a binary file.
1829 static int LoadBinarySource(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
1831 uint i;
1833 fseek(fp, (long)src->mOffset, SEEK_SET);
1834 for(i = 0;i < n;i++)
1836 if(!ReadBinAsDouble(fp, src->mPath, order, src->mType, src->mSize, src->mBits, &hrir[i]))
1837 return 0;
1838 if(src->mSkip > 0)
1839 fseek(fp, (long)src->mSkip, SEEK_CUR);
1841 return 1;
1844 // Load a source HRIR from an ASCII text file containing a list of elements
1845 // separated by whitespace or common list operators (',', ';', ':', '|').
1846 static int LoadAsciiSource(FILE *fp, const SourceRefT *src, const uint n, double *hrir)
1848 TokenReaderT tr;
1849 uint i, j;
1850 double dummy;
1852 TrSetup(fp, NULL, &tr);
1853 for(i = 0;i < src->mOffset;i++)
1855 if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &dummy))
1856 return (0);
1858 for(i = 0;i < n;i++)
1860 if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &hrir[i]))
1861 return 0;
1862 for(j = 0;j < src->mSkip;j++)
1864 if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &dummy))
1865 return 0;
1868 return 1;
1871 // Load a source HRIR from a supported file type.
1872 static int LoadSource(SourceRefT *src, const uint hrirRate, const uint n, double *hrir)
1874 int result;
1875 FILE *fp;
1877 if (src->mFormat == SF_ASCII)
1878 fp = fopen(src->mPath, "r");
1879 else
1880 fp = fopen(src->mPath, "rb");
1881 if(fp == NULL)
1883 fprintf(stderr, "Error: Could not open source file '%s'.\n", src->mPath);
1884 return 0;
1886 if(src->mFormat == SF_WAVE)
1887 result = LoadWaveSource(fp, src, hrirRate, n, hrir);
1888 else if(src->mFormat == SF_BIN_LE)
1889 result = LoadBinarySource(fp, src, BO_LITTLE, n, hrir);
1890 else if(src->mFormat == SF_BIN_BE)
1891 result = LoadBinarySource(fp, src, BO_BIG, n, hrir);
1892 else
1893 result = LoadAsciiSource(fp, src, n, hrir);
1894 fclose(fp);
1895 return result;
1899 /***************************
1900 *** File storage output ***
1901 ***************************/
1903 // Write an ASCII string to a file.
1904 static int WriteAscii(const char *out, FILE *fp, const char *filename)
1906 size_t len;
1908 len = strlen(out);
1909 if(fwrite(out, 1, len, fp) != len)
1911 fclose(fp);
1912 fprintf(stderr, "Error: Bad write to file '%s'.\n", filename);
1913 return 0;
1915 return 1;
1918 // Write a binary value of the given byte order and byte size to a file,
1919 // loading it from a 32-bit unsigned integer.
1920 static int WriteBin4(const ByteOrderT order, const uint bytes, const uint32 in, FILE *fp, const char *filename)
1922 uint8 out[4];
1923 uint i;
1925 switch(order)
1927 case BO_LITTLE:
1928 for(i = 0;i < bytes;i++)
1929 out[i] = (in>>(i*8)) & 0x000000FF;
1930 break;
1931 case BO_BIG:
1932 for(i = 0;i < bytes;i++)
1933 out[bytes - i - 1] = (in>>(i*8)) & 0x000000FF;
1934 break;
1935 default:
1936 break;
1938 if(fwrite(out, 1, bytes, fp) != bytes)
1940 fprintf(stderr, "Error: Bad write to file '%s'.\n", filename);
1941 return 0;
1943 return 1;
1946 // Store the OpenAL Soft HRTF data set.
1947 static int StoreMhr(const HrirDataT *hData, const int experimental, const char *filename)
1949 uint e, step, end, n, j, i;
1950 uint dither_seed;
1951 FILE *fp;
1952 int v;
1954 if((fp=fopen(filename, "wb")) == NULL)
1956 fprintf(stderr, "Error: Could not open MHR file '%s'.\n", filename);
1957 return 0;
1959 if(!WriteAscii(experimental ? MHR_FORMAT_EXPERIMENTAL : MHR_FORMAT, fp, filename))
1960 return 0;
1961 if(!WriteBin4(BO_LITTLE, 4, (uint32)hData->mIrRate, fp, filename))
1962 return 0;
1963 if(experimental)
1965 if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mSampleType, fp, filename))
1966 return 0;
1967 if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mChannelType, fp, filename))
1968 return 0;
1970 if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mIrPoints, fp, filename))
1971 return 0;
1972 if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mEvCount, fp, filename))
1973 return 0;
1974 for(e = 0;e < hData->mEvCount;e++)
1976 if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mAzCount[e], fp, filename))
1977 return 0;
1979 step = hData->mIrSize;
1980 end = hData->mIrCount * step;
1981 n = hData->mIrPoints;
1982 dither_seed = 22222;
1983 for(j = 0;j < end;j += step)
1985 const double scale = (!experimental || hData->mSampleType == ST_S16) ? 32767.0 :
1986 ((hData->mSampleType == ST_S24) ? 8388607.0 : 0.0);
1987 const int bps = (!experimental || hData->mSampleType == ST_S16) ? 2 :
1988 ((hData->mSampleType == ST_S24) ? 3 : 0);
1989 double out[MAX_TRUNCSIZE];
1990 for(i = 0;i < n;i++)
1991 out[i] = TpdfDither(scale * hData->mHrirs[j+i], &dither_seed);
1992 for(i = 0;i < n;i++)
1994 v = (int)Clamp(out[i], -scale-1.0, scale);
1995 if(!WriteBin4(BO_LITTLE, bps, (uint32)v, fp, filename))
1996 return 0;
1999 for(j = 0;j < hData->mIrCount;j++)
2001 v = (int)fmin(round(hData->mIrRate * hData->mHrtds[j]), MAX_HRTD);
2002 if(!WriteBin4(BO_LITTLE, 1, (uint32)v, fp, filename))
2003 return 0;
2005 fclose(fp);
2006 return 1;
2010 /***********************
2011 *** HRTF processing ***
2012 ***********************/
2014 // Calculate the onset time of an HRIR and average it with any existing
2015 // timing for its elevation and azimuth.
2016 static void AverageHrirOnset(const double *hrir, const double f, const uint ei, const uint ai, const HrirDataT *hData)
2018 double mag;
2019 uint n, i, j;
2021 mag = 0.0;
2022 n = hData->mIrPoints;
2023 for(i = 0;i < n;i++)
2024 mag = fmax(fabs(hrir[i]), mag);
2025 mag *= 0.15;
2026 for(i = 0;i < n;i++)
2028 if(fabs(hrir[i]) >= mag)
2029 break;
2031 j = hData->mEvOffset[ei] + ai;
2032 hData->mHrtds[j] = Lerp(hData->mHrtds[j], ((double)i) / hData->mIrRate, f);
2035 // Calculate the magnitude response of an HRIR and average it with any
2036 // existing responses for its elevation and azimuth.
2037 static void AverageHrirMagnitude(const double *hrir, const double f, const uint ei, const uint ai, const HrirDataT *hData)
2039 uint n, m, i, j;
2040 Complex *cplx;
2041 double *mags;
2043 n = hData->mFftSize;
2044 cplx = calloc(sizeof(*cplx), n);
2045 mags = calloc(sizeof(*mags), n);
2046 for(i = 0;i < hData->mIrPoints;i++)
2047 cplx[i] = MakeComplex(hrir[i], 0.0);
2048 for(;i < n;i++)
2049 cplx[i] = MakeComplex(0.0, 0.0);
2050 FftForward(n, cplx, cplx);
2051 MagnitudeResponse(n, cplx, mags);
2052 m = 1 + (n / 2);
2053 j = (hData->mEvOffset[ei] + ai) * hData->mIrSize;
2054 for(i = 0;i < m;i++)
2055 hData->mHrirs[j+i] = Lerp(hData->mHrirs[j+i], mags[i], f);
2056 free(mags);
2057 free(cplx);
2060 /* Calculate the contribution of each HRIR to the diffuse-field average based
2061 * on the area of its surface patch. All patches are centered at the HRIR
2062 * coordinates on the unit sphere and are measured by solid angle.
2064 static void CalculateDfWeights(const HrirDataT *hData, double *weights)
2066 double evs, sum, ev, up_ev, down_ev, solidAngle;
2067 uint ei;
2069 evs = 90.0 / (hData->mEvCount - 1);
2070 sum = 0.0;
2071 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
2073 // For each elevation, calculate the upper and lower limits of the
2074 // patch band.
2075 ev = -90.0 + (ei * 2.0 * evs);
2076 if(ei < (hData->mEvCount - 1))
2077 up_ev = (ev + evs) * M_PI / 180.0;
2078 else
2079 up_ev = M_PI / 2.0;
2080 if(ei > 0)
2081 down_ev = (ev - evs) * M_PI / 180.0;
2082 else
2083 down_ev = -M_PI / 2.0;
2084 // Calculate the area of the patch band.
2085 solidAngle = 2.0 * M_PI * (sin(up_ev) - sin(down_ev));
2086 // Each weight is the area of one patch.
2087 weights[ei] = solidAngle / hData->mAzCount [ei];
2088 // Sum the total surface area covered by the HRIRs.
2089 sum += solidAngle;
2091 // Normalize the weights given the total surface coverage.
2092 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
2093 weights[ei] /= sum;
2096 /* Calculate the diffuse-field average from the given magnitude responses of
2097 * the HRIR set. Weighting can be applied to compensate for the varying
2098 * surface area covered by each HRIR. The final average can then be limited
2099 * by the specified magnitude range (in positive dB; 0.0 to skip).
2101 static void CalculateDiffuseFieldAverage(const HrirDataT *hData, const int weighted, const double limit, double *dfa)
2103 uint ei, ai, count, step, start, end, m, j, i;
2104 double *weights;
2106 weights = CreateArray(hData->mEvCount);
2107 if(weighted)
2109 // Use coverage weighting to calculate the average.
2110 CalculateDfWeights(hData, weights);
2112 else
2114 // If coverage weighting is not used, the weights still need to be
2115 // averaged by the number of HRIRs.
2116 count = 0;
2117 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
2118 count += hData->mAzCount [ei];
2119 for(ei = hData->mEvStart;ei < hData->mEvCount;ei++)
2120 weights[ei] = 1.0 / count;
2122 ei = hData->mEvStart;
2123 ai = 0;
2124 step = hData->mIrSize;
2125 start = hData->mEvOffset[ei] * step;
2126 end = hData->mIrCount * step;
2127 m = 1 + (hData->mFftSize / 2);
2128 for(i = 0;i < m;i++)
2129 dfa[i] = 0.0;
2130 for(j = start;j < end;j += step)
2132 // Get the weight for this HRIR's contribution.
2133 double weight = weights[ei];
2134 // Add this HRIR's weighted power average to the total.
2135 for(i = 0;i < m;i++)
2136 dfa[i] += weight * hData->mHrirs[j+i] * hData->mHrirs[j+i];
2137 // Determine the next weight to use.
2138 ai++;
2139 if(ai >= hData->mAzCount[ei])
2141 ei++;
2142 ai = 0;
2145 // Finish the average calculation and keep it from being too small.
2146 for(i = 0;i < m;i++)
2147 dfa[i] = fmax(sqrt(dfa[i]), EPSILON);
2148 // Apply a limit to the magnitude range of the diffuse-field average if
2149 // desired.
2150 if(limit > 0.0)
2151 LimitMagnitudeResponse(hData->mFftSize, limit, dfa, dfa);
2152 DestroyArray(weights);
2155 // Perform diffuse-field equalization on the magnitude responses of the HRIR
2156 // set using the given average response.
2157 static void DiffuseFieldEqualize(const double *dfa, const HrirDataT *hData)
2159 uint step, start, end, m, j, i;
2161 step = hData->mIrSize;
2162 start = hData->mEvOffset[hData->mEvStart] * step;
2163 end = hData->mIrCount * step;
2164 m = 1 + (hData->mFftSize / 2);
2165 for(j = start;j < end;j += step)
2167 for(i = 0;i < m;i++)
2168 hData->mHrirs[j+i] /= dfa[i];
2172 // Perform minimum-phase reconstruction using the magnitude responses of the
2173 // HRIR set.
2174 static void ReconstructHrirs(const HrirDataT *hData)
2176 uint step, start, end, n, j, i;
2177 uint pcdone, lastpc;
2178 Complex *cplx;
2180 pcdone = lastpc = 0;
2181 printf("%3d%% done.", pcdone);
2182 fflush(stdout);
2184 step = hData->mIrSize;
2185 start = hData->mEvOffset[hData->mEvStart] * step;
2186 end = hData->mIrCount * step;
2187 n = hData->mFftSize;
2188 cplx = calloc(sizeof(*cplx), n);
2189 for(j = start;j < end;j += step)
2191 MinimumPhase(n, &hData->mHrirs[j], cplx);
2192 FftInverse(n, cplx, cplx);
2193 for(i = 0;i < hData->mIrPoints;i++)
2194 hData->mHrirs[j+i] = cplx[i].Real;
2195 pcdone = (j+step-start) * 100 / (end-start);
2196 if(pcdone != lastpc)
2198 lastpc = pcdone;
2199 printf("\r%3d%% done.", pcdone);
2200 fflush(stdout);
2203 free(cplx);
2204 printf("\n");
2207 // Resamples the HRIRs for use at the given sampling rate.
2208 static void ResampleHrirs(const uint rate, HrirDataT *hData)
2210 uint n, step, start, end, j;
2211 ResamplerT rs;
2213 ResamplerSetup(&rs, hData->mIrRate, rate);
2214 n = hData->mIrPoints;
2215 step = hData->mIrSize;
2216 start = hData->mEvOffset[hData->mEvStart] * step;
2217 end = hData->mIrCount * step;
2218 for(j = start;j < end;j += step)
2219 ResamplerRun(&rs, n, &hData->mHrirs[j], n, &hData->mHrirs[j]);
2220 ResamplerClear(&rs);
2221 hData->mIrRate = rate;
2224 /* Given an elevation index and an azimuth, calculate the indices of the two
2225 * HRIRs that bound the coordinate along with a factor for calculating the
2226 * continous HRIR using interpolation.
2228 static void CalcAzIndices(const HrirDataT *hData, const uint ei, const double az, uint *j0, uint *j1, double *jf)
2230 double af;
2231 uint ai;
2233 af = ((2.0*M_PI) + az) * hData->mAzCount[ei] / (2.0*M_PI);
2234 ai = ((uint)af) % hData->mAzCount[ei];
2235 af -= floor(af);
2237 *j0 = hData->mEvOffset[ei] + ai;
2238 *j1 = hData->mEvOffset[ei] + ((ai+1) % hData->mAzCount [ei]);
2239 *jf = af;
2242 // Synthesize any missing onset timings at the bottom elevations. This just
2243 // blends between slightly exaggerated known onsets. Not an accurate model.
2244 static void SynthesizeOnsets(HrirDataT *hData)
2246 uint oi, e, a, j0, j1;
2247 double t, of, jf;
2249 oi = hData->mEvStart;
2250 t = 0.0;
2251 for(a = 0;a < hData->mAzCount[oi];a++)
2252 t += hData->mHrtds[hData->mEvOffset[oi] + a];
2253 hData->mHrtds[0] = 1.32e-4 + (t / hData->mAzCount[oi]);
2254 for(e = 1;e < hData->mEvStart;e++)
2256 of = ((double)e) / hData->mEvStart;
2257 for(a = 0;a < hData->mAzCount[e];a++)
2259 CalcAzIndices(hData, oi, a * 2.0 * M_PI / hData->mAzCount[e], &j0, &j1, &jf);
2260 hData->mHrtds[hData->mEvOffset[e] + a] = Lerp(hData->mHrtds[0], Lerp(hData->mHrtds[j0], hData->mHrtds[j1], jf), of);
2265 /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
2266 * now this just blends the lowest elevation HRIRs together and applies some
2267 * attenuation and high frequency damping. It is a simple, if inaccurate
2268 * model.
2270 static void SynthesizeHrirs (HrirDataT *hData)
2272 uint oi, a, e, step, n, i, j;
2273 double lp[4], s0, s1;
2274 double of, b;
2275 uint j0, j1;
2276 double jf;
2278 if(hData->mEvStart <= 0)
2279 return;
2280 step = hData->mIrSize;
2281 oi = hData->mEvStart;
2282 n = hData->mIrPoints;
2283 for(i = 0;i < n;i++)
2284 hData->mHrirs[i] = 0.0;
2285 for(a = 0;a < hData->mAzCount[oi];a++)
2287 j = (hData->mEvOffset[oi] + a) * step;
2288 for(i = 0;i < n;i++)
2289 hData->mHrirs[i] += hData->mHrirs[j+i] / hData->mAzCount[oi];
2291 for(e = 1;e < hData->mEvStart;e++)
2293 of = ((double)e) / hData->mEvStart;
2294 b = (1.0 - of) * (3.5e-6 * hData->mIrRate);
2295 for(a = 0;a < hData->mAzCount[e];a++)
2297 j = (hData->mEvOffset[e] + a) * step;
2298 CalcAzIndices(hData, oi, a * 2.0 * M_PI / hData->mAzCount[e], &j0, &j1, &jf);
2299 j0 *= step;
2300 j1 *= step;
2301 lp[0] = 0.0;
2302 lp[1] = 0.0;
2303 lp[2] = 0.0;
2304 lp[3] = 0.0;
2305 for(i = 0;i < n;i++)
2307 s0 = hData->mHrirs[i];
2308 s1 = Lerp(hData->mHrirs[j0+i], hData->mHrirs[j1+i], jf);
2309 s0 = Lerp(s0, s1, of);
2310 lp[0] = Lerp(s0, lp[0], b);
2311 lp[1] = Lerp(lp[0], lp[1], b);
2312 lp[2] = Lerp(lp[1], lp[2], b);
2313 lp[3] = Lerp(lp[2], lp[3], b);
2314 hData->mHrirs[j+i] = lp[3];
2318 b = 3.5e-6 * hData->mIrRate;
2319 lp[0] = 0.0;
2320 lp[1] = 0.0;
2321 lp[2] = 0.0;
2322 lp[3] = 0.0;
2323 for(i = 0;i < n;i++)
2325 s0 = hData->mHrirs[i];
2326 lp[0] = Lerp(s0, lp[0], b);
2327 lp[1] = Lerp(lp[0], lp[1], b);
2328 lp[2] = Lerp(lp[1], lp[2], b);
2329 lp[3] = Lerp(lp[2], lp[3], b);
2330 hData->mHrirs[i] = lp[3];
2332 hData->mEvStart = 0;
2335 // The following routines assume a full set of HRIRs for all elevations.
2337 // Normalize the HRIR set and slightly attenuate the result.
2338 static void NormalizeHrirs (const HrirDataT *hData)
2340 uint step, end, n, j, i;
2341 double maxLevel;
2343 step = hData->mIrSize;
2344 end = hData->mIrCount * step;
2345 n = hData->mIrPoints;
2346 maxLevel = 0.0;
2347 for(j = 0;j < end;j += step)
2349 for(i = 0;i < n;i++)
2350 maxLevel = fmax(fabs(hData->mHrirs[j+i]), maxLevel);
2352 maxLevel = 1.01 * maxLevel;
2353 for(j = 0;j < end;j += step)
2355 for(i = 0;i < n;i++)
2356 hData->mHrirs[j+i] /= maxLevel;
2360 // Calculate the left-ear time delay using a spherical head model.
2361 static double CalcLTD(const double ev, const double az, const double rad, const double dist)
2363 double azp, dlp, l, al;
2365 azp = asin(cos(ev) * sin(az));
2366 dlp = sqrt((dist*dist) + (rad*rad) + (2.0*dist*rad*sin(azp)));
2367 l = sqrt((dist*dist) - (rad*rad));
2368 al = (0.5 * M_PI) + azp;
2369 if(dlp > l)
2370 dlp = l + (rad * (al - acos(rad / dist)));
2371 return (dlp / 343.3);
2374 // Calculate the effective head-related time delays for each minimum-phase
2375 // HRIR.
2376 static void CalculateHrtds (const HeadModelT model, const double radius, HrirDataT *hData)
2378 double minHrtd, maxHrtd;
2379 uint e, a, j;
2380 double t;
2382 minHrtd = 1000.0;
2383 maxHrtd = -1000.0;
2384 for(e = 0;e < hData->mEvCount;e++)
2386 for(a = 0;a < hData->mAzCount[e];a++)
2388 j = hData->mEvOffset[e] + a;
2389 if(model == HM_DATASET)
2390 t = hData->mHrtds[j] * radius / hData->mRadius;
2391 else
2392 t = CalcLTD((-90.0 + (e * 180.0 / (hData->mEvCount - 1))) * M_PI / 180.0,
2393 (a * 360.0 / hData->mAzCount [e]) * M_PI / 180.0,
2394 radius, hData->mDistance);
2395 hData->mHrtds[j] = t;
2396 maxHrtd = fmax(t, maxHrtd);
2397 minHrtd = fmin(t, minHrtd);
2400 maxHrtd -= minHrtd;
2401 for(j = 0;j < hData->mIrCount;j++)
2402 hData->mHrtds[j] -= minHrtd;
2403 hData->mMaxHrtd = maxHrtd;
2407 // Process the data set definition to read and validate the data set metrics.
2408 static int ProcessMetrics(TokenReaderT *tr, const uint fftSize, const uint truncSize, HrirDataT *hData)
2410 int hasRate = 0, hasPoints = 0, hasAzimuths = 0;
2411 int hasRadius = 0, hasDistance = 0;
2412 char ident[MAX_IDENT_LEN+1];
2413 uint line, col;
2414 double fpVal;
2415 uint points;
2416 int intVal;
2418 while(!(hasRate && hasPoints && hasAzimuths && hasRadius && hasDistance))
2420 TrIndication(tr, & line, & col);
2421 if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
2422 return 0;
2423 if(strcasecmp(ident, "rate") == 0)
2425 if(hasRate)
2427 TrErrorAt(tr, line, col, "Redefinition of 'rate'.\n");
2428 return 0;
2430 if(!TrReadOperator(tr, "="))
2431 return 0;
2432 if(!TrReadInt(tr, MIN_RATE, MAX_RATE, &intVal))
2433 return 0;
2434 hData->mIrRate = (uint)intVal;
2435 hasRate = 1;
2437 else if(strcasecmp(ident, "points") == 0)
2439 if (hasPoints) {
2440 TrErrorAt(tr, line, col, "Redefinition of 'points'.\n");
2441 return 0;
2443 if(!TrReadOperator(tr, "="))
2444 return 0;
2445 TrIndication(tr, &line, &col);
2446 if(!TrReadInt(tr, MIN_POINTS, MAX_POINTS, &intVal))
2447 return 0;
2448 points = (uint)intVal;
2449 if(fftSize > 0 && points > fftSize)
2451 TrErrorAt(tr, line, col, "Value exceeds the overridden FFT size.\n");
2452 return 0;
2454 if(points < truncSize)
2456 TrErrorAt(tr, line, col, "Value is below the truncation size.\n");
2457 return 0;
2459 hData->mIrPoints = points;
2460 if(fftSize <= 0)
2462 hData->mFftSize = DEFAULT_FFTSIZE;
2463 hData->mIrSize = 1 + (DEFAULT_FFTSIZE / 2);
2465 else
2467 hData->mFftSize = fftSize;
2468 hData->mIrSize = 1 + (fftSize / 2);
2469 if(points > hData->mIrSize)
2470 hData->mIrSize = points;
2472 hasPoints = 1;
2474 else if(strcasecmp(ident, "azimuths") == 0)
2476 if(hasAzimuths)
2478 TrErrorAt(tr, line, col, "Redefinition of 'azimuths'.\n");
2479 return 0;
2481 if(!TrReadOperator(tr, "="))
2482 return 0;
2483 hData->mIrCount = 0;
2484 hData->mEvCount = 0;
2485 hData->mEvOffset[0] = 0;
2486 for(;;)
2488 if(!TrReadInt(tr, MIN_AZ_COUNT, MAX_AZ_COUNT, &intVal))
2489 return 0;
2490 hData->mAzCount[hData->mEvCount] = (uint)intVal;
2491 hData->mIrCount += (uint)intVal;
2492 hData->mEvCount ++;
2493 if(!TrIsOperator(tr, ","))
2494 break;
2495 if(hData->mEvCount >= MAX_EV_COUNT)
2497 TrError(tr, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT);
2498 return 0;
2500 hData->mEvOffset[hData->mEvCount] = hData->mEvOffset[hData->mEvCount - 1] + ((uint)intVal);
2501 TrReadOperator(tr, ",");
2503 if(hData->mEvCount < MIN_EV_COUNT)
2505 TrErrorAt(tr, line, col, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT);
2506 return 0;
2508 hasAzimuths = 1;
2510 else if(strcasecmp(ident, "radius") == 0)
2512 if(hasRadius)
2514 TrErrorAt(tr, line, col, "Redefinition of 'radius'.\n");
2515 return 0;
2517 if(!TrReadOperator(tr, "="))
2518 return 0;
2519 if(!TrReadFloat(tr, MIN_RADIUS, MAX_RADIUS, &fpVal))
2520 return 0;
2521 hData->mRadius = fpVal;
2522 hasRadius = 1;
2524 else if(strcasecmp(ident, "distance") == 0)
2526 if(hasDistance)
2528 TrErrorAt(tr, line, col, "Redefinition of 'distance'.\n");
2529 return 0;
2531 if(!TrReadOperator(tr, "="))
2532 return 0;
2533 if(!TrReadFloat(tr, MIN_DISTANCE, MAX_DISTANCE, & fpVal))
2534 return 0;
2535 hData->mDistance = fpVal;
2536 hasDistance = 1;
2538 else
2540 TrErrorAt(tr, line, col, "Expected a metric name.\n");
2541 return 0;
2543 TrSkipWhitespace (tr);
2545 return 1;
2548 // Parse an index pair from the data set definition.
2549 static int ReadIndexPair(TokenReaderT *tr, const HrirDataT *hData, uint *ei, uint *ai)
2551 int intVal;
2552 if(!TrReadInt(tr, 0, (int)hData->mEvCount, &intVal))
2553 return 0;
2554 *ei = (uint)intVal;
2555 if(!TrReadOperator(tr, ","))
2556 return 0;
2557 if(!TrReadInt(tr, 0, (int)hData->mAzCount[*ei], &intVal))
2558 return 0;
2559 *ai = (uint)intVal;
2560 return 1;
2563 // Match the source format from a given identifier.
2564 static SourceFormatT MatchSourceFormat(const char *ident)
2566 if(strcasecmp(ident, "wave") == 0)
2567 return SF_WAVE;
2568 if(strcasecmp(ident, "bin_le") == 0)
2569 return SF_BIN_LE;
2570 if(strcasecmp(ident, "bin_be") == 0)
2571 return SF_BIN_BE;
2572 if(strcasecmp(ident, "ascii") == 0)
2573 return SF_ASCII;
2574 return SF_NONE;
2577 // Match the source element type from a given identifier.
2578 static ElementTypeT MatchElementType(const char *ident)
2580 if(strcasecmp(ident, "int") == 0)
2581 return ET_INT;
2582 if(strcasecmp(ident, "fp") == 0)
2583 return ET_FP;
2584 return ET_NONE;
2587 // Parse and validate a source reference from the data set definition.
2588 static int ReadSourceRef(TokenReaderT *tr, SourceRefT *src)
2590 char ident[MAX_IDENT_LEN+1];
2591 uint line, col;
2592 int intVal;
2594 TrIndication(tr, &line, &col);
2595 if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
2596 return 0;
2597 src->mFormat = MatchSourceFormat(ident);
2598 if(src->mFormat == SF_NONE)
2600 TrErrorAt(tr, line, col, "Expected a source format.\n");
2601 return 0;
2603 if(!TrReadOperator(tr, "("))
2604 return 0;
2605 if(src->mFormat == SF_WAVE)
2607 if(!TrReadInt(tr, 0, MAX_WAVE_CHANNELS, &intVal))
2608 return 0;
2609 src->mType = ET_NONE;
2610 src->mSize = 0;
2611 src->mBits = 0;
2612 src->mChannel = (uint)intVal;
2613 src->mSkip = 0;
2615 else
2617 TrIndication(tr, &line, &col);
2618 if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
2619 return 0;
2620 src->mType = MatchElementType(ident);
2621 if(src->mType == ET_NONE)
2623 TrErrorAt(tr, line, col, "Expected a source element type.\n");
2624 return 0;
2626 if(src->mFormat == SF_BIN_LE || src->mFormat == SF_BIN_BE)
2628 if(!TrReadOperator(tr, ","))
2629 return 0;
2630 if(src->mType == ET_INT)
2632 if(!TrReadInt(tr, MIN_BIN_SIZE, MAX_BIN_SIZE, &intVal))
2633 return 0;
2634 src->mSize = (uint)intVal;
2635 if(!TrIsOperator(tr, ","))
2636 src->mBits = (int)(8*src->mSize);
2637 else
2639 TrReadOperator(tr, ",");
2640 TrIndication(tr, &line, &col);
2641 if(!TrReadInt(tr, -2147483647-1, 2147483647, &intVal))
2642 return 0;
2643 if(abs(intVal) < MIN_BIN_BITS || ((uint)abs(intVal)) > (8*src->mSize))
2645 TrErrorAt(tr, line, col, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS, 8*src->mSize);
2646 return 0;
2648 src->mBits = intVal;
2651 else
2653 TrIndication(tr, &line, &col);
2654 if(!TrReadInt(tr, -2147483647-1, 2147483647, &intVal))
2655 return 0;
2656 if(intVal != 4 && intVal != 8)
2658 TrErrorAt(tr, line, col, "Expected a value of 4 or 8.\n");
2659 return 0;
2661 src->mSize = (uint)intVal;
2662 src->mBits = 0;
2665 else if(src->mFormat == SF_ASCII && src->mType == ET_INT)
2667 if(!TrReadOperator(tr, ","))
2668 return 0;
2669 if(!TrReadInt(tr, MIN_ASCII_BITS, MAX_ASCII_BITS, &intVal))
2670 return 0;
2671 src->mSize = 0;
2672 src->mBits = intVal;
2674 else
2676 src->mSize = 0;
2677 src->mBits = 0;
2680 if(!TrIsOperator(tr, ";"))
2681 src->mSkip = 0;
2682 else
2684 TrReadOperator(tr, ";");
2685 if(!TrReadInt (tr, 0, 0x7FFFFFFF, &intVal))
2686 return 0;
2687 src->mSkip = (uint)intVal;
2690 if(!TrReadOperator(tr, ")"))
2691 return 0;
2692 if(TrIsOperator(tr, "@"))
2694 TrReadOperator(tr, "@");
2695 if(!TrReadInt(tr, 0, 0x7FFFFFFF, &intVal))
2696 return 0;
2697 src->mOffset = (uint)intVal;
2699 else
2700 src->mOffset = 0;
2701 if(!TrReadOperator(tr, ":"))
2702 return 0;
2703 if(!TrReadString(tr, MAX_PATH_LEN, src->mPath))
2704 return 0;
2705 return 1;
2708 // Process the list of sources in the data set definition.
2709 static int ProcessSources(const HeadModelT model, TokenReaderT *tr, HrirDataT *hData)
2711 uint *setCount, *setFlag;
2712 uint line, col, ei, ai;
2713 SourceRefT src;
2714 double factor;
2715 double *hrir;
2716 int count;
2718 printf("Loading sources...");
2719 fflush(stdout);
2721 count = 0;
2722 setCount = (uint*)calloc(hData->mEvCount, sizeof(uint));
2723 setFlag = (uint*)calloc(hData->mIrCount, sizeof(uint));
2724 hrir = CreateArray(hData->mIrPoints);
2725 while(TrIsOperator(tr, "["))
2727 TrIndication(tr, & line, & col);
2728 TrReadOperator(tr, "[");
2729 if(!ReadIndexPair(tr, hData, &ei, &ai))
2730 goto error;
2731 if(!TrReadOperator(tr, "]"))
2732 goto error;
2733 if(setFlag[hData->mEvOffset[ei] + ai])
2735 TrErrorAt(tr, line, col, "Redefinition of source.\n");
2736 goto error;
2738 if(!TrReadOperator(tr, "="))
2739 goto error;
2741 factor = 1.0;
2742 for(;;)
2744 if(!ReadSourceRef(tr, &src))
2745 goto error;
2747 // TODO: Would be nice to display 'x of y files', but that would
2748 // require preparing the source refs first to get a total count
2749 // before loading them.
2750 ++count;
2751 printf("\rLoading sources... %d file%s", count, (count==1)?"":"s");
2752 fflush(stdout);
2754 if(!LoadSource(&src, hData->mIrRate, hData->mIrPoints, hrir))
2755 goto error;
2757 if(model == HM_DATASET)
2758 AverageHrirOnset(hrir, 1.0 / factor, ei, ai, hData);
2759 AverageHrirMagnitude(hrir, 1.0 / factor, ei, ai, hData);
2760 factor += 1.0;
2761 if(!TrIsOperator(tr, "+"))
2762 break;
2763 TrReadOperator(tr, "+");
2765 setFlag[hData->mEvOffset[ei] + ai] = 1;
2766 setCount[ei]++;
2768 printf("\n");
2770 ei = 0;
2771 while(ei < hData->mEvCount && setCount[ei] < 1)
2772 ei++;
2773 if(ei < hData->mEvCount)
2775 hData->mEvStart = ei;
2776 while(ei < hData->mEvCount && setCount[ei] == hData->mAzCount[ei])
2777 ei++;
2778 if(ei >= hData->mEvCount)
2780 if(!TrLoad(tr))
2782 DestroyArray(hrir);
2783 free(setFlag);
2784 free(setCount);
2785 return 1;
2787 TrError(tr, "Errant data at end of source list.\n");
2789 else
2790 TrError(tr, "Missing sources for elevation index %d.\n", ei);
2792 else
2793 TrError(tr, "Missing source references.\n");
2795 error:
2796 DestroyArray(hrir);
2797 free(setFlag);
2798 free(setCount);
2799 return 0;
2802 /* Parse the data set definition and process the source data, storing the
2803 * resulting data set as desired. If the input name is NULL it will read
2804 * from standard input.
2806 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 int experimental, const char *outName)
2808 char rateStr[8+1], expName[MAX_PATH_LEN];
2809 TokenReaderT tr;
2810 HrirDataT hData;
2811 FILE *fp;
2812 int ret;
2814 hData.mIrRate = 0;
2815 hData.mSampleType = ST_S24;
2816 hData.mChannelType = CT_LEFTONLY;
2817 hData.mIrPoints = 0;
2818 hData.mFftSize = 0;
2819 hData.mIrSize = 0;
2820 hData.mIrCount = 0;
2821 hData.mEvCount = 0;
2822 hData.mRadius = 0;
2823 hData.mDistance = 0;
2824 fprintf(stdout, "Reading HRIR definition from %s...\n", inName?inName:"stdin");
2825 if(inName != NULL)
2827 fp = fopen(inName, "r");
2828 if(fp == NULL)
2830 fprintf(stderr, "Error: Could not open definition file '%s'\n", inName);
2831 return 0;
2833 TrSetup(fp, inName, &tr);
2835 else
2837 fp = stdin;
2838 TrSetup(fp, "<stdin>", &tr);
2840 if(!ProcessMetrics(&tr, fftSize, truncSize, &hData))
2842 if(inName != NULL)
2843 fclose(fp);
2844 return 0;
2846 hData.mHrirs = CreateArray(hData.mIrCount * hData.mIrSize);
2847 hData.mHrtds = CreateArray(hData.mIrCount);
2848 if(!ProcessSources(model, &tr, &hData))
2850 DestroyArray(hData.mHrtds);
2851 DestroyArray(hData.mHrirs);
2852 if(inName != NULL)
2853 fclose(fp);
2854 return 0;
2856 if(fp != stdin)
2857 fclose(fp);
2858 if(equalize)
2860 double *dfa = CreateArray(1 + (hData.mFftSize/2));
2861 fprintf(stdout, "Calculating diffuse-field average...\n");
2862 CalculateDiffuseFieldAverage(&hData, surface, limit, dfa);
2863 fprintf(stdout, "Performing diffuse-field equalization...\n");
2864 DiffuseFieldEqualize(dfa, &hData);
2865 DestroyArray(dfa);
2867 fprintf(stdout, "Performing minimum phase reconstruction...\n");
2868 ReconstructHrirs(&hData);
2869 if(outRate != 0 && outRate != hData.mIrRate)
2871 fprintf(stdout, "Resampling HRIRs...\n");
2872 ResampleHrirs(outRate, &hData);
2874 fprintf(stdout, "Truncating minimum-phase HRIRs...\n");
2875 hData.mIrPoints = truncSize;
2876 fprintf(stdout, "Synthesizing missing elevations...\n");
2877 if(model == HM_DATASET)
2878 SynthesizeOnsets(&hData);
2879 SynthesizeHrirs(&hData);
2880 fprintf(stdout, "Normalizing final HRIRs...\n");
2881 NormalizeHrirs(&hData);
2882 fprintf(stdout, "Calculating impulse delays...\n");
2883 CalculateHrtds(model, (radius > DEFAULT_CUSTOM_RADIUS) ? radius : hData.mRadius, &hData);
2884 snprintf(rateStr, 8, "%u", hData.mIrRate);
2885 StrSubst(outName, "%r", rateStr, MAX_PATH_LEN, expName);
2886 fprintf(stdout, "Creating MHR data set %s...\n", expName);
2887 ret = StoreMhr(&hData, experimental, expName);
2889 DestroyArray(hData.mHrtds);
2890 DestroyArray(hData.mHrirs);
2891 return ret;
2894 static void PrintHelp(const char *argv0, FILE *ofile)
2896 fprintf(ofile, "Usage: %s <command> [<option>...]\n\n", argv0);
2897 fprintf(ofile, "Options:\n");
2898 fprintf(ofile, " -m Ignored for compatibility.\n");
2899 fprintf(ofile, " -r <rate> Change the data set sample rate to the specified value and\n");
2900 fprintf(ofile, " resample the HRIRs accordingly.\n");
2901 fprintf(ofile, " -f <points> Override the FFT window size (default: %u).\n", DEFAULT_FFTSIZE);
2902 fprintf(ofile, " -e {on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE ? "on" : "off"));
2903 fprintf(ofile, " -s {on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE ? "on" : "off"));
2904 fprintf(ofile, " -l {<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
2905 fprintf(ofile, " average (default: %.2f).\n", DEFAULT_LIMIT);
2906 fprintf(ofile, " -w <points> Specify the size of the truncation window that's applied\n");
2907 fprintf(ofile, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE);
2908 fprintf(ofile, " -d {dataset| Specify the model used for calculating the head-delay timing\n");
2909 fprintf(ofile, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL == HM_DATASET) ? "dataset" : "sphere"));
2910 fprintf(ofile, " -c <size> Use a customized head radius measured ear-to-ear in meters.\n");
2911 fprintf(ofile, " -i <filename> Specify an HRIR definition file to use (defaults to stdin).\n");
2912 fprintf(ofile, " -o <filename> Specify an output file. Overrides command-selected default.\n");
2913 fprintf(ofile, " Use of '%%r' will be substituted with the data set sample rate.\n");
2916 #ifdef _WIN32
2917 #define main my_main
2918 int main(int argc, char *argv[]);
2920 static char **arglist;
2921 static void cleanup_arglist(void)
2923 int i;
2924 for(i = 0;arglist[i];i++)
2925 free(arglist[i]);
2926 free(arglist);
2929 int wmain(int argc, const wchar_t *wargv[])
2931 int i;
2933 atexit(cleanup_arglist);
2934 arglist = calloc(sizeof(*arglist), argc+1);
2935 for(i = 0;i < argc;i++)
2936 arglist[i] = ToUTF8(wargv[i]);
2938 return main(argc, arglist);
2940 #endif
2942 // Standard command line dispatch.
2943 int main(int argc, char *argv[])
2945 const char *inName = NULL, *outName = NULL;
2946 uint outRate, fftSize;
2947 int equalize, surface;
2948 int experimental;
2949 char *end = NULL;
2950 HeadModelT model;
2951 uint truncSize;
2952 double radius;
2953 double limit;
2954 int opt;
2956 if(argc < 2)
2958 fprintf(stdout, "HRTF Processing and Composition Utility\n\n");
2959 PrintHelp(argv[0], stdout);
2960 exit(EXIT_SUCCESS);
2963 outName = "./oalsoft_hrtf_%r.mhr";
2964 outRate = 0;
2965 fftSize = 0;
2966 equalize = DEFAULT_EQUALIZE;
2967 surface = DEFAULT_SURFACE;
2968 limit = DEFAULT_LIMIT;
2969 truncSize = DEFAULT_TRUNCSIZE;
2970 model = DEFAULT_HEAD_MODEL;
2971 radius = DEFAULT_CUSTOM_RADIUS;
2972 experimental = 0;
2974 while((opt=getopt(argc, argv, "mr:f:e:s:l:w:d:c:e:i:o:xh")) != -1)
2976 switch(opt)
2978 case 'm':
2979 fprintf(stderr, "Ignoring unused command '-m'.\n");
2980 break;
2982 case 'r':
2983 outRate = strtoul(optarg, &end, 10);
2984 if(end[0] != '\0' || outRate < MIN_RATE || outRate > MAX_RATE)
2986 fprintf(stderr, "Error: Got unexpected value \"%s\" for option -%c, expected between %u to %u.\n", optarg, opt, MIN_RATE, MAX_RATE);
2987 exit(EXIT_FAILURE);
2989 break;
2991 case 'f':
2992 fftSize = strtoul(optarg, &end, 10);
2993 if(end[0] != '\0' || (fftSize&(fftSize-1)) || fftSize < MIN_FFTSIZE || fftSize > MAX_FFTSIZE)
2995 fprintf(stderr, "Error: Got unexpected value \"%s\" for option -%c, expected a power-of-two between %u to %u.\n", optarg, opt, MIN_FFTSIZE, MAX_FFTSIZE);
2996 exit(EXIT_FAILURE);
2998 break;
3000 case 'e':
3001 if(strcmp(optarg, "on") == 0)
3002 equalize = 1;
3003 else if(strcmp(optarg, "off") == 0)
3004 equalize = 0;
3005 else
3007 fprintf(stderr, "Error: Got unexpected value \"%s\" for option -%c, expected on or off.\n", optarg, opt);
3008 exit(EXIT_FAILURE);
3010 break;
3012 case 's':
3013 if(strcmp(optarg, "on") == 0)
3014 surface = 1;
3015 else if(strcmp(optarg, "off") == 0)
3016 surface = 0;
3017 else
3019 fprintf(stderr, "Error: Got unexpected value \"%s\" for option -%c, expected on or off.\n", optarg, opt);
3020 exit(EXIT_FAILURE);
3022 break;
3024 case 'l':
3025 if(strcmp(optarg, "none") == 0)
3026 limit = 0.0;
3027 else
3029 limit = strtod(optarg, &end);
3030 if(end[0] != '\0' || limit < MIN_LIMIT || limit > MAX_LIMIT)
3032 fprintf(stderr, "Error: Got unexpected value \"%s\" for option -%c, expected between %.0f to %.0f.\n", optarg, opt, MIN_LIMIT, MAX_LIMIT);
3033 exit(EXIT_FAILURE);
3036 break;
3038 case 'w':
3039 truncSize = strtoul(optarg, &end, 10);
3040 if(end[0] != '\0' || truncSize < MIN_TRUNCSIZE || truncSize > MAX_TRUNCSIZE || (truncSize%MOD_TRUNCSIZE))
3042 fprintf(stderr, "Error: Got unexpected value \"%s\" for option -%c, expected multiple of %u between %u to %u.\n", optarg, opt, MOD_TRUNCSIZE, MIN_TRUNCSIZE, MAX_TRUNCSIZE);
3043 exit(EXIT_FAILURE);
3045 break;
3047 case 'd':
3048 if(strcmp(optarg, "dataset") == 0)
3049 model = HM_DATASET;
3050 else if(strcmp(optarg, "sphere") == 0)
3051 model = HM_SPHERE;
3052 else
3054 fprintf(stderr, "Error: Got unexpected value \"%s\" for option -%c, expected dataset or sphere.\n", optarg, opt);
3055 exit(EXIT_FAILURE);
3057 break;
3059 case 'c':
3060 radius = strtod(optarg, &end);
3061 if(end[0] != '\0' || radius < MIN_CUSTOM_RADIUS || radius > MAX_CUSTOM_RADIUS)
3063 fprintf(stderr, "Error: Got unexpected value \"%s\" for option -%c, expected between %.2f to %.2f.\n", optarg, opt, MIN_CUSTOM_RADIUS, MAX_CUSTOM_RADIUS);
3064 exit(EXIT_FAILURE);
3066 break;
3068 case 'i':
3069 inName = optarg;
3070 break;
3072 case 'o':
3073 outName = optarg;
3074 break;
3076 case 'x':
3077 experimental = 1;
3078 break;
3080 case 'h':
3081 PrintHelp(argv[0], stdout);
3082 exit(EXIT_SUCCESS);
3084 default: /* '?' */
3085 PrintHelp(argv[0], stderr);
3086 exit(EXIT_FAILURE);
3090 if(!ProcessDefinition(inName, outRate, fftSize, equalize, surface, limit,
3091 truncSize, model, radius, experimental, outName))
3092 return -1;
3093 fprintf(stdout, "Operation completed.\n");
3095 return EXIT_SUCCESS;