makehrtf.c 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476
  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. In-place operation is possible only if both the real and imaginary
  882. * parts are in-place together.
  883. */
  884. // Performs bit-reversal ordering.
  885. static void FftArrange(const uint n, const Complex *in, Complex *out)
  886. {
  887. uint rk, k, m;
  888. if(in == out)
  889. {
  890. // Handle in-place arrangement.
  891. rk = 0;
  892. for(k = 0;k < n;k++)
  893. {
  894. if(rk > k)
  895. {
  896. Complex temp = in[rk];
  897. out[rk] = in[k];
  898. out[k] = temp;
  899. }
  900. m = n;
  901. while(rk&(m >>= 1))
  902. rk &= ~m;
  903. rk |= m;
  904. }
  905. }
  906. else
  907. {
  908. // Handle copy arrangement.
  909. rk = 0;
  910. for(k = 0;k < n;k++)
  911. {
  912. out[rk] = in[k];
  913. m = n;
  914. while(rk&(m >>= 1))
  915. rk &= ~m;
  916. rk |= m;
  917. }
  918. }
  919. }
  920. // Performs the summation.
  921. static void FftSummation(const int n, const double s, Complex *cplx)
  922. {
  923. double pi;
  924. int m, m2;
  925. int i, k, mk;
  926. pi = s * M_PI;
  927. for(m = 1, m2 = 2;m < n; m <<= 1, m2 <<= 1)
  928. {
  929. // v = Complex (-2.0 * sin (0.5 * pi / m) * sin (0.5 * pi / m), -sin (pi / m))
  930. double sm = sin(0.5 * pi / m);
  931. Complex v = MakeComplex(-2.0*sm*sm, -sin(pi / m));
  932. Complex w = MakeComplex(1.0, 0.0);
  933. for(i = 0;i < m;i++)
  934. {
  935. for(k = i;k < n;k += m2)
  936. {
  937. Complex t;
  938. mk = k + m;
  939. t = c_mul(w, cplx[mk]);
  940. cplx[mk] = c_sub(cplx[k], t);
  941. cplx[k] = c_add(cplx[k], t);
  942. }
  943. w = c_add(w, c_mul(v, w));
  944. }
  945. }
  946. }
  947. // Performs a forward FFT.
  948. static void FftForward(const uint n, const Complex *in, Complex *out)
  949. {
  950. FftArrange(n, in, out);
  951. FftSummation(n, 1.0, out);
  952. }
  953. // Performs an inverse FFT.
  954. static void FftInverse(const uint n, const Complex *in, Complex *out)
  955. {
  956. double f;
  957. uint i;
  958. FftArrange(n, in, out);
  959. FftSummation(n, -1.0, out);
  960. f = 1.0 / n;
  961. for(i = 0;i < n;i++)
  962. out[i] = c_muls(out[i], f);
  963. }
  964. /* Calculate the complex helical sequence (or discrete-time analytical signal)
  965. * of the given input using the Hilbert transform. Given the natural logarithm
  966. * of a signal's magnitude response, the imaginary components can be used as
  967. * the angles for minimum-phase reconstruction.
  968. */
  969. static void Hilbert(const uint n, const Complex *in, Complex *out)
  970. {
  971. uint i;
  972. if(in == out)
  973. {
  974. // Handle in-place operation.
  975. for(i = 0;i < n;i++)
  976. out[i].Imag = 0.0;
  977. }
  978. else
  979. {
  980. // Handle copy operation.
  981. for(i = 0;i < n;i++)
  982. out[i] = MakeComplex(in[i].Real, 0.0);
  983. }
  984. FftInverse(n, out, out);
  985. for(i = 1;i < (n+1)/2;i++)
  986. out[i] = c_muls(out[i], 2.0);
  987. /* Increment i if n is even. */
  988. i += (n&1)^1;
  989. for(;i < n;i++)
  990. out[i] = MakeComplex(0.0, 0.0);
  991. FftForward(n, out, out);
  992. }
  993. /* Calculate the magnitude response of the given input. This is used in
  994. * place of phase decomposition, since the phase residuals are discarded for
  995. * minimum phase reconstruction. The mirrored half of the response is also
  996. * discarded.
  997. */
  998. static void MagnitudeResponse(const uint n, const Complex *in, double *out)
  999. {
  1000. const uint m = 1 + (n / 2);
  1001. uint i;
  1002. for(i = 0;i < m;i++)
  1003. out[i] = fmax(c_abs(in[i]), EPSILON);
  1004. }
  1005. /* Apply a range limit (in dB) to the given magnitude response. This is used
  1006. * to adjust the effects of the diffuse-field average on the equalization
  1007. * process.
  1008. */
  1009. static void LimitMagnitudeResponse(const uint n, const uint m, const double limit, const double *in, double *out)
  1010. {
  1011. double halfLim;
  1012. uint i, lower, upper;
  1013. double ave;
  1014. halfLim = limit / 2.0;
  1015. // Convert the response to dB.
  1016. for(i = 0;i < m;i++)
  1017. out[i] = 20.0 * log10(in[i]);
  1018. // Use six octaves to calculate the average magnitude of the signal.
  1019. lower = ((uint)ceil(n / pow(2.0, 8.0))) - 1;
  1020. upper = ((uint)floor(n / pow(2.0, 2.0))) - 1;
  1021. ave = 0.0;
  1022. for(i = lower;i <= upper;i++)
  1023. ave += out[i];
  1024. ave /= upper - lower + 1;
  1025. // Keep the response within range of the average magnitude.
  1026. for(i = 0;i < m;i++)
  1027. out[i] = Clamp(out[i], ave - halfLim, ave + halfLim);
  1028. // Convert the response back to linear magnitude.
  1029. for(i = 0;i < m;i++)
  1030. out[i] = pow(10.0, out[i] / 20.0);
  1031. }
  1032. /* Reconstructs the minimum-phase component for the given magnitude response
  1033. * of a signal. This is equivalent to phase recomposition, sans the missing
  1034. * residuals (which were discarded). The mirrored half of the response is
  1035. * reconstructed.
  1036. */
  1037. static void MinimumPhase(const uint n, const double *in, Complex *out)
  1038. {
  1039. const uint m = 1 + (n / 2);
  1040. double *mags;
  1041. uint i;
  1042. mags = CreateDoubles(n);
  1043. for(i = 0;i < m;i++)
  1044. {
  1045. mags[i] = fmax(EPSILON, in[i]);
  1046. out[i] = MakeComplex(log(mags[i]), 0.0);
  1047. }
  1048. for(;i < n;i++)
  1049. {
  1050. mags[i] = mags[n - i];
  1051. out[i] = out[n - i];
  1052. }
  1053. Hilbert(n, out, out);
  1054. // Remove any DC offset the filter has.
  1055. mags[0] = EPSILON;
  1056. for(i = 0;i < n;i++)
  1057. {
  1058. Complex a = c_exp(MakeComplex(0.0, out[i].Imag));
  1059. out[i] = c_mul(MakeComplex(mags[i], 0.0), a);
  1060. }
  1061. free(mags);
  1062. }
  1063. /***************************
  1064. *** Resampler functions ***
  1065. ***************************/
  1066. /* This is the normalized cardinal sine (sinc) function.
  1067. *
  1068. * sinc(x) = { 1, x = 0
  1069. * { sin(pi x) / (pi x), otherwise.
  1070. */
  1071. static double Sinc(const double x)
  1072. {
  1073. if(fabs(x) < EPSILON)
  1074. return 1.0;
  1075. return sin(M_PI * x) / (M_PI * x);
  1076. }
  1077. /* The zero-order modified Bessel function of the first kind, used for the
  1078. * Kaiser window.
  1079. *
  1080. * I_0(x) = sum_{k=0}^inf (1 / k!)^2 (x / 2)^(2 k)
  1081. * = sum_{k=0}^inf ((x / 2)^k / k!)^2
  1082. */
  1083. static double BesselI_0(const double x)
  1084. {
  1085. double term, sum, x2, y, last_sum;
  1086. int k;
  1087. // Start at k=1 since k=0 is trivial.
  1088. term = 1.0;
  1089. sum = 1.0;
  1090. x2 = x/2.0;
  1091. k = 1;
  1092. // Let the integration converge until the term of the sum is no longer
  1093. // significant.
  1094. do {
  1095. y = x2 / k;
  1096. k++;
  1097. last_sum = sum;
  1098. term *= y * y;
  1099. sum += term;
  1100. } while(sum != last_sum);
  1101. return sum;
  1102. }
  1103. /* Calculate a Kaiser window from the given beta value and a normalized k
  1104. * [-1, 1].
  1105. *
  1106. * w(k) = { I_0(B sqrt(1 - k^2)) / I_0(B), -1 <= k <= 1
  1107. * { 0, elsewhere.
  1108. *
  1109. * Where k can be calculated as:
  1110. *
  1111. * k = i / l, where -l <= i <= l.
  1112. *
  1113. * or:
  1114. *
  1115. * k = 2 i / M - 1, where 0 <= i <= M.
  1116. */
  1117. static double Kaiser(const double b, const double k)
  1118. {
  1119. if(!(k >= -1.0 && k <= 1.0))
  1120. return 0.0;
  1121. return BesselI_0(b * sqrt(1.0 - k*k)) / BesselI_0(b);
  1122. }
  1123. // Calculates the greatest common divisor of a and b.
  1124. static uint Gcd(uint x, uint y)
  1125. {
  1126. while(y > 0)
  1127. {
  1128. uint z = y;
  1129. y = x % y;
  1130. x = z;
  1131. }
  1132. return x;
  1133. }
  1134. /* Calculates the size (order) of the Kaiser window. Rejection is in dB and
  1135. * the transition width is normalized frequency (0.5 is nyquist).
  1136. *
  1137. * M = { ceil((r - 7.95) / (2.285 2 pi f_t)), r > 21
  1138. * { ceil(5.79 / 2 pi f_t), r <= 21.
  1139. *
  1140. */
  1141. static uint CalcKaiserOrder(const double rejection, const double transition)
  1142. {
  1143. double w_t = 2.0 * M_PI * transition;
  1144. if(rejection > 21.0)
  1145. return (uint)ceil((rejection - 7.95) / (2.285 * w_t));
  1146. return (uint)ceil(5.79 / w_t);
  1147. }
  1148. // Calculates the beta value of the Kaiser window. Rejection is in dB.
  1149. static double CalcKaiserBeta(const double rejection)
  1150. {
  1151. if(rejection > 50.0)
  1152. return 0.1102 * (rejection - 8.7);
  1153. if(rejection >= 21.0)
  1154. return (0.5842 * pow(rejection - 21.0, 0.4)) +
  1155. (0.07886 * (rejection - 21.0));
  1156. return 0.0;
  1157. }
  1158. /* Calculates a point on the Kaiser-windowed sinc filter for the given half-
  1159. * width, beta, gain, and cutoff. The point is specified in non-normalized
  1160. * samples, from 0 to M, where M = (2 l + 1).
  1161. *
  1162. * w(k) 2 p f_t sinc(2 f_t x)
  1163. *
  1164. * x -- centered sample index (i - l)
  1165. * k -- normalized and centered window index (x / l)
  1166. * w(k) -- window function (Kaiser)
  1167. * p -- gain compensation factor when sampling
  1168. * f_t -- normalized center frequency (or cutoff; 0.5 is nyquist)
  1169. */
  1170. static double SincFilter(const int l, const double b, const double gain, const double cutoff, const int i)
  1171. {
  1172. return Kaiser(b, (double)(i - l) / l) * 2.0 * gain * cutoff * Sinc(2.0 * cutoff * (i - l));
  1173. }
  1174. /* This is a polyphase sinc-filtered resampler.
  1175. *
  1176. * Upsample Downsample
  1177. *
  1178. * p/q = 3/2 p/q = 3/5
  1179. *
  1180. * M-+-+-+-> M-+-+-+->
  1181. * -------------------+ ---------------------+
  1182. * p s * f f f f|f| | p s * f f f f f |
  1183. * | 0 * 0 0 0|0|0 | | 0 * 0 0 0 0|0| |
  1184. * v 0 * 0 0|0|0 0 | v 0 * 0 0 0|0|0 |
  1185. * s * f|f|f f f | s * f f|f|f f |
  1186. * 0 * |0|0 0 0 0 | 0 * 0|0|0 0 0 |
  1187. * --------+=+--------+ 0 * |0|0 0 0 0 |
  1188. * d . d .|d|. d . d ----------+=+--------+
  1189. * d . . . .|d|. . . .
  1190. * q->
  1191. * q-+-+-+->
  1192. *
  1193. * P_f(i,j) = q i mod p + pj
  1194. * P_s(i,j) = floor(q i / p) - j
  1195. * d[i=0..N-1] = sum_{j=0}^{floor((M - 1) / p)} {
  1196. * { f[P_f(i,j)] s[P_s(i,j)], P_f(i,j) < M
  1197. * { 0, P_f(i,j) >= M. }
  1198. */
  1199. // Calculate the resampling metrics and build the Kaiser-windowed sinc filter
  1200. // that's used to cut frequencies above the destination nyquist.
  1201. static void ResamplerSetup(ResamplerT *rs, const uint srcRate, const uint dstRate)
  1202. {
  1203. double cutoff, width, beta;
  1204. uint gcd, l;
  1205. int i;
  1206. gcd = Gcd(srcRate, dstRate);
  1207. rs->mP = dstRate / gcd;
  1208. rs->mQ = srcRate / gcd;
  1209. /* The cutoff is adjusted by half the transition width, so the transition
  1210. * ends before the nyquist (0.5). Both are scaled by the downsampling
  1211. * factor.
  1212. */
  1213. if(rs->mP > rs->mQ)
  1214. {
  1215. cutoff = 0.475 / rs->mP;
  1216. width = 0.05 / rs->mP;
  1217. }
  1218. else
  1219. {
  1220. cutoff = 0.475 / rs->mQ;
  1221. width = 0.05 / rs->mQ;
  1222. }
  1223. // A rejection of -180 dB is used for the stop band. Round up when
  1224. // calculating the left offset to avoid increasing the transition width.
  1225. l = (CalcKaiserOrder(180.0, width)+1) / 2;
  1226. beta = CalcKaiserBeta(180.0);
  1227. rs->mM = l*2 + 1;
  1228. rs->mL = l;
  1229. rs->mF = CreateDoubles(rs->mM);
  1230. for(i = 0;i < ((int)rs->mM);i++)
  1231. rs->mF[i] = SincFilter((int)l, beta, rs->mP, cutoff, i);
  1232. }
  1233. // Clean up after the resampler.
  1234. static void ResamplerClear(ResamplerT *rs)
  1235. {
  1236. free(rs->mF);
  1237. rs->mF = NULL;
  1238. }
  1239. // Perform the upsample-filter-downsample resampling operation using a
  1240. // polyphase filter implementation.
  1241. static void ResamplerRun(ResamplerT *rs, const uint inN, const double *in, const uint outN, double *out)
  1242. {
  1243. const uint p = rs->mP, q = rs->mQ, m = rs->mM, l = rs->mL;
  1244. const double *f = rs->mF;
  1245. uint j_f, j_s;
  1246. double *work;
  1247. uint i;
  1248. if(outN == 0)
  1249. return;
  1250. // Handle in-place operation.
  1251. if(in == out)
  1252. work = CreateDoubles(outN);
  1253. else
  1254. work = out;
  1255. // Resample the input.
  1256. for(i = 0;i < outN;i++)
  1257. {
  1258. double r = 0.0;
  1259. // Input starts at l to compensate for the filter delay. This will
  1260. // drop any build-up from the first half of the filter.
  1261. j_f = (l + (q * i)) % p;
  1262. j_s = (l + (q * i)) / p;
  1263. while(j_f < m)
  1264. {
  1265. // Only take input when 0 <= j_s < inN. This single unsigned
  1266. // comparison catches both cases.
  1267. if(j_s < inN)
  1268. r += f[j_f] * in[j_s];
  1269. j_f += p;
  1270. j_s--;
  1271. }
  1272. work[i] = r;
  1273. }
  1274. // Clean up after in-place operation.
  1275. if(work != out)
  1276. {
  1277. for(i = 0;i < outN;i++)
  1278. out[i] = work[i];
  1279. free(work);
  1280. }
  1281. }
  1282. /*************************
  1283. *** File source input ***
  1284. *************************/
  1285. // Read a binary value of the specified byte order and byte size from a file,
  1286. // storing it as a 32-bit unsigned integer.
  1287. static int ReadBin4(FILE *fp, const char *filename, const ByteOrderT order, const uint bytes, uint32 *out)
  1288. {
  1289. uint8 in[4];
  1290. uint32 accum;
  1291. uint i;
  1292. if(fread(in, 1, bytes, fp) != bytes)
  1293. {
  1294. fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
  1295. return 0;
  1296. }
  1297. accum = 0;
  1298. switch(order)
  1299. {
  1300. case BO_LITTLE:
  1301. for(i = 0;i < bytes;i++)
  1302. accum = (accum<<8) | in[bytes - i - 1];
  1303. break;
  1304. case BO_BIG:
  1305. for(i = 0;i < bytes;i++)
  1306. accum = (accum<<8) | in[i];
  1307. break;
  1308. default:
  1309. break;
  1310. }
  1311. *out = accum;
  1312. return 1;
  1313. }
  1314. // Read a binary value of the specified byte order from a file, storing it as
  1315. // a 64-bit unsigned integer.
  1316. static int ReadBin8(FILE *fp, const char *filename, const ByteOrderT order, uint64 *out)
  1317. {
  1318. uint8 in [8];
  1319. uint64 accum;
  1320. uint i;
  1321. if(fread(in, 1, 8, fp) != 8)
  1322. {
  1323. fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
  1324. return 0;
  1325. }
  1326. accum = 0ULL;
  1327. switch(order)
  1328. {
  1329. case BO_LITTLE:
  1330. for(i = 0;i < 8;i++)
  1331. accum = (accum<<8) | in[8 - i - 1];
  1332. break;
  1333. case BO_BIG:
  1334. for(i = 0;i < 8;i++)
  1335. accum = (accum<<8) | in[i];
  1336. break;
  1337. default:
  1338. break;
  1339. }
  1340. *out = accum;
  1341. return 1;
  1342. }
  1343. /* Read a binary value of the specified type, byte order, and byte size from
  1344. * a file, converting it to a double. For integer types, the significant
  1345. * bits are used to normalize the result. The sign of bits determines
  1346. * whether they are padded toward the MSB (negative) or LSB (positive).
  1347. * Floating-point types are not normalized.
  1348. */
  1349. static int ReadBinAsDouble(FILE *fp, const char *filename, const ByteOrderT order, const ElementTypeT type, const uint bytes, const int bits, double *out)
  1350. {
  1351. union {
  1352. uint32 ui;
  1353. int32 i;
  1354. float f;
  1355. } v4;
  1356. union {
  1357. uint64 ui;
  1358. double f;
  1359. } v8;
  1360. *out = 0.0;
  1361. if(bytes > 4)
  1362. {
  1363. if(!ReadBin8(fp, filename, order, &v8.ui))
  1364. return 0;
  1365. if(type == ET_FP)
  1366. *out = v8.f;
  1367. }
  1368. else
  1369. {
  1370. if(!ReadBin4(fp, filename, order, bytes, &v4.ui))
  1371. return 0;
  1372. if(type == ET_FP)
  1373. *out = v4.f;
  1374. else
  1375. {
  1376. if(bits > 0)
  1377. v4.ui >>= (8*bytes) - ((uint)bits);
  1378. else
  1379. v4.ui &= (0xFFFFFFFF >> (32+bits));
  1380. if(v4.ui&(uint)(1<<(abs(bits)-1)))
  1381. v4.ui |= (0xFFFFFFFF << abs (bits));
  1382. *out = v4.i / (double)(1<<(abs(bits)-1));
  1383. }
  1384. }
  1385. return 1;
  1386. }
  1387. /* Read an ascii value of the specified type from a file, converting it to a
  1388. * double. For integer types, the significant bits are used to normalize the
  1389. * result. The sign of the bits should always be positive. This also skips
  1390. * up to one separator character before the element itself.
  1391. */
  1392. static int ReadAsciiAsDouble(TokenReaderT *tr, const char *filename, const ElementTypeT type, const uint bits, double *out)
  1393. {
  1394. if(TrIsOperator(tr, ","))
  1395. TrReadOperator(tr, ",");
  1396. else if(TrIsOperator(tr, ":"))
  1397. TrReadOperator(tr, ":");
  1398. else if(TrIsOperator(tr, ";"))
  1399. TrReadOperator(tr, ";");
  1400. else if(TrIsOperator(tr, "|"))
  1401. TrReadOperator(tr, "|");
  1402. if(type == ET_FP)
  1403. {
  1404. if(!TrReadFloat(tr, -HUGE_VAL, HUGE_VAL, out))
  1405. {
  1406. fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
  1407. return 0;
  1408. }
  1409. }
  1410. else
  1411. {
  1412. int v;
  1413. if(!TrReadInt(tr, -(1<<(bits-1)), (1<<(bits-1))-1, &v))
  1414. {
  1415. fprintf(stderr, "Error: Bad read from file '%s'.\n", filename);
  1416. return 0;
  1417. }
  1418. *out = v / (double)((1<<(bits-1))-1);
  1419. }
  1420. return 1;
  1421. }
  1422. // Read the RIFF/RIFX WAVE format chunk from a file, validating it against
  1423. // the source parameters and data set metrics.
  1424. static int ReadWaveFormat(FILE *fp, const ByteOrderT order, const uint hrirRate, SourceRefT *src)
  1425. {
  1426. uint32 fourCC, chunkSize;
  1427. uint32 format, channels, rate, dummy, block, size, bits;
  1428. chunkSize = 0;
  1429. do {
  1430. if(chunkSize > 0)
  1431. fseek (fp, (long) chunkSize, SEEK_CUR);
  1432. if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
  1433. !ReadBin4(fp, src->mPath, order, 4, &chunkSize))
  1434. return 0;
  1435. } while(fourCC != FOURCC_FMT);
  1436. if(!ReadBin4(fp, src->mPath, order, 2, &format) ||
  1437. !ReadBin4(fp, src->mPath, order, 2, &channels) ||
  1438. !ReadBin4(fp, src->mPath, order, 4, &rate) ||
  1439. !ReadBin4(fp, src->mPath, order, 4, &dummy) ||
  1440. !ReadBin4(fp, src->mPath, order, 2, &block))
  1441. return 0;
  1442. block /= channels;
  1443. if(chunkSize > 14)
  1444. {
  1445. if(!ReadBin4(fp, src->mPath, order, 2, &size))
  1446. return 0;
  1447. size /= 8;
  1448. if(block > size)
  1449. size = block;
  1450. }
  1451. else
  1452. size = block;
  1453. if(format == WAVE_FORMAT_EXTENSIBLE)
  1454. {
  1455. fseek(fp, 2, SEEK_CUR);
  1456. if(!ReadBin4(fp, src->mPath, order, 2, &bits))
  1457. return 0;
  1458. if(bits == 0)
  1459. bits = 8 * size;
  1460. fseek(fp, 4, SEEK_CUR);
  1461. if(!ReadBin4(fp, src->mPath, order, 2, &format))
  1462. return 0;
  1463. fseek(fp, (long)(chunkSize - 26), SEEK_CUR);
  1464. }
  1465. else
  1466. {
  1467. bits = 8 * size;
  1468. if(chunkSize > 14)
  1469. fseek(fp, (long)(chunkSize - 16), SEEK_CUR);
  1470. else
  1471. fseek(fp, (long)(chunkSize - 14), SEEK_CUR);
  1472. }
  1473. if(format != WAVE_FORMAT_PCM && format != WAVE_FORMAT_IEEE_FLOAT)
  1474. {
  1475. fprintf(stderr, "Error: Unsupported WAVE format in file '%s'.\n", src->mPath);
  1476. return 0;
  1477. }
  1478. if(src->mChannel >= channels)
  1479. {
  1480. fprintf(stderr, "Error: Missing source channel in WAVE file '%s'.\n", src->mPath);
  1481. return 0;
  1482. }
  1483. if(rate != hrirRate)
  1484. {
  1485. fprintf(stderr, "Error: Mismatched source sample rate in WAVE file '%s'.\n", src->mPath);
  1486. return 0;
  1487. }
  1488. if(format == WAVE_FORMAT_PCM)
  1489. {
  1490. if(size < 2 || size > 4)
  1491. {
  1492. fprintf(stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src->mPath);
  1493. return 0;
  1494. }
  1495. if(bits < 16 || bits > (8*size))
  1496. {
  1497. fprintf (stderr, "Error: Bad significant bits in WAVE file '%s'.\n", src->mPath);
  1498. return 0;
  1499. }
  1500. src->mType = ET_INT;
  1501. }
  1502. else
  1503. {
  1504. if(size != 4 && size != 8)
  1505. {
  1506. fprintf(stderr, "Error: Unsupported sample size in WAVE file '%s'.\n", src->mPath);
  1507. return 0;
  1508. }
  1509. src->mType = ET_FP;
  1510. }
  1511. src->mSize = size;
  1512. src->mBits = (int)bits;
  1513. src->mSkip = channels;
  1514. return 1;
  1515. }
  1516. // Read a RIFF/RIFX WAVE data chunk, converting all elements to doubles.
  1517. static int ReadWaveData(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
  1518. {
  1519. int pre, post, skip;
  1520. uint i;
  1521. pre = (int)(src->mSize * src->mChannel);
  1522. post = (int)(src->mSize * (src->mSkip - src->mChannel - 1));
  1523. skip = 0;
  1524. for(i = 0;i < n;i++)
  1525. {
  1526. skip += pre;
  1527. if(skip > 0)
  1528. fseek(fp, skip, SEEK_CUR);
  1529. if(!ReadBinAsDouble(fp, src->mPath, order, src->mType, src->mSize, src->mBits, &hrir[i]))
  1530. return 0;
  1531. skip = post;
  1532. }
  1533. if(skip > 0)
  1534. fseek(fp, skip, SEEK_CUR);
  1535. return 1;
  1536. }
  1537. // Read the RIFF/RIFX WAVE list or data chunk, converting all elements to
  1538. // doubles.
  1539. static int ReadWaveList(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
  1540. {
  1541. uint32 fourCC, chunkSize, listSize, count;
  1542. uint block, skip, offset, i;
  1543. double lastSample;
  1544. for(;;)
  1545. {
  1546. if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
  1547. !ReadBin4(fp, src->mPath, order, 4, &chunkSize))
  1548. return 0;
  1549. if(fourCC == FOURCC_DATA)
  1550. {
  1551. block = src->mSize * src->mSkip;
  1552. count = chunkSize / block;
  1553. if(count < (src->mOffset + n))
  1554. {
  1555. fprintf(stderr, "Error: Bad read from file '%s'.\n", src->mPath);
  1556. return 0;
  1557. }
  1558. fseek(fp, (long)(src->mOffset * block), SEEK_CUR);
  1559. if(!ReadWaveData(fp, src, order, n, &hrir[0]))
  1560. return 0;
  1561. return 1;
  1562. }
  1563. else if(fourCC == FOURCC_LIST)
  1564. {
  1565. if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC))
  1566. return 0;
  1567. chunkSize -= 4;
  1568. if(fourCC == FOURCC_WAVL)
  1569. break;
  1570. }
  1571. if(chunkSize > 0)
  1572. fseek(fp, (long)chunkSize, SEEK_CUR);
  1573. }
  1574. listSize = chunkSize;
  1575. block = src->mSize * src->mSkip;
  1576. skip = src->mOffset;
  1577. offset = 0;
  1578. lastSample = 0.0;
  1579. while(offset < n && listSize > 8)
  1580. {
  1581. if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
  1582. !ReadBin4(fp, src->mPath, order, 4, &chunkSize))
  1583. return 0;
  1584. listSize -= 8 + chunkSize;
  1585. if(fourCC == FOURCC_DATA)
  1586. {
  1587. count = chunkSize / block;
  1588. if(count > skip)
  1589. {
  1590. fseek(fp, (long)(skip * block), SEEK_CUR);
  1591. chunkSize -= skip * block;
  1592. count -= skip;
  1593. skip = 0;
  1594. if(count > (n - offset))
  1595. count = n - offset;
  1596. if(!ReadWaveData(fp, src, order, count, &hrir[offset]))
  1597. return 0;
  1598. chunkSize -= count * block;
  1599. offset += count;
  1600. lastSample = hrir [offset - 1];
  1601. }
  1602. else
  1603. {
  1604. skip -= count;
  1605. count = 0;
  1606. }
  1607. }
  1608. else if(fourCC == FOURCC_SLNT)
  1609. {
  1610. if(!ReadBin4(fp, src->mPath, order, 4, &count))
  1611. return 0;
  1612. chunkSize -= 4;
  1613. if(count > skip)
  1614. {
  1615. count -= skip;
  1616. skip = 0;
  1617. if(count > (n - offset))
  1618. count = n - offset;
  1619. for(i = 0; i < count; i ++)
  1620. hrir[offset + i] = lastSample;
  1621. offset += count;
  1622. }
  1623. else
  1624. {
  1625. skip -= count;
  1626. count = 0;
  1627. }
  1628. }
  1629. if(chunkSize > 0)
  1630. fseek(fp, (long)chunkSize, SEEK_CUR);
  1631. }
  1632. if(offset < n)
  1633. {
  1634. fprintf(stderr, "Error: Bad read from file '%s'.\n", src->mPath);
  1635. return 0;
  1636. }
  1637. return 1;
  1638. }
  1639. // Load a source HRIR from a RIFF/RIFX WAVE file.
  1640. static int LoadWaveSource(FILE *fp, SourceRefT *src, const uint hrirRate, const uint n, double *hrir)
  1641. {
  1642. uint32 fourCC, dummy;
  1643. ByteOrderT order;
  1644. if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC) ||
  1645. !ReadBin4(fp, src->mPath, BO_LITTLE, 4, &dummy))
  1646. return 0;
  1647. if(fourCC == FOURCC_RIFF)
  1648. order = BO_LITTLE;
  1649. else if(fourCC == FOURCC_RIFX)
  1650. order = BO_BIG;
  1651. else
  1652. {
  1653. fprintf(stderr, "Error: No RIFF/RIFX chunk in file '%s'.\n", src->mPath);
  1654. return 0;
  1655. }
  1656. if(!ReadBin4(fp, src->mPath, BO_LITTLE, 4, &fourCC))
  1657. return 0;
  1658. if(fourCC != FOURCC_WAVE)
  1659. {
  1660. fprintf(stderr, "Error: Not a RIFF/RIFX WAVE file '%s'.\n", src->mPath);
  1661. return 0;
  1662. }
  1663. if(!ReadWaveFormat(fp, order, hrirRate, src))
  1664. return 0;
  1665. if(!ReadWaveList(fp, src, order, n, hrir))
  1666. return 0;
  1667. return 1;
  1668. }
  1669. // Load a source HRIR from a binary file.
  1670. static int LoadBinarySource(FILE *fp, const SourceRefT *src, const ByteOrderT order, const uint n, double *hrir)
  1671. {
  1672. uint i;
  1673. fseek(fp, (long)src->mOffset, SEEK_SET);
  1674. for(i = 0;i < n;i++)
  1675. {
  1676. if(!ReadBinAsDouble(fp, src->mPath, order, src->mType, src->mSize, src->mBits, &hrir[i]))
  1677. return 0;
  1678. if(src->mSkip > 0)
  1679. fseek(fp, (long)src->mSkip, SEEK_CUR);
  1680. }
  1681. return 1;
  1682. }
  1683. // Load a source HRIR from an ASCII text file containing a list of elements
  1684. // separated by whitespace or common list operators (',', ';', ':', '|').
  1685. static int LoadAsciiSource(FILE *fp, const SourceRefT *src, const uint n, double *hrir)
  1686. {
  1687. TokenReaderT tr;
  1688. uint i, j;
  1689. double dummy;
  1690. TrSetup(fp, NULL, &tr);
  1691. for(i = 0;i < src->mOffset;i++)
  1692. {
  1693. if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &dummy))
  1694. return 0;
  1695. }
  1696. for(i = 0;i < n;i++)
  1697. {
  1698. if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &hrir[i]))
  1699. return 0;
  1700. for(j = 0;j < src->mSkip;j++)
  1701. {
  1702. if(!ReadAsciiAsDouble(&tr, src->mPath, src->mType, (uint)src->mBits, &dummy))
  1703. return 0;
  1704. }
  1705. }
  1706. return 1;
  1707. }
  1708. // Load a source HRIR from a supported file type.
  1709. static int LoadSource(SourceRefT *src, const uint hrirRate, const uint n, double *hrir)
  1710. {
  1711. int result;
  1712. FILE *fp;
  1713. if(src->mFormat == SF_ASCII)
  1714. fp = fopen(src->mPath, "r");
  1715. else
  1716. fp = fopen(src->mPath, "rb");
  1717. if(fp == NULL)
  1718. {
  1719. fprintf(stderr, "Error: Could not open source file '%s'.\n", src->mPath);
  1720. return 0;
  1721. }
  1722. if(src->mFormat == SF_WAVE)
  1723. result = LoadWaveSource(fp, src, hrirRate, n, hrir);
  1724. else if(src->mFormat == SF_BIN_LE)
  1725. result = LoadBinarySource(fp, src, BO_LITTLE, n, hrir);
  1726. else if(src->mFormat == SF_BIN_BE)
  1727. result = LoadBinarySource(fp, src, BO_BIG, n, hrir);
  1728. else
  1729. result = LoadAsciiSource(fp, src, n, hrir);
  1730. fclose(fp);
  1731. return result;
  1732. }
  1733. /***************************
  1734. *** File storage output ***
  1735. ***************************/
  1736. // Write an ASCII string to a file.
  1737. static int WriteAscii(const char *out, FILE *fp, const char *filename)
  1738. {
  1739. size_t len;
  1740. len = strlen(out);
  1741. if(fwrite(out, 1, len, fp) != len)
  1742. {
  1743. fclose(fp);
  1744. fprintf(stderr, "Error: Bad write to file '%s'.\n", filename);
  1745. return 0;
  1746. }
  1747. return 1;
  1748. }
  1749. // Write a binary value of the given byte order and byte size to a file,
  1750. // loading it from a 32-bit unsigned integer.
  1751. static int WriteBin4(const ByteOrderT order, const uint bytes, const uint32 in, FILE *fp, const char *filename)
  1752. {
  1753. uint8 out[4];
  1754. uint i;
  1755. switch(order)
  1756. {
  1757. case BO_LITTLE:
  1758. for(i = 0;i < bytes;i++)
  1759. out[i] = (in>>(i*8)) & 0x000000FF;
  1760. break;
  1761. case BO_BIG:
  1762. for(i = 0;i < bytes;i++)
  1763. out[bytes - i - 1] = (in>>(i*8)) & 0x000000FF;
  1764. break;
  1765. default:
  1766. break;
  1767. }
  1768. if(fwrite(out, 1, bytes, fp) != bytes)
  1769. {
  1770. fprintf(stderr, "Error: Bad write to file '%s'.\n", filename);
  1771. return 0;
  1772. }
  1773. return 1;
  1774. }
  1775. // Store the OpenAL Soft HRTF data set.
  1776. static int StoreMhr(const HrirDataT *hData, const char *filename)
  1777. {
  1778. uint channels = (hData->mChannelType == CT_STEREO) ? 2 : 1;
  1779. uint n = hData->mIrPoints;
  1780. FILE *fp;
  1781. uint fi, ei, ai, i;
  1782. uint dither_seed = 22222;
  1783. if((fp=fopen(filename, "wb")) == NULL)
  1784. {
  1785. fprintf(stderr, "Error: Could not open MHR file '%s'.\n", filename);
  1786. return 0;
  1787. }
  1788. if(!WriteAscii(MHR_FORMAT, fp, filename))
  1789. return 0;
  1790. if(!WriteBin4(BO_LITTLE, 4, (uint32)hData->mIrRate, fp, filename))
  1791. return 0;
  1792. if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mSampleType, fp, filename))
  1793. return 0;
  1794. if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mChannelType, fp, filename))
  1795. return 0;
  1796. if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mIrPoints, fp, filename))
  1797. return 0;
  1798. if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mFdCount, fp, filename))
  1799. return 0;
  1800. for(fi = 0;fi < hData->mFdCount;fi++)
  1801. {
  1802. if(!WriteBin4(BO_LITTLE, 2, (uint32)(1000.0 * hData->mFds[fi].mDistance), fp, filename))
  1803. return 0;
  1804. if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mFds[fi].mEvCount, fp, filename))
  1805. return 0;
  1806. for(ei = 0;ei < hData->mFds[fi].mEvCount;ei++)
  1807. {
  1808. if(!WriteBin4(BO_LITTLE, 1, (uint32)hData->mFds[fi].mEvs[ei].mAzCount, fp, filename))
  1809. return 0;
  1810. }
  1811. }
  1812. for(fi = 0;fi < hData->mFdCount;fi++)
  1813. {
  1814. const double scale = (hData->mSampleType == ST_S16) ? 32767.0 :
  1815. ((hData->mSampleType == ST_S24) ? 8388607.0 : 0.0);
  1816. const int bps = (hData->mSampleType == ST_S16) ? 2 :
  1817. ((hData->mSampleType == ST_S24) ? 3 : 0);
  1818. for(ei = 0;ei < hData->mFds[fi].mEvCount;ei++)
  1819. {
  1820. for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
  1821. {
  1822. HrirAzT *azd = &hData->mFds[fi].mEvs[ei].mAzs[ai];
  1823. double out[2 * MAX_TRUNCSIZE];
  1824. TpdfDither(out, azd->mIrs[0], scale, n, channels, &dither_seed);
  1825. if(hData->mChannelType == CT_STEREO)
  1826. TpdfDither(out+1, azd->mIrs[1], scale, n, channels, &dither_seed);
  1827. for(i = 0;i < (channels * n);i++)
  1828. {
  1829. int v = (int)Clamp(out[i], -scale-1.0, scale);
  1830. if(!WriteBin4(BO_LITTLE, bps, (uint32)v, fp, filename))
  1831. return 0;
  1832. }
  1833. }
  1834. }
  1835. }
  1836. for(fi = 0;fi < hData->mFdCount;fi++)
  1837. {
  1838. for(ei = 0;ei < hData->mFds[fi].mEvCount;ei++)
  1839. {
  1840. for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
  1841. {
  1842. HrirAzT *azd = &hData->mFds[fi].mEvs[ei].mAzs[ai];
  1843. int v = (int)fmin(round(hData->mIrRate * azd->mDelays[0]), MAX_HRTD);
  1844. if(!WriteBin4(BO_LITTLE, 1, (uint32)v, fp, filename))
  1845. return 0;
  1846. if(hData->mChannelType == CT_STEREO)
  1847. {
  1848. v = (int)fmin(round(hData->mIrRate * azd->mDelays[1]), MAX_HRTD);
  1849. if(!WriteBin4(BO_LITTLE, 1, (uint32)v, fp, filename))
  1850. return 0;
  1851. }
  1852. }
  1853. }
  1854. }
  1855. fclose(fp);
  1856. return 1;
  1857. }
  1858. /***********************
  1859. *** HRTF processing ***
  1860. ***********************/
  1861. // Calculate the onset time of an HRIR and average it with any existing
  1862. // timing for its field, elevation, azimuth, and ear.
  1863. static double AverageHrirOnset(const uint rate, const uint n, const double *hrir, const double f, const double onset)
  1864. {
  1865. double mag = 0.0;
  1866. uint i;
  1867. for(i = 0;i < n;i++)
  1868. mag = fmax(fabs(hrir[i]), mag);
  1869. mag *= 0.15;
  1870. for(i = 0;i < n;i++)
  1871. {
  1872. if(fabs(hrir[i]) >= mag)
  1873. break;
  1874. }
  1875. return Lerp(onset, (double)i / rate, f);
  1876. }
  1877. // Calculate the magnitude response of an HRIR and average it with any
  1878. // existing responses for its field, elevation, azimuth, and ear.
  1879. static void AverageHrirMagnitude(const uint points, const uint n, const double *hrir, const double f, double *mag)
  1880. {
  1881. uint m = 1 + (n / 2), i;
  1882. Complex *h = CreateComplexes(n);
  1883. double *r = CreateDoubles(n);
  1884. for(i = 0;i < points;i++)
  1885. h[i] = MakeComplex(hrir[i], 0.0);
  1886. for(;i < n;i++)
  1887. h[i] = MakeComplex(0.0, 0.0);
  1888. FftForward(n, h, h);
  1889. MagnitudeResponse(n, h, r);
  1890. for(i = 0;i < m;i++)
  1891. mag[i] = Lerp(mag[i], r[i], f);
  1892. free(r);
  1893. free(h);
  1894. }
  1895. /* Calculate the contribution of each HRIR to the diffuse-field average based
  1896. * on the area of its surface patch. All patches are centered at the HRIR
  1897. * coordinates on the unit sphere and are measured by solid angle.
  1898. */
  1899. static void CalculateDfWeights(const HrirDataT *hData, double *weights)
  1900. {
  1901. double sum, evs, ev, upperEv, lowerEv, solidAngle;
  1902. uint fi, ei;
  1903. sum = 0.0;
  1904. for(fi = 0;fi < hData->mFdCount;fi++)
  1905. {
  1906. evs = M_PI / 2.0 / (hData->mFds[fi].mEvCount - 1);
  1907. for(ei = hData->mFds[fi].mEvStart;ei < hData->mFds[fi].mEvCount;ei++)
  1908. {
  1909. // For each elevation, calculate the upper and lower limits of
  1910. // the patch band.
  1911. ev = hData->mFds[fi].mEvs[ei].mElevation;
  1912. lowerEv = fmax(-M_PI / 2.0, ev - evs);
  1913. upperEv = fmin(M_PI / 2.0, ev + evs);
  1914. // Calculate the area of the patch band.
  1915. solidAngle = 2.0 * M_PI * (sin(upperEv) - sin(lowerEv));
  1916. // Each weight is the area of one patch.
  1917. weights[(fi * MAX_EV_COUNT) + ei] = solidAngle / hData->mFds[fi].mEvs[ei].mAzCount;
  1918. // Sum the total surface area covered by the HRIRs of all fields.
  1919. sum += solidAngle;
  1920. }
  1921. }
  1922. /* TODO: It may be interesting to experiment with how a volume-based
  1923. weighting performs compared to the existing distance-indepenent
  1924. surface patches.
  1925. */
  1926. for(fi = 0;fi < hData->mFdCount;fi++)
  1927. {
  1928. // Normalize the weights given the total surface coverage for all
  1929. // fields.
  1930. for(ei = hData->mFds[fi].mEvStart;ei < hData->mFds[fi].mEvCount;ei++)
  1931. weights[(fi * MAX_EV_COUNT) + ei] /= sum;
  1932. }
  1933. }
  1934. /* Calculate the diffuse-field average from the given magnitude responses of
  1935. * the HRIR set. Weighting can be applied to compensate for the varying
  1936. * surface area covered by each HRIR. The final average can then be limited
  1937. * by the specified magnitude range (in positive dB; 0.0 to skip).
  1938. */
  1939. static void CalculateDiffuseFieldAverage(const HrirDataT *hData, const uint channels, const uint m, const int weighted, const double limit, double *dfa)
  1940. {
  1941. double *weights = CreateDoubles(hData->mFdCount * MAX_EV_COUNT);
  1942. uint count, ti, fi, ei, i, ai;
  1943. if(weighted)
  1944. {
  1945. // Use coverage weighting to calculate the average.
  1946. CalculateDfWeights(hData, weights);
  1947. }
  1948. else
  1949. {
  1950. double weight;
  1951. // If coverage weighting is not used, the weights still need to be
  1952. // averaged by the number of existing HRIRs.
  1953. count = hData->mIrCount;
  1954. for(fi = 0;fi < hData->mFdCount;fi++)
  1955. {
  1956. for(ei = 0;ei < hData->mFds[fi].mEvStart;ei++)
  1957. count -= hData->mFds[fi].mEvs[ei].mAzCount;
  1958. }
  1959. weight = 1.0 / count;
  1960. for(fi = 0;fi < hData->mFdCount;fi++)
  1961. {
  1962. for(ei = hData->mFds[fi].mEvStart;ei < hData->mFds[fi].mEvCount;ei++)
  1963. weights[(fi * MAX_EV_COUNT) + ei] = weight;
  1964. }
  1965. }
  1966. for(ti = 0;ti < channels;ti++)
  1967. {
  1968. for(i = 0;i < m;i++)
  1969. dfa[(ti * m) + i] = 0.0;
  1970. for(fi = 0;fi < hData->mFdCount;fi++)
  1971. {
  1972. for(ei = hData->mFds[fi].mEvStart;ei < hData->mFds[fi].mEvCount;ei++)
  1973. {
  1974. for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
  1975. {
  1976. HrirAzT *azd = &hData->mFds[fi].mEvs[ei].mAzs[ai];
  1977. // Get the weight for this HRIR's contribution.
  1978. double weight = weights[(fi * MAX_EV_COUNT) + ei];
  1979. // Add this HRIR's weighted power average to the total.
  1980. for(i = 0;i < m;i++)
  1981. dfa[(ti * m) + i] += weight * azd->mIrs[ti][i] * azd->mIrs[ti][i];
  1982. }
  1983. }
  1984. }
  1985. // Finish the average calculation and keep it from being too small.
  1986. for(i = 0;i < m;i++)
  1987. dfa[(ti * m) + i] = fmax(sqrt(dfa[(ti * m) + i]), EPSILON);
  1988. // Apply a limit to the magnitude range of the diffuse-field average
  1989. // if desired.
  1990. if(limit > 0.0)
  1991. LimitMagnitudeResponse(hData->mFftSize, m, limit, &dfa[ti * m], &dfa[ti * m]);
  1992. }
  1993. free(weights);
  1994. }
  1995. // Perform diffuse-field equalization on the magnitude responses of the HRIR
  1996. // set using the given average response.
  1997. static void DiffuseFieldEqualize(const uint channels, const uint m, const double *dfa, const HrirDataT *hData)
  1998. {
  1999. uint ti, fi, ei, ai, i;
  2000. for(ti = 0;ti < channels;ti++)
  2001. {
  2002. for(fi = 0;fi < hData->mFdCount;fi++)
  2003. {
  2004. for(ei = hData->mFds[fi].mEvStart;ei < hData->mFds[fi].mEvCount;ei++)
  2005. {
  2006. for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
  2007. {
  2008. HrirAzT *azd = &hData->mFds[fi].mEvs[ei].mAzs[ai];
  2009. for(i = 0;i < m;i++)
  2010. azd->mIrs[ti][i] /= dfa[(ti * m) + i];
  2011. }
  2012. }
  2013. }
  2014. }
  2015. }
  2016. // Perform minimum-phase reconstruction using the magnitude responses of the
  2017. // HRIR set.
  2018. static void ReconstructHrirs(const HrirDataT *hData)
  2019. {
  2020. uint channels = (hData->mChannelType == CT_STEREO) ? 2 : 1;
  2021. uint n = hData->mFftSize;
  2022. uint ti, fi, ei, ai, i;
  2023. Complex *h = CreateComplexes(n);
  2024. uint total, count, pcdone, lastpc;
  2025. total = hData->mIrCount;
  2026. for(fi = 0;fi < hData->mFdCount;fi++)
  2027. {
  2028. for(ei = 0;ei < hData->mFds[fi].mEvStart;ei++)
  2029. total -= hData->mFds[fi].mEvs[ei].mAzCount;
  2030. }
  2031. total *= channels;
  2032. count = pcdone = lastpc = 0;
  2033. printf("%3d%% done.", pcdone);
  2034. fflush(stdout);
  2035. for(ti = 0;ti < channels;ti++)
  2036. {
  2037. for(fi = 0;fi < hData->mFdCount;fi++)
  2038. {
  2039. for(ei = hData->mFds[fi].mEvStart;ei < hData->mFds[fi].mEvCount;ei++)
  2040. {
  2041. for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
  2042. {
  2043. HrirAzT *azd = &hData->mFds[fi].mEvs[ei].mAzs[ai];
  2044. MinimumPhase(n, azd->mIrs[ti], h);
  2045. FftInverse(n, h, h);
  2046. for(i = 0;i < hData->mIrPoints;i++)
  2047. azd->mIrs[ti][i] = h[i].Real;
  2048. pcdone = ++count * 100 / total;
  2049. if(pcdone != lastpc)
  2050. {
  2051. lastpc = pcdone;
  2052. printf("\r%3d%% done.", pcdone);
  2053. fflush(stdout);
  2054. }
  2055. }
  2056. }
  2057. }
  2058. }
  2059. printf("\n");
  2060. free(h);
  2061. }
  2062. // Resamples the HRIRs for use at the given sampling rate.
  2063. static void ResampleHrirs(const uint rate, HrirDataT *hData)
  2064. {
  2065. uint channels = (hData->mChannelType == CT_STEREO) ? 2 : 1;
  2066. uint n = hData->mIrPoints;
  2067. uint ti, fi, ei, ai;
  2068. ResamplerT rs;
  2069. ResamplerSetup(&rs, hData->mIrRate, rate);
  2070. for(ti = 0;ti < channels;ti++)
  2071. {
  2072. for(fi = 0;fi < hData->mFdCount;fi++)
  2073. {
  2074. for(ei = hData->mFds[fi].mEvStart;ei < hData->mFds[fi].mEvCount;ei++)
  2075. {
  2076. for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
  2077. {
  2078. HrirAzT *azd = &hData->mFds[fi].mEvs[ei].mAzs[ai];
  2079. ResamplerRun(&rs, n, azd->mIrs[ti], n, azd->mIrs[ti]);
  2080. }
  2081. }
  2082. }
  2083. }
  2084. hData->mIrRate = rate;
  2085. ResamplerClear(&rs);
  2086. }
  2087. /* Given field and elevation indices and an azimuth, calculate the indices of
  2088. * the two HRIRs that bound the coordinate along with a factor for
  2089. * calculating the continuous HRIR using interpolation.
  2090. */
  2091. static void CalcAzIndices(const HrirDataT *hData, const uint fi, const uint ei, const double az, uint *a0, uint *a1, double *af)
  2092. {
  2093. double f = (2.0*M_PI + az) * hData->mFds[fi].mEvs[ei].mAzCount / (2.0*M_PI);
  2094. uint i = (uint)f % hData->mFds[fi].mEvs[ei].mAzCount;
  2095. f -= floor(f);
  2096. *a0 = i;
  2097. *a1 = (i + 1) % hData->mFds[fi].mEvs[ei].mAzCount;
  2098. *af = f;
  2099. }
  2100. // Synthesize any missing onset timings at the bottom elevations of each
  2101. // field. This just blends between slightly exaggerated known onsets (not
  2102. // an accurate model).
  2103. static void SynthesizeOnsets(HrirDataT *hData)
  2104. {
  2105. uint channels = (hData->mChannelType == CT_STEREO) ? 2 : 1;
  2106. uint ti, fi, oi, ai, ei, a0, a1;
  2107. double t, of, af;
  2108. for(ti = 0;ti < channels;ti++)
  2109. {
  2110. for(fi = 0;fi < hData->mFdCount;fi++)
  2111. {
  2112. if(hData->mFds[fi].mEvStart <= 0)
  2113. continue;
  2114. oi = hData->mFds[fi].mEvStart;
  2115. t = 0.0;
  2116. for(ai = 0;ai < hData->mFds[fi].mEvs[oi].mAzCount;ai++)
  2117. t += hData->mFds[fi].mEvs[oi].mAzs[ai].mDelays[ti];
  2118. hData->mFds[fi].mEvs[0].mAzs[0].mDelays[ti] = 1.32e-4 + (t / hData->mFds[fi].mEvs[oi].mAzCount);
  2119. for(ei = 1;ei < hData->mFds[fi].mEvStart;ei++)
  2120. {
  2121. of = (double)ei / hData->mFds[fi].mEvStart;
  2122. for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
  2123. {
  2124. CalcAzIndices(hData, fi, oi, hData->mFds[fi].mEvs[ei].mAzs[ai].mAzimuth, &a0, &a1, &af);
  2125. hData->mFds[fi].mEvs[ei].mAzs[ai].mDelays[ti] = Lerp(hData->mFds[fi].mEvs[0].mAzs[0].mDelays[ti], Lerp(hData->mFds[fi].mEvs[oi].mAzs[a0].mDelays[ti], hData->mFds[fi].mEvs[oi].mAzs[a1].mDelays[ti], af), of);
  2126. }
  2127. }
  2128. }
  2129. }
  2130. }
  2131. /* Attempt to synthesize any missing HRIRs at the bottom elevations of each
  2132. * field. Right now this just blends the lowest elevation HRIRs together and
  2133. * applies some attenuation and high frequency damping. It is a simple, if
  2134. * inaccurate model.
  2135. */
  2136. static void SynthesizeHrirs(HrirDataT *hData)
  2137. {
  2138. uint channels = (hData->mChannelType == CT_STEREO) ? 2 : 1;
  2139. uint n = hData->mIrPoints;
  2140. uint ti, fi, ai, ei, i;
  2141. double lp[4], s0, s1;
  2142. double of, b;
  2143. uint a0, a1;
  2144. double af;
  2145. for(fi = 0;fi < hData->mFdCount;fi++)
  2146. {
  2147. const uint oi = hData->mFds[fi].mEvStart;
  2148. if(oi <= 0) continue;
  2149. for(ti = 0;ti < channels;ti++)
  2150. {
  2151. for(i = 0;i < n;i++)
  2152. hData->mFds[fi].mEvs[0].mAzs[0].mIrs[ti][i] = 0.0;
  2153. for(ai = 0;ai < hData->mFds[fi].mEvs[oi].mAzCount;ai++)
  2154. {
  2155. for(i = 0;i < n;i++)
  2156. hData->mFds[fi].mEvs[0].mAzs[0].mIrs[ti][i] += hData->mFds[fi].mEvs[oi].mAzs[ai].mIrs[ti][i] /
  2157. hData->mFds[fi].mEvs[oi].mAzCount;
  2158. }
  2159. for(ei = 1;ei < hData->mFds[fi].mEvStart;ei++)
  2160. {
  2161. of = (double)ei / hData->mFds[fi].mEvStart;
  2162. b = (1.0 - of) * (3.5e-6 * hData->mIrRate);
  2163. for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
  2164. {
  2165. CalcAzIndices(hData, fi, oi, hData->mFds[fi].mEvs[ei].mAzs[ai].mAzimuth, &a0, &a1, &af);
  2166. lp[0] = 0.0;
  2167. lp[1] = 0.0;
  2168. lp[2] = 0.0;
  2169. lp[3] = 0.0;
  2170. for(i = 0;i < n;i++)
  2171. {
  2172. s0 = hData->mFds[fi].mEvs[0].mAzs[0].mIrs[ti][i];
  2173. s1 = Lerp(hData->mFds[fi].mEvs[oi].mAzs[a0].mIrs[ti][i],
  2174. hData->mFds[fi].mEvs[oi].mAzs[a1].mIrs[ti][i], af);
  2175. s0 = Lerp(s0, s1, of);
  2176. lp[0] = Lerp(s0, lp[0], b);
  2177. lp[1] = Lerp(lp[0], lp[1], b);
  2178. lp[2] = Lerp(lp[1], lp[2], b);
  2179. lp[3] = Lerp(lp[2], lp[3], b);
  2180. hData->mFds[fi].mEvs[ei].mAzs[ai].mIrs[ti][i] = lp[3];
  2181. }
  2182. }
  2183. }
  2184. b = 3.5e-6 * hData->mIrRate;
  2185. lp[0] = 0.0;
  2186. lp[1] = 0.0;
  2187. lp[2] = 0.0;
  2188. lp[3] = 0.0;
  2189. for(i = 0;i < n;i++)
  2190. {
  2191. s0 = hData->mFds[fi].mEvs[0].mAzs[0].mIrs[ti][i];
  2192. lp[0] = Lerp(s0, lp[0], b);
  2193. lp[1] = Lerp(lp[0], lp[1], b);
  2194. lp[2] = Lerp(lp[1], lp[2], b);
  2195. lp[3] = Lerp(lp[2], lp[3], b);
  2196. hData->mFds[fi].mEvs[0].mAzs[0].mIrs[ti][i] = lp[3];
  2197. }
  2198. }
  2199. hData->mFds[fi].mEvStart = 0;
  2200. }
  2201. }
  2202. // The following routines assume a full set of HRIRs for all elevations.
  2203. // Normalize the HRIR set and slightly attenuate the result.
  2204. static void NormalizeHrirs(const HrirDataT *hData)
  2205. {
  2206. uint channels = (hData->mChannelType == CT_STEREO) ? 2 : 1;
  2207. uint n = hData->mIrPoints;
  2208. uint ti, fi, ei, ai, i;
  2209. double maxLevel = 0.0;
  2210. for(ti = 0;ti < channels;ti++)
  2211. {
  2212. for(fi = 0;fi < hData->mFdCount;fi++)
  2213. {
  2214. for(ei = 0;ei < hData->mFds[fi].mEvCount;ei++)
  2215. {
  2216. for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
  2217. {
  2218. HrirAzT *azd = &hData->mFds[fi].mEvs[ei].mAzs[ai];
  2219. for(i = 0;i < n;i++)
  2220. maxLevel = fmax(fabs(azd->mIrs[ti][i]), maxLevel);
  2221. }
  2222. }
  2223. }
  2224. }
  2225. maxLevel = 1.01 * maxLevel;
  2226. for(ti = 0;ti < channels;ti++)
  2227. {
  2228. for(fi = 0;fi < hData->mFdCount;fi++)
  2229. {
  2230. for(ei = 0;ei < hData->mFds[fi].mEvCount;ei++)
  2231. {
  2232. for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
  2233. {
  2234. HrirAzT *azd = &hData->mFds[fi].mEvs[ei].mAzs[ai];
  2235. for(i = 0;i < n;i++)
  2236. azd->mIrs[ti][i] /= maxLevel;
  2237. }
  2238. }
  2239. }
  2240. }
  2241. }
  2242. // Calculate the left-ear time delay using a spherical head model.
  2243. static double CalcLTD(const double ev, const double az, const double rad, const double dist)
  2244. {
  2245. double azp, dlp, l, al;
  2246. azp = asin(cos(ev) * sin(az));
  2247. dlp = sqrt((dist*dist) + (rad*rad) + (2.0*dist*rad*sin(azp)));
  2248. l = sqrt((dist*dist) - (rad*rad));
  2249. al = (0.5 * M_PI) + azp;
  2250. if(dlp > l)
  2251. dlp = l + (rad * (al - acos(rad / dist)));
  2252. return dlp / 343.3;
  2253. }
  2254. // Calculate the effective head-related time delays for each minimum-phase
  2255. // HRIR.
  2256. static void CalculateHrtds(const HeadModelT model, const double radius, HrirDataT *hData)
  2257. {
  2258. uint channels = (hData->mChannelType == CT_STEREO) ? 2 : 1;
  2259. double minHrtd = INFINITY, maxHrtd = -INFINITY;
  2260. uint ti, fi, ei, ai;
  2261. double t;
  2262. if(model == HM_DATASET)
  2263. {
  2264. for(ti = 0;ti < channels;ti++)
  2265. {
  2266. for(fi = 0;fi < hData->mFdCount;fi++)
  2267. {
  2268. for(ei = 0;ei < hData->mFds[fi].mEvCount;ei++)
  2269. {
  2270. for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
  2271. {
  2272. HrirAzT *azd = &hData->mFds[fi].mEvs[ei].mAzs[ai];
  2273. t = azd->mDelays[ti] * radius / hData->mRadius;
  2274. azd->mDelays[ti] = t;
  2275. maxHrtd = fmax(t, maxHrtd);
  2276. minHrtd = fmin(t, minHrtd);
  2277. }
  2278. }
  2279. }
  2280. }
  2281. }
  2282. else
  2283. {
  2284. for(ti = 0;ti < channels;ti++)
  2285. {
  2286. for(fi = 0;fi < hData->mFdCount;fi++)
  2287. {
  2288. for(ei = 0;ei < hData->mFds[fi].mEvCount;ei++)
  2289. {
  2290. HrirEvT *evd = &hData->mFds[fi].mEvs[ei];
  2291. for(ai = 0;ai < evd->mAzCount;ai++)
  2292. {
  2293. HrirAzT *azd = &evd->mAzs[ai];
  2294. t = CalcLTD(evd->mElevation, azd->mAzimuth, radius, hData->mFds[fi].mDistance);
  2295. azd->mDelays[ti] = t;
  2296. maxHrtd = fmax(t, maxHrtd);
  2297. minHrtd = fmin(t, minHrtd);
  2298. }
  2299. }
  2300. }
  2301. }
  2302. }
  2303. for(ti = 0;ti < channels;ti++)
  2304. {
  2305. for(fi = 0;fi < hData->mFdCount;fi++)
  2306. {
  2307. for(ei = 0;ei < hData->mFds[fi].mEvCount;ei++)
  2308. {
  2309. for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
  2310. hData->mFds[fi].mEvs[ei].mAzs[ai].mDelays[ti] -= minHrtd;
  2311. }
  2312. }
  2313. }
  2314. }
  2315. // Clear the initial HRIR data state.
  2316. static void ResetHrirData(HrirDataT *hData)
  2317. {
  2318. hData->mIrRate = 0;
  2319. hData->mSampleType = ST_S24;
  2320. hData->mChannelType = CT_NONE;
  2321. hData->mIrPoints = 0;
  2322. hData->mFftSize = 0;
  2323. hData->mIrSize = 0;
  2324. hData->mRadius = 0.0;
  2325. hData->mIrCount = 0;
  2326. hData->mFdCount = 0;
  2327. hData->mFds = NULL;
  2328. }
  2329. // Allocate and configure dynamic HRIR structures.
  2330. 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)
  2331. {
  2332. uint evTotal = 0, azTotal = 0, fi, ei, ai;
  2333. for(fi = 0;fi < fdCount;fi++)
  2334. {
  2335. evTotal += evCounts[fi];
  2336. for(ei = 0;ei < evCounts[fi];ei++)
  2337. azTotal += azCounts[(fi * MAX_EV_COUNT) + ei];
  2338. }
  2339. if(!fdCount || !evTotal || !azTotal)
  2340. return 0;
  2341. hData->mFds = calloc(fdCount, sizeof(*hData->mFds));
  2342. if(hData->mFds == NULL)
  2343. return 0;
  2344. hData->mFds[0].mEvs = calloc(evTotal, sizeof(*hData->mFds[0].mEvs));
  2345. if(hData->mFds[0].mEvs == NULL)
  2346. return 0;
  2347. hData->mFds[0].mEvs[0].mAzs = calloc(azTotal, sizeof(*hData->mFds[0].mEvs[0].mAzs));
  2348. if(hData->mFds[0].mEvs[0].mAzs == NULL)
  2349. return 0;
  2350. hData->mIrCount = azTotal;
  2351. hData->mFdCount = fdCount;
  2352. evTotal = 0;
  2353. azTotal = 0;
  2354. for(fi = 0;fi < fdCount;fi++)
  2355. {
  2356. hData->mFds[fi].mDistance = distances[fi];
  2357. hData->mFds[fi].mEvCount = evCounts[fi];
  2358. hData->mFds[fi].mEvStart = 0;
  2359. hData->mFds[fi].mEvs = &hData->mFds[0].mEvs[evTotal];
  2360. evTotal += evCounts[fi];
  2361. for(ei = 0;ei < evCounts[fi];ei++)
  2362. {
  2363. uint azCount = azCounts[(fi * MAX_EV_COUNT) + ei];
  2364. hData->mFds[fi].mIrCount += azCount;
  2365. hData->mFds[fi].mEvs[ei].mElevation = -M_PI / 2.0 + M_PI * ei / (evCounts[fi] - 1);
  2366. hData->mFds[fi].mEvs[ei].mIrCount += azCount;
  2367. hData->mFds[fi].mEvs[ei].mAzCount = azCount;
  2368. hData->mFds[fi].mEvs[ei].mAzs = &hData->mFds[0].mEvs[0].mAzs[azTotal];
  2369. for(ai = 0;ai < azCount;ai++)
  2370. {
  2371. hData->mFds[fi].mEvs[ei].mAzs[ai].mAzimuth = 2.0 * M_PI * ai / azCount;
  2372. hData->mFds[fi].mEvs[ei].mAzs[ai].mIndex = azTotal + ai;
  2373. hData->mFds[fi].mEvs[ei].mAzs[ai].mDelays[0] = 0.0;
  2374. hData->mFds[fi].mEvs[ei].mAzs[ai].mDelays[1] = 0.0;
  2375. hData->mFds[fi].mEvs[ei].mAzs[ai].mIrs[0] = NULL;
  2376. hData->mFds[fi].mEvs[ei].mAzs[ai].mIrs[1] = NULL;
  2377. }
  2378. azTotal += azCount;
  2379. }
  2380. }
  2381. return 1;
  2382. }
  2383. // Clean up HRIR data.
  2384. static void FreeHrirData(HrirDataT *hData)
  2385. {
  2386. if(hData->mFds != NULL)
  2387. {
  2388. if(hData->mFds[0].mEvs != NULL)
  2389. {
  2390. if(hData->mFds[0].mEvs[0].mAzs)
  2391. {
  2392. if(hData->mFds[0].mEvs[0].mAzs[0].mIrs[0] != NULL)
  2393. free(hData->mFds[0].mEvs[0].mAzs[0].mIrs[0]);
  2394. free(hData->mFds[0].mEvs[0].mAzs);
  2395. }
  2396. free(hData->mFds[0].mEvs);
  2397. }
  2398. free(hData->mFds);
  2399. hData->mFds = NULL;
  2400. }
  2401. }
  2402. // Match the channel type from a given identifier.
  2403. static ChannelTypeT MatchChannelType(const char *ident)
  2404. {
  2405. if(strcasecmp(ident, "mono") == 0)
  2406. return CT_MONO;
  2407. if(strcasecmp(ident, "stereo") == 0)
  2408. return CT_STEREO;
  2409. return CT_NONE;
  2410. }
  2411. // Process the data set definition to read and validate the data set metrics.
  2412. static int ProcessMetrics(TokenReaderT *tr, const uint fftSize, const uint truncSize, HrirDataT *hData)
  2413. {
  2414. int hasRate = 0, hasType = 0, hasPoints = 0, hasRadius = 0;
  2415. int hasDistance = 0, hasAzimuths = 0;
  2416. char ident[MAX_IDENT_LEN+1];
  2417. uint line, col;
  2418. double fpVal;
  2419. uint points;
  2420. int intVal;
  2421. double distances[MAX_FD_COUNT];
  2422. uint fdCount = 0;
  2423. uint evCounts[MAX_FD_COUNT];
  2424. uint *azCounts = calloc(MAX_FD_COUNT * MAX_EV_COUNT, sizeof(*azCounts));
  2425. if(azCounts == NULL)
  2426. {
  2427. fprintf(stderr, "Error: Out of memory.\n");
  2428. exit(-1);
  2429. }
  2430. TrIndication(tr, &line, &col);
  2431. while(TrIsIdent(tr))
  2432. {
  2433. TrIndication(tr, &line, &col);
  2434. if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
  2435. goto error;
  2436. if(strcasecmp(ident, "rate") == 0)
  2437. {
  2438. if(hasRate)
  2439. {
  2440. TrErrorAt(tr, line, col, "Redefinition of 'rate'.\n");
  2441. goto error;
  2442. }
  2443. if(!TrReadOperator(tr, "="))
  2444. goto error;
  2445. if(!TrReadInt(tr, MIN_RATE, MAX_RATE, &intVal))
  2446. goto error;
  2447. hData->mIrRate = (uint)intVal;
  2448. hasRate = 1;
  2449. }
  2450. else if(strcasecmp(ident, "type") == 0)
  2451. {
  2452. char type[MAX_IDENT_LEN+1];
  2453. if(hasType)
  2454. {
  2455. TrErrorAt(tr, line, col, "Redefinition of 'type'.\n");
  2456. goto error;
  2457. }
  2458. if(!TrReadOperator(tr, "="))
  2459. goto error;
  2460. if(!TrReadIdent(tr, MAX_IDENT_LEN, type))
  2461. goto error;
  2462. hData->mChannelType = MatchChannelType(type);
  2463. if(hData->mChannelType == CT_NONE)
  2464. {
  2465. TrErrorAt(tr, line, col, "Expected a channel type.\n");
  2466. goto error;
  2467. }
  2468. hasType = 1;
  2469. }
  2470. else if(strcasecmp(ident, "points") == 0)
  2471. {
  2472. if(hasPoints)
  2473. {
  2474. TrErrorAt(tr, line, col, "Redefinition of 'points'.\n");
  2475. goto error;
  2476. }
  2477. if(!TrReadOperator(tr, "="))
  2478. goto error;
  2479. TrIndication(tr, &line, &col);
  2480. if(!TrReadInt(tr, MIN_POINTS, MAX_POINTS, &intVal))
  2481. goto error;
  2482. points = (uint)intVal;
  2483. if(fftSize > 0 && points > fftSize)
  2484. {
  2485. TrErrorAt(tr, line, col, "Value exceeds the overridden FFT size.\n");
  2486. goto error;
  2487. }
  2488. if(points < truncSize)
  2489. {
  2490. TrErrorAt(tr, line, col, "Value is below the truncation size.\n");
  2491. goto error;
  2492. }
  2493. hData->mIrPoints = points;
  2494. if(fftSize <= 0)
  2495. {
  2496. hData->mFftSize = DEFAULT_FFTSIZE;
  2497. hData->mIrSize = 1 + (DEFAULT_FFTSIZE / 2);
  2498. }
  2499. else
  2500. {
  2501. hData->mFftSize = fftSize;
  2502. hData->mIrSize = 1 + (fftSize / 2);
  2503. if(points > hData->mIrSize)
  2504. hData->mIrSize = points;
  2505. }
  2506. hasPoints = 1;
  2507. }
  2508. else if(strcasecmp(ident, "radius") == 0)
  2509. {
  2510. if(hasRadius)
  2511. {
  2512. TrErrorAt(tr, line, col, "Redefinition of 'radius'.\n");
  2513. goto error;
  2514. }
  2515. if(!TrReadOperator(tr, "="))
  2516. goto error;
  2517. if(!TrReadFloat(tr, MIN_RADIUS, MAX_RADIUS, &fpVal))
  2518. goto error;
  2519. hData->mRadius = fpVal;
  2520. hasRadius = 1;
  2521. }
  2522. else if(strcasecmp(ident, "distance") == 0)
  2523. {
  2524. uint count = 0;
  2525. if(hasDistance)
  2526. {
  2527. TrErrorAt(tr, line, col, "Redefinition of 'distance'.\n");
  2528. goto error;
  2529. }
  2530. if(!TrReadOperator(tr, "="))
  2531. goto error;
  2532. for(;;)
  2533. {
  2534. if(!TrReadFloat(tr, MIN_DISTANCE, MAX_DISTANCE, &fpVal))
  2535. goto error;
  2536. if(count > 0 && fpVal <= distances[count - 1])
  2537. {
  2538. TrError(tr, "Distances are not ascending.\n");
  2539. goto error;
  2540. }
  2541. distances[count++] = fpVal;
  2542. if(!TrIsOperator(tr, ","))
  2543. break;
  2544. if(count >= MAX_FD_COUNT)
  2545. {
  2546. TrError(tr, "Exceeded the maximum of %d fields.\n", MAX_FD_COUNT);
  2547. goto error;
  2548. }
  2549. TrReadOperator(tr, ",");
  2550. }
  2551. if(fdCount != 0 && count != fdCount)
  2552. {
  2553. TrError(tr, "Did not match the specified number of %d fields.\n", fdCount);
  2554. goto error;
  2555. }
  2556. fdCount = count;
  2557. hasDistance = 1;
  2558. }
  2559. else if(strcasecmp(ident, "azimuths") == 0)
  2560. {
  2561. uint count = 0;
  2562. if(hasAzimuths)
  2563. {
  2564. TrErrorAt(tr, line, col, "Redefinition of 'azimuths'.\n");
  2565. goto error;
  2566. }
  2567. if(!TrReadOperator(tr, "="))
  2568. goto error;
  2569. evCounts[0] = 0;
  2570. for(;;)
  2571. {
  2572. if(!TrReadInt(tr, MIN_AZ_COUNT, MAX_AZ_COUNT, &intVal))
  2573. goto error;
  2574. azCounts[(count * MAX_EV_COUNT) + evCounts[count]++] = (uint)intVal;
  2575. if(TrIsOperator(tr, ","))
  2576. {
  2577. if(evCounts[count] >= MAX_EV_COUNT)
  2578. {
  2579. TrError(tr, "Exceeded the maximum of %d elevations.\n", MAX_EV_COUNT);
  2580. goto error;
  2581. }
  2582. TrReadOperator(tr, ",");
  2583. }
  2584. else
  2585. {
  2586. if(evCounts[count] < MIN_EV_COUNT)
  2587. {
  2588. TrErrorAt(tr, line, col, "Did not reach the minimum of %d azimuth counts.\n", MIN_EV_COUNT);
  2589. goto error;
  2590. }
  2591. if(azCounts[count * MAX_EV_COUNT] != 1 || azCounts[(count * MAX_EV_COUNT) + evCounts[count] - 1] != 1)
  2592. {
  2593. TrError(tr, "Poles are not singular for field %d.\n", count - 1);
  2594. goto error;
  2595. }
  2596. count++;
  2597. if(TrIsOperator(tr, ";"))
  2598. {
  2599. if(count >= MAX_FD_COUNT)
  2600. {
  2601. TrError(tr, "Exceeded the maximum number of %d fields.\n", MAX_FD_COUNT);
  2602. goto error;
  2603. }
  2604. evCounts[count] = 0;
  2605. TrReadOperator(tr, ";");
  2606. }
  2607. else
  2608. {
  2609. break;
  2610. }
  2611. }
  2612. }
  2613. if(fdCount != 0 && count != fdCount)
  2614. {
  2615. TrError(tr, "Did not match the specified number of %d fields.\n", fdCount);
  2616. goto error;
  2617. }
  2618. fdCount = count;
  2619. hasAzimuths = 1;
  2620. }
  2621. else
  2622. {
  2623. TrErrorAt(tr, line, col, "Expected a metric name.\n");
  2624. goto error;
  2625. }
  2626. TrSkipWhitespace(tr);
  2627. }
  2628. if(!(hasRate && hasPoints && hasRadius && hasDistance && hasAzimuths))
  2629. {
  2630. TrErrorAt(tr, line, col, "Expected a metric name.\n");
  2631. goto error;
  2632. }
  2633. if(distances[0] < hData->mRadius)
  2634. {
  2635. TrError(tr, "Distance cannot start below head radius.\n");
  2636. goto error;
  2637. }
  2638. if(hData->mChannelType == CT_NONE)
  2639. hData->mChannelType = CT_MONO;
  2640. if(!PrepareHrirData(fdCount, distances, evCounts, azCounts, hData))
  2641. {
  2642. fprintf(stderr, "Error: Out of memory.\n");
  2643. exit(-1);
  2644. }
  2645. free(azCounts);
  2646. return 1;
  2647. error:
  2648. free(azCounts);
  2649. return 0;
  2650. }
  2651. // Parse an index triplet from the data set definition.
  2652. static int ReadIndexTriplet(TokenReaderT *tr, const HrirDataT *hData, uint *fi, uint *ei, uint *ai)
  2653. {
  2654. int intVal;
  2655. if(hData->mFdCount > 1)
  2656. {
  2657. if(!TrReadInt(tr, 0, (int)hData->mFdCount - 1, &intVal))
  2658. return 0;
  2659. *fi = (uint)intVal;
  2660. if(!TrReadOperator(tr, ","))
  2661. return 0;
  2662. }
  2663. else
  2664. {
  2665. *fi = 0;
  2666. }
  2667. if(!TrReadInt(tr, 0, (int)hData->mFds[*fi].mEvCount - 1, &intVal))
  2668. return 0;
  2669. *ei = (uint)intVal;
  2670. if(!TrReadOperator(tr, ","))
  2671. return 0;
  2672. if(!TrReadInt(tr, 0, (int)hData->mFds[*fi].mEvs[*ei].mAzCount - 1, &intVal))
  2673. return 0;
  2674. *ai = (uint)intVal;
  2675. return 1;
  2676. }
  2677. // Match the source format from a given identifier.
  2678. static SourceFormatT MatchSourceFormat(const char *ident)
  2679. {
  2680. if(strcasecmp(ident, "wave") == 0)
  2681. return SF_WAVE;
  2682. if(strcasecmp(ident, "bin_le") == 0)
  2683. return SF_BIN_LE;
  2684. if(strcasecmp(ident, "bin_be") == 0)
  2685. return SF_BIN_BE;
  2686. if(strcasecmp(ident, "ascii") == 0)
  2687. return SF_ASCII;
  2688. return SF_NONE;
  2689. }
  2690. // Match the source element type from a given identifier.
  2691. static ElementTypeT MatchElementType(const char *ident)
  2692. {
  2693. if(strcasecmp(ident, "int") == 0)
  2694. return ET_INT;
  2695. if(strcasecmp(ident, "fp") == 0)
  2696. return ET_FP;
  2697. return ET_NONE;
  2698. }
  2699. // Parse and validate a source reference from the data set definition.
  2700. static int ReadSourceRef(TokenReaderT *tr, SourceRefT *src)
  2701. {
  2702. char ident[MAX_IDENT_LEN+1];
  2703. uint line, col;
  2704. int intVal;
  2705. TrIndication(tr, &line, &col);
  2706. if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
  2707. return 0;
  2708. src->mFormat = MatchSourceFormat(ident);
  2709. if(src->mFormat == SF_NONE)
  2710. {
  2711. TrErrorAt(tr, line, col, "Expected a source format.\n");
  2712. return 0;
  2713. }
  2714. if(!TrReadOperator(tr, "("))
  2715. return 0;
  2716. if(src->mFormat == SF_WAVE)
  2717. {
  2718. if(!TrReadInt(tr, 0, MAX_WAVE_CHANNELS, &intVal))
  2719. return 0;
  2720. src->mType = ET_NONE;
  2721. src->mSize = 0;
  2722. src->mBits = 0;
  2723. src->mChannel = (uint)intVal;
  2724. src->mSkip = 0;
  2725. }
  2726. else
  2727. {
  2728. TrIndication(tr, &line, &col);
  2729. if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
  2730. return 0;
  2731. src->mType = MatchElementType(ident);
  2732. if(src->mType == ET_NONE)
  2733. {
  2734. TrErrorAt(tr, line, col, "Expected a source element type.\n");
  2735. return 0;
  2736. }
  2737. if(src->mFormat == SF_BIN_LE || src->mFormat == SF_BIN_BE)
  2738. {
  2739. if(!TrReadOperator(tr, ","))
  2740. return 0;
  2741. if(src->mType == ET_INT)
  2742. {
  2743. if(!TrReadInt(tr, MIN_BIN_SIZE, MAX_BIN_SIZE, &intVal))
  2744. return 0;
  2745. src->mSize = (uint)intVal;
  2746. if(!TrIsOperator(tr, ","))
  2747. src->mBits = (int)(8*src->mSize);
  2748. else
  2749. {
  2750. TrReadOperator(tr, ",");
  2751. TrIndication(tr, &line, &col);
  2752. if(!TrReadInt(tr, -2147483647-1, 2147483647, &intVal))
  2753. return 0;
  2754. if(abs(intVal) < MIN_BIN_BITS || (uint)abs(intVal) > (8*src->mSize))
  2755. {
  2756. TrErrorAt(tr, line, col, "Expected a value of (+/-) %d to %d.\n", MIN_BIN_BITS, 8*src->mSize);
  2757. return 0;
  2758. }
  2759. src->mBits = intVal;
  2760. }
  2761. }
  2762. else
  2763. {
  2764. TrIndication(tr, &line, &col);
  2765. if(!TrReadInt(tr, -2147483647-1, 2147483647, &intVal))
  2766. return 0;
  2767. if(intVal != 4 && intVal != 8)
  2768. {
  2769. TrErrorAt(tr, line, col, "Expected a value of 4 or 8.\n");
  2770. return 0;
  2771. }
  2772. src->mSize = (uint)intVal;
  2773. src->mBits = 0;
  2774. }
  2775. }
  2776. else if(src->mFormat == SF_ASCII && src->mType == ET_INT)
  2777. {
  2778. if(!TrReadOperator(tr, ","))
  2779. return 0;
  2780. if(!TrReadInt(tr, MIN_ASCII_BITS, MAX_ASCII_BITS, &intVal))
  2781. return 0;
  2782. src->mSize = 0;
  2783. src->mBits = intVal;
  2784. }
  2785. else
  2786. {
  2787. src->mSize = 0;
  2788. src->mBits = 0;
  2789. }
  2790. if(!TrIsOperator(tr, ";"))
  2791. src->mSkip = 0;
  2792. else
  2793. {
  2794. TrReadOperator(tr, ";");
  2795. if(!TrReadInt(tr, 0, 0x7FFFFFFF, &intVal))
  2796. return 0;
  2797. src->mSkip = (uint)intVal;
  2798. }
  2799. }
  2800. if(!TrReadOperator(tr, ")"))
  2801. return 0;
  2802. if(TrIsOperator(tr, "@"))
  2803. {
  2804. TrReadOperator(tr, "@");
  2805. if(!TrReadInt(tr, 0, 0x7FFFFFFF, &intVal))
  2806. return 0;
  2807. src->mOffset = (uint)intVal;
  2808. }
  2809. else
  2810. src->mOffset = 0;
  2811. if(!TrReadOperator(tr, ":"))
  2812. return 0;
  2813. if(!TrReadString(tr, MAX_PATH_LEN, src->mPath))
  2814. return 0;
  2815. return 1;
  2816. }
  2817. // Match the target ear (index) from a given identifier.
  2818. static int MatchTargetEar(const char *ident)
  2819. {
  2820. if(strcasecmp(ident, "left") == 0)
  2821. return 0;
  2822. if(strcasecmp(ident, "right") == 0)
  2823. return 1;
  2824. return -1;
  2825. }
  2826. // Process the list of sources in the data set definition.
  2827. static int ProcessSources(const HeadModelT model, TokenReaderT *tr, HrirDataT *hData)
  2828. {
  2829. uint channels = (hData->mChannelType == CT_STEREO) ? 2 : 1;
  2830. double *hrirs = CreateDoubles(channels * hData->mIrCount * hData->mIrSize);
  2831. double *hrir = CreateDoubles(hData->mIrPoints);
  2832. uint line, col, fi, ei, ai, ti;
  2833. int count;
  2834. printf("Loading sources...");
  2835. fflush(stdout);
  2836. count = 0;
  2837. while(TrIsOperator(tr, "["))
  2838. {
  2839. double factor[2] = { 1.0, 1.0 };
  2840. TrIndication(tr, &line, &col);
  2841. TrReadOperator(tr, "[");
  2842. if(!ReadIndexTriplet(tr, hData, &fi, &ei, &ai))
  2843. goto error;
  2844. if(!TrReadOperator(tr, "]"))
  2845. goto error;
  2846. HrirAzT *azd = &hData->mFds[fi].mEvs[ei].mAzs[ai];
  2847. if(azd->mIrs[0] != NULL)
  2848. {
  2849. TrErrorAt(tr, line, col, "Redefinition of source.\n");
  2850. goto error;
  2851. }
  2852. if(!TrReadOperator(tr, "="))
  2853. goto error;
  2854. for(;;)
  2855. {
  2856. SourceRefT src;
  2857. uint ti = 0;
  2858. if(!ReadSourceRef(tr, &src))
  2859. goto error;
  2860. // TODO: Would be nice to display 'x of y files', but that would
  2861. // require preparing the source refs first to get a total count
  2862. // before loading them.
  2863. ++count;
  2864. printf("\rLoading sources... %d file%s", count, (count==1)?"":"s");
  2865. fflush(stdout);
  2866. if(!LoadSource(&src, hData->mIrRate, hData->mIrPoints, hrir))
  2867. goto error;
  2868. if(hData->mChannelType == CT_STEREO)
  2869. {
  2870. char ident[MAX_IDENT_LEN+1];
  2871. if(!TrReadIdent(tr, MAX_IDENT_LEN, ident))
  2872. goto error;
  2873. ti = MatchTargetEar(ident);
  2874. if((int)ti < 0)
  2875. {
  2876. TrErrorAt(tr, line, col, "Expected a target ear.\n");
  2877. goto error;
  2878. }
  2879. }
  2880. azd->mIrs[ti] = &hrirs[hData->mIrSize * (ti * hData->mIrCount + azd->mIndex)];
  2881. if(model == HM_DATASET)
  2882. azd->mDelays[ti] = AverageHrirOnset(hData->mIrRate, hData->mIrPoints, hrir, 1.0 / factor[ti], azd->mDelays[ti]);
  2883. AverageHrirMagnitude(hData->mIrPoints, hData->mFftSize, hrir, 1.0 / factor[ti], azd->mIrs[ti]);
  2884. factor[ti] += 1.0;
  2885. if(!TrIsOperator(tr, "+"))
  2886. break;
  2887. TrReadOperator(tr, "+");
  2888. }
  2889. if(hData->mChannelType == CT_STEREO)
  2890. {
  2891. if(azd->mIrs[0] == NULL)
  2892. {
  2893. TrErrorAt(tr, line, col, "Missing left ear source reference(s).\n");
  2894. goto error;
  2895. }
  2896. else if(azd->mIrs[1] == NULL)
  2897. {
  2898. TrErrorAt(tr, line, col, "Missing right ear source reference(s).\n");
  2899. goto error;
  2900. }
  2901. }
  2902. }
  2903. printf("\n");
  2904. for(fi = 0;fi < hData->mFdCount;fi++)
  2905. {
  2906. for(ei = 0;ei < hData->mFds[fi].mEvCount;ei++)
  2907. {
  2908. for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
  2909. {
  2910. HrirAzT *azd = &hData->mFds[fi].mEvs[ei].mAzs[ai];
  2911. if(azd->mIrs[0] != NULL)
  2912. break;
  2913. }
  2914. if(ai < hData->mFds[fi].mEvs[ei].mAzCount)
  2915. break;
  2916. }
  2917. if(ei >= hData->mFds[fi].mEvCount)
  2918. {
  2919. TrError(tr, "Missing source references [ %d, *, * ].\n", fi);
  2920. goto error;
  2921. }
  2922. hData->mFds[fi].mEvStart = ei;
  2923. for(;ei < hData->mFds[fi].mEvCount;ei++)
  2924. {
  2925. for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
  2926. {
  2927. HrirAzT *azd = &hData->mFds[fi].mEvs[ei].mAzs[ai];
  2928. if(azd->mIrs[0] == NULL)
  2929. {
  2930. TrError(tr, "Missing source reference [ %d, %d, %d ].\n", fi, ei, ai);
  2931. goto error;
  2932. }
  2933. }
  2934. }
  2935. }
  2936. for(ti = 0;ti < channels;ti++)
  2937. {
  2938. for(fi = 0;fi < hData->mFdCount;fi++)
  2939. {
  2940. for(ei = 0;ei < hData->mFds[fi].mEvCount;ei++)
  2941. {
  2942. for(ai = 0;ai < hData->mFds[fi].mEvs[ei].mAzCount;ai++)
  2943. {
  2944. HrirAzT *azd = &hData->mFds[fi].mEvs[ei].mAzs[ai];
  2945. azd->mIrs[ti] = &hrirs[hData->mIrSize * (ti * hData->mIrCount + azd->mIndex)];
  2946. }
  2947. }
  2948. }
  2949. }
  2950. if(!TrLoad(tr))
  2951. {
  2952. free(hrir);
  2953. return 1;
  2954. }
  2955. TrError(tr, "Errant data at end of source list.\n");
  2956. error:
  2957. free(hrir);
  2958. return 0;
  2959. }
  2960. /* Parse the data set definition and process the source data, storing the
  2961. * resulting data set as desired. If the input name is NULL it will read
  2962. * from standard input.
  2963. */
  2964. 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)
  2965. {
  2966. char rateStr[8+1], expName[MAX_PATH_LEN];
  2967. TokenReaderT tr;
  2968. HrirDataT hData;
  2969. FILE *fp;
  2970. int ret;
  2971. ResetHrirData(&hData);
  2972. fprintf(stdout, "Reading HRIR definition from %s...\n", inName?inName:"stdin");
  2973. if(inName != NULL)
  2974. {
  2975. fp = fopen(inName, "r");
  2976. if(fp == NULL)
  2977. {
  2978. fprintf(stderr, "Error: Could not open definition file '%s'\n", inName);
  2979. return 0;
  2980. }
  2981. TrSetup(fp, inName, &tr);
  2982. }
  2983. else
  2984. {
  2985. fp = stdin;
  2986. TrSetup(fp, "<stdin>", &tr);
  2987. }
  2988. if(!ProcessMetrics(&tr, fftSize, truncSize, &hData))
  2989. {
  2990. if(inName != NULL)
  2991. fclose(fp);
  2992. return 0;
  2993. }
  2994. if(!ProcessSources(model, &tr, &hData))
  2995. {
  2996. FreeHrirData(&hData);
  2997. if(inName != NULL)
  2998. fclose(fp);
  2999. return 0;
  3000. }
  3001. if(fp != stdin)
  3002. fclose(fp);
  3003. if(equalize)
  3004. {
  3005. uint c = (hData.mChannelType == CT_STEREO) ? 2 : 1;
  3006. uint m = 1 + hData.mFftSize / 2;
  3007. double *dfa = CreateDoubles(c * m);
  3008. fprintf(stdout, "Calculating diffuse-field average...\n");
  3009. CalculateDiffuseFieldAverage(&hData, c, m, surface, limit, dfa);
  3010. fprintf(stdout, "Performing diffuse-field equalization...\n");
  3011. DiffuseFieldEqualize(c, m, dfa, &hData);
  3012. free(dfa);
  3013. }
  3014. fprintf(stdout, "Performing minimum phase reconstruction...\n");
  3015. ReconstructHrirs(&hData);
  3016. if(outRate != 0 && outRate != hData.mIrRate)
  3017. {
  3018. fprintf(stdout, "Resampling HRIRs...\n");
  3019. ResampleHrirs(outRate, &hData);
  3020. }
  3021. fprintf(stdout, "Truncating minimum-phase HRIRs...\n");
  3022. hData.mIrPoints = truncSize;
  3023. fprintf(stdout, "Synthesizing missing elevations...\n");
  3024. if(model == HM_DATASET)
  3025. SynthesizeOnsets(&hData);
  3026. SynthesizeHrirs(&hData);
  3027. fprintf(stdout, "Normalizing final HRIRs...\n");
  3028. NormalizeHrirs(&hData);
  3029. fprintf(stdout, "Calculating impulse delays...\n");
  3030. CalculateHrtds(model, (radius > DEFAULT_CUSTOM_RADIUS) ? radius : hData.mRadius, &hData);
  3031. snprintf(rateStr, 8, "%u", hData.mIrRate);
  3032. StrSubst(outName, "%r", rateStr, MAX_PATH_LEN, expName);
  3033. fprintf(stdout, "Creating MHR data set %s...\n", expName);
  3034. ret = StoreMhr(&hData, expName);
  3035. FreeHrirData(&hData);
  3036. return ret;
  3037. }
  3038. static void PrintHelp(const char *argv0, FILE *ofile)
  3039. {
  3040. fprintf(ofile, "Usage: %s [<option>...]\n\n", argv0);
  3041. fprintf(ofile, "Options:\n");
  3042. fprintf(ofile, " -m Ignored for compatibility.\n");
  3043. fprintf(ofile, " -r <rate> Change the data set sample rate to the specified value and\n");
  3044. fprintf(ofile, " resample the HRIRs accordingly.\n");
  3045. fprintf(ofile, " -f <points> Override the FFT window size (default: %u).\n", DEFAULT_FFTSIZE);
  3046. fprintf(ofile, " -e {on|off} Toggle diffuse-field equalization (default: %s).\n", (DEFAULT_EQUALIZE ? "on" : "off"));
  3047. fprintf(ofile, " -s {on|off} Toggle surface-weighted diffuse-field average (default: %s).\n", (DEFAULT_SURFACE ? "on" : "off"));
  3048. fprintf(ofile, " -l {<dB>|none} Specify a limit to the magnitude range of the diffuse-field\n");
  3049. fprintf(ofile, " average (default: %.2f).\n", DEFAULT_LIMIT);
  3050. fprintf(ofile, " -w <points> Specify the size of the truncation window that's applied\n");
  3051. fprintf(ofile, " after minimum-phase reconstruction (default: %u).\n", DEFAULT_TRUNCSIZE);
  3052. fprintf(ofile, " -d {dataset| Specify the model used for calculating the head-delay timing\n");
  3053. fprintf(ofile, " sphere} values (default: %s).\n", ((DEFAULT_HEAD_MODEL == HM_DATASET) ? "dataset" : "sphere"));
  3054. fprintf(ofile, " -c <size> Use a customized head radius measured ear-to-ear in meters.\n");
  3055. fprintf(ofile, " -i <filename> Specify an HRIR definition file to use (defaults to stdin).\n");
  3056. fprintf(ofile, " -o <filename> Specify an output file. Use of '%%r' will be substituted with\n");
  3057. fprintf(ofile, " the data set sample rate.\n");
  3058. }
  3059. // Standard command line dispatch.
  3060. int main(int argc, char *argv[])
  3061. {
  3062. const char *inName = NULL, *outName = NULL;
  3063. uint outRate, fftSize;
  3064. int equalize, surface;
  3065. char *end = NULL;
  3066. HeadModelT model;
  3067. uint truncSize;
  3068. double radius;
  3069. double limit;
  3070. int opt;
  3071. GET_UNICODE_ARGS(&argc, &argv);
  3072. if(argc < 2)
  3073. {
  3074. fprintf(stdout, "HRTF Processing and Composition Utility\n\n");
  3075. PrintHelp(argv[0], stdout);
  3076. exit(EXIT_SUCCESS);
  3077. }
  3078. outName = "./oalsoft_hrtf_%r.mhr";
  3079. outRate = 0;
  3080. fftSize = 0;
  3081. equalize = DEFAULT_EQUALIZE;
  3082. surface = DEFAULT_SURFACE;
  3083. limit = DEFAULT_LIMIT;
  3084. truncSize = DEFAULT_TRUNCSIZE;
  3085. model = DEFAULT_HEAD_MODEL;
  3086. radius = DEFAULT_CUSTOM_RADIUS;
  3087. while((opt=getopt(argc, argv, "mr:f:e:s:l:w:d:c:e:i:o:h")) != -1)
  3088. {
  3089. switch(opt)
  3090. {
  3091. case 'm':
  3092. fprintf(stderr, "Ignoring unused command '-m'.\n");
  3093. break;
  3094. case 'r':
  3095. outRate = strtoul(optarg, &end, 10);
  3096. if(end[0] != '\0' || outRate < MIN_RATE || outRate > MAX_RATE)
  3097. {
  3098. fprintf(stderr, "Error: Got unexpected value \"%s\" for option -%c, expected between %u to %u.\n", optarg, opt, MIN_RATE, MAX_RATE);
  3099. exit(EXIT_FAILURE);
  3100. }
  3101. break;
  3102. case 'f':
  3103. fftSize = strtoul(optarg, &end, 10);
  3104. if(end[0] != '\0' || (fftSize&(fftSize-1)) || fftSize < MIN_FFTSIZE || fftSize > MAX_FFTSIZE)
  3105. {
  3106. 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);
  3107. exit(EXIT_FAILURE);
  3108. }
  3109. break;
  3110. case 'e':
  3111. if(strcmp(optarg, "on") == 0)
  3112. equalize = 1;
  3113. else if(strcmp(optarg, "off") == 0)
  3114. equalize = 0;
  3115. else
  3116. {
  3117. fprintf(stderr, "Error: Got unexpected value \"%s\" for option -%c, expected on or off.\n", optarg, opt);
  3118. exit(EXIT_FAILURE);
  3119. }
  3120. break;
  3121. case 's':
  3122. if(strcmp(optarg, "on") == 0)
  3123. surface = 1;
  3124. else if(strcmp(optarg, "off") == 0)
  3125. surface = 0;
  3126. else
  3127. {
  3128. fprintf(stderr, "Error: Got unexpected value \"%s\" for option -%c, expected on or off.\n", optarg, opt);
  3129. exit(EXIT_FAILURE);
  3130. }
  3131. break;
  3132. case 'l':
  3133. if(strcmp(optarg, "none") == 0)
  3134. limit = 0.0;
  3135. else
  3136. {
  3137. limit = strtod(optarg, &end);
  3138. if(end[0] != '\0' || limit < MIN_LIMIT || limit > MAX_LIMIT)
  3139. {
  3140. fprintf(stderr, "Error: Got unexpected value \"%s\" for option -%c, expected between %.0f to %.0f.\n", optarg, opt, MIN_LIMIT, MAX_LIMIT);
  3141. exit(EXIT_FAILURE);
  3142. }
  3143. }
  3144. break;
  3145. case 'w':
  3146. truncSize = strtoul(optarg, &end, 10);
  3147. if(end[0] != '\0' || truncSize < MIN_TRUNCSIZE || truncSize > MAX_TRUNCSIZE || (truncSize%MOD_TRUNCSIZE))
  3148. {
  3149. 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);
  3150. exit(EXIT_FAILURE);
  3151. }
  3152. break;
  3153. case 'd':
  3154. if(strcmp(optarg, "dataset") == 0)
  3155. model = HM_DATASET;
  3156. else if(strcmp(optarg, "sphere") == 0)
  3157. model = HM_SPHERE;
  3158. else
  3159. {
  3160. fprintf(stderr, "Error: Got unexpected value \"%s\" for option -%c, expected dataset or sphere.\n", optarg, opt);
  3161. exit(EXIT_FAILURE);
  3162. }
  3163. break;
  3164. case 'c':
  3165. radius = strtod(optarg, &end);
  3166. if(end[0] != '\0' || radius < MIN_CUSTOM_RADIUS || radius > MAX_CUSTOM_RADIUS)
  3167. {
  3168. fprintf(stderr, "Error: Got unexpected value \"%s\" for option -%c, expected between %.2f to %.2f.\n", optarg, opt, MIN_CUSTOM_RADIUS, MAX_CUSTOM_RADIUS);
  3169. exit(EXIT_FAILURE);
  3170. }
  3171. break;
  3172. case 'i':
  3173. inName = optarg;
  3174. break;
  3175. case 'o':
  3176. outName = optarg;
  3177. break;
  3178. case 'h':
  3179. PrintHelp(argv[0], stdout);
  3180. exit(EXIT_SUCCESS);
  3181. default: /* '?' */
  3182. PrintHelp(argv[0], stderr);
  3183. exit(EXIT_FAILURE);
  3184. }
  3185. }
  3186. if(!ProcessDefinition(inName, outRate, fftSize, equalize, surface, limit,
  3187. truncSize, model, radius, outName))
  3188. return -1;
  3189. fprintf(stdout, "Operation completed.\n");
  3190. return EXIT_SUCCESS;
  3191. }