makehrtf.c 87 KB

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