Add experimental support for 24-bit, dual-ear HRTFs
[openal-soft.git] / Alc / hrtf.c
blob14e350c0c3644cd7ce7dc0d20b6ad445d97127b1
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.
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.
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
21 #include "config.h"
23 #include <stdlib.h>
24 #include <ctype.h>
26 #include "AL/al.h"
27 #include "AL/alc.h"
28 #include "alMain.h"
29 #include "alSource.h"
30 #include "alu.h"
31 #include "bformatdec.h"
32 #include "hrtf.h"
34 #include "compat.h"
35 #include "almalloc.h"
38 /* Current data set limits defined by the makehrtf utility. */
39 #define MIN_IR_SIZE (8)
40 #define MAX_IR_SIZE (512)
41 #define MOD_IR_SIZE (8)
43 #define MIN_EV_COUNT (5)
44 #define MAX_EV_COUNT (128)
46 #define MIN_AZ_COUNT (1)
47 #define MAX_AZ_COUNT (128)
49 struct HrtfEntry {
50 struct HrtfEntry *next;
51 struct Hrtf *handle;
52 char filename[];
55 static const ALchar magicMarker00[8] = "MinPHR00";
56 static const ALchar magicMarker01[8] = "MinPHR01";
57 /* FIXME: Set with the right number when finalized. */
58 static const ALchar magicMarker02[18] = "MinPHRTEMPDONOTUSE";
60 /* First value for pass-through coefficients (remaining are 0), used for omni-
61 * directional sounds. */
62 static const ALfloat PassthruCoeff = 0.707106781187f/*sqrt(0.5)*/;
64 static ATOMIC_FLAG LoadedHrtfLock = ATOMIC_FLAG_INIT;
65 static struct HrtfEntry *LoadedHrtfs = NULL;
68 /* Calculate the elevation index given the polar elevation in radians. This
69 * will return an index between 0 and (evcount - 1). Assumes the FPU is in
70 * round-to-zero mode.
72 static ALsizei CalcEvIndex(ALsizei evcount, ALfloat ev, ALfloat *mu)
74 ALsizei idx;
75 ev = (F_PI_2+ev) * (evcount-1) / F_PI;
76 idx = mini(fastf2i(ev), evcount-1);
78 *mu = ev - idx;
79 return idx;
82 /* Calculate the azimuth index given the polar azimuth in radians. This will
83 * return an index between 0 and (azcount - 1). Assumes the FPU is in round-to-
84 * zero mode.
86 static ALsizei CalcAzIndex(ALsizei azcount, ALfloat az, ALfloat *mu)
88 ALsizei idx;
89 az = (F_TAU+az) * azcount / F_TAU;
91 idx = fastf2i(az) % azcount;
92 *mu = az - floorf(az);
93 return idx;
96 /* Calculates static HRIR coefficients and delays for the given polar elevation
97 * and azimuth in radians. The coefficients are normalized.
99 void GetHrtfCoeffs(const struct Hrtf *Hrtf, ALfloat elevation, ALfloat azimuth, ALfloat spread, ALfloat (*coeffs)[2], ALsizei *delays)
101 ALsizei evidx, azidx, idx[4];
102 ALsizei evoffset;
103 ALfloat emu, amu[2];
104 ALfloat blend[4];
105 ALfloat dirfact;
106 ALsizei i, c;
108 dirfact = 1.0f - (spread / F_TAU);
110 /* Claculate the lower elevation index. */
111 evidx = CalcEvIndex(Hrtf->evCount, elevation, &emu);
112 evoffset = Hrtf->evOffset[evidx];
114 /* Calculate lower azimuth index. */
115 azidx= CalcAzIndex(Hrtf->azCount[evidx], azimuth, &amu[0]);
117 /* Calculate the lower HRIR indices. */
118 idx[0] = evoffset + azidx;
119 idx[1] = evoffset + ((azidx+1) % Hrtf->azCount[evidx]);
120 if(evidx < Hrtf->evCount-1)
122 /* Increment elevation to the next (upper) index. */
123 evidx++;
124 evoffset = Hrtf->evOffset[evidx];
126 /* Calculate upper azimuth index. */
127 azidx = CalcAzIndex(Hrtf->azCount[evidx], azimuth, &amu[1]);
129 /* Calculate the upper HRIR indices. */
130 idx[2] = evoffset + azidx;
131 idx[3] = evoffset + ((azidx+1) % Hrtf->azCount[evidx]);
133 else
135 /* If the lower elevation is the top index, the upper elevation is the
136 * same as the lower.
138 amu[1] = amu[0];
139 idx[2] = idx[0];
140 idx[3] = idx[1];
143 /* Calculate bilinear blending weights, attenuated according to the
144 * directional panning factor.
146 blend[0] = (1.0f-emu) * (1.0f-amu[0]) * dirfact;
147 blend[1] = (1.0f-emu) * ( amu[0]) * dirfact;
148 blend[2] = ( emu) * (1.0f-amu[1]) * dirfact;
149 blend[3] = ( emu) * ( amu[1]) * dirfact;
151 /* Calculate the blended HRIR delays. */
152 delays[0] = fastf2i(
153 Hrtf->delays[idx[0]][0]*blend[0] + Hrtf->delays[idx[1]][0]*blend[1] +
154 Hrtf->delays[idx[2]][0]*blend[2] + Hrtf->delays[idx[3]][0]*blend[3] + 0.5f
156 delays[1] = fastf2i(
157 Hrtf->delays[idx[0]][1]*blend[0] + Hrtf->delays[idx[1]][1]*blend[1] +
158 Hrtf->delays[idx[2]][1]*blend[2] + Hrtf->delays[idx[3]][1]*blend[3] + 0.5f
161 /* Calculate the sample offsets for the HRIR indices. */
162 idx[0] *= Hrtf->irSize;
163 idx[1] *= Hrtf->irSize;
164 idx[2] *= Hrtf->irSize;
165 idx[3] *= Hrtf->irSize;
167 /* Calculate the blended HRIR coefficients. */
168 coeffs[0][0] = PassthruCoeff * (1.0f-dirfact);
169 coeffs[0][1] = PassthruCoeff * (1.0f-dirfact);
170 for(i = 1;i < Hrtf->irSize;i++)
172 coeffs[i][0] = 0.0f;
173 coeffs[i][1] = 0.0f;
175 for(c = 0;c < 4;c++)
177 for(i = 0;i < Hrtf->irSize;i++)
179 coeffs[i][0] += Hrtf->coeffs[idx[c]+i][0] * blend[c];
180 coeffs[i][1] += Hrtf->coeffs[idx[c]+i][1] * blend[c];
186 void BuildBFormatHrtf(const struct Hrtf *Hrtf, DirectHrtfState *state, ALsizei NumChannels, const ALfloat (*restrict AmbiPoints)[2], const ALfloat (*restrict AmbiMatrix)[2][MAX_AMBI_COEFFS], ALsizei AmbiCount)
188 /* Set this to 2 for dual-band HRTF processing. May require a higher quality
189 * band-splitter, or better calculation of the new IR length to deal with the
190 * tail generated by the filter.
192 #define NUM_BANDS 2
193 BandSplitter splitter;
194 ALsizei idx[HRTF_AMBI_MAX_CHANNELS];
195 ALsizei min_delay = HRTF_HISTORY_LENGTH;
196 ALfloat temps[3][HRIR_LENGTH];
197 ALsizei max_length = 0;
198 ALsizei i, c, b;
200 for(c = 0;c < AmbiCount;c++)
202 ALuint evidx, azidx;
203 ALuint evoffset;
204 ALuint azcount;
206 /* Calculate elevation index. */
207 evidx = (ALsizei)floorf((F_PI_2 + AmbiPoints[c][0]) *
208 (Hrtf->evCount-1)/F_PI + 0.5f);
209 evidx = mini(evidx, Hrtf->evCount-1);
211 azcount = Hrtf->azCount[evidx];
212 evoffset = Hrtf->evOffset[evidx];
214 /* Calculate azimuth index for this elevation. */
215 azidx = (ALsizei)floorf((F_TAU+AmbiPoints[c][1]) *
216 azcount/F_TAU + 0.5f) % azcount;
218 /* Calculate indices for left and right channels. */
219 idx[c] = evoffset + azidx;
221 min_delay = mini(min_delay, mini(Hrtf->delays[idx[c]][0], Hrtf->delays[idx[c]][1]));
224 memset(temps, 0, sizeof(temps));
225 bandsplit_init(&splitter, 400.0f / (ALfloat)Hrtf->sampleRate);
226 for(c = 0;c < AmbiCount;c++)
228 const ALfloat (*fir)[2] = &Hrtf->coeffs[idx[c] * Hrtf->irSize];
229 ALsizei ldelay = Hrtf->delays[idx[c]][0] - min_delay;
230 ALsizei rdelay = Hrtf->delays[idx[c]][1] - min_delay;
232 max_length = maxi(max_length,
233 mini(maxi(ldelay, rdelay) + Hrtf->irSize, HRIR_LENGTH)
236 if(NUM_BANDS == 1)
238 for(i = 0;i < NumChannels;++i)
240 ALsizei lidx = ldelay, ridx = rdelay;
241 ALsizei j = 0;
242 while(lidx < HRIR_LENGTH && ridx < HRIR_LENGTH && j < Hrtf->irSize)
244 state->Chan[i].Coeffs[lidx++][0] += fir[j][0] * AmbiMatrix[c][0][i];
245 state->Chan[i].Coeffs[ridx++][1] += fir[j][1] * AmbiMatrix[c][0][i];
246 j++;
250 else
252 /* Band-split left HRIR into low and high frequency responses. */
253 bandsplit_clear(&splitter);
254 for(i = 0;i < Hrtf->irSize;i++)
255 temps[2][i] = fir[i][0];
256 bandsplit_process(&splitter, temps[0], temps[1], temps[2], HRIR_LENGTH);
258 /* Apply left ear response with delay. */
259 for(i = 0;i < NumChannels;++i)
261 for(b = 0;b < NUM_BANDS;b++)
263 ALsizei lidx = ldelay;
264 ALsizei j = 0;
265 while(lidx < HRIR_LENGTH)
266 state->Chan[i].Coeffs[lidx++][0] += temps[b][j++] * AmbiMatrix[c][b][i];
270 /* Band-split right HRIR into low and high frequency responses. */
271 bandsplit_clear(&splitter);
272 for(i = 0;i < Hrtf->irSize;i++)
273 temps[2][i] = fir[i][1];
274 bandsplit_process(&splitter, temps[0], temps[1], temps[2], HRIR_LENGTH);
276 /* Apply right ear response with delay. */
277 for(i = 0;i < NumChannels;++i)
279 for(b = 0;b < NUM_BANDS;b++)
281 ALsizei ridx = rdelay;
282 ALsizei j = 0;
283 while(ridx < HRIR_LENGTH)
284 state->Chan[i].Coeffs[ridx++][1] += temps[b][j++] * AmbiMatrix[c][b][i];
289 /* Round up to the next IR size multiple. */
290 max_length = RoundUp(max_length, MOD_IR_SIZE);
292 TRACE("Skipped min delay: %d, new combined length: %d\n", min_delay, max_length);
293 state->IrSize = max_length;
294 #undef NUM_BANDS
298 static struct Hrtf *CreateHrtfStore(ALuint rate, ALsizei irSize, ALsizei evCount, ALsizei irCount,
299 const ALubyte *azCount, const ALushort *evOffset,
300 const ALfloat (*coeffs)[2], const ALubyte (*delays)[2],
301 const char *filename)
303 struct Hrtf *Hrtf;
304 size_t total;
306 total = sizeof(struct Hrtf);
307 total += sizeof(Hrtf->azCount[0])*evCount;
308 total = RoundUp(total, sizeof(ALushort)); /* Align for ushort fields */
309 total += sizeof(Hrtf->evOffset[0])*evCount;
310 total = RoundUp(total, 16); /* Align for coefficients using SIMD */
311 total += sizeof(Hrtf->coeffs[0])*irSize*irCount;
312 total += sizeof(Hrtf->delays[0])*irCount;
314 Hrtf = al_calloc(16, total);
315 if(Hrtf == NULL)
316 ERR("Out of memory allocating storage for %s.\n", filename);
317 else
319 uintptr_t offset = sizeof(struct Hrtf);
320 char *base = (char*)Hrtf;
321 ALushort *_evOffset;
322 ALubyte *_azCount;
323 ALubyte (*_delays)[2];
324 ALfloat (*_coeffs)[2];
325 ALsizei i;
327 InitRef(&Hrtf->ref, 0);
328 Hrtf->sampleRate = rate;
329 Hrtf->irSize = irSize;
330 Hrtf->evCount = evCount;
332 /* Set up pointers to storage following the main HRTF struct. */
333 _azCount = (ALubyte*)(base + offset); Hrtf->azCount = _azCount;
334 offset += sizeof(_azCount[0])*evCount;
336 offset = RoundUp(offset, sizeof(ALushort)); /* Align for ushort fields */
337 _evOffset = (ALushort*)(base + offset); Hrtf->evOffset = _evOffset;
338 offset += sizeof(_evOffset[0])*evCount;
340 offset = RoundUp(offset, 16); /* Align for coefficients using SIMD */
341 _coeffs = (ALfloat(*)[2])(base + offset); Hrtf->coeffs = _coeffs;
342 offset += sizeof(_coeffs[0])*irSize*irCount;
344 _delays = (ALubyte(*)[2])(base + offset); Hrtf->delays = _delays;
345 offset += sizeof(_delays[0])*irCount;
347 /* Copy input data to storage. */
348 for(i = 0;i < evCount;i++) _azCount[i] = azCount[i];
349 for(i = 0;i < evCount;i++) _evOffset[i] = evOffset[i];
350 for(i = 0;i < irSize*irCount;i++)
352 _coeffs[i][0] = coeffs[i][0];
353 _coeffs[i][1] = coeffs[i][1];
355 for(i = 0;i < irCount;i++)
357 _delays[i][0] = delays[i][0];
358 _delays[i][1] = delays[i][1];
361 assert(offset == total);
364 return Hrtf;
367 static ALubyte GetLE_ALubyte(const ALubyte **data, size_t *len)
369 ALubyte ret = (*data)[0];
370 *data += 1; *len -= 1;
371 return ret;
374 static ALshort GetLE_ALshort(const ALubyte **data, size_t *len)
376 ALshort ret = (*data)[0] | ((*data)[1]<<8);
377 *data += 2; *len -= 2;
378 return ret;
381 static ALushort GetLE_ALushort(const ALubyte **data, size_t *len)
383 ALushort ret = (*data)[0] | ((*data)[1]<<8);
384 *data += 2; *len -= 2;
385 return ret;
388 static ALint GetLE_ALint24(const ALubyte **data, size_t *len)
390 ALint ret = (*data)[0] | ((*data)[1]<<8) | ((*data)[2]<<16);
391 *data += 3; *len -= 3;
392 return (ret^0x800000) - 0x800000;
395 static ALuint GetLE_ALuint(const ALubyte **data, size_t *len)
397 ALuint ret = (*data)[0] | ((*data)[1]<<8) | ((*data)[2]<<16) | ((*data)[3]<<24);
398 *data += 4; *len -= 4;
399 return ret;
402 static const ALubyte *Get_ALubytePtr(const ALubyte **data, size_t *len, size_t size)
404 const ALubyte *ret = *data;
405 *data += size; *len -= size;
406 return ret;
409 static struct Hrtf *LoadHrtf00(const ALubyte *data, size_t datalen, const char *filename)
411 const ALubyte maxDelay = HRTF_HISTORY_LENGTH-1;
412 struct Hrtf *Hrtf = NULL;
413 ALboolean failed = AL_FALSE;
414 ALuint rate = 0;
415 ALushort irCount = 0;
416 ALushort irSize = 0;
417 ALubyte evCount = 0;
418 ALubyte *azCount = NULL;
419 ALushort *evOffset = NULL;
420 ALfloat (*coeffs)[2] = NULL;
421 ALubyte (*delays)[2] = NULL;
422 ALsizei i, j;
424 if(datalen < 9)
426 ERR("Unexpected end of %s data (req %d, rem "SZFMT")\n", filename, 9, datalen);
427 return NULL;
430 rate = GetLE_ALuint(&data, &datalen);
432 irCount = GetLE_ALushort(&data, &datalen);
434 irSize = GetLE_ALushort(&data, &datalen);
436 evCount = GetLE_ALubyte(&data, &datalen);
438 if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
440 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
441 irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
442 failed = AL_TRUE;
444 if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
446 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
447 evCount, MIN_EV_COUNT, MAX_EV_COUNT);
448 failed = AL_TRUE;
450 if(failed)
451 return NULL;
453 if(datalen < evCount*2u)
455 ERR("Unexpected end of %s data (req %d, rem "SZFMT")\n", filename, evCount*2, datalen);
456 return NULL;
459 azCount = malloc(sizeof(azCount[0])*evCount);
460 evOffset = malloc(sizeof(evOffset[0])*evCount);
461 if(azCount == NULL || evOffset == NULL)
463 ERR("Out of memory.\n");
464 failed = AL_TRUE;
467 if(!failed)
469 evOffset[0] = GetLE_ALushort(&data, &datalen);
470 for(i = 1;i < evCount;i++)
472 evOffset[i] = GetLE_ALushort(&data, &datalen);
473 if(evOffset[i] <= evOffset[i-1])
475 ERR("Invalid evOffset: evOffset[%d]=%d (last=%d)\n",
476 i, evOffset[i], evOffset[i-1]);
477 failed = AL_TRUE;
480 azCount[i-1] = evOffset[i] - evOffset[i-1];
481 if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
483 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
484 i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
485 failed = AL_TRUE;
488 if(irCount <= evOffset[i-1])
490 ERR("Invalid evOffset: evOffset[%d]=%d (irCount=%d)\n",
491 i-1, evOffset[i-1], irCount);
492 failed = AL_TRUE;
495 azCount[i-1] = irCount - evOffset[i-1];
496 if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
498 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
499 i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
500 failed = AL_TRUE;
504 if(!failed)
506 coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
507 delays = malloc(sizeof(delays[0])*irCount);
508 if(coeffs == NULL || delays == NULL)
510 ERR("Out of memory.\n");
511 failed = AL_TRUE;
515 if(!failed)
517 size_t reqsize = 2*irSize*irCount + irCount;
518 if(datalen < reqsize)
520 ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT")\n",
521 filename, reqsize, datalen);
522 failed = AL_TRUE;
526 if(!failed)
528 for(i = 0;i < irCount;i++)
530 for(j = 0;j < irSize;j++)
531 coeffs[i*irSize + j][0] = GetLE_ALshort(&data, &datalen) / 32768.0f;
534 for(i = 0;i < irCount;i++)
536 delays[i][0] = GetLE_ALubyte(&data, &datalen);
537 if(delays[i][0] > maxDelay)
539 ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i][0], maxDelay);
540 failed = AL_TRUE;
545 if(!failed)
547 /* Mirror the left ear responses to the right ear. */
548 for(i = 0;i < evCount;i++)
550 ALushort evoffset = evOffset[i];
551 ALubyte azcount = azCount[i];
552 for(j = 0;j < azcount;j++)
554 ALsizei lidx = evoffset + j;
555 ALsizei ridx = evoffset + ((azcount-j) % azcount);
556 ALsizei k;
558 for(k = 0;k < irSize;k++)
559 coeffs[ridx*irSize + k][1] = coeffs[lidx*irSize + k][0];
560 delays[ridx][1] = delays[lidx][0];
564 Hrtf = CreateHrtfStore(rate, irSize, evCount, irCount, azCount,
565 evOffset, coeffs, delays, filename);
568 free(azCount);
569 free(evOffset);
570 free(coeffs);
571 free(delays);
572 return Hrtf;
575 static struct Hrtf *LoadHrtf01(const ALubyte *data, size_t datalen, const char *filename)
577 const ALubyte maxDelay = HRTF_HISTORY_LENGTH-1;
578 struct Hrtf *Hrtf = NULL;
579 ALboolean failed = AL_FALSE;
580 ALuint rate = 0;
581 ALushort irCount = 0;
582 ALushort irSize = 0;
583 ALubyte evCount = 0;
584 const ALubyte *azCount = NULL;
585 ALushort *evOffset = NULL;
586 ALfloat (*coeffs)[2] = NULL;
587 ALubyte (*delays)[2] = NULL;
588 ALsizei i, j;
590 if(datalen < 6)
592 ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, 6, datalen);
593 return NULL;
596 rate = GetLE_ALuint(&data, &datalen);
598 irSize = GetLE_ALubyte(&data, &datalen);
600 evCount = GetLE_ALubyte(&data, &datalen);
602 if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
604 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
605 irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
606 failed = AL_TRUE;
608 if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
610 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
611 evCount, MIN_EV_COUNT, MAX_EV_COUNT);
612 failed = AL_TRUE;
614 if(failed)
615 return NULL;
617 if(datalen < evCount)
619 ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, evCount, datalen);
620 return NULL;
623 azCount = Get_ALubytePtr(&data, &datalen, evCount);
625 evOffset = malloc(sizeof(evOffset[0])*evCount);
626 if(azCount == NULL || evOffset == NULL)
628 ERR("Out of memory.\n");
629 failed = AL_TRUE;
632 if(!failed)
634 for(i = 0;i < evCount;i++)
636 if(azCount[i] < MIN_AZ_COUNT || azCount[i] > MAX_AZ_COUNT)
638 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
639 i, azCount[i], MIN_AZ_COUNT, MAX_AZ_COUNT);
640 failed = AL_TRUE;
645 if(!failed)
647 evOffset[0] = 0;
648 irCount = azCount[0];
649 for(i = 1;i < evCount;i++)
651 evOffset[i] = evOffset[i-1] + azCount[i-1];
652 irCount += azCount[i];
655 coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
656 delays = malloc(sizeof(delays[0])*irCount);
657 if(coeffs == NULL || delays == NULL)
659 ERR("Out of memory.\n");
660 failed = AL_TRUE;
664 if(!failed)
666 size_t reqsize = 2*irSize*irCount + irCount;
667 if(datalen < reqsize)
669 ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT"\n",
670 filename, reqsize, datalen);
671 failed = AL_TRUE;
675 if(!failed)
677 for(i = 0;i < irCount;i++)
679 for(j = 0;j < irSize;j++)
680 coeffs[i*irSize + j][0] = GetLE_ALshort(&data, &datalen) / 32768.0f;
683 for(i = 0;i < irCount;i++)
685 delays[i][0] = GetLE_ALubyte(&data, &datalen);
686 if(delays[i][0] > maxDelay)
688 ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i][0], maxDelay);
689 failed = AL_TRUE;
694 if(!failed)
696 /* Mirror the left ear responses to the right ear. */
697 for(i = 0;i < evCount;i++)
699 ALushort evoffset = evOffset[i];
700 ALubyte azcount = azCount[i];
701 for(j = 0;j < azcount;j++)
703 ALsizei lidx = evoffset + j;
704 ALsizei ridx = evoffset + ((azcount-j) % azcount);
705 ALsizei k;
707 for(k = 0;k < irSize;k++)
708 coeffs[ridx*irSize + k][1] = coeffs[lidx*irSize + k][0];
709 delays[ridx][1] = delays[lidx][0];
713 Hrtf = CreateHrtfStore(rate, irSize, evCount, irCount, azCount,
714 evOffset, coeffs, delays, filename);
717 free(evOffset);
718 free(coeffs);
719 free(delays);
720 return Hrtf;
723 #define SAMPLETYPE_S16 0
724 #define SAMPLETYPE_S24 1
726 #define CHANTYPE_LEFTONLY 0
727 #define CHANTYPE_LEFTRIGHT 1
729 static struct Hrtf *LoadHrtf02(const ALubyte *data, size_t datalen, const char *filename)
731 const ALubyte maxDelay = HRTF_HISTORY_LENGTH-1;
732 struct Hrtf *Hrtf = NULL;
733 ALboolean failed = AL_FALSE;
734 ALuint rate = 0;
735 ALubyte sampleType;
736 ALubyte channelType;
737 ALushort irCount = 0;
738 ALushort irSize = 0;
739 ALubyte evCount = 0;
740 const ALubyte *azCount = NULL;
741 ALushort *evOffset = NULL;
742 ALfloat (*coeffs)[2] = NULL;
743 ALubyte (*delays)[2] = NULL;
744 ALsizei i, j;
746 if(datalen < 6)
748 ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, 6, datalen);
749 return NULL;
752 rate = GetLE_ALuint(&data, &datalen);
753 sampleType = GetLE_ALubyte(&data, &datalen);
754 channelType = GetLE_ALubyte(&data, &datalen);
756 irSize = GetLE_ALubyte(&data, &datalen);
758 evCount = GetLE_ALubyte(&data, &datalen);
760 if(sampleType > SAMPLETYPE_S24)
762 ERR("Unsupported sample type: %d\n", sampleType);
763 failed = AL_TRUE;
765 if(channelType > CHANTYPE_LEFTRIGHT)
767 ERR("Unsupported channel type: %d\n", channelType);
768 failed = AL_TRUE;
771 if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
773 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
774 irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
775 failed = AL_TRUE;
777 if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
779 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
780 evCount, MIN_EV_COUNT, MAX_EV_COUNT);
781 failed = AL_TRUE;
783 if(failed)
784 return NULL;
786 if(datalen < evCount)
788 ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, evCount, datalen);
789 return NULL;
792 azCount = Get_ALubytePtr(&data, &datalen, evCount);
794 evOffset = malloc(sizeof(evOffset[0])*evCount);
795 if(azCount == NULL || evOffset == NULL)
797 ERR("Out of memory.\n");
798 failed = AL_TRUE;
801 if(!failed)
803 for(i = 0;i < evCount;i++)
805 if(azCount[i] < MIN_AZ_COUNT || azCount[i] > MAX_AZ_COUNT)
807 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
808 i, azCount[i], MIN_AZ_COUNT, MAX_AZ_COUNT);
809 failed = AL_TRUE;
814 if(!failed)
816 evOffset[0] = 0;
817 irCount = azCount[0];
818 for(i = 1;i < evCount;i++)
820 evOffset[i] = evOffset[i-1] + azCount[i-1];
821 irCount += azCount[i];
824 coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
825 delays = malloc(sizeof(delays[0])*irCount);
826 if(coeffs == NULL || delays == NULL)
828 ERR("Out of memory.\n");
829 failed = AL_TRUE;
833 if(!failed)
835 size_t reqsize = 2*irSize*irCount + irCount;
836 if(datalen < reqsize)
838 ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT"\n",
839 filename, reqsize, datalen);
840 failed = AL_TRUE;
844 if(!failed)
846 if(channelType == CHANTYPE_LEFTONLY || channelType == CHANTYPE_LEFTRIGHT)
848 if(sampleType == SAMPLETYPE_S16)
849 for(i = 0;i < irCount;i++)
851 for(j = 0;j < irSize;j++)
852 coeffs[i*irSize + j][0] = GetLE_ALshort(&data, &datalen) / 32768.0f;
854 else if(sampleType == SAMPLETYPE_S24)
855 for(i = 0;i < irCount;i++)
857 for(j = 0;j < irSize;j++)
858 coeffs[i*irSize + j][0] = GetLE_ALint24(&data, &datalen) / 8388608.0f;
861 if(channelType == CHANTYPE_LEFTRIGHT)
863 if(sampleType == SAMPLETYPE_S16)
864 for(i = 0;i < irCount;i++)
866 for(j = 0;j < irSize;j++)
867 coeffs[i*irSize + j][1] = GetLE_ALshort(&data, &datalen) / 32768.0f;
869 else if(sampleType == SAMPLETYPE_S24)
870 for(i = 0;i < irCount;i++)
872 for(j = 0;j < irSize;j++)
873 coeffs[i*irSize + j][1] = GetLE_ALint24(&data, &datalen) / 8388608.0f;
876 if(channelType == CHANTYPE_LEFTONLY || channelType == CHANTYPE_LEFTRIGHT)
878 for(i = 0;i < irCount;i++)
880 delays[i][0] = GetLE_ALubyte(&data, &datalen);
881 if(delays[i][0] > maxDelay)
883 ERR("Invalid delays[%d][0]: %d (%d)\n", i, delays[i][0], maxDelay);
884 failed = AL_TRUE;
888 if(channelType == CHANTYPE_LEFTRIGHT)
890 for(i = 0;i < irCount;i++)
892 delays[i][1] = GetLE_ALubyte(&data, &datalen);
893 if(delays[i][1] > maxDelay)
895 ERR("Invalid delays[%d][1]: %d (%d)\n", i, delays[i][1], maxDelay);
896 failed = AL_TRUE;
902 if(!failed)
904 if(channelType == CHANTYPE_LEFTONLY)
906 /* Mirror the left ear responses to the right ear. */
907 for(i = 0;i < evCount;i++)
909 ALushort evoffset = evOffset[i];
910 ALubyte azcount = azCount[i];
911 for(j = 0;j < azcount;j++)
913 ALsizei lidx = evoffset + j;
914 ALsizei ridx = evoffset + ((azcount-j) % azcount);
915 ALsizei k;
917 for(k = 0;k < irSize;k++)
918 coeffs[ridx*irSize + k][1] = coeffs[lidx*irSize + k][0];
919 delays[ridx][1] = delays[lidx][0];
924 Hrtf = CreateHrtfStore(rate, irSize, evCount, irCount, azCount,
925 evOffset, coeffs, delays, filename);
928 free(evOffset);
929 free(coeffs);
930 free(delays);
931 return Hrtf;
935 static void AddFileEntry(vector_EnumeratedHrtf *list, const_al_string filename)
937 EnumeratedHrtf entry = { AL_STRING_INIT_STATIC(), NULL };
938 struct HrtfEntry *loaded_entry;
939 const EnumeratedHrtf *iter;
940 const char *name;
941 const char *ext;
942 int i;
944 /* Check if this file has already been loaded globally. */
945 loaded_entry = LoadedHrtfs;
946 while(loaded_entry)
948 if(alstr_cmp_cstr(filename, loaded_entry->filename) == 0)
950 /* Check if this entry has already been added to the list. */
951 #define MATCH_ENTRY(i) (loaded_entry == (i)->hrtf)
952 VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_ENTRY);
953 if(iter != VECTOR_END(*list))
955 TRACE("Skipping duplicate file entry %s\n", alstr_get_cstr(filename));
956 return;
958 #undef MATCH_FNAME
960 break;
962 loaded_entry = loaded_entry->next;
965 if(!loaded_entry)
967 TRACE("Got new file \"%s\"\n", alstr_get_cstr(filename));
969 loaded_entry = al_calloc(DEF_ALIGN,
970 FAM_SIZE(struct HrtfEntry, filename, alstr_length(filename)+1)
972 loaded_entry->next = LoadedHrtfs;
973 loaded_entry->handle = NULL;
974 strcpy(loaded_entry->filename, alstr_get_cstr(filename));
975 LoadedHrtfs = loaded_entry;
978 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
979 * format update). */
980 name = strrchr(alstr_get_cstr(filename), '/');
981 if(!name) name = strrchr(alstr_get_cstr(filename), '\\');
982 if(!name) name = alstr_get_cstr(filename);
983 else ++name;
985 ext = strrchr(name, '.');
987 i = 0;
988 do {
989 if(!ext)
990 alstr_copy_cstr(&entry.name, name);
991 else
992 alstr_copy_range(&entry.name, name, ext);
993 if(i != 0)
995 char str[64];
996 snprintf(str, sizeof(str), " #%d", i+1);
997 alstr_append_cstr(&entry.name, str);
999 ++i;
1001 #define MATCH_NAME(i) (alstr_cmp(entry.name, (i)->name) == 0)
1002 VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_NAME);
1003 #undef MATCH_NAME
1004 } while(iter != VECTOR_END(*list));
1005 entry.hrtf = loaded_entry;
1007 TRACE("Adding entry \"%s\" from file \"%s\"\n", alstr_get_cstr(entry.name),
1008 alstr_get_cstr(filename));
1009 VECTOR_PUSH_BACK(*list, entry);
1012 /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
1013 * for input instead of opening the given filename.
1015 static void AddBuiltInEntry(vector_EnumeratedHrtf *list, const_al_string filename, size_t residx)
1017 EnumeratedHrtf entry = { AL_STRING_INIT_STATIC(), NULL };
1018 struct HrtfEntry *loaded_entry;
1019 struct Hrtf *hrtf = NULL;
1020 const EnumeratedHrtf *iter;
1021 const char *name;
1022 const char *ext;
1023 int i;
1025 loaded_entry = LoadedHrtfs;
1026 while(loaded_entry)
1028 if(alstr_cmp_cstr(filename, loaded_entry->filename) == 0)
1030 #define MATCH_ENTRY(i) (loaded_entry == (i)->hrtf)
1031 VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_ENTRY);
1032 if(iter != VECTOR_END(*list))
1034 TRACE("Skipping duplicate file entry %s\n", alstr_get_cstr(filename));
1035 return;
1037 #undef MATCH_FNAME
1039 break;
1041 loaded_entry = loaded_entry->next;
1044 if(!loaded_entry)
1046 size_t namelen = alstr_length(filename)+32;
1048 TRACE("Got new file \"%s\"\n", alstr_get_cstr(filename));
1050 loaded_entry = al_calloc(DEF_ALIGN,
1051 FAM_SIZE(struct HrtfEntry, filename, namelen)
1053 loaded_entry->next = LoadedHrtfs;
1054 loaded_entry->handle = hrtf;
1055 snprintf(loaded_entry->filename, namelen, "!"SZFMT"_%s",
1056 residx, alstr_get_cstr(filename));
1057 LoadedHrtfs = loaded_entry;
1060 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1061 * format update). */
1062 name = strrchr(alstr_get_cstr(filename), '/');
1063 if(!name) name = strrchr(alstr_get_cstr(filename), '\\');
1064 if(!name) name = alstr_get_cstr(filename);
1065 else ++name;
1067 ext = strrchr(name, '.');
1069 i = 0;
1070 do {
1071 if(!ext)
1072 alstr_copy_cstr(&entry.name, name);
1073 else
1074 alstr_copy_range(&entry.name, name, ext);
1075 if(i != 0)
1077 char str[64];
1078 snprintf(str, sizeof(str), " #%d", i+1);
1079 alstr_append_cstr(&entry.name, str);
1081 ++i;
1083 #define MATCH_NAME(i) (alstr_cmp(entry.name, (i)->name) == 0)
1084 VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_NAME);
1085 #undef MATCH_NAME
1086 } while(iter != VECTOR_END(*list));
1087 entry.hrtf = loaded_entry;
1089 TRACE("Adding built-in entry \"%s\"\n", alstr_get_cstr(entry.name));
1090 VECTOR_PUSH_BACK(*list, entry);
1094 #define IDR_DEFAULT_44100_MHR 1
1095 #define IDR_DEFAULT_48000_MHR 2
1097 #ifndef ALSOFT_EMBED_HRTF_DATA
1099 static const ALubyte *GetResource(int UNUSED(name), size_t *size)
1101 *size = 0;
1102 return NULL;
1105 #else
1107 #include "default-44100.mhr.h"
1108 #include "default-48000.mhr.h"
1110 static const ALubyte *GetResource(int name, size_t *size)
1112 if(name == IDR_DEFAULT_44100_MHR)
1114 *size = sizeof(hrtf_default_44100);
1115 return hrtf_default_44100;
1117 if(name == IDR_DEFAULT_48000_MHR)
1119 *size = sizeof(hrtf_default_48000);
1120 return hrtf_default_48000;
1122 *size = 0;
1123 return NULL;
1125 #endif
1127 vector_EnumeratedHrtf EnumerateHrtf(const_al_string devname)
1129 vector_EnumeratedHrtf list = VECTOR_INIT_STATIC();
1130 const char *defaulthrtf = "";
1131 const char *pathlist = "";
1132 bool usedefaults = true;
1134 if(ConfigValueStr(alstr_get_cstr(devname), NULL, "hrtf-paths", &pathlist))
1136 al_string pname = AL_STRING_INIT_STATIC();
1137 while(pathlist && *pathlist)
1139 const char *next, *end;
1141 while(isspace(*pathlist) || *pathlist == ',')
1142 pathlist++;
1143 if(*pathlist == '\0')
1144 continue;
1146 next = strchr(pathlist, ',');
1147 if(next)
1148 end = next++;
1149 else
1151 end = pathlist + strlen(pathlist);
1152 usedefaults = false;
1155 while(end != pathlist && isspace(*(end-1)))
1156 --end;
1157 if(end != pathlist)
1159 vector_al_string flist;
1160 size_t i;
1162 alstr_copy_range(&pname, pathlist, end);
1164 flist = SearchDataFiles(".mhr", alstr_get_cstr(pname));
1165 for(i = 0;i < VECTOR_SIZE(flist);i++)
1166 AddFileEntry(&list, VECTOR_ELEM(flist, i));
1167 VECTOR_FOR_EACH(al_string, flist, alstr_reset);
1168 VECTOR_DEINIT(flist);
1171 pathlist = next;
1174 alstr_reset(&pname);
1176 else if(ConfigValueExists(alstr_get_cstr(devname), NULL, "hrtf_tables"))
1177 ERR("The hrtf_tables option is deprecated, please use hrtf-paths instead.\n");
1179 if(usedefaults)
1181 al_string ename = AL_STRING_INIT_STATIC();
1182 vector_al_string flist;
1183 const ALubyte *rdata;
1184 size_t rsize, i;
1186 flist = SearchDataFiles(".mhr", "openal/hrtf");
1187 for(i = 0;i < VECTOR_SIZE(flist);i++)
1188 AddFileEntry(&list, VECTOR_ELEM(flist, i));
1189 VECTOR_FOR_EACH(al_string, flist, alstr_reset);
1190 VECTOR_DEINIT(flist);
1192 rdata = GetResource(IDR_DEFAULT_44100_MHR, &rsize);
1193 if(rdata != NULL && rsize > 0)
1195 alstr_copy_cstr(&ename, "Built-In 44100hz");
1196 AddBuiltInEntry(&list, ename, IDR_DEFAULT_44100_MHR);
1199 rdata = GetResource(IDR_DEFAULT_48000_MHR, &rsize);
1200 if(rdata != NULL && rsize > 0)
1202 alstr_copy_cstr(&ename, "Built-In 48000hz");
1203 AddBuiltInEntry(&list, ename, IDR_DEFAULT_48000_MHR);
1205 alstr_reset(&ename);
1208 if(VECTOR_SIZE(list) > 1 && ConfigValueStr(alstr_get_cstr(devname), NULL, "default-hrtf", &defaulthrtf))
1210 const EnumeratedHrtf *iter;
1211 /* Find the preferred HRTF and move it to the front of the list. */
1212 #define FIND_ENTRY(i) (alstr_cmp_cstr((i)->name, defaulthrtf) == 0)
1213 VECTOR_FIND_IF(iter, const EnumeratedHrtf, list, FIND_ENTRY);
1214 #undef FIND_ENTRY
1215 if(iter == VECTOR_END(list))
1216 WARN("Failed to find default HRTF \"%s\"\n", defaulthrtf);
1217 else if(iter != VECTOR_BEGIN(list))
1219 EnumeratedHrtf entry = *iter;
1220 memmove(&VECTOR_ELEM(list,1), &VECTOR_ELEM(list,0),
1221 (iter-VECTOR_BEGIN(list))*sizeof(EnumeratedHrtf));
1222 VECTOR_ELEM(list,0) = entry;
1226 return list;
1229 void FreeHrtfList(vector_EnumeratedHrtf *list)
1231 #define CLEAR_ENTRY(i) alstr_reset(&(i)->name)
1232 VECTOR_FOR_EACH(EnumeratedHrtf, *list, CLEAR_ENTRY);
1233 VECTOR_DEINIT(*list);
1234 #undef CLEAR_ENTRY
1237 struct Hrtf *GetLoadedHrtf(struct HrtfEntry *entry)
1239 struct Hrtf *hrtf = NULL;
1240 struct FileMapping fmap;
1241 const ALubyte *rdata;
1242 const char *name;
1243 size_t residx;
1244 size_t rsize;
1245 char ch;
1247 while(ATOMIC_FLAG_TEST_AND_SET(&LoadedHrtfLock, almemory_order_seq_cst))
1248 althrd_yield();
1250 if(entry->handle)
1252 hrtf = entry->handle;
1253 Hrtf_IncRef(hrtf);
1254 goto done;
1257 fmap.ptr = NULL;
1258 fmap.len = 0;
1259 if(sscanf(entry->filename, "!"SZFMT"%c", &residx, &ch) == 2 && ch == '_')
1261 name = strchr(entry->filename, ch)+1;
1263 TRACE("Loading %s...\n", name);
1264 rdata = GetResource(residx, &rsize);
1265 if(rdata == NULL || rsize == 0)
1267 ERR("Could not get resource "SZFMT", %s\n", residx, name);
1268 goto done;
1271 else
1273 name = entry->filename;
1275 TRACE("Loading %s...\n", entry->filename);
1276 fmap = MapFileToMem(entry->filename);
1277 if(fmap.ptr == NULL)
1279 ERR("Could not open %s\n", entry->filename);
1280 goto done;
1283 rdata = fmap.ptr;
1284 rsize = fmap.len;
1287 if(rsize < sizeof(magicMarker02))
1288 ERR("%s data is too short ("SZFMT" bytes)\n", name, rsize);
1289 else if(memcmp(rdata, magicMarker02, sizeof(magicMarker02)) == 0)
1291 TRACE("Detected data set format v2\n");
1292 hrtf = LoadHrtf02(rdata+sizeof(magicMarker02),
1293 rsize-sizeof(magicMarker02), name
1296 else if(memcmp(rdata, magicMarker01, sizeof(magicMarker01)) == 0)
1298 TRACE("Detected data set format v1\n");
1299 hrtf = LoadHrtf01(rdata+sizeof(magicMarker01),
1300 rsize-sizeof(magicMarker01), name
1303 else if(memcmp(rdata, magicMarker00, sizeof(magicMarker00)) == 0)
1305 TRACE("Detected data set format v0\n");
1306 hrtf = LoadHrtf00(rdata+sizeof(magicMarker00),
1307 rsize-sizeof(magicMarker00), name
1310 else
1311 ERR("Invalid header in %s: \"%.8s\"\n", name, (const char*)rdata);
1312 if(fmap.ptr)
1313 UnmapFileMem(&fmap);
1315 if(!hrtf)
1317 ERR("Failed to load %s\n", name);
1318 goto done;
1320 entry->handle = hrtf;
1321 Hrtf_IncRef(hrtf);
1323 TRACE("Loaded HRTF support for format: %s %uhz\n",
1324 DevFmtChannelsString(DevFmtStereo), hrtf->sampleRate);
1326 done:
1327 ATOMIC_FLAG_CLEAR(&LoadedHrtfLock, almemory_order_seq_cst);
1328 return hrtf;
1332 void Hrtf_IncRef(struct Hrtf *hrtf)
1334 uint ref = IncrementRef(&hrtf->ref);
1335 TRACEREF("%p increasing refcount to %u\n", hrtf, ref);
1338 void Hrtf_DecRef(struct Hrtf *hrtf)
1340 struct HrtfEntry *Hrtf;
1341 uint ref = DecrementRef(&hrtf->ref);
1342 TRACEREF("%p decreasing refcount to %u\n", hrtf, ref);
1343 if(ref == 0)
1345 while(ATOMIC_FLAG_TEST_AND_SET(&LoadedHrtfLock, almemory_order_seq_cst))
1346 althrd_yield();
1348 Hrtf = LoadedHrtfs;
1349 while(Hrtf != NULL)
1351 /* Need to double-check that it's still unused, as another device
1352 * could've reacquired this HRTF after its reference went to 0 and
1353 * before the lock was taken.
1355 if(hrtf == Hrtf->handle && ReadRef(&hrtf->ref) == 0)
1357 al_free(Hrtf->handle);
1358 Hrtf->handle = NULL;
1359 TRACE("Unloaded unused HRTF %s\n", Hrtf->filename);
1361 Hrtf = Hrtf->next;
1364 ATOMIC_FLAG_CLEAR(&LoadedHrtfLock, almemory_order_seq_cst);
1369 void FreeHrtfs(void)
1371 struct HrtfEntry *Hrtf = LoadedHrtfs;
1372 LoadedHrtfs = NULL;
1374 while(Hrtf != NULL)
1376 struct HrtfEntry *next = Hrtf->next;
1377 al_free(Hrtf->handle);
1378 al_free(Hrtf);
1379 Hrtf = next;