Accumulate the B-Format HRTF responses using doubles
[openal-soft.git] / Alc / hrtf.c
blobfb2e0068505936b1a637f0fca9ecb866defac920
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"
33 #include "alconfig.h"
35 #include "compat.h"
36 #include "almalloc.h"
39 /* Current data set limits defined by the makehrtf utility. */
40 #define MIN_IR_SIZE (8)
41 #define MAX_IR_SIZE (512)
42 #define MOD_IR_SIZE (8)
44 #define MIN_FD_COUNT (1)
45 #define MAX_FD_COUNT (16)
47 #define MIN_FD_DISTANCE (50)
48 #define MAX_FD_DISTANCE (2500)
50 #define MIN_EV_COUNT (5)
51 #define MAX_EV_COUNT (128)
53 #define MIN_AZ_COUNT (1)
54 #define MAX_AZ_COUNT (128)
56 #define MAX_HRIR_DELAY (HRTF_HISTORY_LENGTH-1)
58 struct HrtfEntry {
59 struct HrtfEntry *next;
60 struct Hrtf *handle;
61 char filename[];
64 static const ALchar magicMarker00[8] = "MinPHR00";
65 static const ALchar magicMarker01[8] = "MinPHR01";
66 static const ALchar magicMarker02[8] = "MinPHR02";
68 /* First value for pass-through coefficients (remaining are 0), used for omni-
69 * directional sounds. */
70 static const ALfloat PassthruCoeff = 0.707106781187f/*sqrt(0.5)*/;
72 static ATOMIC_FLAG LoadedHrtfLock = ATOMIC_FLAG_INIT;
73 static struct HrtfEntry *LoadedHrtfs = NULL;
76 /* Calculate the elevation index given the polar elevation in radians. This
77 * will return an index between 0 and (evcount - 1). Assumes the FPU is in
78 * round-to-zero mode.
80 static ALsizei CalcEvIndex(ALsizei evcount, ALfloat ev, ALfloat *mu)
82 ALsizei idx;
83 ev = (F_PI_2+ev) * (evcount-1) / F_PI;
84 idx = mini(fastf2i(ev), evcount-1);
86 *mu = ev - idx;
87 return idx;
90 /* Calculate the azimuth index given the polar azimuth in radians. This will
91 * return an index between 0 and (azcount - 1). Assumes the FPU is in round-to-
92 * zero mode.
94 static ALsizei CalcAzIndex(ALsizei azcount, ALfloat az, ALfloat *mu)
96 ALsizei idx;
97 az = (F_TAU+az) * azcount / F_TAU;
99 idx = fastf2i(az) % azcount;
100 *mu = az - floorf(az);
101 return idx;
104 /* Calculates static HRIR coefficients and delays for the given polar elevation
105 * and azimuth in radians. The coefficients are normalized.
107 void GetHrtfCoeffs(const struct Hrtf *Hrtf, ALfloat elevation, ALfloat azimuth, ALfloat spread,
108 ALfloat (*restrict coeffs)[2], ALsizei *delays)
110 ALsizei evidx, azidx, idx[4];
111 ALsizei evoffset;
112 ALfloat emu, amu[2];
113 ALfloat blend[4];
114 ALfloat dirfact;
115 ALsizei i, c;
117 dirfact = 1.0f - (spread / F_TAU);
119 /* Claculate the lower elevation index. */
120 evidx = CalcEvIndex(Hrtf->evCount, elevation, &emu);
121 evoffset = Hrtf->evOffset[evidx];
123 /* Calculate lower azimuth index. */
124 azidx= CalcAzIndex(Hrtf->azCount[evidx], azimuth, &amu[0]);
126 /* Calculate the lower HRIR indices. */
127 idx[0] = evoffset + azidx;
128 idx[1] = evoffset + ((azidx+1) % Hrtf->azCount[evidx]);
129 if(evidx < Hrtf->evCount-1)
131 /* Increment elevation to the next (upper) index. */
132 evidx++;
133 evoffset = Hrtf->evOffset[evidx];
135 /* Calculate upper azimuth index. */
136 azidx = CalcAzIndex(Hrtf->azCount[evidx], azimuth, &amu[1]);
138 /* Calculate the upper HRIR indices. */
139 idx[2] = evoffset + azidx;
140 idx[3] = evoffset + ((azidx+1) % Hrtf->azCount[evidx]);
142 else
144 /* If the lower elevation is the top index, the upper elevation is the
145 * same as the lower.
147 amu[1] = amu[0];
148 idx[2] = idx[0];
149 idx[3] = idx[1];
152 /* Calculate bilinear blending weights, attenuated according to the
153 * directional panning factor.
155 blend[0] = (1.0f-emu) * (1.0f-amu[0]) * dirfact;
156 blend[1] = (1.0f-emu) * ( amu[0]) * dirfact;
157 blend[2] = ( emu) * (1.0f-amu[1]) * dirfact;
158 blend[3] = ( emu) * ( amu[1]) * dirfact;
160 /* Calculate the blended HRIR delays. */
161 delays[0] = fastf2i(
162 Hrtf->delays[idx[0]][0]*blend[0] + Hrtf->delays[idx[1]][0]*blend[1] +
163 Hrtf->delays[idx[2]][0]*blend[2] + Hrtf->delays[idx[3]][0]*blend[3] + 0.5f
165 delays[1] = fastf2i(
166 Hrtf->delays[idx[0]][1]*blend[0] + Hrtf->delays[idx[1]][1]*blend[1] +
167 Hrtf->delays[idx[2]][1]*blend[2] + Hrtf->delays[idx[3]][1]*blend[3] + 0.5f
170 /* Calculate the sample offsets for the HRIR indices. */
171 idx[0] *= Hrtf->irSize;
172 idx[1] *= Hrtf->irSize;
173 idx[2] *= Hrtf->irSize;
174 idx[3] *= Hrtf->irSize;
176 coeffs = ASSUME_ALIGNED(coeffs, 16);
177 /* Calculate the blended HRIR coefficients. */
178 coeffs[0][0] = PassthruCoeff * (1.0f-dirfact);
179 coeffs[0][1] = PassthruCoeff * (1.0f-dirfact);
180 for(i = 1;i < Hrtf->irSize;i++)
182 coeffs[i][0] = 0.0f;
183 coeffs[i][1] = 0.0f;
185 for(c = 0;c < 4;c++)
187 const ALfloat (*restrict srccoeffs)[2] = ASSUME_ALIGNED(Hrtf->coeffs+idx[c], 16);
188 for(i = 0;i < Hrtf->irSize;i++)
190 coeffs[i][0] += srccoeffs[i][0] * blend[c];
191 coeffs[i][1] += srccoeffs[i][1] * blend[c];
197 void BuildBFormatHrtf(const struct Hrtf *Hrtf, DirectHrtfState *state, ALsizei NumChannels, const struct AngularPoint *AmbiPoints, const ALfloat (*restrict AmbiMatrix)[MAX_AMBI_COEFFS], ALsizei AmbiCount, const ALfloat *restrict AmbiOrderHFGain)
199 /* Set this to 2 for dual-band HRTF processing. May require a higher quality
200 * band-splitter, or better calculation of the new IR length to deal with the
201 * tail generated by the filter.
203 #define NUM_BANDS 2
204 BandSplitter splitter;
205 ALdouble (*tmpres)[HRIR_LENGTH][2];
206 ALsizei idx[HRTF_AMBI_MAX_CHANNELS];
207 ALsizei min_delay = HRTF_HISTORY_LENGTH;
208 ALfloat temps[3][HRIR_LENGTH];
209 ALsizei max_length = 0;
210 ALsizei i, c, b;
212 for(c = 0;c < AmbiCount;c++)
214 ALuint evidx, azidx;
215 ALuint evoffset;
216 ALuint azcount;
218 /* Calculate elevation index. */
219 evidx = (ALsizei)floorf((F_PI_2 + AmbiPoints[c].Elev) *
220 (Hrtf->evCount-1)/F_PI + 0.5f);
221 evidx = clampi(evidx, 0, Hrtf->evCount-1);
223 azcount = Hrtf->azCount[evidx];
224 evoffset = Hrtf->evOffset[evidx];
226 /* Calculate azimuth index for this elevation. */
227 azidx = (ALsizei)floorf((F_TAU+AmbiPoints[c].Azim) *
228 azcount/F_TAU + 0.5f) % azcount;
230 /* Calculate indices for left and right channels. */
231 idx[c] = evoffset + azidx;
233 min_delay = mini(min_delay, mini(Hrtf->delays[idx[c]][0], Hrtf->delays[idx[c]][1]));
236 tmpres = al_calloc(16, NumChannels * sizeof(*tmpres));
238 memset(temps, 0, sizeof(temps));
239 bandsplit_init(&splitter, 400.0f / (ALfloat)Hrtf->sampleRate);
240 for(c = 0;c < AmbiCount;c++)
242 const ALfloat (*fir)[2] = &Hrtf->coeffs[idx[c] * Hrtf->irSize];
243 ALsizei ldelay = Hrtf->delays[idx[c]][0] - min_delay;
244 ALsizei rdelay = Hrtf->delays[idx[c]][1] - min_delay;
246 max_length = maxi(max_length,
247 mini(maxi(ldelay, rdelay) + Hrtf->irSize, HRIR_LENGTH)
250 if(NUM_BANDS == 1)
252 for(i = 0;i < NumChannels;++i)
254 ALdouble mult = (ALdouble)AmbiOrderHFGain[(ALsizei)floor(sqrt(i))] *
255 AmbiMatrix[c][i];
256 ALsizei lidx = ldelay, ridx = rdelay;
257 ALsizei j = 0;
258 while(lidx < HRIR_LENGTH && ridx < HRIR_LENGTH && j < Hrtf->irSize)
260 tmpres[i][lidx++][0] += fir[j][0] * mult;
261 tmpres[i][ridx++][1] += fir[j][1] * mult;
262 j++;
266 else
268 /* Band-split left HRIR into low and high frequency responses. */
269 bandsplit_clear(&splitter);
270 for(i = 0;i < Hrtf->irSize;i++)
271 temps[2][i] = fir[i][0];
272 bandsplit_process(&splitter, temps[0], temps[1], temps[2], HRIR_LENGTH);
274 /* Apply left ear response with delay. */
275 for(i = 0;i < NumChannels;++i)
277 ALfloat hfgain = AmbiOrderHFGain[(ALsizei)floor(sqrt(i))];
278 for(b = 0;b < NUM_BANDS;b++)
280 ALdouble mult = AmbiMatrix[c][i] * (ALdouble)((b==0) ? hfgain : 1.0);
281 ALsizei lidx = ldelay;
282 ALsizei j = 0;
283 while(lidx < HRIR_LENGTH)
284 tmpres[i][lidx++][0] += temps[b][j++] * mult;
288 /* Band-split right HRIR into low and high frequency responses. */
289 bandsplit_clear(&splitter);
290 for(i = 0;i < Hrtf->irSize;i++)
291 temps[2][i] = fir[i][1];
292 bandsplit_process(&splitter, temps[0], temps[1], temps[2], HRIR_LENGTH);
294 /* Apply right ear response with delay. */
295 for(i = 0;i < NumChannels;++i)
297 ALfloat hfgain = AmbiOrderHFGain[(ALsizei)floor(sqrt(i))];
298 for(b = 0;b < NUM_BANDS;b++)
300 ALdouble mult = AmbiMatrix[c][i] * (ALdouble)((b==0) ? hfgain : 1.0);
301 ALsizei ridx = rdelay;
302 ALsizei j = 0;
303 while(ridx < HRIR_LENGTH)
304 tmpres[i][ridx++][1] += temps[b][j++] * mult;
309 /* Round up to the next IR size multiple. */
310 max_length += MOD_IR_SIZE-1;
311 max_length -= max_length%MOD_IR_SIZE;
313 for(i = 0;i < NumChannels;++i)
315 int idx;
316 for(idx = 0;idx < HRIR_LENGTH;idx++)
318 state->Chan[i].Coeffs[idx][0] = (ALfloat)tmpres[i][idx][0];
319 state->Chan[i].Coeffs[idx][1] = (ALfloat)tmpres[i][idx][1];
323 al_free(tmpres);
324 tmpres = NULL;
326 TRACE("Skipped delay: %d, new FIR length: %d\n", min_delay, max_length);
327 state->IrSize = max_length;
328 #undef NUM_BANDS
332 static struct Hrtf *CreateHrtfStore(ALuint rate, ALsizei irSize,
333 ALfloat distance, ALsizei evCount, ALsizei irCount, const ALubyte *azCount,
334 const ALushort *evOffset, const ALfloat (*coeffs)[2], const ALubyte (*delays)[2],
335 const char *filename)
337 struct Hrtf *Hrtf;
338 size_t total;
340 total = sizeof(struct Hrtf);
341 total += sizeof(Hrtf->azCount[0])*evCount;
342 total = RoundUp(total, sizeof(ALushort)); /* Align for ushort fields */
343 total += sizeof(Hrtf->evOffset[0])*evCount;
344 total = RoundUp(total, 16); /* Align for coefficients using SIMD */
345 total += sizeof(Hrtf->coeffs[0])*irSize*irCount;
346 total += sizeof(Hrtf->delays[0])*irCount;
348 Hrtf = al_calloc(16, total);
349 if(Hrtf == NULL)
350 ERR("Out of memory allocating storage for %s.\n", filename);
351 else
353 uintptr_t offset = sizeof(struct Hrtf);
354 char *base = (char*)Hrtf;
355 ALushort *_evOffset;
356 ALubyte *_azCount;
357 ALubyte (*_delays)[2];
358 ALfloat (*_coeffs)[2];
359 ALsizei i;
361 InitRef(&Hrtf->ref, 0);
362 Hrtf->sampleRate = rate;
363 Hrtf->irSize = irSize;
364 Hrtf->distance = distance;
365 Hrtf->evCount = evCount;
367 /* Set up pointers to storage following the main HRTF struct. */
368 _azCount = (ALubyte*)(base + offset);
369 offset += sizeof(_azCount[0])*evCount;
371 offset = RoundUp(offset, sizeof(ALushort)); /* Align for ushort fields */
372 _evOffset = (ALushort*)(base + offset);
373 offset += sizeof(_evOffset[0])*evCount;
375 offset = RoundUp(offset, 16); /* Align for coefficients using SIMD */
376 _coeffs = (ALfloat(*)[2])(base + offset);
377 offset += sizeof(_coeffs[0])*irSize*irCount;
379 _delays = (ALubyte(*)[2])(base + offset);
380 offset += sizeof(_delays[0])*irCount;
382 assert(offset == total);
384 /* Copy input data to storage. */
385 for(i = 0;i < evCount;i++) _azCount[i] = azCount[i];
386 for(i = 0;i < evCount;i++) _evOffset[i] = evOffset[i];
387 for(i = 0;i < irSize*irCount;i++)
389 _coeffs[i][0] = coeffs[i][0];
390 _coeffs[i][1] = coeffs[i][1];
392 for(i = 0;i < irCount;i++)
394 _delays[i][0] = delays[i][0];
395 _delays[i][1] = delays[i][1];
398 /* Finally, assign the storage pointers. */
399 Hrtf->azCount = _azCount;
400 Hrtf->evOffset = _evOffset;
401 Hrtf->coeffs = _coeffs;
402 Hrtf->delays = _delays;
405 return Hrtf;
408 static ALubyte GetLE_ALubyte(const ALubyte **data, size_t *len)
410 ALubyte ret = (*data)[0];
411 *data += 1; *len -= 1;
412 return ret;
415 static ALshort GetLE_ALshort(const ALubyte **data, size_t *len)
417 ALshort ret = (*data)[0] | ((*data)[1]<<8);
418 *data += 2; *len -= 2;
419 return ret;
422 static ALushort GetLE_ALushort(const ALubyte **data, size_t *len)
424 ALushort ret = (*data)[0] | ((*data)[1]<<8);
425 *data += 2; *len -= 2;
426 return ret;
429 static ALint GetLE_ALint24(const ALubyte **data, size_t *len)
431 ALint ret = (*data)[0] | ((*data)[1]<<8) | ((*data)[2]<<16);
432 *data += 3; *len -= 3;
433 return (ret^0x800000) - 0x800000;
436 static ALuint GetLE_ALuint(const ALubyte **data, size_t *len)
438 ALuint ret = (*data)[0] | ((*data)[1]<<8) | ((*data)[2]<<16) | ((*data)[3]<<24);
439 *data += 4; *len -= 4;
440 return ret;
443 static const ALubyte *Get_ALubytePtr(const ALubyte **data, size_t *len, size_t size)
445 const ALubyte *ret = *data;
446 *data += size; *len -= size;
447 return ret;
450 static struct Hrtf *LoadHrtf00(const ALubyte *data, size_t datalen, const char *filename)
452 struct Hrtf *Hrtf = NULL;
453 ALboolean failed = AL_FALSE;
454 ALuint rate = 0;
455 ALushort irCount = 0;
456 ALushort irSize = 0;
457 ALubyte evCount = 0;
458 ALubyte *azCount = NULL;
459 ALushort *evOffset = NULL;
460 ALfloat (*coeffs)[2] = NULL;
461 ALubyte (*delays)[2] = NULL;
462 ALsizei i, j;
464 if(datalen < 9)
466 ERR("Unexpected end of %s data (req %d, rem "SZFMT")\n", filename, 9, datalen);
467 return NULL;
470 rate = GetLE_ALuint(&data, &datalen);
472 irCount = GetLE_ALushort(&data, &datalen);
474 irSize = GetLE_ALushort(&data, &datalen);
476 evCount = GetLE_ALubyte(&data, &datalen);
478 if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
480 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
481 irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
482 failed = AL_TRUE;
484 if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
486 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
487 evCount, MIN_EV_COUNT, MAX_EV_COUNT);
488 failed = AL_TRUE;
490 if(failed)
491 return NULL;
493 if(datalen < evCount*2u)
495 ERR("Unexpected end of %s data (req %d, rem "SZFMT")\n", filename, evCount*2, datalen);
496 return NULL;
499 azCount = malloc(sizeof(azCount[0])*evCount);
500 evOffset = malloc(sizeof(evOffset[0])*evCount);
501 if(azCount == NULL || evOffset == NULL)
503 ERR("Out of memory.\n");
504 failed = AL_TRUE;
507 if(!failed)
509 evOffset[0] = GetLE_ALushort(&data, &datalen);
510 for(i = 1;i < evCount;i++)
512 evOffset[i] = GetLE_ALushort(&data, &datalen);
513 if(evOffset[i] <= evOffset[i-1])
515 ERR("Invalid evOffset: evOffset[%d]=%d (last=%d)\n",
516 i, evOffset[i], evOffset[i-1]);
517 failed = AL_TRUE;
520 azCount[i-1] = evOffset[i] - evOffset[i-1];
521 if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
523 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
524 i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
525 failed = AL_TRUE;
528 if(irCount <= evOffset[i-1])
530 ERR("Invalid evOffset: evOffset[%d]=%d (irCount=%d)\n",
531 i-1, evOffset[i-1], irCount);
532 failed = AL_TRUE;
535 azCount[i-1] = irCount - evOffset[i-1];
536 if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
538 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
539 i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
540 failed = AL_TRUE;
544 if(!failed)
546 coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
547 delays = malloc(sizeof(delays[0])*irCount);
548 if(coeffs == NULL || delays == NULL)
550 ERR("Out of memory.\n");
551 failed = AL_TRUE;
555 if(!failed)
557 size_t reqsize = 2*irSize*irCount + irCount;
558 if(datalen < reqsize)
560 ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT")\n",
561 filename, reqsize, datalen);
562 failed = AL_TRUE;
566 if(!failed)
568 for(i = 0;i < irCount;i++)
570 for(j = 0;j < irSize;j++)
571 coeffs[i*irSize + j][0] = GetLE_ALshort(&data, &datalen) / 32768.0f;
574 for(i = 0;i < irCount;i++)
576 delays[i][0] = GetLE_ALubyte(&data, &datalen);
577 if(delays[i][0] > MAX_HRIR_DELAY)
579 ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i][0], MAX_HRIR_DELAY);
580 failed = AL_TRUE;
585 if(!failed)
587 /* Mirror the left ear responses to the right ear. */
588 for(i = 0;i < evCount;i++)
590 ALushort evoffset = evOffset[i];
591 ALubyte azcount = azCount[i];
592 for(j = 0;j < azcount;j++)
594 ALsizei lidx = evoffset + j;
595 ALsizei ridx = evoffset + ((azcount-j) % azcount);
596 ALsizei k;
598 for(k = 0;k < irSize;k++)
599 coeffs[ridx*irSize + k][1] = coeffs[lidx*irSize + k][0];
600 delays[ridx][1] = delays[lidx][0];
604 Hrtf = CreateHrtfStore(rate, irSize, 0.0f, evCount, irCount, azCount,
605 evOffset, coeffs, delays, filename);
608 free(azCount);
609 free(evOffset);
610 free(coeffs);
611 free(delays);
612 return Hrtf;
615 static struct Hrtf *LoadHrtf01(const ALubyte *data, size_t datalen, const char *filename)
617 struct Hrtf *Hrtf = NULL;
618 ALboolean failed = AL_FALSE;
619 ALuint rate = 0;
620 ALushort irCount = 0;
621 ALushort irSize = 0;
622 ALubyte evCount = 0;
623 const ALubyte *azCount = NULL;
624 ALushort *evOffset = NULL;
625 ALfloat (*coeffs)[2] = NULL;
626 ALubyte (*delays)[2] = NULL;
627 ALsizei i, j;
629 if(datalen < 6)
631 ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, 6, datalen);
632 return NULL;
635 rate = GetLE_ALuint(&data, &datalen);
637 irSize = GetLE_ALubyte(&data, &datalen);
639 evCount = GetLE_ALubyte(&data, &datalen);
641 if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
643 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
644 irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
645 failed = AL_TRUE;
647 if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
649 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
650 evCount, MIN_EV_COUNT, MAX_EV_COUNT);
651 failed = AL_TRUE;
653 if(failed)
654 return NULL;
656 if(datalen < evCount)
658 ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, evCount, datalen);
659 return NULL;
662 azCount = Get_ALubytePtr(&data, &datalen, evCount);
664 evOffset = malloc(sizeof(evOffset[0])*evCount);
665 if(azCount == NULL || evOffset == NULL)
667 ERR("Out of memory.\n");
668 failed = AL_TRUE;
671 if(!failed)
673 for(i = 0;i < evCount;i++)
675 if(azCount[i] < MIN_AZ_COUNT || azCount[i] > MAX_AZ_COUNT)
677 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
678 i, azCount[i], MIN_AZ_COUNT, MAX_AZ_COUNT);
679 failed = AL_TRUE;
684 if(!failed)
686 evOffset[0] = 0;
687 irCount = azCount[0];
688 for(i = 1;i < evCount;i++)
690 evOffset[i] = evOffset[i-1] + azCount[i-1];
691 irCount += azCount[i];
694 coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
695 delays = malloc(sizeof(delays[0])*irCount);
696 if(coeffs == NULL || delays == NULL)
698 ERR("Out of memory.\n");
699 failed = AL_TRUE;
703 if(!failed)
705 size_t reqsize = 2*irSize*irCount + irCount;
706 if(datalen < reqsize)
708 ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT"\n",
709 filename, reqsize, datalen);
710 failed = AL_TRUE;
714 if(!failed)
716 for(i = 0;i < irCount;i++)
718 for(j = 0;j < irSize;j++)
719 coeffs[i*irSize + j][0] = GetLE_ALshort(&data, &datalen) / 32768.0f;
722 for(i = 0;i < irCount;i++)
724 delays[i][0] = GetLE_ALubyte(&data, &datalen);
725 if(delays[i][0] > MAX_HRIR_DELAY)
727 ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i][0], MAX_HRIR_DELAY);
728 failed = AL_TRUE;
733 if(!failed)
735 /* Mirror the left ear responses to the right ear. */
736 for(i = 0;i < evCount;i++)
738 ALushort evoffset = evOffset[i];
739 ALubyte azcount = azCount[i];
740 for(j = 0;j < azcount;j++)
742 ALsizei lidx = evoffset + j;
743 ALsizei ridx = evoffset + ((azcount-j) % azcount);
744 ALsizei k;
746 for(k = 0;k < irSize;k++)
747 coeffs[ridx*irSize + k][1] = coeffs[lidx*irSize + k][0];
748 delays[ridx][1] = delays[lidx][0];
752 Hrtf = CreateHrtfStore(rate, irSize, 0.0f, evCount, irCount, azCount,
753 evOffset, coeffs, delays, filename);
756 free(evOffset);
757 free(coeffs);
758 free(delays);
759 return Hrtf;
762 #define SAMPLETYPE_S16 0
763 #define SAMPLETYPE_S24 1
765 #define CHANTYPE_LEFTONLY 0
766 #define CHANTYPE_LEFTRIGHT 1
768 static struct Hrtf *LoadHrtf02(const ALubyte *data, size_t datalen, const char *filename)
770 struct Hrtf *Hrtf = NULL;
771 ALboolean failed = AL_FALSE;
772 ALuint rate = 0;
773 ALubyte sampleType;
774 ALubyte channelType;
775 ALushort irCount = 0;
776 ALushort irSize = 0;
777 ALubyte fdCount = 0;
778 ALushort distance = 0;
779 ALubyte evCount = 0;
780 const ALubyte *azCount = NULL;
781 ALushort *evOffset = NULL;
782 ALfloat (*coeffs)[2] = NULL;
783 ALubyte (*delays)[2] = NULL;
784 ALsizei i, j;
786 if(datalen < 8)
788 ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, 8, datalen);
789 return NULL;
792 rate = GetLE_ALuint(&data, &datalen);
793 sampleType = GetLE_ALubyte(&data, &datalen);
794 channelType = GetLE_ALubyte(&data, &datalen);
796 irSize = GetLE_ALubyte(&data, &datalen);
798 fdCount = GetLE_ALubyte(&data, &datalen);
800 if(sampleType > SAMPLETYPE_S24)
802 ERR("Unsupported sample type: %d\n", sampleType);
803 failed = AL_TRUE;
805 if(channelType > CHANTYPE_LEFTRIGHT)
807 ERR("Unsupported channel type: %d\n", channelType);
808 failed = AL_TRUE;
811 if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
813 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
814 irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
815 failed = AL_TRUE;
817 if(fdCount != 1)
819 ERR("Multiple field-depths not supported: fdCount=%d (%d to %d)\n",
820 evCount, MIN_FD_COUNT, MAX_FD_COUNT);
821 failed = AL_TRUE;
823 if(failed)
824 return NULL;
826 for(i = 0;i < fdCount;i++)
828 if(datalen < 3)
830 ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, 3, datalen);
831 return NULL;
834 distance = GetLE_ALushort(&data, &datalen);
835 if(distance < MIN_FD_DISTANCE || distance > MAX_FD_DISTANCE)
837 ERR("Unsupported field distance: distance=%d (%dmm to %dmm)\n",
838 distance, MIN_FD_DISTANCE, MAX_FD_DISTANCE);
839 failed = AL_TRUE;
842 evCount = GetLE_ALubyte(&data, &datalen);
843 if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
845 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
846 evCount, MIN_EV_COUNT, MAX_EV_COUNT);
847 failed = AL_TRUE;
849 if(failed)
850 return NULL;
852 if(datalen < evCount)
854 ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, evCount, datalen);
855 return NULL;
858 azCount = Get_ALubytePtr(&data, &datalen, evCount);
859 for(j = 0;j < evCount;j++)
861 if(azCount[j] < MIN_AZ_COUNT || azCount[j] > MAX_AZ_COUNT)
863 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
864 j, azCount[j], MIN_AZ_COUNT, MAX_AZ_COUNT);
865 failed = AL_TRUE;
869 if(failed)
870 return NULL;
872 evOffset = malloc(sizeof(evOffset[0])*evCount);
873 if(azCount == NULL || evOffset == NULL)
875 ERR("Out of memory.\n");
876 failed = AL_TRUE;
879 if(!failed)
881 evOffset[0] = 0;
882 irCount = azCount[0];
883 for(i = 1;i < evCount;i++)
885 evOffset[i] = evOffset[i-1] + azCount[i-1];
886 irCount += azCount[i];
889 coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
890 delays = malloc(sizeof(delays[0])*irCount);
891 if(coeffs == NULL || delays == NULL)
893 ERR("Out of memory.\n");
894 failed = AL_TRUE;
898 if(!failed)
900 size_t reqsize = 2*irSize*irCount + irCount;
901 if(datalen < reqsize)
903 ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT"\n",
904 filename, reqsize, datalen);
905 failed = AL_TRUE;
909 if(!failed)
911 if(channelType == CHANTYPE_LEFTONLY)
913 if(sampleType == SAMPLETYPE_S16)
914 for(i = 0;i < irCount;i++)
916 for(j = 0;j < irSize;j++)
917 coeffs[i*irSize + j][0] = GetLE_ALshort(&data, &datalen) / 32768.0f;
919 else if(sampleType == SAMPLETYPE_S24)
920 for(i = 0;i < irCount;i++)
922 for(j = 0;j < irSize;j++)
923 coeffs[i*irSize + j][0] = GetLE_ALint24(&data, &datalen) / 8388608.0f;
926 for(i = 0;i < irCount;i++)
928 delays[i][0] = GetLE_ALubyte(&data, &datalen);
929 if(delays[i][0] > MAX_HRIR_DELAY)
931 ERR("Invalid delays[%d][0]: %d (%d)\n", i, delays[i][0], MAX_HRIR_DELAY);
932 failed = AL_TRUE;
936 else if(channelType == CHANTYPE_LEFTRIGHT)
938 if(sampleType == SAMPLETYPE_S16)
939 for(i = 0;i < irCount;i++)
941 for(j = 0;j < irSize;j++)
943 coeffs[i*irSize + j][0] = GetLE_ALshort(&data, &datalen) / 32768.0f;
944 coeffs[i*irSize + j][1] = GetLE_ALshort(&data, &datalen) / 32768.0f;
947 else if(sampleType == SAMPLETYPE_S24)
948 for(i = 0;i < irCount;i++)
950 for(j = 0;j < irSize;j++)
952 coeffs[i*irSize + j][0] = GetLE_ALint24(&data, &datalen) / 8388608.0f;
953 coeffs[i*irSize + j][1] = GetLE_ALint24(&data, &datalen) / 8388608.0f;
957 for(i = 0;i < irCount;i++)
959 delays[i][0] = GetLE_ALubyte(&data, &datalen);
960 if(delays[i][0] > MAX_HRIR_DELAY)
962 ERR("Invalid delays[%d][0]: %d (%d)\n", i, delays[i][0], MAX_HRIR_DELAY);
963 failed = AL_TRUE;
965 delays[i][1] = GetLE_ALubyte(&data, &datalen);
966 if(delays[i][1] > MAX_HRIR_DELAY)
968 ERR("Invalid delays[%d][1]: %d (%d)\n", i, delays[i][1], MAX_HRIR_DELAY);
969 failed = AL_TRUE;
975 if(!failed)
977 if(channelType == CHANTYPE_LEFTONLY)
979 /* Mirror the left ear responses to the right ear. */
980 for(i = 0;i < evCount;i++)
982 ALushort evoffset = evOffset[i];
983 ALubyte azcount = azCount[i];
984 for(j = 0;j < azcount;j++)
986 ALsizei lidx = evoffset + j;
987 ALsizei ridx = evoffset + ((azcount-j) % azcount);
988 ALsizei k;
990 for(k = 0;k < irSize;k++)
991 coeffs[ridx*irSize + k][1] = coeffs[lidx*irSize + k][0];
992 delays[ridx][1] = delays[lidx][0];
997 Hrtf = CreateHrtfStore(rate, irSize,
998 (ALfloat)distance / 1000.0f, evCount, irCount, azCount, evOffset,
999 coeffs, delays, filename
1003 free(evOffset);
1004 free(coeffs);
1005 free(delays);
1006 return Hrtf;
1010 static void AddFileEntry(vector_EnumeratedHrtf *list, const_al_string filename)
1012 EnumeratedHrtf entry = { AL_STRING_INIT_STATIC(), NULL };
1013 struct HrtfEntry *loaded_entry;
1014 const EnumeratedHrtf *iter;
1015 const char *name;
1016 const char *ext;
1017 int i;
1019 /* Check if this file has already been loaded globally. */
1020 loaded_entry = LoadedHrtfs;
1021 while(loaded_entry)
1023 if(alstr_cmp_cstr(filename, loaded_entry->filename) == 0)
1025 /* Check if this entry has already been added to the list. */
1026 #define MATCH_ENTRY(i) (loaded_entry == (i)->hrtf)
1027 VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_ENTRY);
1028 if(iter != VECTOR_END(*list))
1030 TRACE("Skipping duplicate file entry %s\n", alstr_get_cstr(filename));
1031 return;
1033 #undef MATCH_FNAME
1035 break;
1037 loaded_entry = loaded_entry->next;
1040 if(!loaded_entry)
1042 TRACE("Got new file \"%s\"\n", alstr_get_cstr(filename));
1044 loaded_entry = al_calloc(DEF_ALIGN,
1045 FAM_SIZE(struct HrtfEntry, filename, alstr_length(filename)+1)
1047 loaded_entry->next = LoadedHrtfs;
1048 loaded_entry->handle = NULL;
1049 strcpy(loaded_entry->filename, alstr_get_cstr(filename));
1050 LoadedHrtfs = loaded_entry;
1053 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1054 * format update). */
1055 name = strrchr(alstr_get_cstr(filename), '/');
1056 if(!name) name = strrchr(alstr_get_cstr(filename), '\\');
1057 if(!name) name = alstr_get_cstr(filename);
1058 else ++name;
1060 ext = strrchr(name, '.');
1062 i = 0;
1063 do {
1064 if(!ext)
1065 alstr_copy_cstr(&entry.name, name);
1066 else
1067 alstr_copy_range(&entry.name, name, ext);
1068 if(i != 0)
1070 char str[64];
1071 snprintf(str, sizeof(str), " #%d", i+1);
1072 alstr_append_cstr(&entry.name, str);
1074 ++i;
1076 #define MATCH_NAME(i) (alstr_cmp(entry.name, (i)->name) == 0)
1077 VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_NAME);
1078 #undef MATCH_NAME
1079 } while(iter != VECTOR_END(*list));
1080 entry.hrtf = loaded_entry;
1082 TRACE("Adding entry \"%s\" from file \"%s\"\n", alstr_get_cstr(entry.name),
1083 alstr_get_cstr(filename));
1084 VECTOR_PUSH_BACK(*list, entry);
1087 /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
1088 * for input instead of opening the given filename.
1090 static void AddBuiltInEntry(vector_EnumeratedHrtf *list, const_al_string filename, ALuint residx)
1092 EnumeratedHrtf entry = { AL_STRING_INIT_STATIC(), NULL };
1093 struct HrtfEntry *loaded_entry;
1094 struct Hrtf *hrtf = NULL;
1095 const EnumeratedHrtf *iter;
1096 const char *name;
1097 const char *ext;
1098 int i;
1100 loaded_entry = LoadedHrtfs;
1101 while(loaded_entry)
1103 if(alstr_cmp_cstr(filename, loaded_entry->filename) == 0)
1105 #define MATCH_ENTRY(i) (loaded_entry == (i)->hrtf)
1106 VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_ENTRY);
1107 if(iter != VECTOR_END(*list))
1109 TRACE("Skipping duplicate file entry %s\n", alstr_get_cstr(filename));
1110 return;
1112 #undef MATCH_FNAME
1114 break;
1116 loaded_entry = loaded_entry->next;
1119 if(!loaded_entry)
1121 size_t namelen = alstr_length(filename)+32;
1123 TRACE("Got new file \"%s\"\n", alstr_get_cstr(filename));
1125 loaded_entry = al_calloc(DEF_ALIGN,
1126 FAM_SIZE(struct HrtfEntry, filename, namelen)
1128 loaded_entry->next = LoadedHrtfs;
1129 loaded_entry->handle = hrtf;
1130 snprintf(loaded_entry->filename, namelen, "!%u_%s",
1131 residx, alstr_get_cstr(filename));
1132 LoadedHrtfs = loaded_entry;
1135 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1136 * format update). */
1137 name = strrchr(alstr_get_cstr(filename), '/');
1138 if(!name) name = strrchr(alstr_get_cstr(filename), '\\');
1139 if(!name) name = alstr_get_cstr(filename);
1140 else ++name;
1142 ext = strrchr(name, '.');
1144 i = 0;
1145 do {
1146 if(!ext)
1147 alstr_copy_cstr(&entry.name, name);
1148 else
1149 alstr_copy_range(&entry.name, name, ext);
1150 if(i != 0)
1152 char str[64];
1153 snprintf(str, sizeof(str), " #%d", i+1);
1154 alstr_append_cstr(&entry.name, str);
1156 ++i;
1158 #define MATCH_NAME(i) (alstr_cmp(entry.name, (i)->name) == 0)
1159 VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_NAME);
1160 #undef MATCH_NAME
1161 } while(iter != VECTOR_END(*list));
1162 entry.hrtf = loaded_entry;
1164 TRACE("Adding built-in entry \"%s\"\n", alstr_get_cstr(entry.name));
1165 VECTOR_PUSH_BACK(*list, entry);
1169 #define IDR_DEFAULT_44100_MHR 1
1170 #define IDR_DEFAULT_48000_MHR 2
1172 #ifndef ALSOFT_EMBED_HRTF_DATA
1174 static const ALubyte *GetResource(int UNUSED(name), size_t *size)
1176 *size = 0;
1177 return NULL;
1180 #else
1182 #include "default-44100.mhr.h"
1183 #include "default-48000.mhr.h"
1185 static const ALubyte *GetResource(int name, size_t *size)
1187 if(name == IDR_DEFAULT_44100_MHR)
1189 *size = sizeof(hrtf_default_44100);
1190 return hrtf_default_44100;
1192 if(name == IDR_DEFAULT_48000_MHR)
1194 *size = sizeof(hrtf_default_48000);
1195 return hrtf_default_48000;
1197 *size = 0;
1198 return NULL;
1200 #endif
1202 vector_EnumeratedHrtf EnumerateHrtf(const_al_string devname)
1204 vector_EnumeratedHrtf list = VECTOR_INIT_STATIC();
1205 const char *defaulthrtf = "";
1206 const char *pathlist = "";
1207 bool usedefaults = true;
1209 if(ConfigValueStr(alstr_get_cstr(devname), NULL, "hrtf-paths", &pathlist))
1211 al_string pname = AL_STRING_INIT_STATIC();
1212 while(pathlist && *pathlist)
1214 const char *next, *end;
1216 while(isspace(*pathlist) || *pathlist == ',')
1217 pathlist++;
1218 if(*pathlist == '\0')
1219 continue;
1221 next = strchr(pathlist, ',');
1222 if(next)
1223 end = next++;
1224 else
1226 end = pathlist + strlen(pathlist);
1227 usedefaults = false;
1230 while(end != pathlist && isspace(*(end-1)))
1231 --end;
1232 if(end != pathlist)
1234 vector_al_string flist;
1235 size_t i;
1237 alstr_copy_range(&pname, pathlist, end);
1239 flist = SearchDataFiles(".mhr", alstr_get_cstr(pname));
1240 for(i = 0;i < VECTOR_SIZE(flist);i++)
1241 AddFileEntry(&list, VECTOR_ELEM(flist, i));
1242 VECTOR_FOR_EACH(al_string, flist, alstr_reset);
1243 VECTOR_DEINIT(flist);
1246 pathlist = next;
1249 alstr_reset(&pname);
1251 else if(ConfigValueExists(alstr_get_cstr(devname), NULL, "hrtf_tables"))
1252 ERR("The hrtf_tables option is deprecated, please use hrtf-paths instead.\n");
1254 if(usedefaults)
1256 al_string ename = AL_STRING_INIT_STATIC();
1257 vector_al_string flist;
1258 const ALubyte *rdata;
1259 size_t rsize, i;
1261 flist = SearchDataFiles(".mhr", "openal/hrtf");
1262 for(i = 0;i < VECTOR_SIZE(flist);i++)
1263 AddFileEntry(&list, VECTOR_ELEM(flist, i));
1264 VECTOR_FOR_EACH(al_string, flist, alstr_reset);
1265 VECTOR_DEINIT(flist);
1267 rdata = GetResource(IDR_DEFAULT_44100_MHR, &rsize);
1268 if(rdata != NULL && rsize > 0)
1270 alstr_copy_cstr(&ename, "Built-In 44100hz");
1271 AddBuiltInEntry(&list, ename, IDR_DEFAULT_44100_MHR);
1274 rdata = GetResource(IDR_DEFAULT_48000_MHR, &rsize);
1275 if(rdata != NULL && rsize > 0)
1277 alstr_copy_cstr(&ename, "Built-In 48000hz");
1278 AddBuiltInEntry(&list, ename, IDR_DEFAULT_48000_MHR);
1280 alstr_reset(&ename);
1283 if(VECTOR_SIZE(list) > 1 && ConfigValueStr(alstr_get_cstr(devname), NULL, "default-hrtf", &defaulthrtf))
1285 const EnumeratedHrtf *iter;
1286 /* Find the preferred HRTF and move it to the front of the list. */
1287 #define FIND_ENTRY(i) (alstr_cmp_cstr((i)->name, defaulthrtf) == 0)
1288 VECTOR_FIND_IF(iter, const EnumeratedHrtf, list, FIND_ENTRY);
1289 #undef FIND_ENTRY
1290 if(iter == VECTOR_END(list))
1291 WARN("Failed to find default HRTF \"%s\"\n", defaulthrtf);
1292 else if(iter != VECTOR_BEGIN(list))
1294 EnumeratedHrtf entry = *iter;
1295 memmove(&VECTOR_ELEM(list,1), &VECTOR_ELEM(list,0),
1296 (iter-VECTOR_BEGIN(list))*sizeof(EnumeratedHrtf));
1297 VECTOR_ELEM(list,0) = entry;
1301 return list;
1304 void FreeHrtfList(vector_EnumeratedHrtf *list)
1306 #define CLEAR_ENTRY(i) alstr_reset(&(i)->name)
1307 VECTOR_FOR_EACH(EnumeratedHrtf, *list, CLEAR_ENTRY);
1308 VECTOR_DEINIT(*list);
1309 #undef CLEAR_ENTRY
1312 struct Hrtf *GetLoadedHrtf(struct HrtfEntry *entry)
1314 struct Hrtf *hrtf = NULL;
1315 struct FileMapping fmap;
1316 const ALubyte *rdata;
1317 const char *name;
1318 ALuint residx;
1319 size_t rsize;
1320 char ch;
1322 while(ATOMIC_FLAG_TEST_AND_SET(&LoadedHrtfLock, almemory_order_seq_cst))
1323 althrd_yield();
1325 if(entry->handle)
1327 hrtf = entry->handle;
1328 Hrtf_IncRef(hrtf);
1329 goto done;
1332 fmap.ptr = NULL;
1333 fmap.len = 0;
1334 if(sscanf(entry->filename, "!%u%c", &residx, &ch) == 2 && ch == '_')
1336 name = strchr(entry->filename, ch)+1;
1338 TRACE("Loading %s...\n", name);
1339 rdata = GetResource(residx, &rsize);
1340 if(rdata == NULL || rsize == 0)
1342 ERR("Could not get resource %u, %s\n", residx, name);
1343 goto done;
1346 else
1348 name = entry->filename;
1350 TRACE("Loading %s...\n", entry->filename);
1351 fmap = MapFileToMem(entry->filename);
1352 if(fmap.ptr == NULL)
1354 ERR("Could not open %s\n", entry->filename);
1355 goto done;
1358 rdata = fmap.ptr;
1359 rsize = fmap.len;
1362 if(rsize < sizeof(magicMarker02))
1363 ERR("%s data is too short ("SZFMT" bytes)\n", name, rsize);
1364 else if(memcmp(rdata, magicMarker02, sizeof(magicMarker02)) == 0)
1366 TRACE("Detected data set format v2\n");
1367 hrtf = LoadHrtf02(rdata+sizeof(magicMarker02),
1368 rsize-sizeof(magicMarker02), name
1371 else if(memcmp(rdata, magicMarker01, sizeof(magicMarker01)) == 0)
1373 TRACE("Detected data set format v1\n");
1374 hrtf = LoadHrtf01(rdata+sizeof(magicMarker01),
1375 rsize-sizeof(magicMarker01), name
1378 else if(memcmp(rdata, magicMarker00, sizeof(magicMarker00)) == 0)
1380 TRACE("Detected data set format v0\n");
1381 hrtf = LoadHrtf00(rdata+sizeof(magicMarker00),
1382 rsize-sizeof(magicMarker00), name
1385 else
1386 ERR("Invalid header in %s: \"%.8s\"\n", name, (const char*)rdata);
1387 if(fmap.ptr)
1388 UnmapFileMem(&fmap);
1390 if(!hrtf)
1392 ERR("Failed to load %s\n", name);
1393 goto done;
1395 entry->handle = hrtf;
1396 Hrtf_IncRef(hrtf);
1398 TRACE("Loaded HRTF support for format: %s %uhz\n",
1399 DevFmtChannelsString(DevFmtStereo), hrtf->sampleRate);
1401 done:
1402 ATOMIC_FLAG_CLEAR(&LoadedHrtfLock, almemory_order_seq_cst);
1403 return hrtf;
1407 void Hrtf_IncRef(struct Hrtf *hrtf)
1409 uint ref = IncrementRef(&hrtf->ref);
1410 TRACEREF("%p increasing refcount to %u\n", hrtf, ref);
1413 void Hrtf_DecRef(struct Hrtf *hrtf)
1415 struct HrtfEntry *Hrtf;
1416 uint ref = DecrementRef(&hrtf->ref);
1417 TRACEREF("%p decreasing refcount to %u\n", hrtf, ref);
1418 if(ref == 0)
1420 while(ATOMIC_FLAG_TEST_AND_SET(&LoadedHrtfLock, almemory_order_seq_cst))
1421 althrd_yield();
1423 Hrtf = LoadedHrtfs;
1424 while(Hrtf != NULL)
1426 /* Need to double-check that it's still unused, as another device
1427 * could've reacquired this HRTF after its reference went to 0 and
1428 * before the lock was taken.
1430 if(hrtf == Hrtf->handle && ReadRef(&hrtf->ref) == 0)
1432 al_free(Hrtf->handle);
1433 Hrtf->handle = NULL;
1434 TRACE("Unloaded unused HRTF %s\n", Hrtf->filename);
1436 Hrtf = Hrtf->next;
1439 ATOMIC_FLAG_CLEAR(&LoadedHrtfLock, almemory_order_seq_cst);
1444 void FreeHrtfs(void)
1446 struct HrtfEntry *Hrtf = LoadedHrtfs;
1447 LoadedHrtfs = NULL;
1449 while(Hrtf != NULL)
1451 struct HrtfEntry *next = Hrtf->next;
1452 al_free(Hrtf->handle);
1453 al_free(Hrtf);
1454 Hrtf = next;