hrtf.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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 (128)
  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. static const ALchar magicMarker00[8] = "MinPHR00";
  41. static const ALchar magicMarker01[8] = "MinPHR01";
  42. /* First value for pass-through coefficients (remaining are 0), used for omni-
  43. * directional sounds. */
  44. static const ALfloat PassthruCoeff = 32767.0f * 0.707106781187f/*sqrt(0.5)*/;
  45. static struct Hrtf *LoadedHrtfs = NULL;
  46. /* Calculate the elevation index given the polar elevation in radians. This
  47. * will return an index between 0 and (evcount - 1). Assumes the FPU is in
  48. * round-to-zero mode.
  49. */
  50. static ALuint CalcEvIndex(ALuint evcount, ALfloat ev)
  51. {
  52. ev = (F_PI_2 + ev) * (evcount-1) / F_PI;
  53. return minu(fastf2u(ev + 0.5f), evcount-1);
  54. }
  55. /* Calculate the azimuth index given the polar azimuth in radians. This will
  56. * return an index between 0 and (azcount - 1). Assumes the FPU is in round-to-
  57. * zero mode.
  58. */
  59. static ALuint CalcAzIndex(ALuint azcount, ALfloat az)
  60. {
  61. az = (F_TAU + az) * azcount / F_TAU;
  62. return fastf2u(az + 0.5f) % azcount;
  63. }
  64. /* Calculates static HRIR coefficients and delays for the given polar elevation
  65. * and azimuth in radians. The coefficients are normalized and attenuated by
  66. * the specified gain.
  67. */
  68. void GetHrtfCoeffs(const struct Hrtf *Hrtf, ALfloat elevation, ALfloat azimuth, ALfloat spread, ALfloat gain, ALfloat (*coeffs)[2], ALuint *delays)
  69. {
  70. ALuint evidx, azidx, lidx, ridx;
  71. ALuint azcount, evoffset;
  72. ALfloat dirfact;
  73. ALuint i;
  74. dirfact = 1.0f - (spread / F_TAU);
  75. /* Claculate elevation index. */
  76. evidx = CalcEvIndex(Hrtf->evCount, elevation);
  77. azcount = Hrtf->azCount[evidx];
  78. evoffset = Hrtf->evOffset[evidx];
  79. /* Calculate azimuth index. */
  80. azidx = CalcAzIndex(Hrtf->azCount[evidx], azimuth);
  81. /* Calculate the HRIR indices for left and right channels. */
  82. lidx = evoffset + azidx;
  83. ridx = evoffset + ((azcount-azidx) % azcount);
  84. /* Calculate the HRIR delays. */
  85. delays[0] = fastf2u(Hrtf->delays[lidx]*dirfact + 0.5f) << HRTFDELAY_BITS;
  86. delays[1] = fastf2u(Hrtf->delays[ridx]*dirfact + 0.5f) << HRTFDELAY_BITS;
  87. /* Calculate the sample offsets for the HRIR indices. */
  88. lidx *= Hrtf->irSize;
  89. ridx *= Hrtf->irSize;
  90. /* Calculate the normalized and attenuated HRIR coefficients. Zero the
  91. * coefficients if gain is too low.
  92. */
  93. if(gain > 0.0001f)
  94. {
  95. gain /= 32767.0f;
  96. i = 0;
  97. coeffs[i][0] = lerp(PassthruCoeff, Hrtf->coeffs[lidx+i], dirfact)*gain;
  98. coeffs[i][1] = lerp(PassthruCoeff, Hrtf->coeffs[ridx+i], dirfact)*gain;
  99. for(i = 1;i < Hrtf->irSize;i++)
  100. {
  101. coeffs[i][0] = Hrtf->coeffs[lidx+i]*gain * dirfact;
  102. coeffs[i][1] = Hrtf->coeffs[ridx+i]*gain * dirfact;
  103. }
  104. }
  105. else
  106. {
  107. for(i = 0;i < Hrtf->irSize;i++)
  108. {
  109. coeffs[i][0] = 0.0f;
  110. coeffs[i][1] = 0.0f;
  111. }
  112. }
  113. }
  114. ALuint BuildBFormatHrtf(const struct Hrtf *Hrtf, ALfloat (*coeffs)[HRIR_LENGTH][2], ALuint NumChannels)
  115. {
  116. static const struct {
  117. ALfloat elevation;
  118. ALfloat azimuth;
  119. } Ambi3DPoints[14] = {
  120. { DEG2RAD( 90.0f), DEG2RAD( 0.0f) },
  121. { DEG2RAD( 35.0f), DEG2RAD( -45.0f) },
  122. { DEG2RAD( 35.0f), DEG2RAD( 45.0f) },
  123. { DEG2RAD( 35.0f), DEG2RAD( 135.0f) },
  124. { DEG2RAD( 35.0f), DEG2RAD(-135.0f) },
  125. { DEG2RAD( 0.0f), DEG2RAD( 0.0f) },
  126. { DEG2RAD( 0.0f), DEG2RAD( 90.0f) },
  127. { DEG2RAD( 0.0f), DEG2RAD( 180.0f) },
  128. { DEG2RAD( 0.0f), DEG2RAD( -90.0f) },
  129. { DEG2RAD(-35.0f), DEG2RAD( -45.0f) },
  130. { DEG2RAD(-35.0f), DEG2RAD( 45.0f) },
  131. { DEG2RAD(-35.0f), DEG2RAD( 135.0f) },
  132. { DEG2RAD(-35.0f), DEG2RAD(-135.0f) },
  133. { DEG2RAD(-90.0f), DEG2RAD( 0.0f) },
  134. };
  135. static const ALfloat Ambi3DMatrix[14][2][MAX_AMBI_COEFFS] = {
  136. { { 0.078851598f, 0.000000000f, 0.070561967f, 0.000000000f }, { 0.0269973975f, 0.0000000000f, 0.0467610443f, 0.0000000000f } },
  137. { { 0.124051278f, 0.059847972f, 0.059847972f, 0.059847972f }, { 0.0269973975f, 0.0269973975f, 0.0269973975f, 0.0269973975f } },
  138. { { 0.124051278f, -0.059847972f, 0.059847972f, 0.059847972f }, { 0.0269973975f, -0.0269973975f, 0.0269973975f, 0.0269973975f } },
  139. { { 0.124051278f, -0.059847972f, 0.059847972f, -0.059847972f }, { 0.0269973975f, -0.0269973975f, 0.0269973975f, -0.0269973975f } },
  140. { { 0.124051278f, 0.059847972f, 0.059847972f, -0.059847972f }, { 0.0269973975f, 0.0269973975f, 0.0269973975f, -0.0269973975f } },
  141. { { 0.078851598f, 0.000000000f, 0.000000000f, 0.070561967f }, { 0.0269973975f, 0.0000000000f, 0.0000000000f, 0.0467610443f } },
  142. { { 0.078851598f, -0.070561967f, 0.000000000f, 0.000000000f }, { 0.0269973975f, -0.0467610443f, 0.0000000000f, 0.0000000000f } },
  143. { { 0.078851598f, 0.000000000f, 0.000000000f, -0.070561967f }, { 0.0269973975f, 0.0000000000f, 0.0000000000f, -0.0467610443f } },
  144. { { 0.078851598f, 0.070561967f, 0.000000000f, 0.000000000f }, { 0.0269973975f, 0.0467610443f, 0.0000000000f, 0.0000000000f } },
  145. { { 0.124051278f, 0.059847972f, -0.059847972f, 0.059847972f }, { 0.0269973975f, 0.0269973975f, -0.0269973975f, 0.0269973975f } },
  146. { { 0.124051278f, -0.059847972f, -0.059847972f, 0.059847972f }, { 0.0269973975f, -0.0269973975f, -0.0269973975f, 0.0269973975f } },
  147. { { 0.124051278f, -0.059847972f, -0.059847972f, -0.059847972f }, { 0.0269973975f, -0.0269973975f, -0.0269973975f, -0.0269973975f } },
  148. { { 0.124051278f, 0.059847972f, -0.059847972f, -0.059847972f }, { 0.0269973975f, 0.0269973975f, -0.0269973975f, -0.0269973975f } },
  149. { { 0.078851598f, 0.000000000f, -0.070561967f, 0.000000000f }, { 0.0269973975f, 0.0000000000f, -0.0467610443f, 0.0000000000f } },
  150. };
  151. /* Change this to 2 for dual-band HRTF processing. May require a higher quality
  152. * band-splitter, or better calculation of the new IR length to deal with the
  153. * tail generated by the filter.
  154. */
  155. #define NUM_BANDS 2
  156. BandSplitter splitter;
  157. ALfloat temps[3][HRIR_LENGTH];
  158. ALuint lidx[14], ridx[14];
  159. ALuint min_delay = HRTF_HISTORY_LENGTH;
  160. ALuint max_length = 0;
  161. ALuint i, j, c, b;
  162. assert(NumChannels == 4);
  163. for(c = 0;c < COUNTOF(Ambi3DPoints);c++)
  164. {
  165. ALuint evidx, azidx;
  166. ALuint evoffset;
  167. ALuint azcount;
  168. /* Calculate elevation index. */
  169. evidx = (ALuint)floorf((F_PI_2 + Ambi3DPoints[c].elevation) *
  170. (Hrtf->evCount-1)/F_PI + 0.5f);
  171. evidx = minu(evidx, Hrtf->evCount-1);
  172. azcount = Hrtf->azCount[evidx];
  173. evoffset = Hrtf->evOffset[evidx];
  174. /* Calculate azimuth index for this elevation. */
  175. azidx = (ALuint)floorf((F_TAU+Ambi3DPoints[c].azimuth) *
  176. azcount/F_TAU + 0.5f) % azcount;
  177. /* Calculate indices for left and right channels. */
  178. lidx[c] = evoffset + azidx;
  179. ridx[c] = evoffset + ((azcount-azidx) % azcount);
  180. min_delay = minu(min_delay, minu(Hrtf->delays[lidx[c]], Hrtf->delays[ridx[c]]));
  181. }
  182. memset(temps, 0, sizeof(temps));
  183. bandsplit_init(&splitter, 400.0f / (ALfloat)Hrtf->sampleRate);
  184. for(c = 0;c < COUNTOF(Ambi3DMatrix);c++)
  185. {
  186. const ALshort *fir;
  187. ALuint delay;
  188. /* Convert the left FIR from shorts to float */
  189. fir = &Hrtf->coeffs[lidx[c] * Hrtf->irSize];
  190. if(NUM_BANDS == 1)
  191. {
  192. for(i = 0;i < Hrtf->irSize;i++)
  193. temps[0][i] = fir[i] / 32767.0f;
  194. }
  195. else
  196. {
  197. /* Band-split left HRIR into low and high frequency responses. */
  198. bandsplit_clear(&splitter);
  199. for(i = 0;i < Hrtf->irSize;i++)
  200. temps[2][i] = fir[i] / 32767.0f;
  201. bandsplit_process(&splitter, temps[0], temps[1], temps[2], HRIR_LENGTH);
  202. }
  203. /* Add to the left output coefficients with the specified delay. */
  204. delay = Hrtf->delays[lidx[c]] - min_delay;
  205. for(i = 0;i < NumChannels;++i)
  206. {
  207. for(b = 0;b < NUM_BANDS;b++)
  208. {
  209. ALuint k = 0;
  210. for(j = delay;j < HRIR_LENGTH;++j)
  211. coeffs[i][j][0] += temps[b][k++] * Ambi3DMatrix[c][b][i];
  212. }
  213. }
  214. max_length = maxu(max_length, minu(delay + Hrtf->irSize, HRIR_LENGTH));
  215. /* Convert the right FIR from shorts to float */
  216. fir = &Hrtf->coeffs[ridx[c] * Hrtf->irSize];
  217. if(NUM_BANDS == 1)
  218. {
  219. for(i = 0;i < Hrtf->irSize;i++)
  220. temps[0][i] = fir[i] / 32767.0f;
  221. }
  222. else
  223. {
  224. /* Band-split right HRIR into low and high frequency responses. */
  225. bandsplit_clear(&splitter);
  226. for(i = 0;i < Hrtf->irSize;i++)
  227. temps[2][i] = fir[i] / 32767.0f;
  228. bandsplit_process(&splitter, temps[0], temps[1], temps[2], HRIR_LENGTH);
  229. }
  230. /* Add to the right output coefficients with the specified delay. */
  231. delay = Hrtf->delays[ridx[c]] - min_delay;
  232. for(i = 0;i < NumChannels;++i)
  233. {
  234. for(b = 0;b < NUM_BANDS;b++)
  235. {
  236. ALuint k = 0;
  237. for(j = delay;j < HRIR_LENGTH;++j)
  238. coeffs[i][j][1] += temps[b][k++] * Ambi3DMatrix[c][b][i];
  239. }
  240. }
  241. max_length = maxu(max_length, minu(delay + Hrtf->irSize, HRIR_LENGTH));
  242. }
  243. TRACE("Skipped min delay: %u, new combined length: %u\n", min_delay, max_length);
  244. #undef NUM_BANDS
  245. return max_length;
  246. }
  247. static struct Hrtf *LoadHrtf00(const ALubyte *data, size_t datalen, const_al_string filename)
  248. {
  249. const ALubyte maxDelay = HRTF_HISTORY_LENGTH-1;
  250. struct Hrtf *Hrtf = NULL;
  251. ALboolean failed = AL_FALSE;
  252. ALuint rate = 0, irCount = 0;
  253. ALushort irSize = 0;
  254. ALubyte evCount = 0;
  255. ALubyte *azCount = NULL;
  256. ALushort *evOffset = NULL;
  257. ALshort *coeffs = NULL;
  258. const ALubyte *delays = NULL;
  259. ALuint i, j;
  260. if(datalen < 9)
  261. {
  262. ERR("Unexpected end of %s data (req %d, rem "SZFMT")\n",
  263. al_string_get_cstr(filename), 9, datalen);
  264. return NULL;
  265. }
  266. rate = *(data++);
  267. rate |= *(data++)<<8;
  268. rate |= *(data++)<<16;
  269. rate |= *(data++)<<24;
  270. datalen -= 4;
  271. irCount = *(data++);
  272. irCount |= *(data++)<<8;
  273. datalen -= 2;
  274. irSize = *(data++);
  275. irSize |= *(data++)<<8;
  276. datalen -= 2;
  277. evCount = *(data++);
  278. datalen -= 1;
  279. if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
  280. {
  281. ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
  282. irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
  283. failed = AL_TRUE;
  284. }
  285. if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
  286. {
  287. ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
  288. evCount, MIN_EV_COUNT, MAX_EV_COUNT);
  289. failed = AL_TRUE;
  290. }
  291. if(failed)
  292. return NULL;
  293. if(datalen < evCount*2)
  294. {
  295. ERR("Unexpected end of %s data (req %d, rem "SZFMT")\n",
  296. al_string_get_cstr(filename), evCount*2, datalen);
  297. return NULL;
  298. }
  299. azCount = malloc(sizeof(azCount[0])*evCount);
  300. evOffset = malloc(sizeof(evOffset[0])*evCount);
  301. if(azCount == NULL || evOffset == NULL)
  302. {
  303. ERR("Out of memory.\n");
  304. failed = AL_TRUE;
  305. }
  306. if(!failed)
  307. {
  308. evOffset[0] = *(data++);
  309. evOffset[0] |= *(data++)<<8;
  310. datalen -= 2;
  311. for(i = 1;i < evCount;i++)
  312. {
  313. evOffset[i] = *(data++);
  314. evOffset[i] |= *(data++)<<8;
  315. datalen -= 2;
  316. if(evOffset[i] <= evOffset[i-1])
  317. {
  318. ERR("Invalid evOffset: evOffset[%d]=%d (last=%d)\n",
  319. i, evOffset[i], evOffset[i-1]);
  320. failed = AL_TRUE;
  321. }
  322. azCount[i-1] = evOffset[i] - evOffset[i-1];
  323. if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
  324. {
  325. ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
  326. i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
  327. failed = AL_TRUE;
  328. }
  329. }
  330. if(irCount <= evOffset[i-1])
  331. {
  332. ERR("Invalid evOffset: evOffset[%d]=%d (irCount=%d)\n",
  333. i-1, evOffset[i-1], irCount);
  334. failed = AL_TRUE;
  335. }
  336. azCount[i-1] = irCount - evOffset[i-1];
  337. if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
  338. {
  339. ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
  340. i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
  341. failed = AL_TRUE;
  342. }
  343. }
  344. if(!failed)
  345. {
  346. coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
  347. if(coeffs == NULL)
  348. {
  349. ERR("Out of memory.\n");
  350. failed = AL_TRUE;
  351. }
  352. }
  353. if(!failed)
  354. {
  355. size_t reqsize = 2*irSize*irCount + irCount;
  356. if(datalen < reqsize)
  357. {
  358. ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT")\n",
  359. al_string_get_cstr(filename), reqsize, datalen);
  360. failed = AL_TRUE;
  361. }
  362. }
  363. if(!failed)
  364. {
  365. for(i = 0;i < irCount*irSize;i+=irSize)
  366. {
  367. for(j = 0;j < irSize;j++)
  368. {
  369. coeffs[i+j] = *(data++);
  370. coeffs[i+j] |= *(data++)<<8;
  371. datalen -= 2;
  372. }
  373. }
  374. delays = data;
  375. data += irCount;
  376. datalen -= irCount;
  377. for(i = 0;i < irCount;i++)
  378. {
  379. if(delays[i] > maxDelay)
  380. {
  381. ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i], maxDelay);
  382. failed = AL_TRUE;
  383. }
  384. }
  385. }
  386. if(!failed)
  387. {
  388. size_t total = sizeof(struct Hrtf);
  389. total += sizeof(azCount[0])*evCount;
  390. total = (total+1)&~1; /* Align for (u)short fields */
  391. total += sizeof(evOffset[0])*evCount;
  392. total += sizeof(coeffs[0])*irSize*irCount;
  393. total += sizeof(delays[0])*irCount;
  394. total += al_string_length(filename)+1;
  395. Hrtf = al_calloc(16, total);
  396. if(Hrtf == NULL)
  397. {
  398. ERR("Out of memory.\n");
  399. failed = AL_TRUE;
  400. }
  401. }
  402. if(!failed)
  403. {
  404. char *base = (char*)Hrtf;
  405. uintptr_t offset = sizeof(*Hrtf);
  406. Hrtf->sampleRate = rate;
  407. Hrtf->irSize = irSize;
  408. Hrtf->evCount = evCount;
  409. Hrtf->azCount = ((ALubyte*)(base + offset)); offset += evCount*sizeof(Hrtf->azCount[0]);
  410. offset = (offset+1)&~1; /* Align for (u)short fields */
  411. Hrtf->evOffset = ((ALushort*)(base + offset)); offset += evCount*sizeof(Hrtf->evOffset[0]);
  412. Hrtf->coeffs = ((ALshort*)(base + offset)); offset += irSize*irCount*sizeof(Hrtf->coeffs[0]);
  413. Hrtf->delays = ((ALubyte*)(base + offset)); offset += irCount*sizeof(Hrtf->delays[0]);
  414. Hrtf->filename = ((char*)(base + offset));
  415. Hrtf->next = NULL;
  416. memcpy((void*)Hrtf->azCount, azCount, sizeof(azCount[0])*evCount);
  417. memcpy((void*)Hrtf->evOffset, evOffset, sizeof(evOffset[0])*evCount);
  418. memcpy((void*)Hrtf->coeffs, coeffs, sizeof(coeffs[0])*irSize*irCount);
  419. memcpy((void*)Hrtf->delays, delays, sizeof(delays[0])*irCount);
  420. memcpy((void*)Hrtf->filename, al_string_get_cstr(filename), al_string_length(filename)+1);
  421. }
  422. free(azCount);
  423. free(evOffset);
  424. free(coeffs);
  425. return Hrtf;
  426. }
  427. static struct Hrtf *LoadHrtf01(const ALubyte *data, size_t datalen, const_al_string filename)
  428. {
  429. const ALubyte maxDelay = HRTF_HISTORY_LENGTH-1;
  430. struct Hrtf *Hrtf = NULL;
  431. ALboolean failed = AL_FALSE;
  432. ALuint rate = 0, irCount = 0;
  433. ALubyte irSize = 0, evCount = 0;
  434. const ALubyte *azCount = NULL;
  435. ALushort *evOffset = NULL;
  436. ALshort *coeffs = NULL;
  437. const ALubyte *delays = NULL;
  438. ALuint i, j;
  439. if(datalen < 6)
  440. {
  441. ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n",
  442. al_string_get_cstr(filename), 6, datalen);
  443. return NULL;
  444. }
  445. rate = *(data++);
  446. rate |= *(data++)<<8;
  447. rate |= *(data++)<<16;
  448. rate |= *(data++)<<24;
  449. datalen -= 4;
  450. irSize = *(data++);
  451. datalen -= 1;
  452. evCount = *(data++);
  453. datalen -= 1;
  454. if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
  455. {
  456. ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
  457. irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
  458. failed = AL_TRUE;
  459. }
  460. if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
  461. {
  462. ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
  463. evCount, MIN_EV_COUNT, MAX_EV_COUNT);
  464. failed = AL_TRUE;
  465. }
  466. if(failed)
  467. return NULL;
  468. if(datalen < evCount)
  469. {
  470. ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n",
  471. al_string_get_cstr(filename), evCount, datalen);
  472. return NULL;
  473. }
  474. azCount = data;
  475. data += evCount;
  476. datalen -= evCount;
  477. evOffset = malloc(sizeof(evOffset[0])*evCount);
  478. if(azCount == NULL || evOffset == NULL)
  479. {
  480. ERR("Out of memory.\n");
  481. failed = AL_TRUE;
  482. }
  483. if(!failed)
  484. {
  485. for(i = 0;i < evCount;i++)
  486. {
  487. if(azCount[i] < MIN_AZ_COUNT || azCount[i] > MAX_AZ_COUNT)
  488. {
  489. ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
  490. i, azCount[i], MIN_AZ_COUNT, MAX_AZ_COUNT);
  491. failed = AL_TRUE;
  492. }
  493. }
  494. }
  495. if(!failed)
  496. {
  497. evOffset[0] = 0;
  498. irCount = azCount[0];
  499. for(i = 1;i < evCount;i++)
  500. {
  501. evOffset[i] = evOffset[i-1] + azCount[i-1];
  502. irCount += azCount[i];
  503. }
  504. coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
  505. if(coeffs == NULL)
  506. {
  507. ERR("Out of memory.\n");
  508. failed = AL_TRUE;
  509. }
  510. }
  511. if(!failed)
  512. {
  513. size_t reqsize = 2*irSize*irCount + irCount;
  514. if(datalen < reqsize)
  515. {
  516. ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT"\n",
  517. al_string_get_cstr(filename), reqsize, datalen);
  518. failed = AL_TRUE;
  519. }
  520. }
  521. if(!failed)
  522. {
  523. for(i = 0;i < irCount*irSize;i+=irSize)
  524. {
  525. for(j = 0;j < irSize;j++)
  526. {
  527. ALshort coeff;
  528. coeff = *(data++);
  529. coeff |= *(data++)<<8;
  530. datalen -= 2;
  531. coeffs[i+j] = coeff;
  532. }
  533. }
  534. delays = data;
  535. data += irCount;
  536. datalen -= irCount;
  537. for(i = 0;i < irCount;i++)
  538. {
  539. if(delays[i] > maxDelay)
  540. {
  541. ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i], maxDelay);
  542. failed = AL_TRUE;
  543. }
  544. }
  545. }
  546. if(!failed)
  547. {
  548. size_t total = sizeof(struct Hrtf);
  549. total += sizeof(azCount[0])*evCount;
  550. total = (total+1)&~1; /* Align for (u)short fields */
  551. total += sizeof(evOffset[0])*evCount;
  552. total += sizeof(coeffs[0])*irSize*irCount;
  553. total += sizeof(delays[0])*irCount;
  554. total += al_string_length(filename)+1;
  555. Hrtf = al_calloc(16, total);
  556. if(Hrtf == NULL)
  557. {
  558. ERR("Out of memory.\n");
  559. failed = AL_TRUE;
  560. }
  561. }
  562. if(!failed)
  563. {
  564. char *base = (char*)Hrtf;
  565. uintptr_t offset = sizeof(*Hrtf);
  566. Hrtf->sampleRate = rate;
  567. Hrtf->irSize = irSize;
  568. Hrtf->evCount = evCount;
  569. Hrtf->azCount = ((ALubyte*)(base + offset)); offset += evCount*sizeof(Hrtf->azCount[0]);
  570. offset = (offset+1)&~1; /* Align for (u)short fields */
  571. Hrtf->evOffset = ((ALushort*)(base + offset)); offset += evCount*sizeof(Hrtf->evOffset[0]);
  572. Hrtf->coeffs = ((ALshort*)(base + offset)); offset += irSize*irCount*sizeof(Hrtf->coeffs[0]);
  573. Hrtf->delays = ((ALubyte*)(base + offset)); offset += irCount*sizeof(Hrtf->delays[0]);
  574. Hrtf->filename = ((char*)(base + offset));
  575. Hrtf->next = NULL;
  576. memcpy((void*)Hrtf->azCount, azCount, sizeof(azCount[0])*evCount);
  577. memcpy((void*)Hrtf->evOffset, evOffset, sizeof(evOffset[0])*evCount);
  578. memcpy((void*)Hrtf->coeffs, coeffs, sizeof(coeffs[0])*irSize*irCount);
  579. memcpy((void*)Hrtf->delays, delays, sizeof(delays[0])*irCount);
  580. memcpy((void*)Hrtf->filename, al_string_get_cstr(filename), al_string_length(filename)+1);
  581. }
  582. free(evOffset);
  583. free(coeffs);
  584. return Hrtf;
  585. }
  586. static void AddFileEntry(vector_HrtfEntry *list, al_string *filename)
  587. {
  588. HrtfEntry entry = { AL_STRING_INIT_STATIC(), NULL };
  589. struct Hrtf *hrtf = NULL;
  590. const HrtfEntry *iter;
  591. struct FileMapping fmap;
  592. const char *name;
  593. const char *ext;
  594. int i;
  595. #define MATCH_FNAME(i) (al_string_cmp_cstr(*filename, (i)->hrtf->filename) == 0)
  596. VECTOR_FIND_IF(iter, const HrtfEntry, *list, MATCH_FNAME);
  597. if(iter != VECTOR_END(*list))
  598. {
  599. TRACE("Skipping duplicate file entry %s\n", al_string_get_cstr(*filename));
  600. goto done;
  601. }
  602. #undef MATCH_FNAME
  603. entry.hrtf = LoadedHrtfs;
  604. while(entry.hrtf)
  605. {
  606. if(al_string_cmp_cstr(*filename, entry.hrtf->filename) == 0)
  607. {
  608. TRACE("Skipping load of already-loaded file %s\n", al_string_get_cstr(*filename));
  609. goto skip_load;
  610. }
  611. entry.hrtf = entry.hrtf->next;
  612. }
  613. TRACE("Loading %s...\n", al_string_get_cstr(*filename));
  614. fmap = MapFileToMem(al_string_get_cstr(*filename));
  615. if(fmap.ptr == NULL)
  616. {
  617. ERR("Could not open %s\n", al_string_get_cstr(*filename));
  618. goto done;
  619. }
  620. if(fmap.len < sizeof(magicMarker01))
  621. ERR("%s data is too short ("SZFMT" bytes)\n", al_string_get_cstr(*filename), fmap.len);
  622. else if(memcmp(fmap.ptr, magicMarker01, sizeof(magicMarker01)) == 0)
  623. {
  624. TRACE("Detected data set format v1\n");
  625. hrtf = LoadHrtf01((const ALubyte*)fmap.ptr+sizeof(magicMarker01),
  626. fmap.len-sizeof(magicMarker01), *filename
  627. );
  628. }
  629. else if(memcmp(fmap.ptr, magicMarker00, sizeof(magicMarker00)) == 0)
  630. {
  631. TRACE("Detected data set format v0\n");
  632. hrtf = LoadHrtf00((const ALubyte*)fmap.ptr+sizeof(magicMarker00),
  633. fmap.len-sizeof(magicMarker00), *filename
  634. );
  635. }
  636. else
  637. ERR("Invalid header in %s: \"%.8s\"\n", al_string_get_cstr(*filename), (const char*)fmap.ptr);
  638. UnmapFileMem(&fmap);
  639. if(!hrtf)
  640. {
  641. ERR("Failed to load %s\n", al_string_get_cstr(*filename));
  642. goto done;
  643. }
  644. hrtf->next = LoadedHrtfs;
  645. LoadedHrtfs = hrtf;
  646. TRACE("Loaded HRTF support for format: %s %uhz\n",
  647. DevFmtChannelsString(DevFmtStereo), hrtf->sampleRate);
  648. entry.hrtf = hrtf;
  649. skip_load:
  650. /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
  651. * format update). */
  652. name = strrchr(al_string_get_cstr(*filename), '/');
  653. if(!name) name = strrchr(al_string_get_cstr(*filename), '\\');
  654. if(!name) name = al_string_get_cstr(*filename);
  655. else ++name;
  656. ext = strrchr(name, '.');
  657. i = 0;
  658. do {
  659. if(!ext)
  660. al_string_copy_cstr(&entry.name, name);
  661. else
  662. al_string_copy_range(&entry.name, name, ext);
  663. if(i != 0)
  664. {
  665. char str[64];
  666. snprintf(str, sizeof(str), " #%d", i+1);
  667. al_string_append_cstr(&entry.name, str);
  668. }
  669. ++i;
  670. #define MATCH_NAME(i) (al_string_cmp(entry.name, (i)->name) == 0)
  671. VECTOR_FIND_IF(iter, const HrtfEntry, *list, MATCH_NAME);
  672. #undef MATCH_NAME
  673. } while(iter != VECTOR_END(*list));
  674. TRACE("Adding entry \"%s\" from file \"%s\"\n", al_string_get_cstr(entry.name),
  675. al_string_get_cstr(*filename));
  676. VECTOR_PUSH_BACK(*list, entry);
  677. done:
  678. al_string_deinit(filename);
  679. }
  680. /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
  681. * for input instead of opening the given filename.
  682. */
  683. static void AddBuiltInEntry(vector_HrtfEntry *list, const ALubyte *data, size_t datalen, al_string *filename)
  684. {
  685. HrtfEntry entry = { AL_STRING_INIT_STATIC(), NULL };
  686. struct Hrtf *hrtf = NULL;
  687. const HrtfEntry *iter;
  688. int i;
  689. #define MATCH_FNAME(i) (al_string_cmp_cstr(*filename, (i)->hrtf->filename) == 0)
  690. VECTOR_FIND_IF(iter, const HrtfEntry, *list, MATCH_FNAME);
  691. if(iter != VECTOR_END(*list))
  692. {
  693. TRACE("Skipping duplicate file entry %s\n", al_string_get_cstr(*filename));
  694. goto done;
  695. }
  696. #undef MATCH_FNAME
  697. entry.hrtf = LoadedHrtfs;
  698. while(entry.hrtf)
  699. {
  700. if(al_string_cmp_cstr(*filename, entry.hrtf->filename) == 0)
  701. {
  702. TRACE("Skipping load of already-loaded file %s\n", al_string_get_cstr(*filename));
  703. goto skip_load;
  704. }
  705. entry.hrtf = entry.hrtf->next;
  706. }
  707. TRACE("Loading %s...\n", al_string_get_cstr(*filename));
  708. if(datalen < sizeof(magicMarker01))
  709. {
  710. ERR("%s data is too short ("SZFMT" bytes)\n", al_string_get_cstr(*filename), datalen);
  711. goto done;
  712. }
  713. if(memcmp(data, magicMarker01, sizeof(magicMarker01)) == 0)
  714. {
  715. TRACE("Detected data set format v1\n");
  716. hrtf = LoadHrtf01(data+sizeof(magicMarker01),
  717. datalen-sizeof(magicMarker01), *filename
  718. );
  719. }
  720. else if(memcmp(data, magicMarker00, sizeof(magicMarker00)) == 0)
  721. {
  722. TRACE("Detected data set format v0\n");
  723. hrtf = LoadHrtf00(data+sizeof(magicMarker00),
  724. datalen-sizeof(magicMarker00), *filename
  725. );
  726. }
  727. else
  728. ERR("Invalid header in %s: \"%.8s\"\n", al_string_get_cstr(*filename), data);
  729. if(!hrtf)
  730. {
  731. ERR("Failed to load %s\n", al_string_get_cstr(*filename));
  732. goto done;
  733. }
  734. hrtf->next = LoadedHrtfs;
  735. LoadedHrtfs = hrtf;
  736. TRACE("Loaded HRTF support for format: %s %uhz\n",
  737. DevFmtChannelsString(DevFmtStereo), hrtf->sampleRate);
  738. entry.hrtf = hrtf;
  739. skip_load:
  740. i = 0;
  741. do {
  742. al_string_copy(&entry.name, *filename);
  743. if(i != 0)
  744. {
  745. char str[64];
  746. snprintf(str, sizeof(str), " #%d", i+1);
  747. al_string_append_cstr(&entry.name, str);
  748. }
  749. ++i;
  750. #define MATCH_NAME(i) (al_string_cmp(entry.name, (i)->name) == 0)
  751. VECTOR_FIND_IF(iter, const HrtfEntry, *list, MATCH_NAME);
  752. #undef MATCH_NAME
  753. } while(iter != VECTOR_END(*list));
  754. TRACE("Adding built-in entry \"%s\"\n", al_string_get_cstr(entry.name));
  755. VECTOR_PUSH_BACK(*list, entry);
  756. done:
  757. al_string_deinit(filename);
  758. }
  759. #ifndef ALSOFT_EMBED_HRTF_DATA
  760. #define IDR_DEFAULT_44100_MHR 0
  761. #define IDR_DEFAULT_48000_MHR 1
  762. static const ALubyte *GetResource(int UNUSED(name), size_t *size)
  763. {
  764. *size = 0;
  765. return NULL;
  766. }
  767. #else
  768. #include "hrtf_res.h"
  769. #ifdef _WIN32
  770. static const ALubyte *GetResource(int name, size_t *size)
  771. {
  772. HMODULE handle;
  773. HGLOBAL res;
  774. HRSRC rc;
  775. GetModuleHandleExW(
  776. GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
  777. (LPCWSTR)GetResource, &handle
  778. );
  779. rc = FindResourceW(handle, MAKEINTRESOURCEW(name), MAKEINTRESOURCEW(MHRTYPE));
  780. res = LoadResource(handle, rc);
  781. *size = SizeofResource(handle, rc);
  782. return LockResource(res);
  783. }
  784. #else
  785. extern const ALubyte _binary_default_44100_mhr_start[] HIDDEN_DECL;
  786. extern const ALubyte _binary_default_44100_mhr_end[] HIDDEN_DECL;
  787. extern const ALubyte _binary_default_44100_mhr_size[] HIDDEN_DECL;
  788. extern const ALubyte _binary_default_48000_mhr_start[] HIDDEN_DECL;
  789. extern const ALubyte _binary_default_48000_mhr_end[] HIDDEN_DECL;
  790. extern const ALubyte _binary_default_48000_mhr_size[] HIDDEN_DECL;
  791. static const ALubyte *GetResource(int name, size_t *size)
  792. {
  793. if(name == IDR_DEFAULT_44100_MHR)
  794. {
  795. /* Make sure all symbols are referenced, to ensure the compiler won't
  796. * ignore the declarations and lose the visibility attribute used to
  797. * hide them (would be nice if ld or objcopy could automatically mark
  798. * them as hidden when generating them, but apparently they can't).
  799. */
  800. const void *volatile ptr =_binary_default_44100_mhr_size;
  801. (void)ptr;
  802. *size = _binary_default_44100_mhr_end - _binary_default_44100_mhr_start;
  803. return _binary_default_44100_mhr_start;
  804. }
  805. if(name == IDR_DEFAULT_48000_MHR)
  806. {
  807. const void *volatile ptr =_binary_default_48000_mhr_size;
  808. (void)ptr;
  809. *size = _binary_default_48000_mhr_end - _binary_default_48000_mhr_start;
  810. return _binary_default_48000_mhr_start;
  811. }
  812. *size = 0;
  813. return NULL;
  814. }
  815. #endif
  816. #endif
  817. vector_HrtfEntry EnumerateHrtf(const_al_string devname)
  818. {
  819. vector_HrtfEntry list = VECTOR_INIT_STATIC();
  820. const char *defaulthrtf = "";
  821. const char *pathlist = "";
  822. bool usedefaults = true;
  823. if(ConfigValueStr(al_string_get_cstr(devname), NULL, "hrtf-paths", &pathlist))
  824. {
  825. while(pathlist && *pathlist)
  826. {
  827. const char *next, *end;
  828. while(isspace(*pathlist) || *pathlist == ',')
  829. pathlist++;
  830. if(*pathlist == '\0')
  831. continue;
  832. next = strchr(pathlist, ',');
  833. if(next)
  834. end = next++;
  835. else
  836. {
  837. end = pathlist + strlen(pathlist);
  838. usedefaults = false;
  839. }
  840. while(end != pathlist && isspace(*(end-1)))
  841. --end;
  842. if(end != pathlist)
  843. {
  844. al_string pname = AL_STRING_INIT_STATIC();
  845. vector_al_string flist;
  846. al_string_append_range(&pname, pathlist, end);
  847. flist = SearchDataFiles(".mhr", al_string_get_cstr(pname));
  848. VECTOR_FOR_EACH_PARAMS(al_string, flist, AddFileEntry, &list);
  849. VECTOR_DEINIT(flist);
  850. al_string_deinit(&pname);
  851. }
  852. pathlist = next;
  853. }
  854. }
  855. else if(ConfigValueExists(al_string_get_cstr(devname), NULL, "hrtf_tables"))
  856. ERR("The hrtf_tables option is deprecated, please use hrtf-paths instead.\n");
  857. if(usedefaults)
  858. {
  859. vector_al_string flist;
  860. const ALubyte *rdata;
  861. size_t rsize;
  862. flist = SearchDataFiles(".mhr", "openal/hrtf");
  863. VECTOR_FOR_EACH_PARAMS(al_string, flist, AddFileEntry, &list);
  864. VECTOR_DEINIT(flist);
  865. rdata = GetResource(IDR_DEFAULT_44100_MHR, &rsize);
  866. if(rdata != NULL && rsize > 0)
  867. {
  868. al_string ename = AL_STRING_INIT_STATIC();
  869. al_string_copy_cstr(&ename, "Built-In 44100hz");
  870. AddBuiltInEntry(&list, rdata, rsize, &ename);
  871. }
  872. rdata = GetResource(IDR_DEFAULT_48000_MHR, &rsize);
  873. if(rdata != NULL && rsize > 0)
  874. {
  875. al_string ename = AL_STRING_INIT_STATIC();
  876. al_string_copy_cstr(&ename, "Built-In 48000hz");
  877. AddBuiltInEntry(&list, rdata, rsize, &ename);
  878. }
  879. }
  880. if(VECTOR_SIZE(list) > 1 && ConfigValueStr(al_string_get_cstr(devname), NULL, "default-hrtf", &defaulthrtf))
  881. {
  882. const HrtfEntry *iter;
  883. /* Find the preferred HRTF and move it to the front of the list. */
  884. #define FIND_ENTRY(i) (al_string_cmp_cstr((i)->name, defaulthrtf) == 0)
  885. VECTOR_FIND_IF(iter, const HrtfEntry, list, FIND_ENTRY);
  886. #undef FIND_ENTRY
  887. if(iter == VECTOR_END(list))
  888. WARN("Failed to find default HRTF \"%s\"\n", defaulthrtf);
  889. else if(iter != VECTOR_BEGIN(list))
  890. {
  891. HrtfEntry entry = *iter;
  892. memmove(&VECTOR_ELEM(list,1), &VECTOR_ELEM(list,0),
  893. (iter-VECTOR_BEGIN(list))*sizeof(HrtfEntry));
  894. VECTOR_ELEM(list,0) = entry;
  895. }
  896. }
  897. return list;
  898. }
  899. void FreeHrtfList(vector_HrtfEntry *list)
  900. {
  901. #define CLEAR_ENTRY(i) do { \
  902. al_string_deinit(&(i)->name); \
  903. } while(0)
  904. VECTOR_FOR_EACH(HrtfEntry, *list, CLEAR_ENTRY);
  905. VECTOR_DEINIT(*list);
  906. #undef CLEAR_ENTRY
  907. }
  908. void FreeHrtfs(void)
  909. {
  910. struct Hrtf *Hrtf = LoadedHrtfs;
  911. LoadedHrtfs = NULL;
  912. while(Hrtf != NULL)
  913. {
  914. struct Hrtf *next = Hrtf->next;
  915. al_free(Hrtf);
  916. Hrtf = next;
  917. }
  918. }