hrtf.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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., 59 Temple Place - Suite 330,
  17. * Boston, MA 02111-1307, 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. static const ALchar magicMarker[8] = "MinPHR00";
  28. #define HRIR_COUNT 828
  29. #define ELEV_COUNT 19
  30. static const ALushort evOffset[ELEV_COUNT] = { 0, 1, 13, 37, 73, 118, 174, 234, 306, 378, 450, 522, 594, 654, 710, 755, 791, 815, 827 };
  31. static const ALubyte azCount[ELEV_COUNT] = { 1, 12, 24, 36, 45, 56, 60, 72, 72, 72, 72, 72, 60, 56, 45, 36, 24, 12, 1 };
  32. static const struct Hrtf {
  33. ALuint sampleRate;
  34. ALshort coeffs[HRIR_COUNT][HRIR_LENGTH];
  35. ALubyte delays[HRIR_COUNT];
  36. } DefaultHrtf = {
  37. 44100,
  38. #include "hrtf_tables.inc"
  39. };
  40. static struct Hrtf *LoadedHrtfs = NULL;
  41. static ALuint NumLoadedHrtfs = 0;
  42. // Calculate the elevation indices given the polar elevation in radians.
  43. // This will return two indices between 0 and (ELEV_COUNT-1) and an
  44. // interpolation factor between 0.0 and 1.0.
  45. static void CalcEvIndices(ALfloat ev, ALuint *evidx, ALfloat *evmu)
  46. {
  47. ev = (F_PI_2 + ev) * (ELEV_COUNT-1) / F_PI;
  48. evidx[0] = fastf2u(ev);
  49. evidx[1] = minu(evidx[0] + 1, ELEV_COUNT-1);
  50. *evmu = ev - evidx[0];
  51. }
  52. // Calculate the azimuth indices given the polar azimuth in radians. This
  53. // will return two indices between 0 and (azCount [ei] - 1) and an
  54. // interpolation factor between 0.0 and 1.0.
  55. static void CalcAzIndices(ALuint evidx, ALfloat az, ALuint *azidx, ALfloat *azmu)
  56. {
  57. az = (F_PI*2.0f + az) * azCount[evidx] / (F_PI*2.0f);
  58. azidx[0] = fastf2u(az) % azCount[evidx];
  59. azidx[1] = (azidx[0] + 1) % azCount[evidx];
  60. *azmu = az - aluFloor(az);
  61. }
  62. // Calculates the normalized HRTF transition factor (delta) from the changes
  63. // in gain and listener to source angle between updates. The result is a
  64. // normalized delta factor than can be used to calculate moving HRIR stepping
  65. // values.
  66. ALfloat CalcHrtfDelta(ALfloat oldGain, ALfloat newGain, const ALfloat olddir[3], const ALfloat newdir[3])
  67. {
  68. ALfloat gainChange, angleChange, change;
  69. // Calculate the normalized dB gain change.
  70. newGain = maxf(newGain, 0.0001f);
  71. oldGain = maxf(oldGain, 0.0001f);
  72. gainChange = aluFabs(aluLog10(newGain / oldGain) / aluLog10(0.0001f));
  73. // Calculate the normalized listener to source angle change when there is
  74. // enough gain to notice it.
  75. angleChange = 0.0f;
  76. if(gainChange > 0.0001f || newGain > 0.0001f)
  77. {
  78. // No angle change when the directions are equal or degenerate (when
  79. // both have zero length).
  80. if(newdir[0]-olddir[0] || newdir[1]-olddir[1] || newdir[2]-olddir[2])
  81. angleChange = aluAcos(olddir[0]*newdir[0] +
  82. olddir[1]*newdir[1] +
  83. olddir[2]*newdir[2]) / F_PI;
  84. }
  85. // Use the largest of the two changes for the delta factor, and apply a
  86. // significance shaping function to it.
  87. change = maxf(angleChange, gainChange) * 2.0f;
  88. return minf(change, 1.0f);
  89. }
  90. // Calculates static HRIR coefficients and delays for the given polar
  91. // elevation and azimuth in radians. Linear interpolation is used to
  92. // increase the apparent resolution of the HRIR dataset. The coefficients
  93. // are also normalized and attenuated by the specified gain.
  94. void GetLerpedHrtfCoeffs(const struct Hrtf *Hrtf, ALfloat elevation, ALfloat azimuth, ALfloat gain, ALfloat (*coeffs)[2], ALuint *delays)
  95. {
  96. ALuint evidx[2], azidx[2];
  97. ALfloat mu[3];
  98. ALuint lidx[4], ridx[4];
  99. ALuint i;
  100. // Claculate elevation indices and interpolation factor.
  101. CalcEvIndices(elevation, evidx, &mu[2]);
  102. // Calculate azimuth indices and interpolation factor for the first
  103. // elevation.
  104. CalcAzIndices(evidx[0], azimuth, azidx, &mu[0]);
  105. // Calculate the first set of linear HRIR indices for left and right
  106. // channels.
  107. lidx[0] = evOffset[evidx[0]] + azidx[0];
  108. lidx[1] = evOffset[evidx[0]] + azidx[1];
  109. ridx[0] = evOffset[evidx[0]] + ((azCount[evidx[0]]-azidx[0]) % azCount[evidx[0]]);
  110. ridx[1] = evOffset[evidx[0]] + ((azCount[evidx[0]]-azidx[1]) % azCount[evidx[0]]);
  111. // Calculate azimuth indices and interpolation factor for the second
  112. // elevation.
  113. CalcAzIndices(evidx[1], azimuth, azidx, &mu[1]);
  114. // Calculate the second set of linear HRIR indices for left and right
  115. // channels.
  116. lidx[2] = evOffset[evidx[1]] + azidx[0];
  117. lidx[3] = evOffset[evidx[1]] + azidx[1];
  118. ridx[2] = evOffset[evidx[1]] + ((azCount[evidx[1]]-azidx[0]) % azCount[evidx[1]]);
  119. ridx[3] = evOffset[evidx[1]] + ((azCount[evidx[1]]-azidx[1]) % azCount[evidx[1]]);
  120. // Calculate the normalized and attenuated HRIR coefficients using linear
  121. // interpolation when there is enough gain to warrant it. Zero the
  122. // coefficients if gain is too low.
  123. if(gain > 0.0001f)
  124. {
  125. gain *= 1.0f/32767.0f;
  126. for(i = 0;i < HRIR_LENGTH;i++)
  127. {
  128. coeffs[i][0] = lerp(lerp(Hrtf->coeffs[lidx[0]][i], Hrtf->coeffs[lidx[1]][i], mu[0]),
  129. lerp(Hrtf->coeffs[lidx[2]][i], Hrtf->coeffs[lidx[3]][i], mu[1]),
  130. mu[2]) * gain;
  131. coeffs[i][1] = lerp(lerp(Hrtf->coeffs[ridx[0]][i], Hrtf->coeffs[ridx[1]][i], mu[0]),
  132. lerp(Hrtf->coeffs[ridx[2]][i], Hrtf->coeffs[ridx[3]][i], mu[1]),
  133. mu[2]) * gain;
  134. }
  135. }
  136. else
  137. {
  138. for(i = 0;i < HRIR_LENGTH;i++)
  139. {
  140. coeffs[i][0] = 0.0f;
  141. coeffs[i][1] = 0.0f;
  142. }
  143. }
  144. // Calculate the HRIR delays using linear interpolation.
  145. delays[0] = fastf2u(lerp(lerp(Hrtf->delays[lidx[0]], Hrtf->delays[lidx[1]], mu[0]),
  146. lerp(Hrtf->delays[lidx[2]], Hrtf->delays[lidx[3]], mu[1]),
  147. mu[2]) * 65536.0f);
  148. delays[1] = fastf2u(lerp(lerp(Hrtf->delays[ridx[0]], Hrtf->delays[ridx[1]], mu[0]),
  149. lerp(Hrtf->delays[ridx[2]], Hrtf->delays[ridx[3]], mu[1]),
  150. mu[2]) * 65536.0f);
  151. }
  152. // Calculates the moving HRIR target coefficients, target delays, and
  153. // stepping values for the given polar elevation and azimuth in radians.
  154. // Linear interpolation is used to increase the apparent resolution of the
  155. // HRIR dataset. The coefficients are also normalized and attenuated by the
  156. // specified gain. Stepping resolution and count is determined using the
  157. // given delta factor between 0.0 and 1.0.
  158. ALuint GetMovingHrtfCoeffs(const struct Hrtf *Hrtf, ALfloat elevation, ALfloat azimuth, ALfloat gain, ALfloat delta, ALint counter, ALfloat (*coeffs)[2], ALuint *delays, ALfloat (*coeffStep)[2], ALint *delayStep)
  159. {
  160. ALuint evidx[2], azidx[2];
  161. ALuint lidx[4], ridx[4];
  162. ALfloat left, right;
  163. ALfloat mu[3];
  164. ALfloat step;
  165. ALuint i;
  166. // Claculate elevation indices and interpolation factor.
  167. CalcEvIndices(elevation, evidx, &mu[2]);
  168. // Calculate azimuth indices and interpolation factor for the first
  169. // elevation.
  170. CalcAzIndices(evidx[0], azimuth, azidx, &mu[0]);
  171. // Calculate the first set of linear HRIR indices for left and right
  172. // channels.
  173. lidx[0] = evOffset[evidx[0]] + azidx[0];
  174. lidx[1] = evOffset[evidx[0]] + azidx[1];
  175. ridx[0] = evOffset[evidx[0]] + ((azCount[evidx[0]]-azidx[0]) % azCount[evidx[0]]);
  176. ridx[1] = evOffset[evidx[0]] + ((azCount[evidx[0]]-azidx[1]) % azCount[evidx[0]]);
  177. // Calculate azimuth indices and interpolation factor for the second
  178. // elevation.
  179. CalcAzIndices(evidx[1], azimuth, azidx, &mu[1]);
  180. // Calculate the second set of linear HRIR indices for left and right
  181. // channels.
  182. lidx[2] = evOffset[evidx[1]] + azidx[0];
  183. lidx[3] = evOffset[evidx[1]] + azidx[1];
  184. ridx[2] = evOffset[evidx[1]] + ((azCount[evidx[1]]-azidx[0]) % azCount[evidx[1]]);
  185. ridx[3] = evOffset[evidx[1]] + ((azCount[evidx[1]]-azidx[1]) % azCount[evidx[1]]);
  186. // Calculate the stepping parameters.
  187. delta = maxf(aluFloor(delta*(Hrtf->sampleRate*0.015f) + 0.5f), 1.0f);
  188. step = 1.0f / delta;
  189. // Calculate the normalized and attenuated target HRIR coefficients using
  190. // linear interpolation when there is enough gain to warrant it. Zero
  191. // the target coefficients if gain is too low. Then calculate the
  192. // coefficient stepping values using the target and previous running
  193. // coefficients.
  194. if(gain > 0.0001f)
  195. {
  196. gain *= 1.0f/32767.0f;
  197. for(i = 0;i < HRIR_LENGTH;i++)
  198. {
  199. left = coeffs[i][0] - (coeffStep[i][0] * counter);
  200. right = coeffs[i][1] - (coeffStep[i][1] * counter);
  201. coeffs[i][0] = lerp(lerp(Hrtf->coeffs[lidx[0]][i], Hrtf->coeffs[lidx[1]][i], mu[0]),
  202. lerp(Hrtf->coeffs[lidx[2]][i], Hrtf->coeffs[lidx[3]][i], mu[1]),
  203. mu[2]) * gain;
  204. coeffs[i][1] = lerp(lerp(Hrtf->coeffs[ridx[0]][i], Hrtf->coeffs[ridx[1]][i], mu[0]),
  205. lerp(Hrtf->coeffs[ridx[2]][i], Hrtf->coeffs[ridx[3]][i], mu[1]),
  206. mu[2]) * gain;
  207. coeffStep[i][0] = step * (coeffs[i][0] - left);
  208. coeffStep[i][1] = step * (coeffs[i][1] - right);
  209. }
  210. }
  211. else
  212. {
  213. for(i = 0;i < HRIR_LENGTH;i++)
  214. {
  215. left = coeffs[i][0] - (coeffStep[i][0] * counter);
  216. right = coeffs[i][1] - (coeffStep[i][1] * counter);
  217. coeffs[i][0] = 0.0f;
  218. coeffs[i][1] = 0.0f;
  219. coeffStep[i][0] = step * -left;
  220. coeffStep[i][1] = step * -right;
  221. }
  222. }
  223. // Calculate the HRIR delays using linear interpolation. Then calculate
  224. // the delay stepping values using the target and previous running
  225. // delays.
  226. left = (ALfloat)(delays[0] - (delayStep[0] * counter));
  227. right = (ALfloat)(delays[1] - (delayStep[1] * counter));
  228. delays[0] = fastf2u(lerp(lerp(Hrtf->delays[lidx[0]], Hrtf->delays[lidx[1]], mu[0]),
  229. lerp(Hrtf->delays[lidx[2]], Hrtf->delays[lidx[3]], mu[1]),
  230. mu[2]) * 65536.0f);
  231. delays[1] = fastf2u(lerp(lerp(Hrtf->delays[ridx[0]], Hrtf->delays[ridx[1]], mu[0]),
  232. lerp(Hrtf->delays[ridx[2]], Hrtf->delays[ridx[3]], mu[1]),
  233. mu[2]) * 65536.0f);
  234. delayStep[0] = fastf2i(step * (delays[0] - left));
  235. delayStep[1] = fastf2i(step * (delays[1] - right));
  236. // The stepping count is the number of samples necessary for the HRIR to
  237. // complete its transition. The mixer will only apply stepping for this
  238. // many samples.
  239. return fastf2u(delta);
  240. }
  241. const struct Hrtf *GetHrtf(ALCdevice *device)
  242. {
  243. if(device->FmtChans == DevFmtStereo)
  244. {
  245. ALuint i;
  246. for(i = 0;i < NumLoadedHrtfs;i++)
  247. {
  248. if(device->Frequency == LoadedHrtfs[i].sampleRate)
  249. return &LoadedHrtfs[i];
  250. }
  251. if(device->Frequency == DefaultHrtf.sampleRate)
  252. return &DefaultHrtf;
  253. }
  254. ERR("Incompatible format: %s %uhz\n",
  255. DevFmtChannelsString(device->FmtChans), device->Frequency);
  256. return NULL;
  257. }
  258. void InitHrtf(void)
  259. {
  260. char *fnamelist=NULL, *next=NULL;
  261. const char *val;
  262. if(ConfigValueStr(NULL, "hrtf_tables", &val))
  263. next = fnamelist = strdup(val);
  264. while(next && *next)
  265. {
  266. const ALubyte maxDelay = SRC_HISTORY_LENGTH-1;
  267. struct Hrtf newdata;
  268. ALboolean failed;
  269. ALchar magic[9];
  270. ALsizei i, j;
  271. char *fname;
  272. FILE *f;
  273. fname = next;
  274. next = strchr(fname, ',');
  275. if(next)
  276. {
  277. while(next != fname)
  278. {
  279. next--;
  280. if(!isspace(*next))
  281. {
  282. *(next++) = '\0';
  283. break;
  284. }
  285. }
  286. while(isspace(*next) || *next == ',')
  287. next++;
  288. }
  289. if(!fname[0])
  290. continue;
  291. TRACE("Loading %s\n", fname);
  292. f = fopen(fname, "rb");
  293. if(f == NULL)
  294. {
  295. ERR("Could not open %s\n", fname);
  296. continue;
  297. }
  298. failed = AL_FALSE;
  299. if(fread(magic, 1, sizeof(magicMarker), f) != sizeof(magicMarker))
  300. {
  301. ERR("Failed to read magic marker\n");
  302. failed = AL_TRUE;
  303. }
  304. else if(memcmp(magic, magicMarker, sizeof(magicMarker)) != 0)
  305. {
  306. magic[8] = 0;
  307. ERR("Invalid magic marker: \"%s\"\n", magic);
  308. failed = AL_TRUE;
  309. }
  310. if(!failed)
  311. {
  312. ALushort hrirCount, hrirSize;
  313. ALubyte evCount;
  314. newdata.sampleRate = fgetc(f);
  315. newdata.sampleRate |= fgetc(f)<<8;
  316. newdata.sampleRate |= fgetc(f)<<16;
  317. newdata.sampleRate |= fgetc(f)<<24;
  318. hrirCount = fgetc(f);
  319. hrirCount |= fgetc(f)<<8;
  320. hrirSize = fgetc(f);
  321. hrirSize |= fgetc(f)<<8;
  322. evCount = fgetc(f);
  323. if(hrirCount != HRIR_COUNT || hrirSize != HRIR_LENGTH || evCount != ELEV_COUNT)
  324. {
  325. ERR("Unsupported value: hrirCount=%d (%d), hrirSize=%d (%d), evCount=%d (%d)\n",
  326. hrirCount, HRIR_COUNT, hrirSize, HRIR_LENGTH, evCount, ELEV_COUNT);
  327. failed = AL_TRUE;
  328. }
  329. }
  330. if(!failed)
  331. {
  332. for(i = 0;i < ELEV_COUNT;i++)
  333. {
  334. ALushort offset;
  335. offset = fgetc(f);
  336. offset |= fgetc(f)<<8;
  337. if(offset != evOffset[i])
  338. {
  339. ERR("Unsupported evOffset[%d] value: %d (%d)\n", i, offset, evOffset[i]);
  340. failed = AL_TRUE;
  341. }
  342. }
  343. }
  344. if(!failed)
  345. {
  346. for(i = 0;i < HRIR_COUNT;i++)
  347. {
  348. for(j = 0;j < HRIR_LENGTH;j++)
  349. {
  350. ALshort coeff;
  351. coeff = fgetc(f);
  352. coeff |= fgetc(f)<<8;
  353. newdata.coeffs[i][j] = coeff;
  354. }
  355. }
  356. for(i = 0;i < HRIR_COUNT;i++)
  357. {
  358. ALubyte delay;
  359. delay = fgetc(f);
  360. newdata.delays[i] = delay;
  361. if(delay > maxDelay)
  362. {
  363. ERR("Invalid delay[%d]: %d (%d)\n", i, delay, maxDelay);
  364. failed = AL_TRUE;
  365. }
  366. }
  367. if(feof(f))
  368. {
  369. ERR("Premature end of data\n");
  370. failed = AL_TRUE;
  371. }
  372. }
  373. fclose(f);
  374. f = NULL;
  375. if(!failed)
  376. {
  377. void *temp = realloc(LoadedHrtfs, (NumLoadedHrtfs+1)*sizeof(LoadedHrtfs[0]));
  378. if(temp != NULL)
  379. {
  380. LoadedHrtfs = temp;
  381. TRACE("Loaded HRTF support for format: %s %uhz\n",
  382. DevFmtChannelsString(DevFmtStereo), newdata.sampleRate);
  383. LoadedHrtfs[NumLoadedHrtfs++] = newdata;
  384. }
  385. }
  386. else
  387. ERR("Failed to load %s\n", fname);
  388. }
  389. free(fnamelist);
  390. fnamelist = NULL;
  391. }
  392. void FreeHrtf(void)
  393. {
  394. NumLoadedHrtfs = 0;
  395. free(LoadedHrtfs);
  396. LoadedHrtfs = NULL;
  397. }