hrtf.c 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461
  1. /**
  2. * OpenAL cross platform audio library
  3. * Copyright (C) 2011 by Chris Robinson
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Library General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Library General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Library General Public
  15. * License along with this library; if not, write to the
  16. * Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. * Or go to http://www.gnu.org/copyleft/lgpl.html
  19. */
  20. #include "config.h"
  21. #include <stdlib.h>
  22. #include <ctype.h>
  23. #include "AL/al.h"
  24. #include "AL/alc.h"
  25. #include "alMain.h"
  26. #include "alSource.h"
  27. #include "alu.h"
  28. #include "hrtf.h"
  29. #include "alconfig.h"
  30. #include "filters/splitter.h"
  31. #include "compat.h"
  32. #include "almalloc.h"
  33. /* Current data set limits defined by the makehrtf utility. */
  34. #define MIN_IR_SIZE (8)
  35. #define MAX_IR_SIZE (512)
  36. #define MOD_IR_SIZE (8)
  37. #define MIN_FD_COUNT (1)
  38. #define MAX_FD_COUNT (16)
  39. #define MIN_FD_DISTANCE (50)
  40. #define MAX_FD_DISTANCE (2500)
  41. #define MIN_EV_COUNT (5)
  42. #define MAX_EV_COUNT (128)
  43. #define MIN_AZ_COUNT (1)
  44. #define MAX_AZ_COUNT (128)
  45. #define MAX_HRIR_DELAY (HRTF_HISTORY_LENGTH-1)
  46. struct HrtfEntry {
  47. struct HrtfEntry *next;
  48. struct Hrtf *handle;
  49. char filename[];
  50. };
  51. static const ALchar magicMarker00[8] = "MinPHR00";
  52. static const ALchar magicMarker01[8] = "MinPHR01";
  53. static const ALchar magicMarker02[8] = "MinPHR02";
  54. /* First value for pass-through coefficients (remaining are 0), used for omni-
  55. * directional sounds. */
  56. static const ALfloat PassthruCoeff = 0.707106781187f/*sqrt(0.5)*/;
  57. static ATOMIC_FLAG LoadedHrtfLock = ATOMIC_FLAG_INIT;
  58. static struct HrtfEntry *LoadedHrtfs = NULL;
  59. /* Calculate the elevation index given the polar elevation in radians. This
  60. * will return an index between 0 and (evcount - 1).
  61. */
  62. static ALsizei CalcEvIndex(ALsizei evcount, ALfloat ev, ALfloat *mu)
  63. {
  64. ALsizei idx;
  65. ev = (F_PI_2+ev) * (evcount-1) / F_PI;
  66. idx = float2int(ev);
  67. *mu = ev - idx;
  68. return mini(idx, evcount-1);
  69. }
  70. /* Calculate the azimuth index given the polar azimuth in radians. This will
  71. * return an index between 0 and (azcount - 1).
  72. */
  73. static ALsizei CalcAzIndex(ALsizei azcount, ALfloat az, ALfloat *mu)
  74. {
  75. ALsizei idx;
  76. az = (F_TAU+az) * azcount / F_TAU;
  77. idx = float2int(az);
  78. *mu = az - idx;
  79. return idx % azcount;
  80. }
  81. /* Calculates static HRIR coefficients and delays for the given polar elevation
  82. * and azimuth in radians. The coefficients are normalized.
  83. */
  84. void GetHrtfCoeffs(const struct Hrtf *Hrtf, ALfloat elevation, ALfloat azimuth, ALfloat spread,
  85. ALfloat (*restrict coeffs)[2], ALsizei *delays)
  86. {
  87. ALsizei evidx, azidx, idx[4];
  88. ALsizei evoffset;
  89. ALfloat emu, amu[2];
  90. ALfloat blend[4];
  91. ALfloat dirfact;
  92. ALsizei i, c;
  93. dirfact = 1.0f - (spread / F_TAU);
  94. /* Claculate the lower elevation index. */
  95. evidx = CalcEvIndex(Hrtf->evCount, elevation, &emu);
  96. evoffset = Hrtf->evOffset[evidx];
  97. /* Calculate lower azimuth index. */
  98. azidx= CalcAzIndex(Hrtf->azCount[evidx], azimuth, &amu[0]);
  99. /* Calculate the lower HRIR indices. */
  100. idx[0] = evoffset + azidx;
  101. idx[1] = evoffset + ((azidx+1) % Hrtf->azCount[evidx]);
  102. if(evidx < Hrtf->evCount-1)
  103. {
  104. /* Increment elevation to the next (upper) index. */
  105. evidx++;
  106. evoffset = Hrtf->evOffset[evidx];
  107. /* Calculate upper azimuth index. */
  108. azidx = CalcAzIndex(Hrtf->azCount[evidx], azimuth, &amu[1]);
  109. /* Calculate the upper HRIR indices. */
  110. idx[2] = evoffset + azidx;
  111. idx[3] = evoffset + ((azidx+1) % Hrtf->azCount[evidx]);
  112. }
  113. else
  114. {
  115. /* If the lower elevation is the top index, the upper elevation is the
  116. * same as the lower.
  117. */
  118. amu[1] = amu[0];
  119. idx[2] = idx[0];
  120. idx[3] = idx[1];
  121. }
  122. /* Calculate bilinear blending weights, attenuated according to the
  123. * directional panning factor.
  124. */
  125. blend[0] = (1.0f-emu) * (1.0f-amu[0]) * dirfact;
  126. blend[1] = (1.0f-emu) * ( amu[0]) * dirfact;
  127. blend[2] = ( emu) * (1.0f-amu[1]) * dirfact;
  128. blend[3] = ( emu) * ( amu[1]) * dirfact;
  129. /* Calculate the blended HRIR delays. */
  130. delays[0] = float2int(
  131. Hrtf->delays[idx[0]][0]*blend[0] + Hrtf->delays[idx[1]][0]*blend[1] +
  132. Hrtf->delays[idx[2]][0]*blend[2] + Hrtf->delays[idx[3]][0]*blend[3] + 0.5f
  133. );
  134. delays[1] = float2int(
  135. Hrtf->delays[idx[0]][1]*blend[0] + Hrtf->delays[idx[1]][1]*blend[1] +
  136. Hrtf->delays[idx[2]][1]*blend[2] + Hrtf->delays[idx[3]][1]*blend[3] + 0.5f
  137. );
  138. /* Calculate the sample offsets for the HRIR indices. */
  139. idx[0] *= Hrtf->irSize;
  140. idx[1] *= Hrtf->irSize;
  141. idx[2] *= Hrtf->irSize;
  142. idx[3] *= Hrtf->irSize;
  143. ASSUME(Hrtf->irSize >= MIN_IR_SIZE && (Hrtf->irSize%MOD_IR_SIZE) == 0);
  144. coeffs = ASSUME_ALIGNED(coeffs, 16);
  145. /* Calculate the blended HRIR coefficients. */
  146. coeffs[0][0] = PassthruCoeff * (1.0f-dirfact);
  147. coeffs[0][1] = PassthruCoeff * (1.0f-dirfact);
  148. for(i = 1;i < Hrtf->irSize;i++)
  149. {
  150. coeffs[i][0] = 0.0f;
  151. coeffs[i][1] = 0.0f;
  152. }
  153. for(c = 0;c < 4;c++)
  154. {
  155. const ALfloat (*restrict srccoeffs)[2] = ASSUME_ALIGNED(Hrtf->coeffs+idx[c], 16);
  156. for(i = 0;i < Hrtf->irSize;i++)
  157. {
  158. coeffs[i][0] += srccoeffs[i][0] * blend[c];
  159. coeffs[i][1] += srccoeffs[i][1] * blend[c];
  160. }
  161. }
  162. }
  163. void BuildBFormatHrtf(const struct Hrtf *Hrtf, DirectHrtfState *state, ALsizei NumChannels, const struct AngularPoint *AmbiPoints, const ALfloat (*restrict AmbiMatrix)[MAX_AMBI_COEFFS], ALsizei AmbiCount, const ALfloat *restrict AmbiOrderHFGain)
  164. {
  165. /* Set this to 2 for dual-band HRTF processing. May require a higher quality
  166. * band-splitter, or better calculation of the new IR length to deal with the
  167. * tail generated by the filter.
  168. */
  169. #define NUM_BANDS 2
  170. BandSplitter splitter;
  171. ALdouble (*tmpres)[HRIR_LENGTH][2];
  172. ALsizei idx[HRTF_AMBI_MAX_CHANNELS];
  173. ALsizei min_delay = HRTF_HISTORY_LENGTH;
  174. ALfloat temps[3][HRIR_LENGTH];
  175. ALsizei max_length = 0;
  176. ALsizei i, c, b;
  177. for(c = 0;c < AmbiCount;c++)
  178. {
  179. ALuint evidx, azidx;
  180. ALuint evoffset;
  181. ALuint azcount;
  182. /* Calculate elevation index. */
  183. evidx = (ALsizei)((F_PI_2+AmbiPoints[c].Elev) * (Hrtf->evCount-1) / F_PI + 0.5f);
  184. evidx = clampi(evidx, 0, Hrtf->evCount-1);
  185. azcount = Hrtf->azCount[evidx];
  186. evoffset = Hrtf->evOffset[evidx];
  187. /* Calculate azimuth index for this elevation. */
  188. azidx = (ALsizei)((F_TAU+AmbiPoints[c].Azim) * azcount / F_TAU + 0.5f) % azcount;
  189. /* Calculate indices for left and right channels. */
  190. idx[c] = evoffset + azidx;
  191. min_delay = mini(min_delay, mini(Hrtf->delays[idx[c]][0], Hrtf->delays[idx[c]][1]));
  192. }
  193. tmpres = al_calloc(16, NumChannels * sizeof(*tmpres));
  194. memset(temps, 0, sizeof(temps));
  195. bandsplit_init(&splitter, 400.0f / (ALfloat)Hrtf->sampleRate);
  196. for(c = 0;c < AmbiCount;c++)
  197. {
  198. const ALfloat (*fir)[2] = &Hrtf->coeffs[idx[c] * Hrtf->irSize];
  199. ALsizei ldelay = Hrtf->delays[idx[c]][0] - min_delay;
  200. ALsizei rdelay = Hrtf->delays[idx[c]][1] - min_delay;
  201. if(NUM_BANDS == 1)
  202. {
  203. max_length = maxi(max_length,
  204. mini(maxi(ldelay, rdelay) + Hrtf->irSize, HRIR_LENGTH)
  205. );
  206. for(i = 0;i < NumChannels;++i)
  207. {
  208. ALdouble mult = (ALdouble)AmbiOrderHFGain[(ALsizei)sqrt(i)] * AmbiMatrix[c][i];
  209. ALsizei lidx = ldelay, ridx = rdelay;
  210. ALsizei j = 0;
  211. while(lidx < HRIR_LENGTH && ridx < HRIR_LENGTH && j < Hrtf->irSize)
  212. {
  213. tmpres[i][lidx++][0] += fir[j][0] * mult;
  214. tmpres[i][ridx++][1] += fir[j][1] * mult;
  215. j++;
  216. }
  217. }
  218. }
  219. else
  220. {
  221. /* Increase the IR size by 2/3rds to account for the tail generated
  222. * by the band-split filter.
  223. */
  224. const ALsizei irsize = mini(Hrtf->irSize*5/3, HRIR_LENGTH);
  225. max_length = maxi(max_length,
  226. mini(maxi(ldelay, rdelay) + irsize, HRIR_LENGTH)
  227. );
  228. /* Band-split left HRIR into low and high frequency responses. */
  229. bandsplit_clear(&splitter);
  230. for(i = 0;i < Hrtf->irSize;i++)
  231. temps[2][i] = fir[i][0];
  232. bandsplit_process(&splitter, temps[0], temps[1], temps[2], HRIR_LENGTH);
  233. /* Apply left ear response with delay. */
  234. for(i = 0;i < NumChannels;++i)
  235. {
  236. ALfloat hfgain = AmbiOrderHFGain[(ALsizei)sqrt(i)];
  237. for(b = 0;b < NUM_BANDS;b++)
  238. {
  239. ALdouble mult = AmbiMatrix[c][i] * (ALdouble)((b==0) ? hfgain : 1.0);
  240. ALsizei lidx = ldelay;
  241. ALsizei j = 0;
  242. while(lidx < HRIR_LENGTH)
  243. tmpres[i][lidx++][0] += temps[b][j++] * mult;
  244. }
  245. }
  246. /* Band-split right HRIR into low and high frequency responses. */
  247. bandsplit_clear(&splitter);
  248. for(i = 0;i < Hrtf->irSize;i++)
  249. temps[2][i] = fir[i][1];
  250. bandsplit_process(&splitter, temps[0], temps[1], temps[2], HRIR_LENGTH);
  251. /* Apply right ear response with delay. */
  252. for(i = 0;i < NumChannels;++i)
  253. {
  254. ALfloat hfgain = AmbiOrderHFGain[(ALsizei)sqrt(i)];
  255. for(b = 0;b < NUM_BANDS;b++)
  256. {
  257. ALdouble mult = AmbiMatrix[c][i] * (ALdouble)((b==0) ? hfgain : 1.0);
  258. ALsizei ridx = rdelay;
  259. ALsizei j = 0;
  260. while(ridx < HRIR_LENGTH)
  261. tmpres[i][ridx++][1] += temps[b][j++] * mult;
  262. }
  263. }
  264. }
  265. }
  266. /* Round up to the next IR size multiple. */
  267. max_length += MOD_IR_SIZE-1;
  268. max_length -= max_length%MOD_IR_SIZE;
  269. for(i = 0;i < NumChannels;++i)
  270. {
  271. int idx;
  272. for(idx = 0;idx < HRIR_LENGTH;idx++)
  273. {
  274. state->Chan[i].Coeffs[idx][0] = (ALfloat)tmpres[i][idx][0];
  275. state->Chan[i].Coeffs[idx][1] = (ALfloat)tmpres[i][idx][1];
  276. }
  277. }
  278. al_free(tmpres);
  279. tmpres = NULL;
  280. TRACE("Skipped delay: %d, new FIR length: %d\n", min_delay, max_length);
  281. state->IrSize = max_length;
  282. #undef NUM_BANDS
  283. }
  284. static struct Hrtf *CreateHrtfStore(ALuint rate, ALsizei irSize,
  285. ALfloat distance, ALsizei evCount, ALsizei irCount, const ALubyte *azCount,
  286. const ALushort *evOffset, const ALfloat (*coeffs)[2], const ALubyte (*delays)[2],
  287. const char *filename)
  288. {
  289. struct Hrtf *Hrtf;
  290. size_t total;
  291. total = sizeof(struct Hrtf);
  292. total += sizeof(Hrtf->azCount[0])*evCount;
  293. total = RoundUp(total, sizeof(ALushort)); /* Align for ushort fields */
  294. total += sizeof(Hrtf->evOffset[0])*evCount;
  295. total = RoundUp(total, 16); /* Align for coefficients using SIMD */
  296. total += sizeof(Hrtf->coeffs[0])*irSize*irCount;
  297. total += sizeof(Hrtf->delays[0])*irCount;
  298. Hrtf = al_calloc(16, total);
  299. if(Hrtf == NULL)
  300. ERR("Out of memory allocating storage for %s.\n", filename);
  301. else
  302. {
  303. uintptr_t offset = sizeof(struct Hrtf);
  304. char *base = (char*)Hrtf;
  305. ALushort *_evOffset;
  306. ALubyte *_azCount;
  307. ALubyte (*_delays)[2];
  308. ALfloat (*_coeffs)[2];
  309. ALsizei i;
  310. InitRef(&Hrtf->ref, 0);
  311. Hrtf->sampleRate = rate;
  312. Hrtf->irSize = irSize;
  313. Hrtf->distance = distance;
  314. Hrtf->evCount = evCount;
  315. /* Set up pointers to storage following the main HRTF struct. */
  316. _azCount = (ALubyte*)(base + offset);
  317. offset += sizeof(_azCount[0])*evCount;
  318. offset = RoundUp(offset, sizeof(ALushort)); /* Align for ushort fields */
  319. _evOffset = (ALushort*)(base + offset);
  320. offset += sizeof(_evOffset[0])*evCount;
  321. offset = RoundUp(offset, 16); /* Align for coefficients using SIMD */
  322. _coeffs = (ALfloat(*)[2])(base + offset);
  323. offset += sizeof(_coeffs[0])*irSize*irCount;
  324. _delays = (ALubyte(*)[2])(base + offset);
  325. offset += sizeof(_delays[0])*irCount;
  326. assert(offset == total);
  327. /* Copy input data to storage. */
  328. for(i = 0;i < evCount;i++) _azCount[i] = azCount[i];
  329. for(i = 0;i < evCount;i++) _evOffset[i] = evOffset[i];
  330. for(i = 0;i < irSize*irCount;i++)
  331. {
  332. _coeffs[i][0] = coeffs[i][0];
  333. _coeffs[i][1] = coeffs[i][1];
  334. }
  335. for(i = 0;i < irCount;i++)
  336. {
  337. _delays[i][0] = delays[i][0];
  338. _delays[i][1] = delays[i][1];
  339. }
  340. /* Finally, assign the storage pointers. */
  341. Hrtf->azCount = _azCount;
  342. Hrtf->evOffset = _evOffset;
  343. Hrtf->coeffs = _coeffs;
  344. Hrtf->delays = _delays;
  345. }
  346. return Hrtf;
  347. }
  348. static ALubyte GetLE_ALubyte(const ALubyte **data, size_t *len)
  349. {
  350. ALubyte ret = (*data)[0];
  351. *data += 1; *len -= 1;
  352. return ret;
  353. }
  354. static ALshort GetLE_ALshort(const ALubyte **data, size_t *len)
  355. {
  356. ALshort ret = (*data)[0] | ((*data)[1]<<8);
  357. *data += 2; *len -= 2;
  358. return ret;
  359. }
  360. static ALushort GetLE_ALushort(const ALubyte **data, size_t *len)
  361. {
  362. ALushort ret = (*data)[0] | ((*data)[1]<<8);
  363. *data += 2; *len -= 2;
  364. return ret;
  365. }
  366. static ALint GetLE_ALint24(const ALubyte **data, size_t *len)
  367. {
  368. ALint ret = (*data)[0] | ((*data)[1]<<8) | ((*data)[2]<<16);
  369. *data += 3; *len -= 3;
  370. return (ret^0x800000) - 0x800000;
  371. }
  372. static ALuint GetLE_ALuint(const ALubyte **data, size_t *len)
  373. {
  374. ALuint ret = (*data)[0] | ((*data)[1]<<8) | ((*data)[2]<<16) | ((*data)[3]<<24);
  375. *data += 4; *len -= 4;
  376. return ret;
  377. }
  378. static const ALubyte *Get_ALubytePtr(const ALubyte **data, size_t *len, size_t size)
  379. {
  380. const ALubyte *ret = *data;
  381. *data += size; *len -= size;
  382. return ret;
  383. }
  384. static struct Hrtf *LoadHrtf00(const ALubyte *data, size_t datalen, const char *filename)
  385. {
  386. struct Hrtf *Hrtf = NULL;
  387. ALboolean failed = AL_FALSE;
  388. ALuint rate = 0;
  389. ALushort irCount = 0;
  390. ALushort irSize = 0;
  391. ALubyte evCount = 0;
  392. ALubyte *azCount = NULL;
  393. ALushort *evOffset = NULL;
  394. ALfloat (*coeffs)[2] = NULL;
  395. ALubyte (*delays)[2] = NULL;
  396. ALsizei i, j;
  397. if(datalen < 9)
  398. {
  399. ERR("Unexpected end of %s data (req %d, rem "SZFMT")\n", filename, 9, datalen);
  400. return NULL;
  401. }
  402. rate = GetLE_ALuint(&data, &datalen);
  403. irCount = GetLE_ALushort(&data, &datalen);
  404. irSize = GetLE_ALushort(&data, &datalen);
  405. evCount = GetLE_ALubyte(&data, &datalen);
  406. if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
  407. {
  408. ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
  409. irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
  410. failed = AL_TRUE;
  411. }
  412. if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
  413. {
  414. ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
  415. evCount, MIN_EV_COUNT, MAX_EV_COUNT);
  416. failed = AL_TRUE;
  417. }
  418. if(failed)
  419. return NULL;
  420. if(datalen < evCount*2u)
  421. {
  422. ERR("Unexpected end of %s data (req %d, rem "SZFMT")\n", filename, evCount*2, datalen);
  423. return NULL;
  424. }
  425. azCount = malloc(sizeof(azCount[0])*evCount);
  426. evOffset = malloc(sizeof(evOffset[0])*evCount);
  427. if(azCount == NULL || evOffset == NULL)
  428. {
  429. ERR("Out of memory.\n");
  430. failed = AL_TRUE;
  431. }
  432. if(!failed)
  433. {
  434. evOffset[0] = GetLE_ALushort(&data, &datalen);
  435. for(i = 1;i < evCount;i++)
  436. {
  437. evOffset[i] = GetLE_ALushort(&data, &datalen);
  438. if(evOffset[i] <= evOffset[i-1])
  439. {
  440. ERR("Invalid evOffset: evOffset[%d]=%d (last=%d)\n",
  441. i, evOffset[i], evOffset[i-1]);
  442. failed = AL_TRUE;
  443. }
  444. azCount[i-1] = evOffset[i] - evOffset[i-1];
  445. if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
  446. {
  447. ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
  448. i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
  449. failed = AL_TRUE;
  450. }
  451. }
  452. if(irCount <= evOffset[i-1])
  453. {
  454. ERR("Invalid evOffset: evOffset[%d]=%d (irCount=%d)\n",
  455. i-1, evOffset[i-1], irCount);
  456. failed = AL_TRUE;
  457. }
  458. azCount[i-1] = irCount - evOffset[i-1];
  459. if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
  460. {
  461. ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
  462. i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
  463. failed = AL_TRUE;
  464. }
  465. }
  466. if(!failed)
  467. {
  468. coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
  469. delays = malloc(sizeof(delays[0])*irCount);
  470. if(coeffs == NULL || delays == NULL)
  471. {
  472. ERR("Out of memory.\n");
  473. failed = AL_TRUE;
  474. }
  475. }
  476. if(!failed)
  477. {
  478. size_t reqsize = 2*irSize*irCount + irCount;
  479. if(datalen < reqsize)
  480. {
  481. ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT")\n",
  482. filename, reqsize, datalen);
  483. failed = AL_TRUE;
  484. }
  485. }
  486. if(!failed)
  487. {
  488. for(i = 0;i < irCount;i++)
  489. {
  490. for(j = 0;j < irSize;j++)
  491. coeffs[i*irSize + j][0] = GetLE_ALshort(&data, &datalen) / 32768.0f;
  492. }
  493. for(i = 0;i < irCount;i++)
  494. {
  495. delays[i][0] = GetLE_ALubyte(&data, &datalen);
  496. if(delays[i][0] > MAX_HRIR_DELAY)
  497. {
  498. ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i][0], MAX_HRIR_DELAY);
  499. failed = AL_TRUE;
  500. }
  501. }
  502. }
  503. if(!failed)
  504. {
  505. /* Mirror the left ear responses to the right ear. */
  506. for(i = 0;i < evCount;i++)
  507. {
  508. ALushort evoffset = evOffset[i];
  509. ALubyte azcount = azCount[i];
  510. for(j = 0;j < azcount;j++)
  511. {
  512. ALsizei lidx = evoffset + j;
  513. ALsizei ridx = evoffset + ((azcount-j) % azcount);
  514. ALsizei k;
  515. for(k = 0;k < irSize;k++)
  516. coeffs[ridx*irSize + k][1] = coeffs[lidx*irSize + k][0];
  517. delays[ridx][1] = delays[lidx][0];
  518. }
  519. }
  520. Hrtf = CreateHrtfStore(rate, irSize, 0.0f, evCount, irCount, azCount,
  521. evOffset, coeffs, delays, filename);
  522. }
  523. free(azCount);
  524. free(evOffset);
  525. free(coeffs);
  526. free(delays);
  527. return Hrtf;
  528. }
  529. static struct Hrtf *LoadHrtf01(const ALubyte *data, size_t datalen, const char *filename)
  530. {
  531. struct Hrtf *Hrtf = NULL;
  532. ALboolean failed = AL_FALSE;
  533. ALuint rate = 0;
  534. ALushort irCount = 0;
  535. ALushort irSize = 0;
  536. ALubyte evCount = 0;
  537. const ALubyte *azCount = NULL;
  538. ALushort *evOffset = NULL;
  539. ALfloat (*coeffs)[2] = NULL;
  540. ALubyte (*delays)[2] = NULL;
  541. ALsizei i, j;
  542. if(datalen < 6)
  543. {
  544. ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, 6, datalen);
  545. return NULL;
  546. }
  547. rate = GetLE_ALuint(&data, &datalen);
  548. irSize = GetLE_ALubyte(&data, &datalen);
  549. evCount = GetLE_ALubyte(&data, &datalen);
  550. if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
  551. {
  552. ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
  553. irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
  554. failed = AL_TRUE;
  555. }
  556. if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
  557. {
  558. ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
  559. evCount, MIN_EV_COUNT, MAX_EV_COUNT);
  560. failed = AL_TRUE;
  561. }
  562. if(failed)
  563. return NULL;
  564. if(datalen < evCount)
  565. {
  566. ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, evCount, datalen);
  567. return NULL;
  568. }
  569. azCount = Get_ALubytePtr(&data, &datalen, evCount);
  570. evOffset = malloc(sizeof(evOffset[0])*evCount);
  571. if(azCount == NULL || evOffset == NULL)
  572. {
  573. ERR("Out of memory.\n");
  574. failed = AL_TRUE;
  575. }
  576. if(!failed)
  577. {
  578. for(i = 0;i < evCount;i++)
  579. {
  580. if(azCount[i] < MIN_AZ_COUNT || azCount[i] > MAX_AZ_COUNT)
  581. {
  582. ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
  583. i, azCount[i], MIN_AZ_COUNT, MAX_AZ_COUNT);
  584. failed = AL_TRUE;
  585. }
  586. }
  587. }
  588. if(!failed)
  589. {
  590. evOffset[0] = 0;
  591. irCount = azCount[0];
  592. for(i = 1;i < evCount;i++)
  593. {
  594. evOffset[i] = evOffset[i-1] + azCount[i-1];
  595. irCount += azCount[i];
  596. }
  597. coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
  598. delays = malloc(sizeof(delays[0])*irCount);
  599. if(coeffs == NULL || delays == NULL)
  600. {
  601. ERR("Out of memory.\n");
  602. failed = AL_TRUE;
  603. }
  604. }
  605. if(!failed)
  606. {
  607. size_t reqsize = 2*irSize*irCount + irCount;
  608. if(datalen < reqsize)
  609. {
  610. ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT"\n",
  611. filename, reqsize, datalen);
  612. failed = AL_TRUE;
  613. }
  614. }
  615. if(!failed)
  616. {
  617. for(i = 0;i < irCount;i++)
  618. {
  619. for(j = 0;j < irSize;j++)
  620. coeffs[i*irSize + j][0] = GetLE_ALshort(&data, &datalen) / 32768.0f;
  621. }
  622. for(i = 0;i < irCount;i++)
  623. {
  624. delays[i][0] = GetLE_ALubyte(&data, &datalen);
  625. if(delays[i][0] > MAX_HRIR_DELAY)
  626. {
  627. ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i][0], MAX_HRIR_DELAY);
  628. failed = AL_TRUE;
  629. }
  630. }
  631. }
  632. if(!failed)
  633. {
  634. /* Mirror the left ear responses to the right ear. */
  635. for(i = 0;i < evCount;i++)
  636. {
  637. ALushort evoffset = evOffset[i];
  638. ALubyte azcount = azCount[i];
  639. for(j = 0;j < azcount;j++)
  640. {
  641. ALsizei lidx = evoffset + j;
  642. ALsizei ridx = evoffset + ((azcount-j) % azcount);
  643. ALsizei k;
  644. for(k = 0;k < irSize;k++)
  645. coeffs[ridx*irSize + k][1] = coeffs[lidx*irSize + k][0];
  646. delays[ridx][1] = delays[lidx][0];
  647. }
  648. }
  649. Hrtf = CreateHrtfStore(rate, irSize, 0.0f, evCount, irCount, azCount,
  650. evOffset, coeffs, delays, filename);
  651. }
  652. free(evOffset);
  653. free(coeffs);
  654. free(delays);
  655. return Hrtf;
  656. }
  657. #define SAMPLETYPE_S16 0
  658. #define SAMPLETYPE_S24 1
  659. #define CHANTYPE_LEFTONLY 0
  660. #define CHANTYPE_LEFTRIGHT 1
  661. static struct Hrtf *LoadHrtf02(const ALubyte *data, size_t datalen, const char *filename)
  662. {
  663. struct Hrtf *Hrtf = NULL;
  664. ALboolean failed = AL_FALSE;
  665. ALuint rate = 0;
  666. ALubyte sampleType;
  667. ALubyte channelType;
  668. ALushort irCount = 0;
  669. ALushort irSize = 0;
  670. ALubyte fdCount = 0;
  671. ALushort distance = 0;
  672. ALubyte evCount = 0;
  673. const ALubyte *azCount = NULL;
  674. ALushort *evOffset = NULL;
  675. ALfloat (*coeffs)[2] = NULL;
  676. ALubyte (*delays)[2] = NULL;
  677. ALsizei i, j;
  678. if(datalen < 8)
  679. {
  680. ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, 8, datalen);
  681. return NULL;
  682. }
  683. rate = GetLE_ALuint(&data, &datalen);
  684. sampleType = GetLE_ALubyte(&data, &datalen);
  685. channelType = GetLE_ALubyte(&data, &datalen);
  686. irSize = GetLE_ALubyte(&data, &datalen);
  687. fdCount = GetLE_ALubyte(&data, &datalen);
  688. if(sampleType > SAMPLETYPE_S24)
  689. {
  690. ERR("Unsupported sample type: %d\n", sampleType);
  691. failed = AL_TRUE;
  692. }
  693. if(channelType > CHANTYPE_LEFTRIGHT)
  694. {
  695. ERR("Unsupported channel type: %d\n", channelType);
  696. failed = AL_TRUE;
  697. }
  698. if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
  699. {
  700. ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
  701. irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
  702. failed = AL_TRUE;
  703. }
  704. if(fdCount != 1)
  705. {
  706. ERR("Multiple field-depths not supported: fdCount=%d (%d to %d)\n",
  707. evCount, MIN_FD_COUNT, MAX_FD_COUNT);
  708. failed = AL_TRUE;
  709. }
  710. if(failed)
  711. return NULL;
  712. for(i = 0;i < fdCount;i++)
  713. {
  714. if(datalen < 3)
  715. {
  716. ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, 3, datalen);
  717. return NULL;
  718. }
  719. distance = GetLE_ALushort(&data, &datalen);
  720. if(distance < MIN_FD_DISTANCE || distance > MAX_FD_DISTANCE)
  721. {
  722. ERR("Unsupported field distance: distance=%d (%dmm to %dmm)\n",
  723. distance, MIN_FD_DISTANCE, MAX_FD_DISTANCE);
  724. failed = AL_TRUE;
  725. }
  726. evCount = GetLE_ALubyte(&data, &datalen);
  727. if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
  728. {
  729. ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
  730. evCount, MIN_EV_COUNT, MAX_EV_COUNT);
  731. failed = AL_TRUE;
  732. }
  733. if(failed)
  734. return NULL;
  735. if(datalen < evCount)
  736. {
  737. ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, evCount, datalen);
  738. return NULL;
  739. }
  740. azCount = Get_ALubytePtr(&data, &datalen, evCount);
  741. for(j = 0;j < evCount;j++)
  742. {
  743. if(azCount[j] < MIN_AZ_COUNT || azCount[j] > MAX_AZ_COUNT)
  744. {
  745. ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
  746. j, azCount[j], MIN_AZ_COUNT, MAX_AZ_COUNT);
  747. failed = AL_TRUE;
  748. }
  749. }
  750. }
  751. if(failed)
  752. return NULL;
  753. evOffset = malloc(sizeof(evOffset[0])*evCount);
  754. if(azCount == NULL || evOffset == NULL)
  755. {
  756. ERR("Out of memory.\n");
  757. failed = AL_TRUE;
  758. }
  759. if(!failed)
  760. {
  761. evOffset[0] = 0;
  762. irCount = azCount[0];
  763. for(i = 1;i < evCount;i++)
  764. {
  765. evOffset[i] = evOffset[i-1] + azCount[i-1];
  766. irCount += azCount[i];
  767. }
  768. coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
  769. delays = malloc(sizeof(delays[0])*irCount);
  770. if(coeffs == NULL || delays == NULL)
  771. {
  772. ERR("Out of memory.\n");
  773. failed = AL_TRUE;
  774. }
  775. }
  776. if(!failed)
  777. {
  778. size_t reqsize = 2*irSize*irCount + irCount;
  779. if(datalen < reqsize)
  780. {
  781. ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT"\n",
  782. filename, reqsize, datalen);
  783. failed = AL_TRUE;
  784. }
  785. }
  786. if(!failed)
  787. {
  788. if(channelType == CHANTYPE_LEFTONLY)
  789. {
  790. if(sampleType == SAMPLETYPE_S16)
  791. for(i = 0;i < irCount;i++)
  792. {
  793. for(j = 0;j < irSize;j++)
  794. coeffs[i*irSize + j][0] = GetLE_ALshort(&data, &datalen) / 32768.0f;
  795. }
  796. else if(sampleType == SAMPLETYPE_S24)
  797. for(i = 0;i < irCount;i++)
  798. {
  799. for(j = 0;j < irSize;j++)
  800. coeffs[i*irSize + j][0] = GetLE_ALint24(&data, &datalen) / 8388608.0f;
  801. }
  802. for(i = 0;i < irCount;i++)
  803. {
  804. delays[i][0] = GetLE_ALubyte(&data, &datalen);
  805. if(delays[i][0] > MAX_HRIR_DELAY)
  806. {
  807. ERR("Invalid delays[%d][0]: %d (%d)\n", i, delays[i][0], MAX_HRIR_DELAY);
  808. failed = AL_TRUE;
  809. }
  810. }
  811. }
  812. else if(channelType == CHANTYPE_LEFTRIGHT)
  813. {
  814. if(sampleType == SAMPLETYPE_S16)
  815. for(i = 0;i < irCount;i++)
  816. {
  817. for(j = 0;j < irSize;j++)
  818. {
  819. coeffs[i*irSize + j][0] = GetLE_ALshort(&data, &datalen) / 32768.0f;
  820. coeffs[i*irSize + j][1] = GetLE_ALshort(&data, &datalen) / 32768.0f;
  821. }
  822. }
  823. else if(sampleType == SAMPLETYPE_S24)
  824. for(i = 0;i < irCount;i++)
  825. {
  826. for(j = 0;j < irSize;j++)
  827. {
  828. coeffs[i*irSize + j][0] = GetLE_ALint24(&data, &datalen) / 8388608.0f;
  829. coeffs[i*irSize + j][1] = GetLE_ALint24(&data, &datalen) / 8388608.0f;
  830. }
  831. }
  832. for(i = 0;i < irCount;i++)
  833. {
  834. delays[i][0] = GetLE_ALubyte(&data, &datalen);
  835. if(delays[i][0] > MAX_HRIR_DELAY)
  836. {
  837. ERR("Invalid delays[%d][0]: %d (%d)\n", i, delays[i][0], MAX_HRIR_DELAY);
  838. failed = AL_TRUE;
  839. }
  840. delays[i][1] = GetLE_ALubyte(&data, &datalen);
  841. if(delays[i][1] > MAX_HRIR_DELAY)
  842. {
  843. ERR("Invalid delays[%d][1]: %d (%d)\n", i, delays[i][1], MAX_HRIR_DELAY);
  844. failed = AL_TRUE;
  845. }
  846. }
  847. }
  848. }
  849. if(!failed)
  850. {
  851. if(channelType == CHANTYPE_LEFTONLY)
  852. {
  853. /* Mirror the left ear responses to the right ear. */
  854. for(i = 0;i < evCount;i++)
  855. {
  856. ALushort evoffset = evOffset[i];
  857. ALubyte azcount = azCount[i];
  858. for(j = 0;j < azcount;j++)
  859. {
  860. ALsizei lidx = evoffset + j;
  861. ALsizei ridx = evoffset + ((azcount-j) % azcount);
  862. ALsizei k;
  863. for(k = 0;k < irSize;k++)
  864. coeffs[ridx*irSize + k][1] = coeffs[lidx*irSize + k][0];
  865. delays[ridx][1] = delays[lidx][0];
  866. }
  867. }
  868. }
  869. Hrtf = CreateHrtfStore(rate, irSize,
  870. (ALfloat)distance / 1000.0f, evCount, irCount, azCount, evOffset,
  871. coeffs, delays, filename
  872. );
  873. }
  874. free(evOffset);
  875. free(coeffs);
  876. free(delays);
  877. return Hrtf;
  878. }
  879. static void AddFileEntry(vector_EnumeratedHrtf *list, const_al_string filename)
  880. {
  881. EnumeratedHrtf entry = { AL_STRING_INIT_STATIC(), NULL };
  882. struct HrtfEntry *loaded_entry;
  883. const EnumeratedHrtf *iter;
  884. const char *name;
  885. const char *ext;
  886. int i;
  887. /* Check if this file has already been loaded globally. */
  888. loaded_entry = LoadedHrtfs;
  889. while(loaded_entry)
  890. {
  891. if(alstr_cmp_cstr(filename, loaded_entry->filename) == 0)
  892. {
  893. /* Check if this entry has already been added to the list. */
  894. #define MATCH_ENTRY(i) (loaded_entry == (i)->hrtf)
  895. VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_ENTRY);
  896. if(iter != VECTOR_END(*list))
  897. {
  898. TRACE("Skipping duplicate file entry %s\n", alstr_get_cstr(filename));
  899. return;
  900. }
  901. #undef MATCH_FNAME
  902. break;
  903. }
  904. loaded_entry = loaded_entry->next;
  905. }
  906. if(!loaded_entry)
  907. {
  908. TRACE("Got new file \"%s\"\n", alstr_get_cstr(filename));
  909. loaded_entry = al_calloc(DEF_ALIGN,
  910. FAM_SIZE(struct HrtfEntry, filename, alstr_length(filename)+1)
  911. );
  912. loaded_entry->next = LoadedHrtfs;
  913. loaded_entry->handle = NULL;
  914. strcpy(loaded_entry->filename, alstr_get_cstr(filename));
  915. LoadedHrtfs = loaded_entry;
  916. }
  917. /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
  918. * format update). */
  919. name = strrchr(alstr_get_cstr(filename), '/');
  920. if(!name) name = strrchr(alstr_get_cstr(filename), '\\');
  921. if(!name) name = alstr_get_cstr(filename);
  922. else ++name;
  923. ext = strrchr(name, '.');
  924. i = 0;
  925. do {
  926. if(!ext)
  927. alstr_copy_cstr(&entry.name, name);
  928. else
  929. alstr_copy_range(&entry.name, name, ext);
  930. if(i != 0)
  931. {
  932. char str[64];
  933. snprintf(str, sizeof(str), " #%d", i+1);
  934. alstr_append_cstr(&entry.name, str);
  935. }
  936. ++i;
  937. #define MATCH_NAME(i) (alstr_cmp(entry.name, (i)->name) == 0)
  938. VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_NAME);
  939. #undef MATCH_NAME
  940. } while(iter != VECTOR_END(*list));
  941. entry.hrtf = loaded_entry;
  942. TRACE("Adding entry \"%s\" from file \"%s\"\n", alstr_get_cstr(entry.name),
  943. alstr_get_cstr(filename));
  944. VECTOR_PUSH_BACK(*list, entry);
  945. }
  946. /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
  947. * for input instead of opening the given filename.
  948. */
  949. static void AddBuiltInEntry(vector_EnumeratedHrtf *list, const_al_string filename, ALuint residx)
  950. {
  951. EnumeratedHrtf entry = { AL_STRING_INIT_STATIC(), NULL };
  952. struct HrtfEntry *loaded_entry;
  953. struct Hrtf *hrtf = NULL;
  954. const EnumeratedHrtf *iter;
  955. const char *name;
  956. const char *ext;
  957. int i;
  958. loaded_entry = LoadedHrtfs;
  959. while(loaded_entry)
  960. {
  961. if(alstr_cmp_cstr(filename, loaded_entry->filename) == 0)
  962. {
  963. #define MATCH_ENTRY(i) (loaded_entry == (i)->hrtf)
  964. VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_ENTRY);
  965. if(iter != VECTOR_END(*list))
  966. {
  967. TRACE("Skipping duplicate file entry %s\n", alstr_get_cstr(filename));
  968. return;
  969. }
  970. #undef MATCH_FNAME
  971. break;
  972. }
  973. loaded_entry = loaded_entry->next;
  974. }
  975. if(!loaded_entry)
  976. {
  977. size_t namelen = alstr_length(filename)+32;
  978. TRACE("Got new file \"%s\"\n", alstr_get_cstr(filename));
  979. loaded_entry = al_calloc(DEF_ALIGN,
  980. FAM_SIZE(struct HrtfEntry, filename, namelen)
  981. );
  982. loaded_entry->next = LoadedHrtfs;
  983. loaded_entry->handle = hrtf;
  984. snprintf(loaded_entry->filename, namelen, "!%u_%s",
  985. residx, alstr_get_cstr(filename));
  986. LoadedHrtfs = loaded_entry;
  987. }
  988. /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
  989. * format update). */
  990. name = strrchr(alstr_get_cstr(filename), '/');
  991. if(!name) name = strrchr(alstr_get_cstr(filename), '\\');
  992. if(!name) name = alstr_get_cstr(filename);
  993. else ++name;
  994. ext = strrchr(name, '.');
  995. i = 0;
  996. do {
  997. if(!ext)
  998. alstr_copy_cstr(&entry.name, name);
  999. else
  1000. alstr_copy_range(&entry.name, name, ext);
  1001. if(i != 0)
  1002. {
  1003. char str[64];
  1004. snprintf(str, sizeof(str), " #%d", i+1);
  1005. alstr_append_cstr(&entry.name, str);
  1006. }
  1007. ++i;
  1008. #define MATCH_NAME(i) (alstr_cmp(entry.name, (i)->name) == 0)
  1009. VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_NAME);
  1010. #undef MATCH_NAME
  1011. } while(iter != VECTOR_END(*list));
  1012. entry.hrtf = loaded_entry;
  1013. TRACE("Adding built-in entry \"%s\"\n", alstr_get_cstr(entry.name));
  1014. VECTOR_PUSH_BACK(*list, entry);
  1015. }
  1016. #define IDR_DEFAULT_44100_MHR 1
  1017. #define IDR_DEFAULT_48000_MHR 2
  1018. #ifndef ALSOFT_EMBED_HRTF_DATA
  1019. static const ALubyte *GetResource(int UNUSED(name), size_t *size)
  1020. {
  1021. *size = 0;
  1022. return NULL;
  1023. }
  1024. #else
  1025. #include "default-44100.mhr.h"
  1026. #include "default-48000.mhr.h"
  1027. static const ALubyte *GetResource(int name, size_t *size)
  1028. {
  1029. if(name == IDR_DEFAULT_44100_MHR)
  1030. {
  1031. *size = sizeof(hrtf_default_44100);
  1032. return hrtf_default_44100;
  1033. }
  1034. if(name == IDR_DEFAULT_48000_MHR)
  1035. {
  1036. *size = sizeof(hrtf_default_48000);
  1037. return hrtf_default_48000;
  1038. }
  1039. *size = 0;
  1040. return NULL;
  1041. }
  1042. #endif
  1043. vector_EnumeratedHrtf EnumerateHrtf(const_al_string devname)
  1044. {
  1045. vector_EnumeratedHrtf list = VECTOR_INIT_STATIC();
  1046. const char *defaulthrtf = "";
  1047. const char *pathlist = "";
  1048. bool usedefaults = true;
  1049. if(ConfigValueStr(alstr_get_cstr(devname), NULL, "hrtf-paths", &pathlist))
  1050. {
  1051. al_string pname = AL_STRING_INIT_STATIC();
  1052. while(pathlist && *pathlist)
  1053. {
  1054. const char *next, *end;
  1055. while(isspace(*pathlist) || *pathlist == ',')
  1056. pathlist++;
  1057. if(*pathlist == '\0')
  1058. continue;
  1059. next = strchr(pathlist, ',');
  1060. if(next)
  1061. end = next++;
  1062. else
  1063. {
  1064. end = pathlist + strlen(pathlist);
  1065. usedefaults = false;
  1066. }
  1067. while(end != pathlist && isspace(*(end-1)))
  1068. --end;
  1069. if(end != pathlist)
  1070. {
  1071. vector_al_string flist;
  1072. size_t i;
  1073. alstr_copy_range(&pname, pathlist, end);
  1074. flist = SearchDataFiles(".mhr", alstr_get_cstr(pname));
  1075. for(i = 0;i < VECTOR_SIZE(flist);i++)
  1076. AddFileEntry(&list, VECTOR_ELEM(flist, i));
  1077. VECTOR_FOR_EACH(al_string, flist, alstr_reset);
  1078. VECTOR_DEINIT(flist);
  1079. }
  1080. pathlist = next;
  1081. }
  1082. alstr_reset(&pname);
  1083. }
  1084. else if(ConfigValueExists(alstr_get_cstr(devname), NULL, "hrtf_tables"))
  1085. ERR("The hrtf_tables option is deprecated, please use hrtf-paths instead.\n");
  1086. if(usedefaults)
  1087. {
  1088. al_string ename = AL_STRING_INIT_STATIC();
  1089. vector_al_string flist;
  1090. const ALubyte *rdata;
  1091. size_t rsize, i;
  1092. flist = SearchDataFiles(".mhr", "openal/hrtf");
  1093. for(i = 0;i < VECTOR_SIZE(flist);i++)
  1094. AddFileEntry(&list, VECTOR_ELEM(flist, i));
  1095. VECTOR_FOR_EACH(al_string, flist, alstr_reset);
  1096. VECTOR_DEINIT(flist);
  1097. rdata = GetResource(IDR_DEFAULT_44100_MHR, &rsize);
  1098. if(rdata != NULL && rsize > 0)
  1099. {
  1100. alstr_copy_cstr(&ename, "Built-In 44100hz");
  1101. AddBuiltInEntry(&list, ename, IDR_DEFAULT_44100_MHR);
  1102. }
  1103. rdata = GetResource(IDR_DEFAULT_48000_MHR, &rsize);
  1104. if(rdata != NULL && rsize > 0)
  1105. {
  1106. alstr_copy_cstr(&ename, "Built-In 48000hz");
  1107. AddBuiltInEntry(&list, ename, IDR_DEFAULT_48000_MHR);
  1108. }
  1109. alstr_reset(&ename);
  1110. }
  1111. if(VECTOR_SIZE(list) > 1 && ConfigValueStr(alstr_get_cstr(devname), NULL, "default-hrtf", &defaulthrtf))
  1112. {
  1113. const EnumeratedHrtf *iter;
  1114. /* Find the preferred HRTF and move it to the front of the list. */
  1115. #define FIND_ENTRY(i) (alstr_cmp_cstr((i)->name, defaulthrtf) == 0)
  1116. VECTOR_FIND_IF(iter, const EnumeratedHrtf, list, FIND_ENTRY);
  1117. #undef FIND_ENTRY
  1118. if(iter == VECTOR_END(list))
  1119. WARN("Failed to find default HRTF \"%s\"\n", defaulthrtf);
  1120. else if(iter != VECTOR_BEGIN(list))
  1121. {
  1122. EnumeratedHrtf entry = *iter;
  1123. memmove(&VECTOR_ELEM(list,1), &VECTOR_ELEM(list,0),
  1124. (iter-VECTOR_BEGIN(list))*sizeof(EnumeratedHrtf));
  1125. VECTOR_ELEM(list,0) = entry;
  1126. }
  1127. }
  1128. return list;
  1129. }
  1130. void FreeHrtfList(vector_EnumeratedHrtf *list)
  1131. {
  1132. #define CLEAR_ENTRY(i) alstr_reset(&(i)->name)
  1133. VECTOR_FOR_EACH(EnumeratedHrtf, *list, CLEAR_ENTRY);
  1134. VECTOR_DEINIT(*list);
  1135. #undef CLEAR_ENTRY
  1136. }
  1137. struct Hrtf *GetLoadedHrtf(struct HrtfEntry *entry)
  1138. {
  1139. struct Hrtf *hrtf = NULL;
  1140. struct FileMapping fmap;
  1141. const ALubyte *rdata;
  1142. const char *name;
  1143. ALuint residx;
  1144. size_t rsize;
  1145. char ch;
  1146. while(ATOMIC_FLAG_TEST_AND_SET(&LoadedHrtfLock, almemory_order_seq_cst))
  1147. althrd_yield();
  1148. if(entry->handle)
  1149. {
  1150. hrtf = entry->handle;
  1151. Hrtf_IncRef(hrtf);
  1152. goto done;
  1153. }
  1154. fmap.ptr = NULL;
  1155. fmap.len = 0;
  1156. if(sscanf(entry->filename, "!%u%c", &residx, &ch) == 2 && ch == '_')
  1157. {
  1158. name = strchr(entry->filename, ch)+1;
  1159. TRACE("Loading %s...\n", name);
  1160. rdata = GetResource(residx, &rsize);
  1161. if(rdata == NULL || rsize == 0)
  1162. {
  1163. ERR("Could not get resource %u, %s\n", residx, name);
  1164. goto done;
  1165. }
  1166. }
  1167. else
  1168. {
  1169. name = entry->filename;
  1170. TRACE("Loading %s...\n", entry->filename);
  1171. fmap = MapFileToMem(entry->filename);
  1172. if(fmap.ptr == NULL)
  1173. {
  1174. ERR("Could not open %s\n", entry->filename);
  1175. goto done;
  1176. }
  1177. rdata = fmap.ptr;
  1178. rsize = fmap.len;
  1179. }
  1180. if(rsize < sizeof(magicMarker02))
  1181. ERR("%s data is too short ("SZFMT" bytes)\n", name, rsize);
  1182. else if(memcmp(rdata, magicMarker02, sizeof(magicMarker02)) == 0)
  1183. {
  1184. TRACE("Detected data set format v2\n");
  1185. hrtf = LoadHrtf02(rdata+sizeof(magicMarker02),
  1186. rsize-sizeof(magicMarker02), name
  1187. );
  1188. }
  1189. else if(memcmp(rdata, magicMarker01, sizeof(magicMarker01)) == 0)
  1190. {
  1191. TRACE("Detected data set format v1\n");
  1192. hrtf = LoadHrtf01(rdata+sizeof(magicMarker01),
  1193. rsize-sizeof(magicMarker01), name
  1194. );
  1195. }
  1196. else if(memcmp(rdata, magicMarker00, sizeof(magicMarker00)) == 0)
  1197. {
  1198. TRACE("Detected data set format v0\n");
  1199. hrtf = LoadHrtf00(rdata+sizeof(magicMarker00),
  1200. rsize-sizeof(magicMarker00), name
  1201. );
  1202. }
  1203. else
  1204. ERR("Invalid header in %s: \"%.8s\"\n", name, (const char*)rdata);
  1205. if(fmap.ptr)
  1206. UnmapFileMem(&fmap);
  1207. if(!hrtf)
  1208. {
  1209. ERR("Failed to load %s\n", name);
  1210. goto done;
  1211. }
  1212. entry->handle = hrtf;
  1213. Hrtf_IncRef(hrtf);
  1214. TRACE("Loaded HRTF support for format: %s %uhz\n",
  1215. DevFmtChannelsString(DevFmtStereo), hrtf->sampleRate);
  1216. done:
  1217. ATOMIC_FLAG_CLEAR(&LoadedHrtfLock, almemory_order_seq_cst);
  1218. return hrtf;
  1219. }
  1220. void Hrtf_IncRef(struct Hrtf *hrtf)
  1221. {
  1222. uint ref = IncrementRef(&hrtf->ref);
  1223. TRACEREF("%p increasing refcount to %u\n", hrtf, ref);
  1224. }
  1225. void Hrtf_DecRef(struct Hrtf *hrtf)
  1226. {
  1227. struct HrtfEntry *Hrtf;
  1228. uint ref = DecrementRef(&hrtf->ref);
  1229. TRACEREF("%p decreasing refcount to %u\n", hrtf, ref);
  1230. if(ref == 0)
  1231. {
  1232. while(ATOMIC_FLAG_TEST_AND_SET(&LoadedHrtfLock, almemory_order_seq_cst))
  1233. althrd_yield();
  1234. Hrtf = LoadedHrtfs;
  1235. while(Hrtf != NULL)
  1236. {
  1237. /* Need to double-check that it's still unused, as another device
  1238. * could've reacquired this HRTF after its reference went to 0 and
  1239. * before the lock was taken.
  1240. */
  1241. if(hrtf == Hrtf->handle && ReadRef(&hrtf->ref) == 0)
  1242. {
  1243. al_free(Hrtf->handle);
  1244. Hrtf->handle = NULL;
  1245. TRACE("Unloaded unused HRTF %s\n", Hrtf->filename);
  1246. }
  1247. Hrtf = Hrtf->next;
  1248. }
  1249. ATOMIC_FLAG_CLEAR(&LoadedHrtfLock, almemory_order_seq_cst);
  1250. }
  1251. }
  1252. void FreeHrtfs(void)
  1253. {
  1254. struct HrtfEntry *Hrtf = LoadedHrtfs;
  1255. LoadedHrtfs = NULL;
  1256. while(Hrtf != NULL)
  1257. {
  1258. struct HrtfEntry *next = Hrtf->next;
  1259. al_free(Hrtf->handle);
  1260. al_free(Hrtf);
  1261. Hrtf = next;
  1262. }
  1263. }