makehrtf.c 85 KB

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