hrtf.c 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  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 "bformatdec.h"
  29. #include "hrtf.h"
  30. #include "compat.h"
  31. #include "almalloc.h"
  32. /* Current data set limits defined by the makehrtf utility. */
  33. #define MIN_IR_SIZE (8)
  34. #define MAX_IR_SIZE (512)
  35. #define MOD_IR_SIZE (8)
  36. #define MIN_EV_COUNT (5)
  37. #define MAX_EV_COUNT (128)
  38. #define MIN_AZ_COUNT (1)
  39. #define MAX_AZ_COUNT (128)
  40. struct HrtfEntry {
  41. struct HrtfEntry *next;
  42. struct Hrtf *handle;
  43. char filename[];
  44. };
  45. static const ALchar magicMarker00[8] = "MinPHR00";
  46. static const ALchar magicMarker01[8] = "MinPHR01";
  47. /* First value for pass-through coefficients (remaining are 0), used for omni-
  48. * directional sounds. */
  49. static const ALfloat PassthruCoeff = 0.707106781187f/*sqrt(0.5)*/;
  50. static ATOMIC_FLAG LoadedHrtfLock = ATOMIC_FLAG_INIT;
  51. static struct HrtfEntry *LoadedHrtfs = NULL;
  52. /* Calculate the elevation index given the polar elevation in radians. This
  53. * will return an index between 0 and (evcount - 1). Assumes the FPU is in
  54. * round-to-zero mode.
  55. */
  56. static ALsizei CalcEvIndex(ALsizei evcount, ALfloat ev, ALfloat *mu)
  57. {
  58. ALsizei idx;
  59. ev = (F_PI_2+ev) * (evcount-1) / F_PI;
  60. idx = mini(fastf2i(ev), evcount-1);
  61. *mu = ev - idx;
  62. return idx;
  63. }
  64. /* Calculate the azimuth index given the polar azimuth in radians. This will
  65. * return an index between 0 and (azcount - 1). Assumes the FPU is in round-to-
  66. * zero mode.
  67. */
  68. static ALsizei CalcAzIndex(ALsizei azcount, ALfloat az, ALfloat *mu)
  69. {
  70. ALsizei idx;
  71. az = (F_TAU+az) * azcount / F_TAU;
  72. idx = fastf2i(az) % azcount;
  73. *mu = az - floorf(az);
  74. return idx;
  75. }
  76. /* Calculates static HRIR coefficients and delays for the given polar elevation
  77. * and azimuth in radians. The coefficients are normalized.
  78. */
  79. void GetHrtfCoeffs(const struct Hrtf *Hrtf, ALfloat elevation, ALfloat azimuth, ALfloat spread, ALfloat (*coeffs)[2], ALsizei *delays)
  80. {
  81. ALsizei evidx, azidx, idx[4];
  82. ALsizei evoffset;
  83. ALfloat emu, amu[2];
  84. ALfloat blend[4];
  85. ALfloat dirfact;
  86. ALsizei i, c;
  87. dirfact = 1.0f - (spread / F_TAU);
  88. /* Claculate the lower elevation index. */
  89. evidx = CalcEvIndex(Hrtf->evCount, elevation, &emu);
  90. evoffset = Hrtf->evOffset[evidx];
  91. /* Calculate lower azimuth index. */
  92. azidx= CalcAzIndex(Hrtf->azCount[evidx], azimuth, &amu[0]);
  93. /* Calculate the lower HRIR indices. */
  94. idx[0] = evoffset + azidx;
  95. idx[1] = evoffset + ((azidx+1) % Hrtf->azCount[evidx]);
  96. if(evidx < Hrtf->evCount-1)
  97. {
  98. /* Increment elevation to the next (upper) index. */
  99. evidx++;
  100. evoffset = Hrtf->evOffset[evidx];
  101. /* Calculate upper azimuth index. */
  102. azidx = CalcAzIndex(Hrtf->azCount[evidx], azimuth, &amu[1]);
  103. /* Calculate the upper HRIR indices. */
  104. idx[2] = evoffset + azidx;
  105. idx[3] = evoffset + ((azidx+1) % Hrtf->azCount[evidx]);
  106. }
  107. else
  108. {
  109. /* If the lower elevation is the top index, the upper elevation is the
  110. * same as the lower.
  111. */
  112. amu[1] = amu[0];
  113. idx[2] = idx[0];
  114. idx[3] = idx[1];
  115. }
  116. /* Calculate bilinear blending weights, attenuated according to the
  117. * directional panning factor.
  118. */
  119. blend[0] = (1.0f-emu) * (1.0f-amu[0]) * dirfact;
  120. blend[1] = (1.0f-emu) * ( amu[0]) * dirfact;
  121. blend[2] = ( emu) * (1.0f-amu[1]) * dirfact;
  122. blend[3] = ( emu) * ( amu[1]) * dirfact;
  123. /* Calculate the blended HRIR delays. */
  124. delays[0] = fastf2i(
  125. Hrtf->delays[idx[0]][0]*blend[0] + Hrtf->delays[idx[1]][0]*blend[1] +
  126. Hrtf->delays[idx[2]][0]*blend[2] + Hrtf->delays[idx[3]][0]*blend[3] + 0.5f
  127. );
  128. delays[1] = fastf2i(
  129. Hrtf->delays[idx[0]][1]*blend[0] + Hrtf->delays[idx[1]][1]*blend[1] +
  130. Hrtf->delays[idx[2]][1]*blend[2] + Hrtf->delays[idx[3]][1]*blend[3] + 0.5f
  131. );
  132. /* Calculate the sample offsets for the HRIR indices. */
  133. idx[0] *= Hrtf->irSize;
  134. idx[1] *= Hrtf->irSize;
  135. idx[2] *= Hrtf->irSize;
  136. idx[3] *= Hrtf->irSize;
  137. /* Calculate the blended HRIR coefficients. */
  138. coeffs[0][0] = PassthruCoeff * (1.0f-dirfact);
  139. coeffs[0][1] = PassthruCoeff * (1.0f-dirfact);
  140. for(i = 1;i < Hrtf->irSize;i++)
  141. {
  142. coeffs[i][0] = 0.0f;
  143. coeffs[i][1] = 0.0f;
  144. }
  145. for(c = 0;c < 4;c++)
  146. {
  147. for(i = 0;i < Hrtf->irSize;i++)
  148. {
  149. coeffs[i][0] += Hrtf->coeffs[idx[c]+i][0] * blend[c];
  150. coeffs[i][1] += Hrtf->coeffs[idx[c]+i][1] * blend[c];
  151. }
  152. }
  153. }
  154. ALsizei BuildBFormatHrtf(const struct Hrtf *Hrtf, DirectHrtfState *state, ALsizei NumChannels, const ALfloat (*restrict AmbiPoints)[2], const ALfloat (*restrict AmbiMatrix)[2][MAX_AMBI_COEFFS], ALsizei AmbiCount)
  155. {
  156. /* Set this to 2 for dual-band HRTF processing. May require a higher quality
  157. * band-splitter, or better calculation of the new IR length to deal with the
  158. * tail generated by the filter.
  159. */
  160. #define NUM_BANDS 2
  161. BandSplitter splitter;
  162. ALsizei idx[HRTF_AMBI_MAX_CHANNELS];
  163. ALsizei min_delay = HRTF_HISTORY_LENGTH;
  164. ALfloat temps[3][HRIR_LENGTH];
  165. ALsizei max_length = 0;
  166. ALsizei i, c, b;
  167. for(c = 0;c < AmbiCount;c++)
  168. {
  169. ALuint evidx, azidx;
  170. ALuint evoffset;
  171. ALuint azcount;
  172. /* Calculate elevation index. */
  173. evidx = (ALsizei)floorf((F_PI_2 + AmbiPoints[c][0]) *
  174. (Hrtf->evCount-1)/F_PI + 0.5f);
  175. evidx = mini(evidx, Hrtf->evCount-1);
  176. azcount = Hrtf->azCount[evidx];
  177. evoffset = Hrtf->evOffset[evidx];
  178. /* Calculate azimuth index for this elevation. */
  179. azidx = (ALsizei)floorf((F_TAU+AmbiPoints[c][1]) *
  180. azcount/F_TAU + 0.5f) % azcount;
  181. /* Calculate indices for left and right channels. */
  182. idx[c] = evoffset + azidx;
  183. min_delay = mini(min_delay, mini(Hrtf->delays[idx[c]][0], Hrtf->delays[idx[c]][1]));
  184. }
  185. memset(temps, 0, sizeof(temps));
  186. bandsplit_init(&splitter, 400.0f / (ALfloat)Hrtf->sampleRate);
  187. for(c = 0;c < AmbiCount;c++)
  188. {
  189. const ALfloat (*fir)[2] = &Hrtf->coeffs[idx[c] * Hrtf->irSize];
  190. ALsizei ldelay = Hrtf->delays[idx[c]][0] - min_delay;
  191. ALsizei rdelay = Hrtf->delays[idx[c]][1] - min_delay;
  192. max_length = maxi(max_length,
  193. mini(maxi(ldelay, rdelay) + Hrtf->irSize, HRIR_LENGTH)
  194. );
  195. if(NUM_BANDS == 1)
  196. {
  197. for(i = 0;i < NumChannels;++i)
  198. {
  199. ALsizei lidx = ldelay, ridx = rdelay;
  200. ALsizei j = 0;
  201. while(lidx < HRIR_LENGTH && ridx < HRIR_LENGTH && j < Hrtf->irSize)
  202. {
  203. state->Chan[i].Coeffs[lidx++][0] += fir[j][0] * AmbiMatrix[c][0][i];
  204. state->Chan[i].Coeffs[ridx++][1] += fir[j][1] * AmbiMatrix[c][0][i];
  205. j++;
  206. }
  207. }
  208. }
  209. else
  210. {
  211. /* Band-split left HRIR into low and high frequency responses. */
  212. bandsplit_clear(&splitter);
  213. for(i = 0;i < Hrtf->irSize;i++)
  214. temps[2][i] = fir[i][0];
  215. bandsplit_process(&splitter, temps[0], temps[1], temps[2], HRIR_LENGTH);
  216. /* Apply left ear response with delay. */
  217. for(i = 0;i < NumChannels;++i)
  218. {
  219. for(b = 0;b < NUM_BANDS;b++)
  220. {
  221. ALsizei lidx = ldelay;
  222. ALsizei j = 0;
  223. while(lidx < HRIR_LENGTH)
  224. state->Chan[i].Coeffs[lidx++][0] += temps[b][j++] * AmbiMatrix[c][b][i];
  225. }
  226. }
  227. /* Band-split right HRIR into low and high frequency responses. */
  228. bandsplit_clear(&splitter);
  229. for(i = 0;i < Hrtf->irSize;i++)
  230. temps[2][i] = fir[i][1];
  231. bandsplit_process(&splitter, temps[0], temps[1], temps[2], HRIR_LENGTH);
  232. /* Apply right ear response with delay. */
  233. for(i = 0;i < NumChannels;++i)
  234. {
  235. for(b = 0;b < NUM_BANDS;b++)
  236. {
  237. ALsizei ridx = rdelay;
  238. ALsizei j = 0;
  239. while(ridx < HRIR_LENGTH)
  240. state->Chan[i].Coeffs[ridx++][1] += temps[b][j++] * AmbiMatrix[c][b][i];
  241. }
  242. }
  243. }
  244. }
  245. /* Round up to the next IR size multiple. */
  246. max_length = RoundUp(max_length, MOD_IR_SIZE);
  247. TRACE("Skipped min delay: %d, new combined length: %d\n", min_delay, max_length);
  248. return max_length;
  249. #undef NUM_BANDS
  250. }
  251. static struct Hrtf *CreateHrtfStore(ALuint rate, ALsizei irSize, ALsizei evCount, ALsizei irCount,
  252. const ALubyte *azCount, const ALushort *evOffset,
  253. const ALfloat (*coeffs)[2], const ALubyte (*delays)[2],
  254. const char *filename)
  255. {
  256. struct Hrtf *Hrtf;
  257. size_t total;
  258. total = sizeof(struct Hrtf);
  259. total += sizeof(Hrtf->azCount[0])*evCount;
  260. total = RoundUp(total, sizeof(ALushort)); /* Align for ushort fields */
  261. total += sizeof(Hrtf->evOffset[0])*evCount;
  262. total = RoundUp(total, 16); /* Align for coefficients using SIMD */
  263. total += sizeof(Hrtf->coeffs[0])*irSize*irCount;
  264. total += sizeof(Hrtf->delays[0])*irCount;
  265. Hrtf = al_calloc(16, total);
  266. if(Hrtf == NULL)
  267. ERR("Out of memory allocating storage for %s.\n", filename);
  268. else
  269. {
  270. uintptr_t offset = sizeof(struct Hrtf);
  271. char *base = (char*)Hrtf;
  272. ALushort *_evOffset;
  273. ALubyte *_azCount;
  274. ALubyte (*_delays)[2];
  275. ALfloat (*_coeffs)[2];
  276. ALsizei i;
  277. InitRef(&Hrtf->ref, 0);
  278. Hrtf->sampleRate = rate;
  279. Hrtf->irSize = irSize;
  280. Hrtf->evCount = evCount;
  281. /* Set up pointers to storage following the main HRTF struct. */
  282. _azCount = (ALubyte*)(base + offset); Hrtf->azCount = _azCount;
  283. offset += sizeof(_azCount[0])*evCount;
  284. offset = RoundUp(offset, sizeof(ALushort)); /* Align for ushort fields */
  285. _evOffset = (ALushort*)(base + offset); Hrtf->evOffset = _evOffset;
  286. offset += sizeof(_evOffset[0])*evCount;
  287. offset = RoundUp(offset, 16); /* Align for coefficients using SIMD */
  288. _coeffs = (ALfloat(*)[2])(base + offset); Hrtf->coeffs = _coeffs;
  289. offset += sizeof(_coeffs[0])*irSize*irCount;
  290. _delays = (ALubyte(*)[2])(base + offset); Hrtf->delays = _delays;
  291. offset += sizeof(_delays[0])*irCount;
  292. /* Copy input data to storage. */
  293. for(i = 0;i < evCount;i++) _azCount[i] = azCount[i];
  294. for(i = 0;i < evCount;i++) _evOffset[i] = evOffset[i];
  295. for(i = 0;i < irSize*irCount;i++)
  296. {
  297. _coeffs[i][0] = coeffs[i][0];
  298. _coeffs[i][1] = coeffs[i][1];
  299. }
  300. for(i = 0;i < irCount;i++)
  301. {
  302. _delays[i][0] = delays[i][0];
  303. _delays[i][1] = delays[i][1];
  304. }
  305. assert(offset == total);
  306. }
  307. return Hrtf;
  308. }
  309. static ALubyte GetLE_ALubyte(const ALubyte **data, size_t *len)
  310. {
  311. ALubyte ret = (*data)[0];
  312. *data += 1; *len -= 1;
  313. return ret;
  314. }
  315. static ALshort GetLE_ALshort(const ALubyte **data, size_t *len)
  316. {
  317. ALshort ret = (*data)[0] | ((*data)[1]<<8);
  318. *data += 2; *len -= 2;
  319. return ret;
  320. }
  321. static ALushort GetLE_ALushort(const ALubyte **data, size_t *len)
  322. {
  323. ALushort ret = (*data)[0] | ((*data)[1]<<8);
  324. *data += 2; *len -= 2;
  325. return ret;
  326. }
  327. static ALint GetLE_ALuint(const ALubyte **data, size_t *len)
  328. {
  329. ALint ret = (*data)[0] | ((*data)[1]<<8) | ((*data)[2]<<16) | ((*data)[3]<<24);
  330. *data += 4; *len -= 4;
  331. return ret;
  332. }
  333. static const ALubyte *Get_ALubytePtr(const ALubyte **data, size_t *len, size_t size)
  334. {
  335. const ALubyte *ret = *data;
  336. *data += size; *len -= size;
  337. return ret;
  338. }
  339. static struct Hrtf *LoadHrtf00(const ALubyte *data, size_t datalen, const char *filename)
  340. {
  341. const ALubyte maxDelay = HRTF_HISTORY_LENGTH-1;
  342. struct Hrtf *Hrtf = NULL;
  343. ALboolean failed = AL_FALSE;
  344. ALuint rate = 0;
  345. ALushort irCount = 0;
  346. ALushort irSize = 0;
  347. ALubyte evCount = 0;
  348. ALubyte *azCount = NULL;
  349. ALushort *evOffset = NULL;
  350. ALfloat (*coeffs)[2] = NULL;
  351. ALubyte (*delays)[2] = NULL;
  352. ALsizei i, j;
  353. if(datalen < 9)
  354. {
  355. ERR("Unexpected end of %s data (req %d, rem "SZFMT")\n", filename, 9, datalen);
  356. return NULL;
  357. }
  358. rate = GetLE_ALuint(&data, &datalen);
  359. irCount = GetLE_ALushort(&data, &datalen);
  360. irSize = GetLE_ALushort(&data, &datalen);
  361. evCount = GetLE_ALubyte(&data, &datalen);
  362. if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
  363. {
  364. ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
  365. irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
  366. failed = AL_TRUE;
  367. }
  368. if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
  369. {
  370. ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
  371. evCount, MIN_EV_COUNT, MAX_EV_COUNT);
  372. failed = AL_TRUE;
  373. }
  374. if(failed)
  375. return NULL;
  376. if(datalen < evCount*2u)
  377. {
  378. ERR("Unexpected end of %s data (req %d, rem "SZFMT")\n", filename, evCount*2, datalen);
  379. return NULL;
  380. }
  381. azCount = malloc(sizeof(azCount[0])*evCount);
  382. evOffset = malloc(sizeof(evOffset[0])*evCount);
  383. if(azCount == NULL || evOffset == NULL)
  384. {
  385. ERR("Out of memory.\n");
  386. failed = AL_TRUE;
  387. }
  388. if(!failed)
  389. {
  390. evOffset[0] = GetLE_ALushort(&data, &datalen);
  391. for(i = 1;i < evCount;i++)
  392. {
  393. evOffset[i] = GetLE_ALushort(&data, &datalen);
  394. if(evOffset[i] <= evOffset[i-1])
  395. {
  396. ERR("Invalid evOffset: evOffset[%d]=%d (last=%d)\n",
  397. i, evOffset[i], evOffset[i-1]);
  398. failed = AL_TRUE;
  399. }
  400. azCount[i-1] = evOffset[i] - evOffset[i-1];
  401. if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
  402. {
  403. ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
  404. i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
  405. failed = AL_TRUE;
  406. }
  407. }
  408. if(irCount <= evOffset[i-1])
  409. {
  410. ERR("Invalid evOffset: evOffset[%d]=%d (irCount=%d)\n",
  411. i-1, evOffset[i-1], irCount);
  412. failed = AL_TRUE;
  413. }
  414. azCount[i-1] = irCount - evOffset[i-1];
  415. if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
  416. {
  417. ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
  418. i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
  419. failed = AL_TRUE;
  420. }
  421. }
  422. if(!failed)
  423. {
  424. coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
  425. delays = malloc(sizeof(delays[0])*irCount);
  426. if(coeffs == NULL || delays == NULL)
  427. {
  428. ERR("Out of memory.\n");
  429. failed = AL_TRUE;
  430. }
  431. }
  432. if(!failed)
  433. {
  434. size_t reqsize = 2*irSize*irCount + irCount;
  435. if(datalen < reqsize)
  436. {
  437. ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT")\n",
  438. filename, reqsize, datalen);
  439. failed = AL_TRUE;
  440. }
  441. }
  442. if(!failed)
  443. {
  444. for(i = 0;i < irCount;i++)
  445. {
  446. for(j = 0;j < irSize;j++)
  447. coeffs[i*irSize + j][0] = GetLE_ALshort(&data, &datalen) / 32768.0f;
  448. }
  449. for(i = 0;i < irCount;i++)
  450. {
  451. delays[i][0] = GetLE_ALubyte(&data, &datalen);
  452. if(delays[i][0] > maxDelay)
  453. {
  454. ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i][0], maxDelay);
  455. failed = AL_TRUE;
  456. }
  457. }
  458. }
  459. if(!failed)
  460. {
  461. /* Mirror the left ear responses to the right ear. */
  462. for(i = 0;i < evCount;i++)
  463. {
  464. ALushort evoffset = evOffset[i];
  465. ALubyte azcount = azCount[i];
  466. for(j = 0;j < azcount;j++)
  467. {
  468. ALsizei lidx = evoffset + j;
  469. ALsizei ridx = evoffset + ((azcount-j) % azcount);
  470. ALsizei k;
  471. for(k = 0;k < irSize;k++)
  472. coeffs[ridx*irSize + k][1] = coeffs[lidx*irSize + k][0];
  473. delays[ridx][1] = delays[lidx][0];
  474. }
  475. }
  476. Hrtf = CreateHrtfStore(rate, irSize, evCount, irCount, azCount,
  477. evOffset, coeffs, delays, filename);
  478. }
  479. free(azCount);
  480. free(evOffset);
  481. free(coeffs);
  482. free(delays);
  483. return Hrtf;
  484. }
  485. static struct Hrtf *LoadHrtf01(const ALubyte *data, size_t datalen, const char *filename)
  486. {
  487. const ALubyte maxDelay = HRTF_HISTORY_LENGTH-1;
  488. struct Hrtf *Hrtf = NULL;
  489. ALboolean failed = AL_FALSE;
  490. ALuint rate = 0;
  491. ALushort irCount = 0;
  492. ALushort irSize = 0;
  493. ALubyte evCount = 0;
  494. const ALubyte *azCount = NULL;
  495. ALushort *evOffset = NULL;
  496. ALfloat (*coeffs)[2] = NULL;
  497. ALubyte (*delays)[2] = NULL;
  498. ALsizei i, j;
  499. if(datalen < 6)
  500. {
  501. ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, 6, datalen);
  502. return NULL;
  503. }
  504. rate = GetLE_ALuint(&data, &datalen);
  505. irSize = GetLE_ALubyte(&data, &datalen);
  506. evCount = GetLE_ALubyte(&data, &datalen);
  507. if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
  508. {
  509. ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
  510. irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
  511. failed = AL_TRUE;
  512. }
  513. if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
  514. {
  515. ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
  516. evCount, MIN_EV_COUNT, MAX_EV_COUNT);
  517. failed = AL_TRUE;
  518. }
  519. if(failed)
  520. return NULL;
  521. if(datalen < evCount)
  522. {
  523. ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, evCount, datalen);
  524. return NULL;
  525. }
  526. azCount = Get_ALubytePtr(&data, &datalen, evCount);
  527. evOffset = malloc(sizeof(evOffset[0])*evCount);
  528. if(azCount == NULL || evOffset == NULL)
  529. {
  530. ERR("Out of memory.\n");
  531. failed = AL_TRUE;
  532. }
  533. if(!failed)
  534. {
  535. for(i = 0;i < evCount;i++)
  536. {
  537. if(azCount[i] < MIN_AZ_COUNT || azCount[i] > MAX_AZ_COUNT)
  538. {
  539. ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
  540. i, azCount[i], MIN_AZ_COUNT, MAX_AZ_COUNT);
  541. failed = AL_TRUE;
  542. }
  543. }
  544. }
  545. if(!failed)
  546. {
  547. evOffset[0] = 0;
  548. irCount = azCount[0];
  549. for(i = 1;i < evCount;i++)
  550. {
  551. evOffset[i] = evOffset[i-1] + azCount[i-1];
  552. irCount += azCount[i];
  553. }
  554. coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
  555. delays = malloc(sizeof(delays[0])*irCount);
  556. if(coeffs == NULL || delays == NULL)
  557. {
  558. ERR("Out of memory.\n");
  559. failed = AL_TRUE;
  560. }
  561. }
  562. if(!failed)
  563. {
  564. size_t reqsize = 2*irSize*irCount + irCount;
  565. if(datalen < reqsize)
  566. {
  567. ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT"\n",
  568. filename, reqsize, datalen);
  569. failed = AL_TRUE;
  570. }
  571. }
  572. if(!failed)
  573. {
  574. for(i = 0;i < irCount;i++)
  575. {
  576. for(j = 0;j < irSize;j++)
  577. coeffs[i*irSize + j][0] = GetLE_ALshort(&data, &datalen) / 32768.0f;
  578. }
  579. for(i = 0;i < irCount;i++)
  580. {
  581. delays[i][0] = GetLE_ALubyte(&data, &datalen);
  582. if(delays[i][0] > maxDelay)
  583. {
  584. ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i][0], maxDelay);
  585. failed = AL_TRUE;
  586. }
  587. }
  588. }
  589. if(!failed)
  590. {
  591. /* Mirror the left ear responses to the right ear. */
  592. for(i = 0;i < evCount;i++)
  593. {
  594. ALushort evoffset = evOffset[i];
  595. ALubyte azcount = azCount[i];
  596. for(j = 0;j < azcount;j++)
  597. {
  598. ALsizei lidx = evoffset + j;
  599. ALsizei ridx = evoffset + ((azcount-j) % azcount);
  600. ALsizei k;
  601. for(k = 0;k < irSize;k++)
  602. coeffs[ridx*irSize + k][1] = coeffs[lidx*irSize + k][0];
  603. delays[ridx][1] = delays[lidx][0];
  604. }
  605. }
  606. Hrtf = CreateHrtfStore(rate, irSize, evCount, irCount, azCount,
  607. evOffset, coeffs, delays, filename);
  608. }
  609. free(evOffset);
  610. free(coeffs);
  611. free(delays);
  612. return Hrtf;
  613. }
  614. static void AddFileEntry(vector_EnumeratedHrtf *list, const_al_string filename)
  615. {
  616. EnumeratedHrtf entry = { AL_STRING_INIT_STATIC(), NULL };
  617. struct HrtfEntry *loaded_entry;
  618. const EnumeratedHrtf *iter;
  619. const char *name;
  620. const char *ext;
  621. int i;
  622. /* Check if this file has already been loaded globally. */
  623. loaded_entry = LoadedHrtfs;
  624. while(loaded_entry)
  625. {
  626. if(alstr_cmp_cstr(filename, loaded_entry->filename) == 0)
  627. {
  628. /* Check if this entry has already been added to the list. */
  629. #define MATCH_ENTRY(i) (loaded_entry == (i)->hrtf)
  630. VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_ENTRY);
  631. if(iter != VECTOR_END(*list))
  632. {
  633. TRACE("Skipping duplicate file entry %s\n", alstr_get_cstr(filename));
  634. return;
  635. }
  636. #undef MATCH_FNAME
  637. break;
  638. }
  639. loaded_entry = loaded_entry->next;
  640. }
  641. if(!loaded_entry)
  642. {
  643. TRACE("Got new file \"%s\"\n", alstr_get_cstr(filename));
  644. loaded_entry = al_calloc(DEF_ALIGN,
  645. FAM_SIZE(struct HrtfEntry, filename, alstr_length(filename)+1)
  646. );
  647. loaded_entry->next = LoadedHrtfs;
  648. loaded_entry->handle = NULL;
  649. strcpy(loaded_entry->filename, alstr_get_cstr(filename));
  650. LoadedHrtfs = loaded_entry;
  651. }
  652. /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
  653. * format update). */
  654. name = strrchr(alstr_get_cstr(filename), '/');
  655. if(!name) name = strrchr(alstr_get_cstr(filename), '\\');
  656. if(!name) name = alstr_get_cstr(filename);
  657. else ++name;
  658. ext = strrchr(name, '.');
  659. i = 0;
  660. do {
  661. if(!ext)
  662. alstr_copy_cstr(&entry.name, name);
  663. else
  664. alstr_copy_range(&entry.name, name, ext);
  665. if(i != 0)
  666. {
  667. char str[64];
  668. snprintf(str, sizeof(str), " #%d", i+1);
  669. alstr_append_cstr(&entry.name, str);
  670. }
  671. ++i;
  672. #define MATCH_NAME(i) (alstr_cmp(entry.name, (i)->name) == 0)
  673. VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_NAME);
  674. #undef MATCH_NAME
  675. } while(iter != VECTOR_END(*list));
  676. entry.hrtf = loaded_entry;
  677. TRACE("Adding entry \"%s\" from file \"%s\"\n", alstr_get_cstr(entry.name),
  678. alstr_get_cstr(filename));
  679. VECTOR_PUSH_BACK(*list, entry);
  680. }
  681. /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
  682. * for input instead of opening the given filename.
  683. */
  684. static void AddBuiltInEntry(vector_EnumeratedHrtf *list, const_al_string filename, size_t residx)
  685. {
  686. EnumeratedHrtf entry = { AL_STRING_INIT_STATIC(), NULL };
  687. struct HrtfEntry *loaded_entry;
  688. struct Hrtf *hrtf = NULL;
  689. const EnumeratedHrtf *iter;
  690. const char *name;
  691. const char *ext;
  692. int i;
  693. loaded_entry = LoadedHrtfs;
  694. while(loaded_entry)
  695. {
  696. if(alstr_cmp_cstr(filename, loaded_entry->filename) == 0)
  697. {
  698. #define MATCH_ENTRY(i) (loaded_entry == (i)->hrtf)
  699. VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_ENTRY);
  700. if(iter != VECTOR_END(*list))
  701. {
  702. TRACE("Skipping duplicate file entry %s\n", alstr_get_cstr(filename));
  703. return;
  704. }
  705. #undef MATCH_FNAME
  706. break;
  707. }
  708. loaded_entry = loaded_entry->next;
  709. }
  710. if(!loaded_entry)
  711. {
  712. size_t namelen = alstr_length(filename)+32;
  713. TRACE("Got new file \"%s\"\n", alstr_get_cstr(filename));
  714. loaded_entry = al_calloc(DEF_ALIGN,
  715. FAM_SIZE(struct HrtfEntry, filename, namelen)
  716. );
  717. loaded_entry->next = LoadedHrtfs;
  718. loaded_entry->handle = hrtf;
  719. snprintf(loaded_entry->filename, namelen, "!"SZFMT"_%s",
  720. residx, alstr_get_cstr(filename));
  721. LoadedHrtfs = loaded_entry;
  722. }
  723. /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
  724. * format update). */
  725. name = strrchr(alstr_get_cstr(filename), '/');
  726. if(!name) name = strrchr(alstr_get_cstr(filename), '\\');
  727. if(!name) name = alstr_get_cstr(filename);
  728. else ++name;
  729. ext = strrchr(name, '.');
  730. i = 0;
  731. do {
  732. if(!ext)
  733. alstr_copy_cstr(&entry.name, name);
  734. else
  735. alstr_copy_range(&entry.name, name, ext);
  736. if(i != 0)
  737. {
  738. char str[64];
  739. snprintf(str, sizeof(str), " #%d", i+1);
  740. alstr_append_cstr(&entry.name, str);
  741. }
  742. ++i;
  743. #define MATCH_NAME(i) (alstr_cmp(entry.name, (i)->name) == 0)
  744. VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_NAME);
  745. #undef MATCH_NAME
  746. } while(iter != VECTOR_END(*list));
  747. entry.hrtf = loaded_entry;
  748. TRACE("Adding built-in entry \"%s\"\n", alstr_get_cstr(entry.name));
  749. VECTOR_PUSH_BACK(*list, entry);
  750. }
  751. #define IDR_DEFAULT_44100_MHR 1
  752. #define IDR_DEFAULT_48000_MHR 2
  753. #ifndef ALSOFT_EMBED_HRTF_DATA
  754. static const ALubyte *GetResource(int UNUSED(name), size_t *size)
  755. {
  756. *size = 0;
  757. return NULL;
  758. }
  759. #else
  760. #include "default-44100.mhr.h"
  761. #include "default-48000.mhr.h"
  762. static const ALubyte *GetResource(int name, size_t *size)
  763. {
  764. if(name == IDR_DEFAULT_44100_MHR)
  765. {
  766. *size = sizeof(hrtf_default_44100);
  767. return hrtf_default_44100;
  768. }
  769. if(name == IDR_DEFAULT_48000_MHR)
  770. {
  771. *size = sizeof(hrtf_default_48000);
  772. return hrtf_default_48000;
  773. }
  774. *size = 0;
  775. return NULL;
  776. }
  777. #endif
  778. vector_EnumeratedHrtf EnumerateHrtf(const_al_string devname)
  779. {
  780. vector_EnumeratedHrtf list = VECTOR_INIT_STATIC();
  781. const char *defaulthrtf = "";
  782. const char *pathlist = "";
  783. bool usedefaults = true;
  784. if(ConfigValueStr(alstr_get_cstr(devname), NULL, "hrtf-paths", &pathlist))
  785. {
  786. al_string pname = AL_STRING_INIT_STATIC();
  787. while(pathlist && *pathlist)
  788. {
  789. const char *next, *end;
  790. while(isspace(*pathlist) || *pathlist == ',')
  791. pathlist++;
  792. if(*pathlist == '\0')
  793. continue;
  794. next = strchr(pathlist, ',');
  795. if(next)
  796. end = next++;
  797. else
  798. {
  799. end = pathlist + strlen(pathlist);
  800. usedefaults = false;
  801. }
  802. while(end != pathlist && isspace(*(end-1)))
  803. --end;
  804. if(end != pathlist)
  805. {
  806. vector_al_string flist;
  807. size_t i;
  808. alstr_copy_range(&pname, pathlist, end);
  809. flist = SearchDataFiles(".mhr", alstr_get_cstr(pname));
  810. for(i = 0;i < VECTOR_SIZE(flist);i++)
  811. AddFileEntry(&list, VECTOR_ELEM(flist, i));
  812. VECTOR_FOR_EACH(al_string, flist, alstr_reset);
  813. VECTOR_DEINIT(flist);
  814. }
  815. pathlist = next;
  816. }
  817. alstr_reset(&pname);
  818. }
  819. else if(ConfigValueExists(alstr_get_cstr(devname), NULL, "hrtf_tables"))
  820. ERR("The hrtf_tables option is deprecated, please use hrtf-paths instead.\n");
  821. if(usedefaults)
  822. {
  823. al_string ename = AL_STRING_INIT_STATIC();
  824. vector_al_string flist;
  825. const ALubyte *rdata;
  826. size_t rsize, i;
  827. flist = SearchDataFiles(".mhr", "openal/hrtf");
  828. for(i = 0;i < VECTOR_SIZE(flist);i++)
  829. AddFileEntry(&list, VECTOR_ELEM(flist, i));
  830. VECTOR_FOR_EACH(al_string, flist, alstr_reset);
  831. VECTOR_DEINIT(flist);
  832. rdata = GetResource(IDR_DEFAULT_44100_MHR, &rsize);
  833. if(rdata != NULL && rsize > 0)
  834. {
  835. alstr_copy_cstr(&ename, "Built-In 44100hz");
  836. AddBuiltInEntry(&list, ename, IDR_DEFAULT_44100_MHR);
  837. }
  838. rdata = GetResource(IDR_DEFAULT_48000_MHR, &rsize);
  839. if(rdata != NULL && rsize > 0)
  840. {
  841. alstr_copy_cstr(&ename, "Built-In 48000hz");
  842. AddBuiltInEntry(&list, ename, IDR_DEFAULT_48000_MHR);
  843. }
  844. alstr_reset(&ename);
  845. }
  846. if(VECTOR_SIZE(list) > 1 && ConfigValueStr(alstr_get_cstr(devname), NULL, "default-hrtf", &defaulthrtf))
  847. {
  848. const EnumeratedHrtf *iter;
  849. /* Find the preferred HRTF and move it to the front of the list. */
  850. #define FIND_ENTRY(i) (alstr_cmp_cstr((i)->name, defaulthrtf) == 0)
  851. VECTOR_FIND_IF(iter, const EnumeratedHrtf, list, FIND_ENTRY);
  852. #undef FIND_ENTRY
  853. if(iter == VECTOR_END(list))
  854. WARN("Failed to find default HRTF \"%s\"\n", defaulthrtf);
  855. else if(iter != VECTOR_BEGIN(list))
  856. {
  857. EnumeratedHrtf entry = *iter;
  858. memmove(&VECTOR_ELEM(list,1), &VECTOR_ELEM(list,0),
  859. (iter-VECTOR_BEGIN(list))*sizeof(EnumeratedHrtf));
  860. VECTOR_ELEM(list,0) = entry;
  861. }
  862. }
  863. return list;
  864. }
  865. void FreeHrtfList(vector_EnumeratedHrtf *list)
  866. {
  867. #define CLEAR_ENTRY(i) alstr_reset(&(i)->name)
  868. VECTOR_FOR_EACH(EnumeratedHrtf, *list, CLEAR_ENTRY);
  869. VECTOR_DEINIT(*list);
  870. #undef CLEAR_ENTRY
  871. }
  872. struct Hrtf *GetLoadedHrtf(struct HrtfEntry *entry)
  873. {
  874. struct Hrtf *hrtf = NULL;
  875. struct FileMapping fmap;
  876. const ALubyte *rdata;
  877. const char *name;
  878. size_t residx;
  879. size_t rsize;
  880. char ch;
  881. while(ATOMIC_FLAG_TEST_AND_SET(&LoadedHrtfLock, almemory_order_seq_cst))
  882. althrd_yield();
  883. if(entry->handle)
  884. {
  885. hrtf = entry->handle;
  886. Hrtf_IncRef(hrtf);
  887. goto done;
  888. }
  889. fmap.ptr = NULL;
  890. fmap.len = 0;
  891. if(sscanf(entry->filename, "!"SZFMT"%c", &residx, &ch) == 2 && ch == '_')
  892. {
  893. name = strchr(entry->filename, ch)+1;
  894. TRACE("Loading %s...\n", name);
  895. rdata = GetResource(residx, &rsize);
  896. if(rdata == NULL || rsize == 0)
  897. {
  898. ERR("Could not get resource "SZFMT", %s\n", residx, name);
  899. goto done;
  900. }
  901. }
  902. else
  903. {
  904. name = entry->filename;
  905. TRACE("Loading %s...\n", entry->filename);
  906. fmap = MapFileToMem(entry->filename);
  907. if(fmap.ptr == NULL)
  908. {
  909. ERR("Could not open %s\n", entry->filename);
  910. goto done;
  911. }
  912. rdata = fmap.ptr;
  913. rsize = fmap.len;
  914. }
  915. if(rsize < sizeof(magicMarker01))
  916. ERR("%s data is too short ("SZFMT" bytes)\n", name, rsize);
  917. else if(memcmp(rdata, magicMarker01, sizeof(magicMarker01)) == 0)
  918. {
  919. TRACE("Detected data set format v1\n");
  920. hrtf = LoadHrtf01(rdata+sizeof(magicMarker01),
  921. rsize-sizeof(magicMarker01), name
  922. );
  923. }
  924. else if(memcmp(rdata, magicMarker00, sizeof(magicMarker00)) == 0)
  925. {
  926. TRACE("Detected data set format v0\n");
  927. hrtf = LoadHrtf00(rdata+sizeof(magicMarker00),
  928. rsize-sizeof(magicMarker00), name
  929. );
  930. }
  931. else
  932. ERR("Invalid header in %s: \"%.8s\"\n", name, (const char*)rdata);
  933. if(fmap.ptr)
  934. UnmapFileMem(&fmap);
  935. if(!hrtf)
  936. {
  937. ERR("Failed to load %s\n", name);
  938. goto done;
  939. }
  940. entry->handle = hrtf;
  941. Hrtf_IncRef(hrtf);
  942. TRACE("Loaded HRTF support for format: %s %uhz\n",
  943. DevFmtChannelsString(DevFmtStereo), hrtf->sampleRate);
  944. done:
  945. ATOMIC_FLAG_CLEAR(&LoadedHrtfLock, almemory_order_seq_cst);
  946. return hrtf;
  947. }
  948. void Hrtf_IncRef(struct Hrtf *hrtf)
  949. {
  950. uint ref = IncrementRef(&hrtf->ref);
  951. TRACEREF("%p increasing refcount to %u\n", hrtf, ref);
  952. }
  953. void Hrtf_DecRef(struct Hrtf *hrtf)
  954. {
  955. struct HrtfEntry *Hrtf;
  956. uint ref = DecrementRef(&hrtf->ref);
  957. TRACEREF("%p decreasing refcount to %u\n", hrtf, ref);
  958. if(ref == 0)
  959. {
  960. while(ATOMIC_FLAG_TEST_AND_SET(&LoadedHrtfLock, almemory_order_seq_cst))
  961. althrd_yield();
  962. Hrtf = LoadedHrtfs;
  963. while(Hrtf != NULL)
  964. {
  965. /* Need to double-check that it's still unused, as another device
  966. * could've reacquired this HRTF after its reference went to 0 and
  967. * before the lock was taken.
  968. */
  969. if(hrtf == Hrtf->handle && ReadRef(&hrtf->ref) == 0)
  970. {
  971. al_free(Hrtf->handle);
  972. Hrtf->handle = NULL;
  973. TRACE("Unloaded unused HRTF %s\n", Hrtf->filename);
  974. }
  975. Hrtf = Hrtf->next;
  976. }
  977. ATOMIC_FLAG_CLEAR(&LoadedHrtfLock, almemory_order_seq_cst);
  978. }
  979. }
  980. void FreeHrtfs(void)
  981. {
  982. struct HrtfEntry *Hrtf = LoadedHrtfs;
  983. LoadedHrtfs = NULL;
  984. while(Hrtf != NULL)
  985. {
  986. struct HrtfEntry *next = Hrtf->next;
  987. al_free(Hrtf->handle);
  988. al_free(Hrtf);
  989. Hrtf = next;
  990. }
  991. }