makehrtf.c 103 KB

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