makehrtf.c 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752
  1. /*
  2. * HRTF utility for producing and demonstrating the process of creating an
  3. * OpenAL Soft compatible HRIR data set.
  4. *
  5. * Copyright (C) 2011-2014 Christopher Fitzgerald
  6. *
  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.
  11. *
  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.
  16. *
  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.
  20. *
  21. * Or visit: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  22. *
  23. * --------------------------------------------------------------------------
  24. *
  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.
  28. *
  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:
  32. *
  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.
  43. *
  44. * The spherical head algorithm for calculating propagation delay was adapted
  45. * from the paper:
  46. *
  47. * Modeling Interaural Time Difference Assuming a Spherical Head
  48. * Joel David Miller
  49. * Music 150, Musical Acoustics, Stanford University
  50. * December 2, 2001
  51. *
  52. * The formulae for calculating the Kaiser window metrics are from the
  53. * the textbook:
  54. *
  55. * Discrete-Time Signal Processing
  56. * Alan V. Oppenheim and Ronald W. Schafer
  57. * Prentice-Hall Signal Processing Series
  58. * 1999
  59. */
  60. // Needed for 64-bit unsigned integer.
  61. #include "config.h"
  62. #include <stdio.h>
  63. #include <stdlib.h>
  64. #include <stdarg.h>
  65. #include <string.h>
  66. #include <ctype.h>
  67. #include <math.h>
  68. // Rely (if naively) on OpenAL's header for the types used for serialization.
  69. #include "AL/al.h"
  70. #ifndef M_PI
  71. #define M_PI (3.14159265358979323846)
  72. #endif
  73. #ifndef HUGE_VAL
  74. #define HUGE_VAL (1.0 / 0.0)
  75. #endif
  76. // The epsilon used to maintain signal stability.
  77. #define EPSILON (1e-15)
  78. // Constants for accessing the token reader's ring buffer.
  79. #define TR_RING_BITS (16)
  80. #define TR_RING_SIZE (1 << TR_RING_BITS)
  81. #define TR_RING_MASK (TR_RING_SIZE - 1)
  82. // The token reader's load interval in bytes.
  83. #define TR_LOAD_SIZE (TR_RING_SIZE >> 2)
  84. // The maximum identifier length used when processing the data set
  85. // definition.
  86. #define MAX_IDENT_LEN (16)
  87. // The maximum path length used when processing filenames.
  88. #define MAX_PATH_LEN (256)
  89. // The limits for the sample 'rate' metric in the data set definition and for
  90. // resampling.
  91. #define MIN_RATE (32000)
  92. #define MAX_RATE (96000)
  93. // The limits for the HRIR 'points' metric in the data set definition.
  94. #define MIN_POINTS (16)
  95. #define MAX_POINTS (8192)
  96. // The limits to the number of 'azimuths' listed in the data set definition.
  97. #define MIN_EV_COUNT (5)
  98. #define MAX_EV_COUNT (128)
  99. // The limits for each of the 'azimuths' listed in the data set definition.
  100. #define MIN_AZ_COUNT (1)
  101. #define MAX_AZ_COUNT (128)
  102. // The limits for the listener's head 'radius' in the data set definition.
  103. #define MIN_RADIUS (0.05)
  104. #define MAX_RADIUS (0.15)
  105. // The limits for the 'distance' from source to listener in the definition
  106. // file.
  107. #define MIN_DISTANCE (0.5)
  108. #define MAX_DISTANCE (2.5)
  109. // The maximum number of channels that can be addressed for a WAVE file
  110. // source listed in the data set definition.
  111. #define MAX_WAVE_CHANNELS (65535)
  112. // The limits to the byte size for a binary source listed in the definition
  113. // file.
  114. #define MIN_BIN_SIZE (2)
  115. #define MAX_BIN_SIZE (4)
  116. // The minimum number of significant bits for binary sources listed in the
  117. // data set definition. The maximum is calculated from the byte size.
  118. #define MIN_BIN_BITS (16)
  119. // The limits to the number of significant bits for an ASCII source listed in
  120. // the data set definition.
  121. #define MIN_ASCII_BITS (16)
  122. #define MAX_ASCII_BITS (32)
  123. // The limits to the FFT window size override on the command line.
  124. #define MIN_FFTSIZE (512)
  125. #define MAX_FFTSIZE (16384)
  126. // The limits to the equalization range limit on the command line.
  127. #define MIN_LIMIT (2.0)
  128. #define MAX_LIMIT (120.0)
  129. // The limits to the truncation window size on the command line.
  130. #define MIN_TRUNCSIZE (8)
  131. #define MAX_TRUNCSIZE (128)
  132. // The limits to the custom head radius on the command line.
  133. #define MIN_CUSTOM_RADIUS (0.05)
  134. #define MAX_CUSTOM_RADIUS (0.15)
  135. // The truncation window size must be a multiple of the below value to allow
  136. // for vectorized convolution.
  137. #define MOD_TRUNCSIZE (8)
  138. // The defaults for the command line options.
  139. #define DEFAULT_EQUALIZE (1)
  140. #define DEFAULT_SURFACE (1)
  141. #define DEFAULT_LIMIT (24.0)
  142. #define DEFAULT_TRUNCSIZE (32)
  143. #define DEFAULT_HEAD_MODEL (HM_DATASET)
  144. #define DEFAULT_CUSTOM_RADIUS (0.0)
  145. // The four-character-codes for RIFF/RIFX WAVE file chunks.
  146. #define FOURCC_RIFF (0x46464952) // 'RIFF'
  147. #define FOURCC_RIFX (0x58464952) // 'RIFX'
  148. #define FOURCC_WAVE (0x45564157) // 'WAVE'
  149. #define FOURCC_FMT (0x20746D66) // 'fmt '
  150. #define FOURCC_DATA (0x61746164) // 'data'
  151. #define FOURCC_LIST (0x5453494C) // 'LIST'
  152. #define FOURCC_WAVL (0x6C766177) // 'wavl'
  153. #define FOURCC_SLNT (0x746E6C73) // 'slnt'
  154. // The supported wave formats.
  155. #define WAVE_FORMAT_PCM (0x0001)
  156. #define WAVE_FORMAT_IEEE_FLOAT (0x0003)
  157. #define WAVE_FORMAT_EXTENSIBLE (0xFFFE)
  158. // The maximum propagation delay value supported by OpenAL Soft.
  159. #define MAX_HRTD (63.0)
  160. // The OpenAL Soft HRTF format marker. It stands for minimum-phase head
  161. // response protocol 01.
  162. #define MHR_FORMAT ("MinPHR01")
  163. // Byte order for the serialization routines.
  164. enum ByteOrderT {
  165. BO_NONE = 0,
  166. BO_LITTLE ,
  167. BO_BIG
  168. };
  169. // Source format for the references listed in the data set definition.
  170. enum SourceFormatT {
  171. SF_NONE = 0,
  172. SF_WAVE , // RIFF/RIFX WAVE file.
  173. SF_BIN_LE , // Little-endian binary file.
  174. SF_BIN_BE , // Big-endian binary file.
  175. SF_ASCII // ASCII text file.
  176. };
  177. // Element types for the references listed in the data set definition.
  178. enum ElementTypeT {
  179. ET_NONE = 0,
  180. ET_INT , // Integer elements.
  181. ET_FP // Floating-point elements.
  182. };
  183. // Head model used for calculating the impulse delays.
  184. enum HeadModelT {
  185. HM_NONE = 0,
  186. HM_DATASET , // Measure the onset from the dataset.
  187. HM_SPHERE // Calculate the onset using a spherical head model.
  188. };
  189. // Desired output format from the command line.
  190. enum OutputFormatT {
  191. OF_NONE = 0,
  192. OF_MHR , // OpenAL Soft MHR data set file.
  193. OF_TABLE // OpenAL Soft built-in table file (used when compiling).
  194. };
  195. // Unsigned integer type.
  196. typedef unsigned int uint;
  197. // Serialization types. The trailing digit indicates the number of bytes.
  198. typedef ALubyte uint1;
  199. typedef ALint int4;
  200. typedef ALuint uint4;
  201. #if defined (HAVE_STDINT_H)
  202. #include <stdint.h>
  203. typedef uint64_t uint8;
  204. #elif defined (HAVE___INT64)
  205. typedef unsigned __int64 uint8;
  206. #elif (SIZEOF_LONG == 8)
  207. typedef unsigned long uint8;
  208. #elif (SIZEOF_LONG_LONG == 8)
  209. typedef unsigned long long uint8;
  210. #endif
  211. typedef enum ByteOrderT ByteOrderT;
  212. typedef enum SourceFormatT SourceFormatT;
  213. typedef enum ElementTypeT ElementTypeT;
  214. typedef enum HeadModelT HeadModelT;
  215. typedef enum OutputFormatT OutputFormatT;
  216. typedef struct TokenReaderT TokenReaderT;
  217. typedef struct SourceRefT SourceRefT;
  218. typedef struct HrirDataT HrirDataT;
  219. typedef struct ResamplerT ResamplerT;
  220. // Token reader state for parsing the data set definition.
  221. struct TokenReaderT {
  222. FILE * mFile;
  223. const char * mName;
  224. uint mLine,
  225. mColumn;
  226. char mRing [TR_RING_SIZE];
  227. size_t mIn,
  228. mOut;
  229. };
  230. // Source reference state used when loading sources.
  231. struct SourceRefT {
  232. SourceFormatT mFormat;
  233. ElementTypeT mType;
  234. uint mSize;
  235. int mBits;
  236. uint mChannel,
  237. mSkip,
  238. mOffset;
  239. char mPath [MAX_PATH_LEN + 1];
  240. };
  241. // The HRIR metrics and data set used when loading, processing, and storing
  242. // the resulting HRTF.
  243. struct HrirDataT {
  244. uint mIrRate,
  245. mIrCount,
  246. mIrSize,
  247. mIrPoints,
  248. mFftSize,
  249. mEvCount,
  250. mEvStart,
  251. mAzCount [MAX_EV_COUNT],
  252. mEvOffset [MAX_EV_COUNT];
  253. double mRadius,
  254. mDistance,
  255. * mHrirs,
  256. * mHrtds,
  257. mMaxHrtd;
  258. };
  259. // The resampler metrics and FIR filter.
  260. struct ResamplerT {
  261. uint mP,
  262. mQ,
  263. mM,
  264. mL;
  265. double * mF;
  266. };
  267. /* Token reader routines for parsing text files. Whitespace is not
  268. * significant. It can process tokens as identifiers, numbers (integer and
  269. * floating-point), strings, and operators. Strings must be encapsulated by
  270. * double-quotes and cannot span multiple lines.
  271. */
  272. // Setup the reader on the given file. The filename can be NULL if no error
  273. // output is desired.
  274. static void TrSetup (FILE * fp, const char * filename, TokenReaderT * tr) {
  275. const char * name = NULL;
  276. char ch;
  277. tr -> mFile = fp;
  278. name = filename;
  279. // If a filename was given, store a pointer to the base name.
  280. if (filename != NULL) {
  281. while ((ch = (* filename)) != '\0') {
  282. if ((ch == '/') || (ch == '\\'))
  283. name = filename + 1;
  284. filename ++;
  285. }
  286. }
  287. tr -> mName = name;
  288. tr -> mLine = 1;
  289. tr -> mColumn = 1;
  290. tr -> mIn = 0;
  291. tr -> mOut = 0;
  292. }
  293. // Prime the reader's ring buffer, and return a result indicating that there
  294. // is text to process.
  295. static int TrLoad (TokenReaderT * tr) {
  296. size_t toLoad, in, count;
  297. toLoad = TR_RING_SIZE - (tr -> mIn - tr -> mOut);
  298. if ((toLoad >= TR_LOAD_SIZE) && (! feof (tr -> mFile))) {
  299. // Load TR_LOAD_SIZE (or less if at the end of the file) per read.
  300. toLoad = TR_LOAD_SIZE;
  301. in = tr -> mIn & TR_RING_MASK;
  302. count = TR_RING_SIZE - in;
  303. if (count < toLoad) {
  304. tr -> mIn += fread (& tr -> mRing [in], 1, count, tr -> mFile);
  305. tr -> mIn += fread (& tr -> mRing [0], 1, toLoad - count, tr -> mFile);
  306. } else {
  307. tr -> mIn += fread (& tr -> mRing [in], 1, toLoad, tr -> mFile);
  308. }
  309. if (tr -> mOut >= TR_RING_SIZE) {
  310. tr -> mOut -= TR_RING_SIZE;
  311. tr -> mIn -= TR_RING_SIZE;
  312. }
  313. }
  314. if (tr -> mIn > tr -> mOut)
  315. return (1);
  316. return (0);
  317. }
  318. // Error display routine. Only displays when the base name is not NULL.
  319. static void TrErrorVA (const TokenReaderT * tr, uint line, uint column, const char * format, va_list argPtr) {
  320. if (tr -> mName != NULL) {
  321. fprintf (stderr, "Error (%s:%u:%u): ", tr -> mName, line, column);
  322. vfprintf (stderr, format, argPtr);
  323. }
  324. }
  325. // Used to display an error at a saved line/column.
  326. static void TrErrorAt (const TokenReaderT * tr, uint line, uint column, const char * format, ...) {
  327. va_list argPtr;
  328. va_start (argPtr, format);
  329. TrErrorVA (tr, line, column, format, argPtr);
  330. va_end (argPtr);
  331. }
  332. // Used to display an error at the current line/column.
  333. static void TrError (const TokenReaderT * tr, const char * format, ...) {
  334. va_list argPtr;
  335. va_start (argPtr, format);
  336. TrErrorVA (tr, tr -> mLine, tr -> mColumn, format, argPtr);
  337. va_end (argPtr);
  338. }
  339. // Skips to the next line.
  340. static void TrSkipLine (TokenReaderT * tr) {
  341. char ch;
  342. while (TrLoad (tr)) {
  343. ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
  344. tr -> mOut ++;
  345. if (ch == '\n') {
  346. tr -> mLine ++;
  347. tr -> mColumn = 1;
  348. break;
  349. }
  350. tr -> mColumn ++;
  351. }
  352. }
  353. // Skips to the next token.
  354. static int TrSkipWhitespace (TokenReaderT * tr) {
  355. char ch;
  356. while (TrLoad (tr)) {
  357. ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
  358. if (isspace (ch)) {
  359. tr -> mOut ++;
  360. if (ch == '\n') {
  361. tr -> mLine ++;
  362. tr -> mColumn = 1;
  363. } else {
  364. tr -> mColumn ++;
  365. }
  366. } else if (ch == '#') {
  367. TrSkipLine (tr);
  368. } else {
  369. return (1);
  370. }
  371. }
  372. return (0);
  373. }
  374. // Get the line and/or column of the next token (or the end of input).
  375. static void TrIndication (TokenReaderT * tr, uint * line, uint * column) {
  376. TrSkipWhitespace (tr);
  377. if (line != NULL)
  378. (* line) = tr -> mLine;
  379. if (column != NULL)
  380. (* column) = tr -> mColumn;
  381. }
  382. // Checks to see if a token is the given operator. It does not display any
  383. // errors and will not proceed to the next token.
  384. static int TrIsOperator (TokenReaderT * tr, const char * op) {
  385. size_t out, len;
  386. char ch;
  387. if (! TrSkipWhitespace (tr))
  388. return (0);
  389. out = tr -> mOut;
  390. len = 0;
  391. while ((op [len] != '\0') && (out < tr -> mIn)) {
  392. ch = tr -> mRing [out & TR_RING_MASK];
  393. if (ch != op [len])
  394. break;
  395. len ++;
  396. out ++;
  397. }
  398. if (op [len] == '\0')
  399. return (1);
  400. return (0);
  401. }
  402. /* The TrRead*() routines obtain the value of a matching token type. They
  403. * display type, form, and boundary errors and will proceed to the next
  404. * token.
  405. */
  406. // Reads and validates an identifier token.
  407. static int TrReadIdent (TokenReaderT * tr, const uint maxLen, char * ident) {
  408. uint col, len;
  409. char ch;
  410. col = tr -> mColumn;
  411. if (TrSkipWhitespace (tr)) {
  412. col = tr -> mColumn;
  413. ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
  414. if ((ch == '_') || isalpha (ch)) {
  415. len = 0;
  416. do {
  417. if (len < maxLen)
  418. ident [len] = ch;
  419. len ++;
  420. tr -> mOut ++;
  421. if (! TrLoad (tr))
  422. break;
  423. ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
  424. } while ((ch == '_') || isdigit (ch) || isalpha (ch));
  425. tr -> mColumn += len;
  426. if (len > maxLen) {
  427. TrErrorAt (tr, tr -> mLine, col, "Identifier is too long.\n");
  428. return (0);
  429. }
  430. ident [len] = '\0';
  431. return (1);
  432. }
  433. }
  434. TrErrorAt (tr, tr -> mLine, col, "Expected an identifier.\n");
  435. return (0);
  436. }
  437. // Reads and validates (including bounds) an integer token.
  438. static int TrReadInt (TokenReaderT * tr, const int loBound, const int hiBound, int * value) {
  439. uint col, digis, len;
  440. char ch, temp [64 + 1];
  441. col = tr -> mColumn;
  442. if (TrSkipWhitespace (tr)) {
  443. col = tr -> mColumn;
  444. len = 0;
  445. ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
  446. if ((ch == '+') || (ch == '-')) {
  447. temp [len] = ch;
  448. len ++;
  449. tr -> mOut ++;
  450. }
  451. digis = 0;
  452. while (TrLoad (tr)) {
  453. ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
  454. if (! isdigit (ch))
  455. break;
  456. if (len < 64)
  457. temp [len] = ch;
  458. len ++;
  459. digis ++;
  460. tr -> mOut ++;
  461. }
  462. tr -> mColumn += len;
  463. if ((digis > 0) && (ch != '.') && (! isalpha (ch))) {
  464. if (len > 64) {
  465. TrErrorAt (tr, tr -> mLine, col, "Integer is too long.");
  466. return (0);
  467. }
  468. temp [len] = '\0';
  469. (* value) = strtol (temp, NULL, 10);
  470. if (((* value) < loBound) || ((* value) > hiBound)) {
  471. TrErrorAt (tr, tr -> mLine, col, "Expected a value from %d to %d.\n", loBound, hiBound);
  472. return (0);
  473. }
  474. return (1);
  475. }
  476. }
  477. TrErrorAt (tr, tr -> mLine, col, "Expected an integer.\n");
  478. return (0);
  479. }
  480. // Reads and validates (including bounds) a float token.
  481. static int TrReadFloat (TokenReaderT * tr, const double loBound, const double hiBound, double * value) {
  482. uint col, digis, len;
  483. char ch, temp [64 + 1];
  484. col = tr -> mColumn;
  485. if (TrSkipWhitespace (tr)) {
  486. col = tr -> mColumn;
  487. len = 0;
  488. ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
  489. if ((ch == '+') || (ch == '-')) {
  490. temp [len] = ch;
  491. len ++;
  492. tr -> mOut ++;
  493. }
  494. digis = 0;
  495. while (TrLoad (tr)) {
  496. ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
  497. if (! isdigit (ch))
  498. break;
  499. if (len < 64)
  500. temp [len] = ch;
  501. len ++;
  502. digis ++;
  503. tr -> mOut ++;
  504. }
  505. if (ch == '.') {
  506. if (len < 64)
  507. temp [len] = ch;
  508. len ++;
  509. tr -> mOut ++;
  510. }
  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 ++;
  520. }
  521. if (digis > 0) {
  522. if ((ch == 'E') || (ch == 'e')) {
  523. if (len < 64)
  524. temp [len] = ch;
  525. len ++;
  526. digis = 0;
  527. tr -> mOut ++;
  528. if ((ch == '+') || (ch == '-')) {
  529. if (len < 64)
  530. temp [len] = ch;
  531. len ++;
  532. tr -> mOut ++;
  533. }
  534. while (TrLoad (tr)) {
  535. ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
  536. if (! isdigit (ch))
  537. break;
  538. if (len < 64)
  539. temp [len] = ch;
  540. len ++;
  541. digis ++;
  542. tr -> mOut ++;
  543. }
  544. }
  545. tr -> mColumn += len;
  546. if ((digis > 0) && (ch != '.') && (! isalpha (ch))) {
  547. if (len > 64) {
  548. TrErrorAt (tr, tr -> mLine, col, "Float is too long.");
  549. return (0);
  550. }
  551. temp [len] = '\0';
  552. (* value) = strtod (temp, NULL);
  553. if (((* value) < loBound) || ((* value) > hiBound)) {
  554. TrErrorAt (tr, tr -> mLine, col, "Expected a value from %f to %f.\n", loBound, hiBound);
  555. return (0);
  556. }
  557. return (1);
  558. }
  559. } else {
  560. tr -> mColumn += len;
  561. }
  562. }
  563. TrErrorAt (tr, tr -> mLine, col, "Expected a float.\n");
  564. return (0);
  565. }
  566. // Reads and validates a string token.
  567. static int TrReadString (TokenReaderT * tr, const uint maxLen, char * text) {
  568. uint col, len;
  569. char ch;
  570. col = tr -> mColumn;
  571. if (TrSkipWhitespace (tr)) {
  572. col = tr -> mColumn;
  573. ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
  574. if (ch == '\"') {
  575. tr -> mOut ++;
  576. len = 0;
  577. while (TrLoad (tr)) {
  578. ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
  579. tr -> mOut ++;
  580. if (ch == '\"')
  581. break;
  582. if (ch == '\n') {
  583. TrErrorAt (tr, tr -> mLine, col, "Unterminated string at end of line.\n");
  584. return (0);
  585. }
  586. if (len < maxLen)
  587. text [len] = ch;
  588. len ++;
  589. }
  590. if (ch != '\"') {
  591. tr -> mColumn += 1 + len;
  592. TrErrorAt (tr, tr -> mLine, col, "Unterminated string at end of input.\n");
  593. return (0);
  594. }
  595. tr -> mColumn += 2 + len;
  596. if (len > maxLen) {
  597. TrErrorAt (tr, tr -> mLine, col, "String is too long.\n");
  598. return (0);
  599. }
  600. text [len] = '\0';
  601. return (1);
  602. }
  603. }
  604. TrErrorAt (tr, tr -> mLine, col, "Expected a string.\n");
  605. return (0);
  606. }
  607. // Reads and validates the given operator.
  608. static int TrReadOperator (TokenReaderT * tr, const char * op) {
  609. uint col, len;
  610. char ch;
  611. col = tr -> mColumn;
  612. if (TrSkipWhitespace (tr)) {
  613. col = tr -> mColumn;
  614. len = 0;
  615. while ((op [len] != '\0') && TrLoad (tr)) {
  616. ch = tr -> mRing [tr -> mOut & TR_RING_MASK];
  617. if (ch != op [len])
  618. break;
  619. len ++;
  620. tr -> mOut ++;
  621. }
  622. tr -> mColumn += len;
  623. if (op [len] == '\0')
  624. return (1);
  625. }
  626. TrErrorAt (tr, tr -> mLine, col, "Expected '%s' operator.\n", op);
  627. return (0);
  628. }
  629. /* Performs a string substitution. Any case-insensitive occurrences of the
  630. * pattern string are replaced with the replacement string. The result is
  631. * truncated if necessary.
  632. */
  633. static int StrSubst (const char * in, const char * pat, const char * rep, const size_t maxLen, char * out) {
  634. size_t inLen, patLen, repLen;
  635. size_t si, di;
  636. int truncated;
  637. inLen = strlen (in);
  638. patLen = strlen (pat);
  639. repLen = strlen (rep);
  640. si = 0;
  641. di = 0;
  642. truncated = 0;
  643. while ((si < inLen) && (di < maxLen)) {
  644. if (patLen <= (inLen - si)) {
  645. if (strncasecmp (& in [si], pat, patLen) == 0) {
  646. if (repLen > (maxLen - di)) {
  647. repLen = maxLen - di;
  648. truncated = 1;
  649. }
  650. strncpy (& out [di], rep, repLen);
  651. si += patLen;
  652. di += repLen;
  653. }
  654. }
  655. out [di] = in [si];
  656. si ++;
  657. di ++;
  658. }
  659. if (si < inLen)
  660. truncated = 1;
  661. out [di] = '\0';
  662. return (! truncated);
  663. }
  664. // Provide missing math routines for MSVC versions < 1800 (Visual Studio 2013).
  665. #if defined(_MSC_VER) && _MSC_VER < 1800
  666. static double round (double val) {
  667. if (val < 0.0)
  668. return (ceil (val - 0.5));
  669. return (floor (val + 0.5));
  670. }
  671. static double fmin (double a, double b) {
  672. return ((a < b) ? a : b);
  673. }
  674. static double fmax (double a, double b) {
  675. return ((a > b) ? a : b);
  676. }
  677. #endif
  678. // Simple clamp routine.
  679. static double Clamp (const double val, const double lower, const double upper) {
  680. return (fmin (fmax (val, lower), upper));
  681. }
  682. // Performs linear interpolation.
  683. static double Lerp (const double a, const double b, const double f) {
  684. return (a + (f * (b - a)));
  685. }
  686. // Performs a high-passed triangular probability density function dither from
  687. // a double to an integer. It assumes the input sample is already scaled.
  688. static int HpTpdfDither (const double in, int * hpHist) {
  689. const double PRNG_SCALE = 1.0 / (RAND_MAX + 1.0);
  690. int prn;
  691. double out;
  692. prn = rand ();
  693. out = round (in + (PRNG_SCALE * (prn - (* hpHist))));
  694. (* hpHist) = prn;
  695. return ((int) out);
  696. }
  697. // Allocates an array of doubles.
  698. static double * CreateArray (const size_t n) {
  699. double * a = NULL;
  700. a = (double *) calloc (n, sizeof (double));
  701. if (a == NULL) {
  702. fprintf (stderr, "Error: Out of memory.\n");
  703. exit (-1);
  704. }
  705. return (a);
  706. }
  707. // Frees an array of doubles.
  708. static void DestroyArray (const double * a) {
  709. free ((void *) a);
  710. }
  711. // Complex number routines. All outputs must be non-NULL.
  712. // Magnitude/absolute value.
  713. static double ComplexAbs (const double r, const double i) {
  714. return (sqrt ((r * r) + (i * i)));
  715. }
  716. // Multiply.
  717. static void ComplexMul (const double aR, const double aI, const double bR, const double bI, double * outR, double * outI) {
  718. (* outR) = (aR * bR) - (aI * bI);
  719. (* outI) = (aI * bR) + (aR * bI);
  720. }
  721. // Base-e exponent.
  722. static void ComplexExp (const double inR, const double inI, double * outR, double * outI) {
  723. double e;
  724. e = exp (inR);
  725. (* outR) = e * cos (inI);
  726. (* outI) = e * sin (inI);
  727. }
  728. /* Fast Fourier transform routines. The number of points must be a power of
  729. * two. In-place operation is possible only if both the real and imaginary
  730. * parts are in-place together.
  731. */
  732. // Performs bit-reversal ordering.
  733. static void FftArrange (const uint n, const double * inR, const double * inI, double * outR, double * outI) {
  734. uint rk, k, m;
  735. double tempR, tempI;
  736. if ((inR == outR) && (inI == outI)) {
  737. // Handle in-place arrangement.
  738. rk = 0;
  739. for (k = 0; k < n; k ++) {
  740. if (rk > k) {
  741. tempR = inR [rk];
  742. tempI = inI [rk];
  743. outR [rk] = inR [k];
  744. outI [rk] = inI [k];
  745. outR [k] = tempR;
  746. outI [k] = tempI;
  747. }
  748. m = n;
  749. while (rk & (m >>= 1))
  750. rk &= ~m;
  751. rk |= m;
  752. }
  753. } else {
  754. // Handle copy arrangement.
  755. rk = 0;
  756. for (k = 0; k < n; k ++) {
  757. outR [rk] = inR [k];
  758. outI [rk] = inI [k];
  759. m = n;
  760. while (rk & (m >>= 1))
  761. rk &= ~m;
  762. rk |= m;
  763. }
  764. }
  765. }
  766. // Performs the summation.
  767. static void FftSummation (const uint n, const double s, double * re, double * im) {
  768. double pi;
  769. uint m, m2;
  770. double vR, vI, wR, wI;
  771. uint i, k, mk;
  772. double tR, tI;
  773. pi = s * M_PI;
  774. for (m = 1, m2 = 2; m < n; m <<= 1, m2 <<= 1) {
  775. // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
  776. vR = sin (0.5 * pi / m);
  777. vR = -2.0 * vR * vR;
  778. vI = -sin (pi / m);
  779. // w = Complex (1.0, 0.0)
  780. wR = 1.0;
  781. wI = 0.0;
  782. for (i = 0; i < m; i ++) {
  783. for (k = i; k < n; k += m2) {
  784. mk = k + m;
  785. // t = ComplexMul (w, out [km2])
  786. tR = (wR * re [mk]) - (wI * im [mk]);
  787. tI = (wR * im [mk]) + (wI * re [mk]);
  788. // out [mk] = ComplexSub (out [k], t)
  789. re [mk] = re [k] - tR;
  790. im [mk] = im [k] - tI;
  791. // out [k] = ComplexAdd (out [k], t)
  792. re [k] += tR;
  793. im [k] += tI;
  794. }
  795. // t = ComplexMul (v, w)
  796. tR = (vR * wR) - (vI * wI);
  797. tI = (vR * wI) + (vI * wR);
  798. // w = ComplexAdd (w, t)
  799. wR += tR;
  800. wI += tI;
  801. }
  802. }
  803. }
  804. // Performs a forward FFT.
  805. static void FftForward (const uint n, const double * inR, const double * inI, double * outR, double * outI) {
  806. FftArrange (n, inR, inI, outR, outI);
  807. FftSummation (n, 1.0, outR, outI);
  808. }
  809. // Performs an inverse FFT.
  810. static void FftInverse (const uint n, const double * inR, const double * inI, double * outR, double * outI) {
  811. double f;
  812. uint i;
  813. FftArrange (n, inR, inI, outR, outI);
  814. FftSummation (n, -1.0, outR, outI);
  815. f = 1.0 / n;
  816. for (i = 0; i < n; i ++) {
  817. outR [i] *= f;
  818. outI [i] *= f;
  819. }
  820. }
  821. /* Calculate the complex helical sequence (or discrete-time analytical
  822. * signal) of the given input using the Hilbert transform. Given the
  823. * negative natural logarithm of a signal's magnitude response, the imaginary
  824. * components can be used as the angles for minimum-phase reconstruction.
  825. */
  826. static void Hilbert (const uint n, const double * in, double * outR, double * outI) {
  827. uint i;
  828. if (in == outR) {
  829. // Handle in-place operation.
  830. for (i = 0; i < n; i ++)
  831. outI [i] = 0.0;
  832. } else {
  833. // Handle copy operation.
  834. for (i = 0; i < n; i ++) {
  835. outR [i] = in [i];
  836. outI [i] = 0.0;
  837. }
  838. }
  839. FftForward (n, outR, outI, outR, outI);
  840. /* Currently the Fourier routines operate only on point counts that are
  841. * powers of two. If that changes and n is odd, the following conditional
  842. * should be: i < (n + 1) / 2.
  843. */
  844. for (i = 1; i < (n / 2); i ++) {
  845. outR [i] *= 2.0;
  846. outI [i] *= 2.0;
  847. }
  848. // If n is odd, the following increment should be skipped.
  849. i ++;
  850. for (; i < n; i ++) {
  851. outR [i] = 0.0;
  852. outI [i] = 0.0;
  853. }
  854. FftInverse (n, outR, outI, outR, outI);
  855. }
  856. /* Calculate the magnitude response of the given input. This is used in
  857. * place of phase decomposition, since the phase residuals are discarded for
  858. * minimum phase reconstruction. The mirrored half of the response is also
  859. * discarded.
  860. */
  861. static void MagnitudeResponse (const uint n, const double * inR, const double * inI, double * out) {
  862. const uint m = 1 + (n / 2);
  863. uint i;
  864. for (i = 0; i < m; i ++)
  865. out [i] = fmax (ComplexAbs (inR [i], inI [i]), EPSILON);
  866. }
  867. /* Apply a range limit (in dB) to the given magnitude response. This is used
  868. * to adjust the effects of the diffuse-field average on the equalization
  869. * process.
  870. */
  871. static void LimitMagnitudeResponse (const uint n, const double limit, const double * in, double * out) {
  872. const uint m = 1 + (n / 2);
  873. double halfLim;
  874. uint i, lower, upper;
  875. double ave;
  876. halfLim = limit / 2.0;
  877. // Convert the response to dB.
  878. for (i = 0; i < m; i ++)
  879. out [i] = 20.0 * log10 (in [i]);
  880. // Use six octaves to calculate the average magnitude of the signal.
  881. lower = ((uint) ceil (n / pow (2.0, 8.0))) - 1;
  882. upper = ((uint) floor (n / pow (2.0, 2.0))) - 1;
  883. ave = 0.0;
  884. for (i = lower; i <= upper; i ++)
  885. ave += out [i];
  886. ave /= upper - lower + 1;
  887. // Keep the response within range of the average magnitude.
  888. for (i = 0; i < m; i ++)
  889. out [i] = Clamp (out [i], ave - halfLim, ave + halfLim);
  890. // Convert the response back to linear magnitude.
  891. for (i = 0; i < m; i ++)
  892. out [i] = pow (10.0, out [i] / 20.0);
  893. }
  894. /* Reconstructs the minimum-phase component for the given magnitude response
  895. * of a signal. This is equivalent to phase recomposition, sans the missing
  896. * residuals (which were discarded). The mirrored half of the response is
  897. * reconstructed.
  898. */
  899. static void MinimumPhase (const uint n, const double * in, double * outR, double * outI) {
  900. const uint m = 1 + (n / 2);
  901. double * mags = NULL;
  902. uint i;
  903. double aR, aI;
  904. mags = CreateArray (n);
  905. for (i = 0; i < m; i ++) {
  906. mags [i] = fmax (in [i], EPSILON);
  907. outR [i] = -log (mags [i]);
  908. }
  909. for (; i < n; i ++) {
  910. mags [i] = mags [n - i];
  911. outR [i] = outR [n - i];
  912. }
  913. Hilbert (n, outR, outR, outI);
  914. // Remove any DC offset the filter has.
  915. outR [0] = 0.0;
  916. outI [0] = 0.0;
  917. for (i = 1; i < n; i ++) {
  918. ComplexExp (0.0, outI [i], & aR, & aI);
  919. ComplexMul (mags [i], 0.0, aR, aI, & outR [i], & outI [i]);
  920. }
  921. DestroyArray (mags);
  922. }
  923. /* This is the normalized cardinal sine (sinc) function.
  924. *
  925. * sinc(x) = { 1, x = 0
  926. * { sin(pi x) / (pi x), otherwise.
  927. */
  928. static double Sinc (const double x) {
  929. if (fabs (x) < EPSILON)
  930. return (1.0);
  931. return (sin (M_PI * x) / (M_PI * x));
  932. }
  933. /* The zero-order modified Bessel function of the first kind, used for the
  934. * Kaiser window.
  935. *
  936. * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
  937. * = sum_{k=0}^inf ((x / 2)^k / k!)^2
  938. */
  939. static double BesselI_0 (const double x) {
  940. double term, sum, x2, y, last_sum;
  941. int k;
  942. // Start at k=1 since k=0 is trivial.
  943. term = 1.0;
  944. sum = 1.0;
  945. x2 = x / 2.0;
  946. k = 1;
  947. // Let the integration converge until the term of the sum is no longer
  948. // significant.
  949. do {
  950. y = x2 / k;
  951. k ++;
  952. last_sum = sum;
  953. term *= y * y;
  954. sum += term;
  955. } while (sum != last_sum);
  956. return (sum);
  957. }
  958. /* Calculate a Kaiser window from the given beta value and a normalized k
  959. * [-1, 1].
  960. *
  961. * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
  962. * { 0, elsewhere.
  963. *
  964. * Where k can be calculated as:
  965. *
  966. * k = i / l, where -l <= i <= l.
  967. *
  968. * or:
  969. *
  970. * k = 2 i / M - 1, where 0 <= i <= M.
  971. */
  972. static double Kaiser (const double b, const double k) {
  973. double k2;
  974. k2 = Clamp (k, -1.0, 1.0);
  975. if ((k < -1.0) || (k > 1.0))
  976. return (0.0);
  977. k2 *= k2;
  978. return (BesselI_0 (b * sqrt (1.0 - k2)) / BesselI_0 (b));
  979. }
  980. // Calculates the greatest common divisor of a and b.
  981. static uint Gcd (const uint a, const uint b) {
  982. uint x, y, z;
  983. x = a;
  984. y = b;
  985. while (y > 0) {
  986. z = y;
  987. y = x % y;
  988. x = z;
  989. }
  990. return (x);
  991. }
  992. /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
  993. * the transition width is normalized frequency (0.5 is nyquist).
  994. *
  995. * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
  996. * { ceil(5.79 / 2 pi f_t), r <= 21.
  997. *
  998. */
  999. static uint CalcKaiserOrder (const double rejection, const double transition) {
  1000. double w_t;
  1001. w_t = 2.0 * M_PI * transition;
  1002. if (rejection > 21.0)
  1003. return ((uint) ceil ((rejection - 7.95) / (2.285 * w_t)));
  1004. return ((uint) ceil (5.79 / w_t));
  1005. }
  1006. // Calculates the beta value of the Kaiser window. Rejection is in dB.
  1007. static double CalcKaiserBeta (const double rejection) {
  1008. if (rejection > 50.0)
  1009. return (0.1102 * (rejection - 8.7));
  1010. else if (rejection >= 21.0)
  1011. return ((0.5842 * pow (rejection - 21.0, 0.4)) +
  1012. (0.07886 * (rejection - 21.0)));
  1013. else
  1014. return (0.0);
  1015. }
  1016. /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
  1017. * width, beta, gain, and cutoff. The point is specified in non-normalized
  1018. * samples, from 0 to M, where M = (2 l + 1).
  1019. *
  1020. * w(k) 2 p f_t sinc(2 f_t x)
  1021. *
  1022. * x -- centered sample index (i - l)
  1023. * k -- normalized and centered window index (x / l)
  1024. * w(k) -- window function (Kaiser)
  1025. * p -- gain compensation factor when sampling
  1026. * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
  1027. */
  1028. static double SincFilter (const int l, const double b, const double gain, const double cutoff, const int i) {
  1029. return (Kaiser (b, ((double) (i - l)) / l) * 2.0 * gain * cutoff * Sinc (2.0 * cutoff * (i - l)));
  1030. }
  1031. /* This is a polyphase sinc-filtered resampler.
  1032. *
  1033. * Upsample Downsample
  1034. *
  1035. * p/q = 3/2 p/q = 3/5
  1036. *
  1037. * M-+-+-+-> M-+-+-+->
  1038. * -------------------+ ---------------------+
  1039. * p s * f f f f|f| | p s * f f f f f |
  1040. * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
  1041. * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
  1042. * s * f|f|f f f | s * f f|f|f f |
  1043. * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
  1044. * --------+=+--------+ 0 * |0|0 0 0 0 |
  1045. * d . d .|d|. d . d ----------+=+--------+
  1046. * d . . . .|d|. . . .
  1047. * q->
  1048. * q-+-+-+->
  1049. *
  1050. * P_f(i,j) = q i mod p + pj
  1051. * P_s(i,j) = floor(q i / p) - j
  1052. * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
  1053. * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
  1054. * { 0, P_f(i,j) >= M. }
  1055. */
  1056. // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
  1057. // that's used to cut frequencies above the destination nyquist.
  1058. static void ResamplerSetup (ResamplerT * rs, const uint srcRate, const uint dstRate) {
  1059. uint gcd, l;
  1060. double cutoff, width, beta;
  1061. int i;
  1062. gcd = Gcd (srcRate, dstRate);
  1063. rs -> mP = dstRate / gcd;
  1064. rs -> mQ = srcRate / gcd;
  1065. /* The cutoff is adjusted by half the transition width, so the transition
  1066. * ends before the nyquist (0.5). Both are scaled by the downsampling
  1067. * factor.
  1068. */
  1069. if (rs -> mP > rs -> mQ) {
  1070. cutoff = 0.45 / rs -> mP;
  1071. width = 0.1 / rs -> mP;
  1072. } else {
  1073. cutoff = 0.45 / rs -> mQ;
  1074. width = 0.1 / rs -> mQ;
  1075. }
  1076. // A rejection of -180 dB is used for the stop band.
  1077. l = CalcKaiserOrder (180.0, width) / 2;
  1078. beta = CalcKaiserBeta (180.0);
  1079. rs -> mM = (2 * l) + 1;
  1080. rs -> mL = l;
  1081. rs -> mF = CreateArray (rs -> mM);
  1082. for (i = 0; i < ((int) rs -> mM); i ++)
  1083. rs -> mF [i] = SincFilter ((int) l, beta, rs -> mP, cutoff, i);
  1084. }
  1085. // Clean up after the resampler.
  1086. static void ResamplerClear (ResamplerT * rs) {
  1087. DestroyArray (rs -> mF);
  1088. rs -> mF = NULL;
  1089. }
  1090. // Perform the upsample-filter-downsample resampling operation using a
  1091. // polyphase filter implementation.
  1092. static void ResamplerRun (ResamplerT * rs, const uint inN, const double * in, const uint outN, double * out) {
  1093. const uint p = rs -> mP, q = rs -> mQ, m = rs -> mM, l = rs -> mL;
  1094. const double * f = rs -> mF;
  1095. double * work = NULL;
  1096. uint i;
  1097. double r;
  1098. uint j_f, j_s;
  1099. // Handle in-place operation.
  1100. if (in == out)
  1101. work = CreateArray (outN);
  1102. else
  1103. work = out;
  1104. // Resample the input.
  1105. for (i = 0; i < outN; i ++) {
  1106. r = 0.0;
  1107. // Input starts at l to compensate for the filter delay. This will
  1108. // drop any build-up from the first half of the filter.
  1109. j_f = (l + (q * i)) % p;
  1110. j_s = (l + (q * i)) / p;
  1111. while (j_f < m) {
  1112. // Only take input when 0 <= j_s < inN. This single unsigned
  1113. // comparison catches both cases.
  1114. if (j_s < inN)
  1115. r += f [j_f] * in [j_s];
  1116. j_f += p;
  1117. j_s --;
  1118. }
  1119. work [i] = r;
  1120. }
  1121. // Clean up after in-place operation.
  1122. if (in == out) {
  1123. for (i = 0; i < outN; i ++)
  1124. out [i] = work [i];
  1125. DestroyArray (work);
  1126. }
  1127. }
  1128. // Read a binary value of the specified byte order and byte size from a file,
  1129. // storing it as a 32-bit unsigned integer.
  1130. static int ReadBin4 (FILE * fp, const char * filename, const ByteOrderT order, const uint bytes, uint4 * out) {
  1131. uint1 in [4];
  1132. uint4 accum;
  1133. uint i;
  1134. if (fread (in, 1, bytes, fp) != bytes) {
  1135. fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
  1136. return (0);
  1137. }
  1138. accum = 0;
  1139. switch (order) {
  1140. case BO_LITTLE :
  1141. for (i = 0; i < bytes; i ++)
  1142. accum = (accum << 8) | in [bytes - i - 1];
  1143. break;
  1144. case BO_BIG :
  1145. for (i = 0; i < bytes; i ++)
  1146. accum = (accum << 8) | in [i];
  1147. break;
  1148. default :
  1149. break;
  1150. }
  1151. (* out) = accum;
  1152. return (1);
  1153. }
  1154. // Read a binary value of the specified byte order from a file, storing it as
  1155. // a 64-bit unsigned integer.
  1156. static int ReadBin8 (FILE * fp, const char * filename, const ByteOrderT order, uint8 * out) {
  1157. uint1 in [8];
  1158. uint8 accum;
  1159. uint i;
  1160. if (fread (in, 1, 8, fp) != 8) {
  1161. fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
  1162. return (0);
  1163. }
  1164. accum = 0ULL;
  1165. switch (order) {
  1166. case BO_LITTLE :
  1167. for (i = 0; i < 8; i ++)
  1168. accum = (accum << 8) | in [8 - i - 1];
  1169. break;
  1170. case BO_BIG :
  1171. for (i = 0; i < 8; i ++)
  1172. accum = (accum << 8) | in [i];
  1173. break;
  1174. default :
  1175. break;
  1176. }
  1177. (* out) = accum;
  1178. return (1);
  1179. }
  1180. // Write an ASCII string to a file.
  1181. static int WriteAscii (const char * out, FILE * fp, const char * filename) {
  1182. size_t len;
  1183. len = strlen (out);
  1184. if (fwrite (out, 1, len, fp) != len) {
  1185. fclose (fp);
  1186. fprintf (stderr, "Error: Bad write to file '%s'.\n", filename);
  1187. return (0);
  1188. }
  1189. return (1);
  1190. }
  1191. // Write a binary value of the given byte order and byte size to a file,
  1192. // loading it from a 32-bit unsigned integer.
  1193. static int WriteBin4 (const ByteOrderT order, const uint bytes, const uint4 in, FILE * fp, const char * filename) {
  1194. uint1 out [4];
  1195. uint i;
  1196. switch (order) {
  1197. case BO_LITTLE :
  1198. for (i = 0; i < bytes; i ++)
  1199. out [i] = (in >> (i * 8)) & 0x000000FF;
  1200. break;
  1201. case BO_BIG :
  1202. for (i = 0; i < bytes; i ++)
  1203. out [bytes - i - 1] = (in >> (i * 8)) & 0x000000FF;
  1204. break;
  1205. default :
  1206. break;
  1207. }
  1208. if (fwrite (out, 1, bytes, fp) != bytes) {
  1209. fprintf (stderr, "Error: Bad write to file '%s'.\n", filename);
  1210. return (0);
  1211. }
  1212. return (1);
  1213. }
  1214. /* Read a binary value of the specified type, byte order, and byte size from
  1215. * a file, converting it to a double. For integer types, the significant
  1216. * bits are used to normalize the result. The sign of bits determines
  1217. * whether they are padded toward the MSB (negative) or LSB (positive).
  1218. * Floating-point types are not normalized.
  1219. */
  1220. static int ReadBinAsDouble (FILE * fp, const char * filename, const ByteOrderT order, const ElementTypeT type, const uint bytes, const int bits, double * out) {
  1221. union {
  1222. uint4 ui;
  1223. int4 i;
  1224. float f;
  1225. } v4;
  1226. union {
  1227. uint8 ui;
  1228. double f;
  1229. } v8;
  1230. (* out) = 0.0;
  1231. if (bytes > 4) {
  1232. if (! ReadBin8 (fp, filename, order, & v8 . ui))
  1233. return (0);
  1234. if (type == ET_FP)
  1235. (* out) = v8 . f;
  1236. } else {
  1237. if (! ReadBin4 (fp, filename, order, bytes, & v4 . ui))
  1238. return (0);
  1239. if (type == ET_FP) {
  1240. (* out) = (double) v4 . f;
  1241. } else {
  1242. if (bits > 0)
  1243. v4 . ui >>= (8 * bytes) - ((uint) bits);
  1244. else
  1245. v4 . ui &= (0xFFFFFFFF >> (32 + bits));
  1246. if (v4 . ui & ((uint) (1 << (abs (bits) - 1))))
  1247. v4 . ui |= (0xFFFFFFFF << abs (bits));
  1248. (* out) = v4 . i / ((double) (1 << (abs (bits) - 1)));
  1249. }
  1250. }
  1251. return (1);
  1252. }
  1253. /* Read an ascii value of the specified type from a file, converting it to a
  1254. * double. For integer types, the significant bits are used to normalize the
  1255. * result. The sign of the bits should always be positive. This also skips
  1256. * up to one separator character before the element itself.
  1257. */
  1258. static int ReadAsciiAsDouble (TokenReaderT * tr, const char * filename, const ElementTypeT type, const uint bits, double * out) {
  1259. int v;
  1260. if (TrIsOperator (tr, ","))
  1261. TrReadOperator (tr, ",");
  1262. else if (TrIsOperator (tr, ":"))
  1263. TrReadOperator (tr, ":");
  1264. else if (TrIsOperator (tr, ";"))
  1265. TrReadOperator (tr, ";");
  1266. else if (TrIsOperator (tr, "|"))
  1267. TrReadOperator (tr, "|");
  1268. if (type == ET_FP) {
  1269. if (! TrReadFloat (tr, -HUGE_VAL, HUGE_VAL, out)) {
  1270. fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
  1271. return (0);
  1272. }
  1273. } else {
  1274. if (! TrReadInt (tr, -(1 << (bits - 1)), (1 << (bits - 1)) - 1, & v)) {
  1275. fprintf (stderr, "Error: Bad read from file '%s'.\n", filename);
  1276. return (0);
  1277. }
  1278. (* out) = v / ((double) ((1 << (bits - 1)) - 1));
  1279. }
  1280. return (1);
  1281. }
  1282. // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
  1283. // the source parameters and data set metrics.
  1284. static int ReadWaveFormat (FILE * fp, const ByteOrderT order, const uint hrirRate, SourceRefT * src) {
  1285. uint4 fourCC, chunkSize;
  1286. uint4 format, channels, rate, dummy, block, size, bits;
  1287. chunkSize = 0;
  1288. do {
  1289. if (chunkSize > 0)
  1290. fseek (fp, (long) chunkSize, SEEK_CUR);
  1291. if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
  1292. (! ReadBin4 (fp, src -> mPath, order, 4, & chunkSize)))
  1293. return (0);
  1294. } while (fourCC != FOURCC_FMT);
  1295. if ((! ReadBin4 (fp, src -> mPath, order, 2, & format)) ||
  1296. (! ReadBin4 (fp, src -> mPath, order, 2, & channels)) ||
  1297. (! ReadBin4 (fp, src -> mPath, order, 4, & rate)) ||
  1298. (! ReadBin4 (fp, src -> mPath, order, 4, & dummy)) ||
  1299. (! ReadBin4 (fp, src -> mPath, order, 2, & block)))
  1300. return (0);
  1301. block /= channels;
  1302. if (chunkSize > 14) {
  1303. if (! ReadBin4 (fp, src -> mPath, order, 2, & size))
  1304. return (0);
  1305. size /= 8;
  1306. if (block > size)
  1307. size = block;
  1308. } else {
  1309. size = block;
  1310. }
  1311. if (format == WAVE_FORMAT_EXTENSIBLE) {
  1312. fseek (fp, 2, SEEK_CUR);
  1313. if (! ReadBin4 (fp, src -> mPath, order, 2, & bits))
  1314. return (0);
  1315. if (bits == 0)
  1316. bits = 8 * size;
  1317. fseek (fp, 4, SEEK_CUR);
  1318. if (! ReadBin4 (fp, src -> mPath, order, 2, & format))
  1319. return (0);
  1320. fseek (fp, (long) (chunkSize - 26), SEEK_CUR);
  1321. } else {
  1322. bits = 8 * size;
  1323. if (chunkSize > 14)
  1324. fseek (fp, (long) (chunkSize - 16), SEEK_CUR);
  1325. else
  1326. fseek (fp, (long) (chunkSize - 14), SEEK_CUR);
  1327. }
  1328. if ((format != WAVE_FORMAT_PCM) && (format != WAVE_FORMAT_IEEE_FLOAT)) {
  1329. fprintf (stderr, "Error: Unsupported WAVE format in file '%s'.\n", src -> mPath);
  1330. return (0);
  1331. }
  1332. if (src -> mChannel >= channels) {
  1333. fprintf (stderr, "Error: Missing source channel in WAVE file '%s'.\n", src -> mPath);
  1334. return (0);
  1335. }
  1336. if (rate != hrirRate) {
  1337. fprintf (stderr, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src -> mPath);
  1338. return (0);
  1339. }
  1340. if (format == WAVE_FORMAT_PCM) {
  1341. if ((size < 2) || (size > 4)) {
  1342. fprintf (stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src -> mPath);
  1343. return (0);
  1344. }
  1345. if ((bits < 16) || (bits > (8 * size))) {
  1346. fprintf (stderr, "Error: Bad significant bits in WAVE file '%s'.\n", src -> mPath);
  1347. return (0);
  1348. }
  1349. src -> mType = ET_INT;
  1350. } else {
  1351. if ((size != 4) && (size != 8)) {
  1352. fprintf (stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src -> mPath);
  1353. return (0);
  1354. }
  1355. src -> mType = ET_FP;
  1356. }
  1357. src -> mSize = size;
  1358. src -> mBits = (int) bits;
  1359. src -> mSkip = channels;
  1360. return (1);
  1361. }
  1362. // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
  1363. static int ReadWaveData (FILE * fp, const SourceRefT * src, const ByteOrderT order, const uint n, double * hrir) {
  1364. int pre, post, skip;
  1365. uint i;
  1366. pre = (int) (src -> mSize * src -> mChannel);
  1367. post = (int) (src -> mSize * (src -> mSkip - src -> mChannel - 1));
  1368. skip = 0;
  1369. for (i = 0; i < n; i ++) {
  1370. skip += pre;
  1371. if (skip > 0)
  1372. fseek (fp, skip, SEEK_CUR);
  1373. if (! ReadBinAsDouble (fp, src -> mPath, order, src -> mType, src -> mSize, src -> mBits, & hrir [i]))
  1374. return (0);
  1375. skip = post;
  1376. }
  1377. if (skip > 0)
  1378. fseek (fp, skip, SEEK_CUR);
  1379. return (1);
  1380. }
  1381. // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
  1382. // doubles.
  1383. static int ReadWaveList (FILE * fp, const SourceRefT * src, const ByteOrderT order, const uint n, double * hrir) {
  1384. uint4 fourCC, chunkSize, listSize, count;
  1385. uint block, skip, offset, i;
  1386. double lastSample;
  1387. for (;;) {
  1388. if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
  1389. (! ReadBin4 (fp, src -> mPath, order, 4, & chunkSize)))
  1390. return (0);
  1391. if (fourCC == FOURCC_DATA) {
  1392. block = src -> mSize * src -> mSkip;
  1393. count = chunkSize / block;
  1394. if (count < (src -> mOffset + n)) {
  1395. fprintf (stderr, "Error: Bad read from file '%s'.\n", src -> mPath);
  1396. return (0);
  1397. }
  1398. fseek (fp, (long) (src -> mOffset * block), SEEK_CUR);
  1399. if (! ReadWaveData (fp, src, order, n, & hrir [0]))
  1400. return (0);
  1401. return (1);
  1402. } else if (fourCC == FOURCC_LIST) {
  1403. if (! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC))
  1404. return (0);
  1405. chunkSize -= 4;
  1406. if (fourCC == FOURCC_WAVL)
  1407. break;
  1408. }
  1409. if (chunkSize > 0)
  1410. fseek (fp, (long) chunkSize, SEEK_CUR);
  1411. }
  1412. listSize = chunkSize;
  1413. block = src -> mSize * src -> mSkip;
  1414. skip = src -> mOffset;
  1415. offset = 0;
  1416. lastSample = 0.0;
  1417. while ((offset < n) && (listSize > 8)) {
  1418. if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
  1419. (! ReadBin4 (fp, src -> mPath, order, 4, & chunkSize)))
  1420. return (0);
  1421. listSize -= 8 + chunkSize;
  1422. if (fourCC == FOURCC_DATA) {
  1423. count = chunkSize / block;
  1424. if (count > skip) {
  1425. fseek (fp, (long) (skip * block), SEEK_CUR);
  1426. chunkSize -= skip * block;
  1427. count -= skip;
  1428. skip = 0;
  1429. if (count > (n - offset))
  1430. count = n - offset;
  1431. if (! ReadWaveData (fp, src, order, count, & hrir [offset]))
  1432. return (0);
  1433. chunkSize -= count * block;
  1434. offset += count;
  1435. lastSample = hrir [offset - 1];
  1436. } else {
  1437. skip -= count;
  1438. count = 0;
  1439. }
  1440. } else if (fourCC == FOURCC_SLNT) {
  1441. if (! ReadBin4 (fp, src -> mPath, order, 4, & count))
  1442. return (0);
  1443. chunkSize -= 4;
  1444. if (count > skip) {
  1445. count -= skip;
  1446. skip = 0;
  1447. if (count > (n - offset))
  1448. count = n - offset;
  1449. for (i = 0; i < count; i ++)
  1450. hrir [offset + i] = lastSample;
  1451. offset += count;
  1452. } else {
  1453. skip -= count;
  1454. count = 0;
  1455. }
  1456. }
  1457. if (chunkSize > 0)
  1458. fseek (fp, (long) chunkSize, SEEK_CUR);
  1459. }
  1460. if (offset < n) {
  1461. fprintf (stderr, "Error: Bad read from file '%s'.\n", src -> mPath);
  1462. return (0);
  1463. }
  1464. return (1);
  1465. }
  1466. // Load a source HRIR from a RIFF/RIFX WAVE file.
  1467. static int LoadWaveSource (FILE * fp, SourceRefT * src, const uint hrirRate, const uint n, double * hrir) {
  1468. uint4 fourCC, dummy;
  1469. ByteOrderT order;
  1470. if ((! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC)) ||
  1471. (! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & dummy)))
  1472. return (0);
  1473. if (fourCC == FOURCC_RIFF) {
  1474. order = BO_LITTLE;
  1475. } else if (fourCC == FOURCC_RIFX) {
  1476. order = BO_BIG;
  1477. } else {
  1478. fprintf (stderr, "Error: No RIFF/RIFX chunk in file '%s'.\n", src -> mPath);
  1479. return (0);
  1480. }
  1481. if (! ReadBin4 (fp, src -> mPath, BO_LITTLE, 4, & fourCC))
  1482. return (0);
  1483. if (fourCC != FOURCC_WAVE) {
  1484. fprintf (stderr, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src -> mPath);
  1485. return (0);
  1486. }
  1487. if (! ReadWaveFormat (fp, order, hrirRate, src))
  1488. return (0);
  1489. if (! ReadWaveList (fp, src, order, n, hrir))
  1490. return (0);
  1491. return (1);
  1492. }
  1493. // Load a source HRIR from a binary file.
  1494. static int LoadBinarySource (FILE * fp, const SourceRefT * src, const ByteOrderT order, const uint n, double * hrir) {
  1495. uint i;
  1496. fseek (fp, (long) src -> mOffset, SEEK_SET);
  1497. for (i = 0; i < n; i ++) {
  1498. if (! ReadBinAsDouble (fp, src -> mPath, order, src -> mType, src -> mSize, src -> mBits, & hrir [i]))
  1499. return (0);
  1500. if (src -> mSkip > 0)
  1501. fseek (fp, (long) src -> mSkip, SEEK_CUR);
  1502. }
  1503. return (1);
  1504. }
  1505. // Load a source HRIR from an ASCII text file containing a list of elements
  1506. // separated by whitespace or common list operators (',', ';', ':', '|').
  1507. static int LoadAsciiSource (FILE * fp, const SourceRefT * src, const uint n, double * hrir) {
  1508. TokenReaderT tr;
  1509. uint i, j;
  1510. double dummy;
  1511. TrSetup (fp, NULL, & tr);
  1512. for (i = 0; i < src -> mOffset; i ++) {
  1513. if (! ReadAsciiAsDouble (& tr, src -> mPath, src -> mType, (uint) src -> mBits, & dummy))
  1514. return (0);
  1515. }
  1516. for (i = 0; i < n; i ++) {
  1517. if (! ReadAsciiAsDouble (& tr, src -> mPath, src -> mType, (uint) src -> mBits, & hrir [i]))
  1518. return (0);
  1519. for (j = 0; j < src -> mSkip; j ++) {
  1520. if (! ReadAsciiAsDouble (& tr, src -> mPath, src -> mType, (uint) src -> mBits, & dummy))
  1521. return (0);
  1522. }
  1523. }
  1524. return (1);
  1525. }
  1526. // Load a source HRIR from a supported file type.
  1527. static int LoadSource (SourceRefT * src, const uint hrirRate, const uint n, double * hrir) {
  1528. FILE * fp = NULL;
  1529. int result;
  1530. if (src -> mFormat == SF_ASCII)
  1531. fp = fopen (src -> mPath, "r");
  1532. else
  1533. fp = fopen (src -> mPath, "rb");
  1534. if (fp == NULL) {
  1535. fprintf (stderr, "Error: Could not open source file '%s'.\n", src -> mPath);
  1536. return (0);
  1537. }
  1538. if (src -> mFormat == SF_WAVE)
  1539. result = LoadWaveSource (fp, src, hrirRate, n, hrir);
  1540. else if (src -> mFormat == SF_BIN_LE)
  1541. result = LoadBinarySource (fp, src, BO_LITTLE, n, hrir);
  1542. else if (src -> mFormat == SF_BIN_BE)
  1543. result = LoadBinarySource (fp, src, BO_BIG, n, hrir);
  1544. else
  1545. result = LoadAsciiSource (fp, src, n, hrir);
  1546. fclose (fp);
  1547. return (result);
  1548. }
  1549. // Calculate the onset time of an HRIR and average it with any existing
  1550. // timing for its elevation and azimuth.
  1551. static void AverageHrirOnset (const double * hrir, const double f, const uint ei, const uint ai, const HrirDataT * hData) {
  1552. double mag;
  1553. uint n, i, j;
  1554. mag = 0.0;
  1555. n = hData -> mIrPoints;
  1556. for (i = 0; i < n; i ++)
  1557. mag = fmax (fabs (hrir [i]), mag);
  1558. mag *= 0.15;
  1559. for (i = 0; i < n; i ++) {
  1560. if (fabs (hrir [i]) >= mag)
  1561. break;
  1562. }
  1563. j = hData -> mEvOffset [ei] + ai;
  1564. hData -> mHrtds [j] = Lerp (hData -> mHrtds [j], ((double) i) / hData -> mIrRate, f);
  1565. }
  1566. // Calculate the magnitude response of an HRIR and average it with any
  1567. // existing responses for its elevation and azimuth.
  1568. static void AverageHrirMagnitude (const double * hrir, const double f, const uint ei, const uint ai, const HrirDataT * hData) {
  1569. double * re = NULL, * im = NULL;
  1570. uint n, m, i, j;
  1571. n = hData -> mFftSize;
  1572. re = CreateArray (n);
  1573. im = CreateArray (n);
  1574. for (i = 0; i < hData -> mIrPoints; i ++) {
  1575. re [i] = hrir [i];
  1576. im [i] = 0.0;
  1577. }
  1578. for (; i < n; i ++) {
  1579. re [i] = 0.0;
  1580. im [i] = 0.0;
  1581. }
  1582. FftForward (n, re, im, re, im);
  1583. MagnitudeResponse (n, re, im, re);
  1584. m = 1 + (n / 2);
  1585. j = (hData -> mEvOffset [ei] + ai) * hData -> mIrSize;
  1586. for (i = 0; i < m; i ++)
  1587. hData -> mHrirs [j + i] = Lerp (hData -> mHrirs [j + i], re [i], f);
  1588. DestroyArray (im);
  1589. DestroyArray (re);
  1590. }
  1591. /* Calculate the contribution of each HRIR to the diffuse-field average based
  1592. * on the area of its surface patch. All patches are centered at the HRIR
  1593. * coordinates on the unit sphere and are measured by solid angle.
  1594. */
  1595. static void CalculateDfWeights (const HrirDataT * hData, double * weights) {
  1596. uint ei;
  1597. double evs, sum, ev, up_ev, down_ev, solidAngle;
  1598. evs = 90.0 / (hData -> mEvCount - 1);
  1599. sum = 0.0;
  1600. for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++) {
  1601. // For each elevation, calculate the upper and lower limits of the
  1602. // patch band.
  1603. ev = -90.0 + (ei * 2.0 * evs);
  1604. if (ei < (hData -> mEvCount - 1))
  1605. up_ev = (ev + evs) * M_PI / 180.0;
  1606. else
  1607. up_ev = M_PI / 2.0;
  1608. if (ei > 0)
  1609. down_ev = (ev - evs) * M_PI / 180.0;
  1610. else
  1611. down_ev = -M_PI / 2.0;
  1612. // Calculate the area of the patch band.
  1613. solidAngle = 2.0 * M_PI * (sin (up_ev) - sin (down_ev));
  1614. // Each weight is the area of one patch.
  1615. weights [ei] = solidAngle / hData -> mAzCount [ei];
  1616. // Sum the total surface area covered by the HRIRs.
  1617. sum += solidAngle;
  1618. }
  1619. // Normalize the weights given the total surface coverage.
  1620. for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++)
  1621. weights [ei] /= sum;
  1622. }
  1623. /* Calculate the diffuse-field average from the given magnitude responses of
  1624. * the HRIR set. Weighting can be applied to compensate for the varying
  1625. * surface area covered by each HRIR. The final average can then be limited
  1626. * by the specified magnitude range (in positive dB; 0.0 to skip).
  1627. */
  1628. static void CalculateDiffuseFieldAverage (const HrirDataT * hData, const int weighted, const double limit, double * dfa) {
  1629. double * weights = NULL;
  1630. uint ei, ai, count, step, start, end, m, j, i;
  1631. double weight;
  1632. weights = CreateArray (hData -> mEvCount);
  1633. if (weighted) {
  1634. // Use coverage weighting to calculate the average.
  1635. CalculateDfWeights (hData, weights);
  1636. } else {
  1637. // If coverage weighting is not used, the weights still need to be
  1638. // averaged by the number of HRIRs.
  1639. count = 0;
  1640. for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++)
  1641. count += hData -> mAzCount [ei];
  1642. for (ei = hData -> mEvStart; ei < hData -> mEvCount; ei ++)
  1643. weights [ei] = 1.0 / count;
  1644. }
  1645. ei = hData -> mEvStart;
  1646. ai = 0;
  1647. step = hData -> mIrSize;
  1648. start = hData -> mEvOffset [ei] * step;
  1649. end = hData -> mIrCount * step;
  1650. m = 1 + (hData -> mFftSize / 2);
  1651. for (i = 0; i < m; i ++)
  1652. dfa [i] = 0.0;
  1653. for (j = start; j < end; j += step) {
  1654. // Get the weight for this HRIR's contribution.
  1655. weight = weights [ei];
  1656. // Add this HRIR's weighted power average to the total.
  1657. for (i = 0; i < m; i ++)
  1658. dfa [i] += weight * hData -> mHrirs [j + i] * hData -> mHrirs [j + i];
  1659. // Determine the next weight to use.
  1660. ai ++;
  1661. if (ai >= hData -> mAzCount [ei]) {
  1662. ei ++;
  1663. ai = 0;
  1664. }
  1665. }
  1666. // Finish the average calculation and keep it from being too small.
  1667. for (i = 0; i < m; i ++)
  1668. dfa [i] = fmax (sqrt (dfa [i]), EPSILON);
  1669. // Apply a limit to the magnitude range of the diffuse-field average if
  1670. // desired.
  1671. if (limit > 0.0)
  1672. LimitMagnitudeResponse (hData -> mFftSize, limit, dfa, dfa);
  1673. DestroyArray (weights);
  1674. }
  1675. // Perform diffuse-field equalization on the magnitude responses of the HRIR
  1676. // set using the given average response.
  1677. static void DiffuseFieldEqualize (const double * dfa, const HrirDataT * hData) {
  1678. uint step, start, end, m, j, i;
  1679. step = hData -> mIrSize;
  1680. start = hData -> mEvOffset [hData -> mEvStart] * step;
  1681. end = hData -> mIrCount * step;
  1682. m = 1 + (hData -> mFftSize / 2);
  1683. for (j = start; j < end; j += step) {
  1684. for (i = 0; i < m; i ++)
  1685. hData -> mHrirs [j + i] /= dfa [i];
  1686. }
  1687. }
  1688. // Perform minimum-phase reconstruction using the magnitude responses of the
  1689. // HRIR set.
  1690. static void ReconstructHrirs (const HrirDataT * hData) {
  1691. double * re = NULL, * im = NULL;
  1692. uint step, start, end, n, j, i;
  1693. step = hData -> mIrSize;
  1694. start = hData -> mEvOffset [hData -> mEvStart] * step;
  1695. end = hData -> mIrCount * step;
  1696. n = hData -> mFftSize;
  1697. re = CreateArray (n);
  1698. im = CreateArray (n);
  1699. for (j = start; j < end; j += step) {
  1700. MinimumPhase (n, & hData -> mHrirs [j], re, im);
  1701. FftInverse (n, re, im, re, im);
  1702. for (i = 0; i < hData -> mIrPoints; i ++)
  1703. hData -> mHrirs [j + i] = re [i];
  1704. }
  1705. DestroyArray (im);
  1706. DestroyArray (re);
  1707. }
  1708. // Resamples the HRIRs for use at the given sampling rate.
  1709. static void ResampleHrirs (const uint rate, HrirDataT * hData) {
  1710. ResamplerT rs;
  1711. uint n, step, start, end, j;
  1712. ResamplerSetup (& rs, hData -> mIrRate, rate);
  1713. n = hData -> mIrPoints;
  1714. step = hData -> mIrSize;
  1715. start = hData -> mEvOffset [hData -> mEvStart] * step;
  1716. end = hData -> mIrCount * step;
  1717. for (j = start; j < end; j += step)
  1718. ResamplerRun (& rs, n, & hData -> mHrirs [j], n, & hData -> mHrirs [j]);
  1719. ResamplerClear (& rs);
  1720. hData -> mIrRate = rate;
  1721. }
  1722. /* Given an elevation index and an azimuth, calculate the indices of the two
  1723. * HRIRs that bound the coordinate along with a factor for calculating the
  1724. * continous HRIR using interpolation.
  1725. */
  1726. static void CalcAzIndices (const HrirDataT * hData, const uint ei, const double az, uint * j0, uint * j1, double * jf) {
  1727. double af;
  1728. uint ai;
  1729. af = ((2.0 * M_PI) + az) * hData -> mAzCount [ei] / (2.0 * M_PI);
  1730. ai = ((uint) af) % hData -> mAzCount [ei];
  1731. af -= floor (af);
  1732. (* j0) = hData -> mEvOffset [ei] + ai;
  1733. (* j1) = hData -> mEvOffset [ei] + ((ai + 1) % hData -> mAzCount [ei]);
  1734. (* jf) = af;
  1735. }
  1736. // Synthesize any missing onset timings at the bottom elevations. This just
  1737. // blends between slightly exaggerated known onsets. Not an accurate model.
  1738. static void SynthesizeOnsets (HrirDataT * hData) {
  1739. uint oi, e, a, j0, j1;
  1740. double t, of, jf;
  1741. oi = hData -> mEvStart;
  1742. t = 0.0;
  1743. for (a = 0; a < hData -> mAzCount [oi]; a ++)
  1744. t += hData -> mHrtds [hData -> mEvOffset [oi] + a];
  1745. hData -> mHrtds [0] = 1.32e-4 + (t / hData -> mAzCount [oi]);
  1746. for (e = 1; e < hData -> mEvStart; e ++) {
  1747. of = ((double) e) / hData -> mEvStart;
  1748. for (a = 0; a < hData -> mAzCount [e]; a ++) {
  1749. CalcAzIndices (hData, oi, a * 2.0 * M_PI / hData -> mAzCount [e], & j0, & j1, & jf);
  1750. hData -> mHrtds [hData -> mEvOffset [e] + a] = Lerp (hData -> mHrtds [0], Lerp (hData -> mHrtds [j0], hData -> mHrtds [j1], jf), of);
  1751. }
  1752. }
  1753. }
  1754. /* Attempt to synthesize any missing HRIRs at the bottom elevations. Right
  1755. * now this just blends the lowest elevation HRIRs together and applies some
  1756. * attenuation and high frequency damping. It is a simple, if inaccurate
  1757. * model.
  1758. */
  1759. static void SynthesizeHrirs (HrirDataT * hData) {
  1760. uint oi, a, e, step, n, i, j;
  1761. double of, b;
  1762. uint j0, j1;
  1763. double jf;
  1764. double lp [4], s0, s1;
  1765. if (hData -> mEvStart <= 0)
  1766. return;
  1767. step = hData -> mIrSize;
  1768. oi = hData -> mEvStart;
  1769. n = hData -> mIrPoints;
  1770. for (i = 0; i < n; i ++)
  1771. hData -> mHrirs [i] = 0.0;
  1772. for (a = 0; a < hData -> mAzCount [oi]; a ++) {
  1773. j = (hData -> mEvOffset [oi] + a) * step;
  1774. for (i = 0; i < n; i ++)
  1775. hData -> mHrirs [i] += hData -> mHrirs [j + i] / hData -> mAzCount [oi];
  1776. }
  1777. for (e = 1; e < hData -> mEvStart; e ++) {
  1778. of = ((double) e) / hData -> mEvStart;
  1779. b = (1.0 - of) * (3.5e-6 * hData -> mIrRate);
  1780. for (a = 0; a < hData -> mAzCount [e]; a ++) {
  1781. j = (hData -> mEvOffset [e] + a) * step;
  1782. CalcAzIndices (hData, oi, a * 2.0 * M_PI / hData -> mAzCount [e], & j0, & j1, & jf);
  1783. j0 *= step;
  1784. j1 *= step;
  1785. lp [0] = 0.0;
  1786. lp [1] = 0.0;
  1787. lp [2] = 0.0;
  1788. lp [3] = 0.0;
  1789. for (i = 0; i < n; i ++) {
  1790. s0 = hData -> mHrirs [i];
  1791. s1 = Lerp (hData -> mHrirs [j0 + i], hData -> mHrirs [j1 + i], jf);
  1792. s0 = Lerp (s0, s1, of);
  1793. lp [0] = Lerp (s0, lp [0], b);
  1794. lp [1] = Lerp (lp [0], lp [1], b);
  1795. lp [2] = Lerp (lp [1], lp [2], b);
  1796. lp [3] = Lerp (lp [2], lp [3], b);
  1797. hData -> mHrirs [j + i] = lp [3];
  1798. }
  1799. }
  1800. }
  1801. b = 3.5e-6 * hData -> mIrRate;
  1802. lp [0] = 0.0;
  1803. lp [1] = 0.0;
  1804. lp [2] = 0.0;
  1805. lp [3] = 0.0;
  1806. for (i = 0; i < n; i ++) {
  1807. s0 = hData -> mHrirs [i];
  1808. lp [0] = Lerp (s0, lp [0], b);
  1809. lp [1] = Lerp (lp [0], lp [1], b);
  1810. lp [2] = Lerp (lp [1], lp [2], b);
  1811. lp [3] = Lerp (lp [2], lp [3], b);
  1812. hData -> mHrirs [i] = lp [3];
  1813. }
  1814. hData -> mEvStart = 0;
  1815. }
  1816. // The following routines assume a full set of HRIRs for all elevations.
  1817. // Normalize the HRIR set and slightly attenuate the result.
  1818. static void NormalizeHrirs (const HrirDataT * hData) {
  1819. uint step, end, n, j, i;
  1820. double maxLevel;
  1821. step = hData -> mIrSize;
  1822. end = hData -> mIrCount * step;
  1823. n = hData -> mIrPoints;
  1824. maxLevel = 0.0;
  1825. for (j = 0; j < end; j += step) {
  1826. for (i = 0; i < n; i ++)
  1827. maxLevel = fmax (fabs (hData -> mHrirs [j + i]), maxLevel);
  1828. }
  1829. maxLevel = 1.01 * maxLevel;
  1830. for (j = 0; j < end; j += step) {
  1831. for (i = 0; i < n; i ++)
  1832. hData -> mHrirs [j + i] /= maxLevel;
  1833. }
  1834. }
  1835. // Calculate the left-ear time delay using a spherical head model.
  1836. static double CalcLTD (const double ev, const double az, const double rad, const double dist) {
  1837. double azp, dlp, l, al;
  1838. azp = asin (cos (ev) * sin (az));
  1839. dlp = sqrt ((dist * dist) + (rad * rad) + (2.0 * dist * rad * sin (azp)));
  1840. l = sqrt ((dist * dist) - (rad * rad));
  1841. al = (0.5 * M_PI) + azp;
  1842. if (dlp > l)
  1843. dlp = l + (rad * (al - acos (rad / dist)));
  1844. return (dlp / 343.3);
  1845. }
  1846. // Calculate the effective head-related time delays for each minimum-phase
  1847. // HRIR.
  1848. static void CalculateHrtds (const HeadModelT model, const double radius, HrirDataT * hData) {
  1849. double minHrtd, maxHrtd;
  1850. uint e, a, j;
  1851. double t;
  1852. minHrtd = 1000.0;
  1853. maxHrtd = -1000.0;
  1854. for (e = 0; e < hData -> mEvCount; e ++) {
  1855. for (a = 0; a < hData -> mAzCount [e]; a ++) {
  1856. j = hData -> mEvOffset [e] + a;
  1857. if (model == HM_DATASET) {
  1858. t = hData -> mHrtds [j] * radius / hData -> mRadius;
  1859. } else {
  1860. t = CalcLTD ((-90.0 + (e * 180.0 / (hData -> mEvCount - 1))) * M_PI / 180.0,
  1861. (a * 360.0 / hData -> mAzCount [e]) * M_PI / 180.0,
  1862. radius, hData -> mDistance);
  1863. }
  1864. hData -> mHrtds [j] = t;
  1865. maxHrtd = fmax (t, maxHrtd);
  1866. minHrtd = fmin (t, minHrtd);
  1867. }
  1868. }
  1869. maxHrtd -= minHrtd;
  1870. for (j = 0; j < hData -> mIrCount; j ++)
  1871. hData -> mHrtds [j] -= minHrtd;
  1872. hData -> mMaxHrtd = maxHrtd;
  1873. }
  1874. // Store the OpenAL Soft HRTF data set.
  1875. static int StoreMhr (const HrirDataT * hData, const char * filename) {
  1876. FILE * fp = NULL;
  1877. uint e, step, end, n, j, i;
  1878. int hpHist, v;
  1879. if ((fp = fopen (filename, "wb")) == NULL) {
  1880. fprintf (stderr, "Error: Could not open MHR file '%s'.\n", filename);
  1881. return (0);
  1882. }
  1883. if (! WriteAscii (MHR_FORMAT, fp, filename))
  1884. return (0);
  1885. if (! WriteBin4 (BO_LITTLE, 4, (uint4) hData -> mIrRate, fp, filename))
  1886. return (0);
  1887. if (! WriteBin4 (BO_LITTLE, 1, (uint4) hData -> mIrPoints, fp, filename))
  1888. return (0);
  1889. if (! WriteBin4 (BO_LITTLE, 1, (uint4) hData -> mEvCount, fp, filename))
  1890. return (0);
  1891. for (e = 0; e < hData -> mEvCount; e ++) {
  1892. if (! WriteBin4 (BO_LITTLE, 1, (uint4) hData -> mAzCount [e], fp, filename))
  1893. return (0);
  1894. }
  1895. step = hData -> mIrSize;
  1896. end = hData -> mIrCount * step;
  1897. n = hData -> mIrPoints;
  1898. srand (0x31DF840C);
  1899. for (j = 0; j < end; j += step) {
  1900. hpHist = 0;
  1901. for (i = 0; i < n; i ++) {
  1902. v = HpTpdfDither (32767.0 * hData -> mHrirs [j + i], & hpHist);
  1903. if (! WriteBin4 (BO_LITTLE, 2, (uint4) v, fp, filename))
  1904. return (0);
  1905. }
  1906. }
  1907. for (j = 0; j < hData -> mIrCount; j ++) {
  1908. v = (int) fmin (round (hData -> mIrRate * hData -> mHrtds [j]), MAX_HRTD);
  1909. if (! WriteBin4 (BO_LITTLE, 1, (uint4) v, fp, filename))
  1910. return (0);
  1911. }
  1912. fclose (fp);
  1913. return (1);
  1914. }
  1915. // Store the OpenAL Soft built-in table.
  1916. static int StoreTable (const HrirDataT * hData, const char * filename) {
  1917. FILE * fp = NULL;
  1918. uint step, end, n, j, i;
  1919. int hpHist, v;
  1920. char text [128 + 1];
  1921. if ((fp = fopen (filename, "wb")) == NULL) {
  1922. fprintf (stderr, "Error: Could not open table file '%s'.\n", filename);
  1923. return (0);
  1924. }
  1925. snprintf (text, 128, "/* Elevation metrics */\n"
  1926. "static const ALubyte defaultAzCount[%u] = { ", hData -> mEvCount);
  1927. if (! WriteAscii (text, fp, filename))
  1928. return (0);
  1929. for (i = 0; i < hData -> mEvCount; i ++) {
  1930. snprintf (text, 128, "%u, ", hData -> mAzCount [i]);
  1931. if (! WriteAscii (text, fp, filename))
  1932. return (0);
  1933. }
  1934. snprintf (text, 128, "};\n"
  1935. "static const ALushort defaultEvOffset[%u] = { ", hData -> mEvCount);
  1936. if (! WriteAscii (text, fp, filename))
  1937. return (0);
  1938. for (i = 0; i < hData -> mEvCount; i ++) {
  1939. snprintf (text, 128, "%u, ", hData -> mEvOffset [i]);
  1940. if (! WriteAscii (text, fp, filename))
  1941. return (0);
  1942. }
  1943. step = hData -> mIrSize;
  1944. end = hData -> mIrCount * step;
  1945. n = hData -> mIrPoints;
  1946. snprintf (text, 128, "};\n\n"
  1947. "/* HRIR Coefficients */\n"
  1948. "static const ALshort defaultCoeffs[%u] =\n{\n", hData -> mIrCount * n);
  1949. if (! WriteAscii (text, fp, filename))
  1950. return (0);
  1951. srand (0x31DF840C);
  1952. for (j = 0; j < end; j += step) {
  1953. if (! WriteAscii (" ", fp, filename))
  1954. return (0);
  1955. hpHist = 0;
  1956. for (i = 0; i < n; i ++) {
  1957. v = HpTpdfDither (32767.0 * hData -> mHrirs [j + i], & hpHist);
  1958. snprintf (text, 128, " %+d,", v);
  1959. if (! WriteAscii (text, fp, filename))
  1960. return (0);
  1961. }
  1962. if (! WriteAscii ("\n", fp, filename))
  1963. return (0);
  1964. }
  1965. snprintf (text, 128, "};\n\n"
  1966. "/* HRIR Delays */\n"
  1967. "static const ALubyte defaultDelays[%u] =\n{\n"
  1968. " ", hData -> mIrCount);
  1969. if (! WriteAscii (text, fp, filename))
  1970. return (0);
  1971. for (j = 0; j < hData -> mIrCount; j ++) {
  1972. v = (int) fmin (round (hData -> mIrRate * hData -> mHrtds [j]), MAX_HRTD);
  1973. snprintf (text, 128, " %d,", v);
  1974. if (! WriteAscii (text, fp, filename))
  1975. return (0);
  1976. }
  1977. if (! WriteAscii ("\n};\n\n"
  1978. "/* Default HRTF Definition */\n", fp, filename))
  1979. return (0);
  1980. snprintf (text, 128, "static const struct Hrtf DefaultHrtf = {\n"
  1981. " %u, %u, %u, defaultAzCount, defaultEvOffset,\n",
  1982. hData -> mIrRate, hData -> mIrPoints, hData -> mEvCount);
  1983. if (! WriteAscii (text, fp, filename))
  1984. return (0);
  1985. if (! WriteAscii (" defaultCoeffs, defaultDelays, NULL\n"
  1986. "};\n", fp, filename))
  1987. return (0);
  1988. fclose (fp);
  1989. return (1);
  1990. }
  1991. // Process the data set definition to read and validate the data set metrics.
  1992. static int ProcessMetrics (TokenReaderT * tr, const uint fftSize, const uint truncSize, HrirDataT * hData) {
  1993. char ident [MAX_IDENT_LEN + 1];
  1994. uint line, col;
  1995. int intVal;
  1996. uint points;
  1997. double fpVal;
  1998. int hasRate = 0, hasPoints = 0, hasAzimuths = 0;
  1999. int hasRadius = 0, hasDistance = 0;
  2000. while (! (hasRate && hasPoints && hasAzimuths && hasRadius && hasDistance)) {
  2001. TrIndication (tr, & line, & col);
  2002. if (! TrReadIdent (tr, MAX_IDENT_LEN, ident))
  2003. return (0);
  2004. if (strcasecmp (ident, "rate") == 0) {
  2005. if (hasRate) {
  2006. TrErrorAt (tr, line, col, "Redefinition of 'rate'.\n");
  2007. return (0);
  2008. }
  2009. if (! TrReadOperator (tr, "="))
  2010. return (0);
  2011. if (! TrReadInt (tr, MIN_RATE, MAX_RATE, & intVal))
  2012. return (0);
  2013. hData -> mIrRate = (uint) intVal;
  2014. hasRate = 1;
  2015. } else if (strcasecmp (ident, "points") == 0) {
  2016. if (hasPoints) {
  2017. TrErrorAt (tr, line, col, "Redefinition of 'points'.\n");
  2018. return (0);
  2019. }
  2020. if (! TrReadOperator (tr, "="))
  2021. return (0);
  2022. TrIndication (tr, & line, & col);
  2023. if (! TrReadInt (tr, MIN_POINTS, MAX_POINTS, & intVal))
  2024. return (0);
  2025. points = (uint) intVal;
  2026. if ((fftSize > 0) && (points > fftSize)) {
  2027. TrErrorAt (tr, line, col, "Value exceeds the overriden FFT size.\n");
  2028. return (0);
  2029. }
  2030. if (points < truncSize) {
  2031. TrErrorAt (tr, line, col, "Value is below the truncation size.\n");
  2032. return (0);
  2033. }
  2034. hData -> mIrPoints = points;
  2035. hData -> mFftSize = fftSize;
  2036. if (fftSize <= 0) {
  2037. points = 1;
  2038. while (points < (4 * hData -> mIrPoints))
  2039. points <<= 1;
  2040. hData -> mFftSize = points;
  2041. hData -> mIrSize = 1 + (points / 2);
  2042. } else {
  2043. hData -> mFftSize = fftSize;
  2044. hData -> mIrSize = 1 + (fftSize / 2);
  2045. if (points > hData -> mIrSize)
  2046. hData -> mIrSize = points;
  2047. }
  2048. hasPoints = 1;
  2049. } else if (strcasecmp (ident, "azimuths") == 0) {
  2050. if (hasAzimuths) {
  2051. TrErrorAt (tr, line, col, "Redefinition of 'azimuths'.\n");
  2052. return (0);
  2053. }
  2054. if (! TrReadOperator (tr, "="))
  2055. return (0);
  2056. hData -> mIrCount = 0;
  2057. hData -> mEvCount = 0;
  2058. hData -> mEvOffset [0] = 0;
  2059. for (;;) {
  2060. if (! TrReadInt (tr, MIN_AZ_COUNT, MAX_AZ_COUNT, & intVal))
  2061. return (0);
  2062. hData -> mAzCount [hData -> mEvCount] = (uint) intVal;
  2063. hData -> mIrCount += (uint) intVal;
  2064. hData -> mEvCount ++;
  2065. if (! TrIsOperator (tr, ","))
  2066. break;
  2067. if (hData -> mEvCount >= MAX_EV_COUNT) {
  2068. TrError (tr, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT);
  2069. return (0);
  2070. }
  2071. hData -> mEvOffset [hData -> mEvCount] = hData -> mEvOffset [hData -> mEvCount - 1] + ((uint) intVal);
  2072. TrReadOperator (tr, ",");
  2073. }
  2074. if (hData -> mEvCount < MIN_EV_COUNT) {
  2075. TrErrorAt (tr, line, col, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT);
  2076. return (0);
  2077. }
  2078. hasAzimuths = 1;
  2079. } else if (strcasecmp (ident, "radius") == 0) {
  2080. if (hasRadius) {
  2081. TrErrorAt (tr, line, col, "Redefinition of 'radius'.\n");
  2082. return (0);
  2083. }
  2084. if (! TrReadOperator (tr, "="))
  2085. return (0);
  2086. if (! TrReadFloat (tr, MIN_RADIUS, MAX_RADIUS, & fpVal))
  2087. return (0);
  2088. hData -> mRadius = fpVal;
  2089. hasRadius = 1;
  2090. } else if (strcasecmp (ident, "distance") == 0) {
  2091. if (hasDistance) {
  2092. TrErrorAt (tr, line, col, "Redefinition of 'distance'.\n");
  2093. return (0);
  2094. }
  2095. if (! TrReadOperator (tr, "="))
  2096. return (0);
  2097. if (! TrReadFloat (tr, MIN_DISTANCE, MAX_DISTANCE, & fpVal))
  2098. return (0);
  2099. hData -> mDistance = fpVal;
  2100. hasDistance = 1;
  2101. } else {
  2102. TrErrorAt (tr, line, col, "Expected a metric name.\n");
  2103. return (0);
  2104. }
  2105. TrSkipWhitespace (tr);
  2106. }
  2107. return (1);
  2108. }
  2109. // Parse an index pair from the data set definition.
  2110. static int ReadIndexPair (TokenReaderT * tr, const HrirDataT * hData, uint * ei, uint * ai) {
  2111. int intVal;
  2112. if (! TrReadInt (tr, 0, (int) hData -> mEvCount, & intVal))
  2113. return (0);
  2114. (* ei) = (uint) intVal;
  2115. if (! TrReadOperator (tr, ","))
  2116. return (0);
  2117. if (! TrReadInt (tr, 0, (int) hData -> mAzCount [(* ei)], & intVal))
  2118. return (0);
  2119. (* ai) = (uint) intVal;
  2120. return (1);
  2121. }
  2122. // Match the source format from a given identifier.
  2123. static SourceFormatT MatchSourceFormat (const char * ident) {
  2124. if (strcasecmp (ident, "wave") == 0)
  2125. return (SF_WAVE);
  2126. else if (strcasecmp (ident, "bin_le") == 0)
  2127. return (SF_BIN_LE);
  2128. else if (strcasecmp (ident, "bin_be") == 0)
  2129. return (SF_BIN_BE);
  2130. else if (strcasecmp (ident, "ascii") == 0)
  2131. return (SF_ASCII);
  2132. return (SF_NONE);
  2133. }
  2134. // Match the source element type from a given identifier.
  2135. static ElementTypeT MatchElementType (const char * ident) {
  2136. if (strcasecmp (ident, "int") == 0)
  2137. return (ET_INT);
  2138. else if (strcasecmp (ident, "fp") == 0)
  2139. return (ET_FP);
  2140. return (ET_NONE);
  2141. }
  2142. // Parse and validate a source reference from the data set definition.
  2143. static int ReadSourceRef (TokenReaderT * tr, SourceRefT * src) {
  2144. uint line, col;
  2145. char ident [MAX_IDENT_LEN + 1];
  2146. int intVal;
  2147. TrIndication (tr, & line, & col);
  2148. if (! TrReadIdent (tr, MAX_IDENT_LEN, ident))
  2149. return (0);
  2150. src -> mFormat = MatchSourceFormat (ident);
  2151. if (src -> mFormat == SF_NONE) {
  2152. TrErrorAt (tr, line, col, "Expected a source format.\n");
  2153. return (0);
  2154. }
  2155. if (! TrReadOperator (tr, "("))
  2156. return (0);
  2157. if (src -> mFormat == SF_WAVE) {
  2158. if (! TrReadInt (tr, 0, MAX_WAVE_CHANNELS, & intVal))
  2159. return (0);
  2160. src -> mType = ET_NONE;
  2161. src -> mSize = 0;
  2162. src -> mBits = 0;
  2163. src -> mChannel = (uint) intVal;
  2164. src -> mSkip = 0;
  2165. } else {
  2166. TrIndication (tr, & line, & col);
  2167. if (! TrReadIdent (tr, MAX_IDENT_LEN, ident))
  2168. return (0);
  2169. src -> mType = MatchElementType (ident);
  2170. if (src -> mType == ET_NONE) {
  2171. TrErrorAt (tr, line, col, "Expected a source element type.\n");
  2172. return (0);
  2173. }
  2174. if ((src -> mFormat == SF_BIN_LE) || (src -> mFormat == SF_BIN_BE)) {
  2175. if (! TrReadOperator (tr, ","))
  2176. return (0);
  2177. if (src -> mType == ET_INT) {
  2178. if (! TrReadInt (tr, MIN_BIN_SIZE, MAX_BIN_SIZE, & intVal))
  2179. return (0);
  2180. src -> mSize = (uint) intVal;
  2181. if (TrIsOperator (tr, ",")) {
  2182. TrReadOperator (tr, ",");
  2183. TrIndication (tr, & line, & col);
  2184. if (! TrReadInt (tr, -2147483647 - 1, 2147483647, & intVal))
  2185. return (0);
  2186. if ((abs (intVal) < MIN_BIN_BITS) || (((uint) abs (intVal)) > (8 * src -> mSize))) {
  2187. TrErrorAt (tr, line, col, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS, 8 * src -> mSize);
  2188. return (0);
  2189. }
  2190. src -> mBits = intVal;
  2191. } else {
  2192. src -> mBits = (int) (8 * src -> mSize);
  2193. }
  2194. } else {
  2195. TrIndication (tr, & line, & col);
  2196. if (! TrReadInt (tr, -2147483647 - 1, 2147483647, & intVal))
  2197. return (0);
  2198. if ((intVal != 4) && (intVal != 8)) {
  2199. TrErrorAt (tr, line, col, "Expected a value of 4 or 8.\n");
  2200. return (0);
  2201. }
  2202. src -> mSize = (uint) intVal;
  2203. src -> mBits = 0;
  2204. }
  2205. } else if ((src -> mFormat == SF_ASCII) && (src -> mType == ET_INT)) {
  2206. if (! TrReadOperator (tr, ","))
  2207. return (0);
  2208. if (! TrReadInt (tr, MIN_ASCII_BITS, MAX_ASCII_BITS, & intVal))
  2209. return (0);
  2210. src -> mSize = 0;
  2211. src -> mBits = intVal;
  2212. } else {
  2213. src -> mSize = 0;
  2214. src -> mBits = 0;
  2215. }
  2216. if (TrIsOperator (tr, ";")) {
  2217. TrReadOperator (tr, ";");
  2218. if (! TrReadInt (tr, 0, 0x7FFFFFFF, & intVal))
  2219. return (0);
  2220. src -> mSkip = (uint) intVal;
  2221. } else {
  2222. src -> mSkip = 0;
  2223. }
  2224. }
  2225. if (! TrReadOperator (tr, ")"))
  2226. return (0);
  2227. if (TrIsOperator (tr, "@")) {
  2228. TrReadOperator (tr, "@");
  2229. if (! TrReadInt (tr, 0, 0x7FFFFFFF, & intVal))
  2230. return (0);
  2231. src -> mOffset = (uint) intVal;
  2232. } else {
  2233. src -> mOffset = 0;
  2234. }
  2235. if (! TrReadOperator (tr, ":"))
  2236. return (0);
  2237. if (! TrReadString (tr, MAX_PATH_LEN, src -> mPath))
  2238. return (0);
  2239. return (1);
  2240. }
  2241. // Process the list of sources in the data set definition.
  2242. static int ProcessSources (const HeadModelT model, TokenReaderT * tr, HrirDataT * hData) {
  2243. uint * setCount = NULL, * setFlag = NULL;
  2244. double * hrir = NULL;
  2245. uint line, col, ei, ai;
  2246. SourceRefT src;
  2247. double factor;
  2248. setCount = (uint *) calloc (hData -> mEvCount, sizeof (uint));
  2249. setFlag = (uint *) calloc (hData -> mIrCount, sizeof (uint));
  2250. hrir = CreateArray (hData -> mIrPoints);
  2251. while (TrIsOperator (tr, "[")) {
  2252. TrIndication (tr, & line, & col);
  2253. TrReadOperator (tr, "[");
  2254. if (ReadIndexPair (tr, hData, & ei, & ai)) {
  2255. if (TrReadOperator (tr, "]")) {
  2256. if (! setFlag [hData -> mEvOffset [ei] + ai]) {
  2257. if (TrReadOperator (tr, "=")) {
  2258. factor = 1.0;
  2259. for (;;) {
  2260. if (ReadSourceRef (tr, & src)) {
  2261. if (LoadSource (& src, hData -> mIrRate, hData -> mIrPoints, hrir)) {
  2262. if (model == HM_DATASET)
  2263. AverageHrirOnset (hrir, 1.0 / factor, ei, ai, hData);
  2264. AverageHrirMagnitude (hrir, 1.0 / factor, ei, ai, hData);
  2265. factor += 1.0;
  2266. if (! TrIsOperator (tr, "+"))
  2267. break;
  2268. TrReadOperator (tr, "+");
  2269. continue;
  2270. }
  2271. }
  2272. DestroyArray (hrir);
  2273. free (setFlag);
  2274. free (setCount);
  2275. return (0);
  2276. }
  2277. setFlag [hData -> mEvOffset [ei] + ai] = 1;
  2278. setCount [ei] ++;
  2279. continue;
  2280. }
  2281. } else {
  2282. TrErrorAt (tr, line, col, "Redefinition of source.\n");
  2283. }
  2284. }
  2285. }
  2286. DestroyArray (hrir);
  2287. free (setFlag);
  2288. free (setCount);
  2289. return (0);
  2290. }
  2291. ei = 0;
  2292. while ((ei < hData -> mEvCount) && (setCount [ei] < 1))
  2293. ei ++;
  2294. if (ei < hData -> mEvCount) {
  2295. hData -> mEvStart = ei;
  2296. while ((ei < hData -> mEvCount) && (setCount [ei] == hData -> mAzCount [ei]))
  2297. ei ++;
  2298. if (ei >= hData -> mEvCount) {
  2299. if (! TrLoad (tr)) {
  2300. DestroyArray (hrir);
  2301. free (setFlag);
  2302. free (setCount);
  2303. return (1);
  2304. } else {
  2305. TrError (tr, "Errant data at end of source list.\n");
  2306. }
  2307. } else {
  2308. TrError (tr, "Missing sources for elevation index %d.\n", ei);
  2309. }
  2310. } else {
  2311. TrError (tr, "Missing source references.\n");
  2312. }
  2313. DestroyArray (hrir);
  2314. free (setFlag);
  2315. free (setCount);
  2316. return (0);
  2317. }
  2318. /* Parse the data set definition and process the source data, storing the
  2319. * resulting data set as desired. If the input name is NULL it will read
  2320. * from standard input.
  2321. */
  2322. 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) {
  2323. FILE * fp = NULL;
  2324. TokenReaderT tr;
  2325. HrirDataT hData;
  2326. double * dfa = NULL;
  2327. char rateStr [8 + 1], expName [MAX_PATH_LEN];
  2328. hData . mIrRate = 0;
  2329. hData . mIrPoints = 0;
  2330. hData . mFftSize = 0;
  2331. hData . mIrSize = 0;
  2332. hData . mIrCount = 0;
  2333. hData . mEvCount = 0;
  2334. hData . mRadius = 0;
  2335. hData . mDistance = 0;
  2336. fprintf (stdout, "Reading HRIR definition...\n");
  2337. if (inName != NULL) {
  2338. fp = fopen (inName, "r");
  2339. if (fp == NULL) {
  2340. fprintf (stderr, "Error: Could not open definition file '%s'\n", inName);
  2341. return (0);
  2342. }
  2343. TrSetup (fp, inName, & tr);
  2344. } else {
  2345. fp = stdin;
  2346. TrSetup (fp, "<stdin>", & tr);
  2347. }
  2348. if (! ProcessMetrics (& tr, fftSize, truncSize, & hData)) {
  2349. if (inName != NULL)
  2350. fclose (fp);
  2351. return (0);
  2352. }
  2353. hData . mHrirs = CreateArray (hData . mIrCount * hData . mIrSize);
  2354. hData . mHrtds = CreateArray (hData . mIrCount);
  2355. if (! ProcessSources (model, & tr, & hData)) {
  2356. DestroyArray (hData . mHrtds);
  2357. DestroyArray (hData . mHrirs);
  2358. if (inName != NULL)
  2359. fclose (fp);
  2360. return (0);
  2361. }
  2362. if (inName != NULL)
  2363. fclose (fp);
  2364. if (equalize) {
  2365. dfa = CreateArray (1 + (hData . mFftSize / 2));
  2366. fprintf (stdout, "Calculating diffuse-field average...\n");
  2367. CalculateDiffuseFieldAverage (& hData, surface, limit, dfa);
  2368. fprintf (stdout, "Performing diffuse-field equalization...\n");
  2369. DiffuseFieldEqualize (dfa, & hData);
  2370. DestroyArray (dfa);
  2371. }
  2372. fprintf (stdout, "Performing minimum phase reconstruction...\n");
  2373. ReconstructHrirs (& hData);
  2374. if ((outRate != 0) && (outRate != hData . mIrRate)) {
  2375. fprintf (stdout, "Resampling HRIRs...\n");
  2376. ResampleHrirs (outRate, & hData);
  2377. }
  2378. fprintf (stdout, "Truncating minimum-phase HRIRs...\n");
  2379. hData . mIrPoints = truncSize;
  2380. fprintf (stdout, "Synthesizing missing elevations...\n");
  2381. if (model == HM_DATASET)
  2382. SynthesizeOnsets (& hData);
  2383. SynthesizeHrirs (& hData);
  2384. fprintf (stdout, "Normalizing final HRIRs...\n");
  2385. NormalizeHrirs (& hData);
  2386. fprintf (stdout, "Calculating impulse delays...\n");
  2387. CalculateHrtds (model, (radius > DEFAULT_CUSTOM_RADIUS) ? radius : hData . mRadius, & hData);
  2388. snprintf (rateStr, 8, "%u", hData . mIrRate);
  2389. StrSubst (outName, "%r", rateStr, MAX_PATH_LEN, expName);
  2390. switch (outFormat) {
  2391. case OF_MHR :
  2392. fprintf (stdout, "Creating MHR data set file...\n");
  2393. if (! StoreMhr (& hData, expName))
  2394. return (0);
  2395. break;
  2396. case OF_TABLE :
  2397. fprintf (stderr, "Creating OpenAL Soft table file...\n");
  2398. if (! StoreTable (& hData, expName))
  2399. return (0);
  2400. break;
  2401. default :
  2402. break;
  2403. }
  2404. DestroyArray (hData . mHrtds);
  2405. DestroyArray (hData . mHrirs);
  2406. return (1);
  2407. }
  2408. // Standard command line dispatch.
  2409. int main (const int argc, const char * argv []) {
  2410. const char * inName = NULL, * outName = NULL;
  2411. OutputFormatT outFormat;
  2412. int argi;
  2413. uint outRate, fftSize;
  2414. int equalize, surface;
  2415. double limit;
  2416. uint truncSize;
  2417. HeadModelT model;
  2418. double radius;
  2419. char * end = NULL;
  2420. if (argc < 2) {
  2421. fprintf (stderr, "Error: No command specified. See '%s -h' for help.\n", argv [0]);
  2422. return (-1);
  2423. }
  2424. if ((strcmp (argv [1], "--help") == 0) || (strcmp (argv [1], "-h") == 0)) {
  2425. fprintf (stdout, "HRTF Processing and Composition Utility\n\n");
  2426. fprintf (stdout, "Usage: %s <command> [<option>...]\n\n", argv [0]);
  2427. fprintf (stdout, "Commands:\n");
  2428. fprintf (stdout, " -m, --make-mhr Makes an OpenAL Soft compatible HRTF data set.\n");
  2429. fprintf (stdout, " Defaults output to: ./oalsoft_hrtf_%%r.mhr\n");
  2430. fprintf (stdout, " -t, --make-tab Makes the built-in table used when compiling OpenAL Soft.\n");
  2431. fprintf (stdout, " Defaults output to: ./hrtf_tables.inc\n");
  2432. fprintf (stdout, " -h, --help Displays this help information.\n\n");
  2433. fprintf (stdout, "Options:\n");
  2434. fprintf (stdout, " -r=<rate> Change the data set sample rate to the specified value and\n");
  2435. fprintf (stdout, " resample the HRIRs accordingly.\n");
  2436. fprintf (stdout, " -f=<points> Override the FFT window size (defaults to the first power-\n");
  2437. fprintf (stdout, " of-two that fits four times the number of HRIR points).\n");
  2438. fprintf (stdout, " -e={on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE ? "on" : "off"));
  2439. fprintf (stdout, " -s={on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE ? "on" : "off"));
  2440. fprintf (stdout, " -l={<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
  2441. fprintf (stdout, " average (default: %.2f).\n", DEFAULT_LIMIT);
  2442. fprintf (stdout, " -w=<points> Specify the size of the truncation window that's applied\n");
  2443. fprintf (stdout, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE);
  2444. fprintf (stdout, " -d={dataset| Specify the model used for calculating the head-delay timing\n");
  2445. fprintf (stdout, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL == HM_DATASET) ? "dataset" : "sphere"));
  2446. fprintf (stdout, " -c=<size> Use a customized head radius measured ear-to-ear in meters.\n");
  2447. fprintf (stdout, " -i=<filename> Specify an HRIR definition file to use (defaults to stdin).\n");
  2448. fprintf (stdout, " -o=<filename> Specify an output file. Overrides command-selected default.\n");
  2449. fprintf (stdout, " Use of '%%r' will be substituted with the data set sample rate.\n");
  2450. return (0);
  2451. }
  2452. if ((strcmp (argv [1], "--make-mhr") == 0) || (strcmp (argv [1], "-m") == 0)) {
  2453. if (argc > 3)
  2454. outName = argv [3];
  2455. else
  2456. outName = "./oalsoft_hrtf_%r.mhr";
  2457. outFormat = OF_MHR;
  2458. } else if ((strcmp (argv [1], "--make-tab") == 0) || (strcmp (argv [1], "-t") == 0)) {
  2459. if (argc > 3)
  2460. outName = argv [3];
  2461. else
  2462. outName = "./hrtf_tables.inc";
  2463. outFormat = OF_TABLE;
  2464. } else {
  2465. fprintf (stderr, "Error: Invalid command '%s'.\n", argv [1]);
  2466. return (-1);
  2467. }
  2468. argi = 2;
  2469. outRate = 0;
  2470. fftSize = 0;
  2471. equalize = DEFAULT_EQUALIZE;
  2472. surface = DEFAULT_SURFACE;
  2473. limit = DEFAULT_LIMIT;
  2474. truncSize = DEFAULT_TRUNCSIZE;
  2475. model = DEFAULT_HEAD_MODEL;
  2476. radius = DEFAULT_CUSTOM_RADIUS;
  2477. while (argi < argc) {
  2478. if (strncmp (argv [argi], "-r=", 3) == 0) {
  2479. outRate = strtoul (& argv [argi] [3], & end, 10);
  2480. if ((end [0] != '\0') || (outRate < MIN_RATE) || (outRate > MAX_RATE)) {
  2481. fprintf (stderr, "Error: Expected a value from %u to %u for '-r'.\n", MIN_RATE, MAX_RATE);
  2482. return (-1);
  2483. }
  2484. } else if (strncmp (argv [argi], "-f=", 3) == 0) {
  2485. fftSize = strtoul (& argv [argi] [3], & end, 10);
  2486. if ((end [0] != '\0') || (fftSize & (fftSize - 1)) || (fftSize < MIN_FFTSIZE) || (fftSize > MAX_FFTSIZE)) {
  2487. fprintf (stderr, "Error: Expected a power-of-two value from %u to %u for '-f'.\n", MIN_FFTSIZE, MAX_FFTSIZE);
  2488. return (-1);
  2489. }
  2490. } else if (strncmp (argv [argi], "-e=", 3) == 0) {
  2491. if (strcmp (& argv [argi] [3], "on") == 0) {
  2492. equalize = 1;
  2493. } else if (strcmp (& argv [argi] [3], "off") == 0) {
  2494. equalize = 0;
  2495. } else {
  2496. fprintf (stderr, "Error: Expected 'on' or 'off' for '-e'.\n");
  2497. return (-1);
  2498. }
  2499. } else if (strncmp (argv [argi], "-s=", 3) == 0) {
  2500. if (strcmp (& argv [argi] [3], "on") == 0) {
  2501. surface = 1;
  2502. } else if (strcmp (& argv [argi] [3], "off") == 0) {
  2503. surface = 0;
  2504. } else {
  2505. fprintf (stderr, "Error: Expected 'on' or 'off' for '-s'.\n");
  2506. return (-1);
  2507. }
  2508. } else if (strncmp (argv [argi], "-l=", 3) == 0) {
  2509. if (strcmp (& argv [argi] [3], "none") == 0) {
  2510. limit = 0.0;
  2511. } else {
  2512. limit = strtod (& argv [argi] [3], & end);
  2513. if ((end [0] != '\0') || (limit < MIN_LIMIT) || (limit > MAX_LIMIT)) {
  2514. fprintf (stderr, "Error: Expected 'none' or a value from %.2f to %.2f for '-l'.\n", MIN_LIMIT, MAX_LIMIT);
  2515. return (-1);
  2516. }
  2517. }
  2518. } else if (strncmp (argv [argi], "-w=", 3) == 0) {
  2519. truncSize = strtoul (& argv [argi] [3], & end, 10);
  2520. if ((end [0] != '\0') || (truncSize < MIN_TRUNCSIZE) || (truncSize > MAX_TRUNCSIZE) || (truncSize % MOD_TRUNCSIZE)) {
  2521. fprintf (stderr, "Error: Expected a value from %u to %u in multiples of %u for '-w'.\n", MIN_TRUNCSIZE, MAX_TRUNCSIZE, MOD_TRUNCSIZE);
  2522. return (-1);
  2523. }
  2524. } else if (strncmp (argv [argi], "-d=", 3) == 0) {
  2525. if (strcmp (& argv [argi] [3], "dataset") == 0) {
  2526. model = HM_DATASET;
  2527. } else if (strcmp (& argv [argi] [3], "sphere") == 0) {
  2528. model = HM_SPHERE;
  2529. } else {
  2530. fprintf (stderr, "Error: Expected 'dataset' or 'sphere' for '-d'.\n");
  2531. return (-1);
  2532. }
  2533. } else if (strncmp (argv [argi], "-c=", 3) == 0) {
  2534. radius = strtod (& argv [argi] [3], & end);
  2535. if ((end [0] != '\0') || (radius < MIN_CUSTOM_RADIUS) || (radius > MAX_CUSTOM_RADIUS)) {
  2536. fprintf (stderr, "Error: Expected a value from %.2f to %.2f for '-c'.\n", MIN_CUSTOM_RADIUS, MAX_CUSTOM_RADIUS);
  2537. return (-1);
  2538. }
  2539. } else if (strncmp (argv [argi], "-i=", 3) == 0) {
  2540. inName = & argv [argi] [3];
  2541. } else if (strncmp (argv [argi], "-o=", 3) == 0) {
  2542. outName = & argv [argi] [3];
  2543. } else {
  2544. fprintf (stderr, "Error: Invalid option '%s'.\n", argv [argi]);
  2545. return (-1);
  2546. }
  2547. argi ++;
  2548. }
  2549. if (! ProcessDefinition (inName, outRate, fftSize, equalize, surface, limit, truncSize, model, radius, outFormat, outName))
  2550. return (-1);
  2551. fprintf (stdout, "Operation completed.\n");
  2552. return (0);
  2553. }