makehrtf.c 89 KB

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