Merge pull request #204 from jhasse/android-byte-order
[openal-soft.git] / Alc / hrtf.c
blobddbd3a28c2286e87bd6071ad1cd7b30a38bf1d86
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 "hrtf.h"
32 #include "alconfig.h"
33 #include "filters/splitter.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).
79 static ALsizei CalcEvIndex(ALsizei evcount, ALfloat ev, ALfloat *mu)
81 ALsizei idx;
82 ev = (F_PI_2+ev) * (evcount-1) / F_PI;
83 idx = float2int(ev);
85 *mu = ev - idx;
86 return mini(idx, evcount-1);
89 /* Calculate the azimuth index given the polar azimuth in radians. This will
90 * return an index between 0 and (azcount - 1).
92 static ALsizei CalcAzIndex(ALsizei azcount, ALfloat az, ALfloat *mu)
94 ALsizei idx;
95 az = (F_TAU+az) * azcount / F_TAU;
97 idx = float2int(az);
98 *mu = az - idx;
99 return idx % azcount;
102 /* Calculates static HRIR coefficients and delays for the given polar elevation
103 * and azimuth in radians. The coefficients are normalized.
105 void GetHrtfCoeffs(const struct Hrtf *Hrtf, ALfloat elevation, ALfloat azimuth, ALfloat spread,
106 ALfloat (*restrict coeffs)[2], ALsizei *delays)
108 ALsizei evidx, azidx, idx[4];
109 ALsizei evoffset;
110 ALfloat emu, amu[2];
111 ALfloat blend[4];
112 ALfloat dirfact;
113 ALsizei i, c;
115 dirfact = 1.0f - (spread / F_TAU);
117 /* Claculate the lower elevation index. */
118 evidx = CalcEvIndex(Hrtf->evCount, elevation, &emu);
119 evoffset = Hrtf->evOffset[evidx];
121 /* Calculate lower azimuth index. */
122 azidx= CalcAzIndex(Hrtf->azCount[evidx], azimuth, &amu[0]);
124 /* Calculate the lower HRIR indices. */
125 idx[0] = evoffset + azidx;
126 idx[1] = evoffset + ((azidx+1) % Hrtf->azCount[evidx]);
127 if(evidx < Hrtf->evCount-1)
129 /* Increment elevation to the next (upper) index. */
130 evidx++;
131 evoffset = Hrtf->evOffset[evidx];
133 /* Calculate upper azimuth index. */
134 azidx = CalcAzIndex(Hrtf->azCount[evidx], azimuth, &amu[1]);
136 /* Calculate the upper HRIR indices. */
137 idx[2] = evoffset + azidx;
138 idx[3] = evoffset + ((azidx+1) % Hrtf->azCount[evidx]);
140 else
142 /* If the lower elevation is the top index, the upper elevation is the
143 * same as the lower.
145 amu[1] = amu[0];
146 idx[2] = idx[0];
147 idx[3] = idx[1];
150 /* Calculate bilinear blending weights, attenuated according to the
151 * directional panning factor.
153 blend[0] = (1.0f-emu) * (1.0f-amu[0]) * dirfact;
154 blend[1] = (1.0f-emu) * ( amu[0]) * dirfact;
155 blend[2] = ( emu) * (1.0f-amu[1]) * dirfact;
156 blend[3] = ( emu) * ( amu[1]) * dirfact;
158 /* Calculate the blended HRIR delays. */
159 delays[0] = fastf2i(
160 Hrtf->delays[idx[0]][0]*blend[0] + Hrtf->delays[idx[1]][0]*blend[1] +
161 Hrtf->delays[idx[2]][0]*blend[2] + Hrtf->delays[idx[3]][0]*blend[3]
163 delays[1] = fastf2i(
164 Hrtf->delays[idx[0]][1]*blend[0] + Hrtf->delays[idx[1]][1]*blend[1] +
165 Hrtf->delays[idx[2]][1]*blend[2] + Hrtf->delays[idx[3]][1]*blend[3]
168 /* Calculate the sample offsets for the HRIR indices. */
169 idx[0] *= Hrtf->irSize;
170 idx[1] *= Hrtf->irSize;
171 idx[2] *= Hrtf->irSize;
172 idx[3] *= Hrtf->irSize;
174 ASSUME(Hrtf->irSize >= MIN_IR_SIZE && (Hrtf->irSize%MOD_IR_SIZE) == 0);
175 coeffs = ASSUME_ALIGNED(coeffs, 16);
176 /* Calculate the blended HRIR coefficients. */
177 coeffs[0][0] = PassthruCoeff * (1.0f-dirfact);
178 coeffs[0][1] = PassthruCoeff * (1.0f-dirfact);
179 for(i = 1;i < Hrtf->irSize;i++)
181 coeffs[i][0] = 0.0f;
182 coeffs[i][1] = 0.0f;
184 for(c = 0;c < 4;c++)
186 const ALfloat (*restrict srccoeffs)[2] = ASSUME_ALIGNED(Hrtf->coeffs+idx[c], 16);
187 for(i = 0;i < Hrtf->irSize;i++)
189 coeffs[i][0] += srccoeffs[i][0] * blend[c];
190 coeffs[i][1] += srccoeffs[i][1] * blend[c];
196 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)
198 /* Set this to 2 for dual-band HRTF processing. May require a higher quality
199 * band-splitter, or better calculation of the new IR length to deal with the
200 * tail generated by the filter.
202 #define NUM_BANDS 2
203 BandSplitter splitter;
204 ALdouble (*tmpres)[HRIR_LENGTH][2];
205 ALsizei *restrict idx;
206 ALsizei min_delay = HRTF_HISTORY_LENGTH;
207 ALsizei max_delay = 0;
208 ALfloat temps[3][HRIR_LENGTH];
209 ALsizei max_length;
210 ALsizei i, c, b;
212 idx = al_calloc(DEF_ALIGN, AmbiCount*sizeof(*idx));
214 for(c = 0;c < AmbiCount;c++)
216 ALuint evidx, azidx;
217 ALuint evoffset;
218 ALuint azcount;
220 /* Calculate elevation index. */
221 evidx = (ALsizei)((F_PI_2+AmbiPoints[c].Elev) * (Hrtf->evCount-1) / F_PI + 0.5f);
222 evidx = clampi(evidx, 0, Hrtf->evCount-1);
224 azcount = Hrtf->azCount[evidx];
225 evoffset = Hrtf->evOffset[evidx];
227 /* Calculate azimuth index for this elevation. */
228 azidx = (ALsizei)((F_TAU+AmbiPoints[c].Azim) * 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]));
234 max_delay = maxi(max_delay, maxi(Hrtf->delays[idx[c]][0], Hrtf->delays[idx[c]][1]));
237 tmpres = al_calloc(16, NumChannels * sizeof(*tmpres));
239 memset(temps, 0, sizeof(temps));
240 bandsplit_init(&splitter, 400.0f / (ALfloat)Hrtf->sampleRate);
241 for(c = 0;c < AmbiCount;c++)
243 const ALfloat (*fir)[2] = &Hrtf->coeffs[idx[c] * Hrtf->irSize];
244 ALsizei ldelay = Hrtf->delays[idx[c]][0] - min_delay;
245 ALsizei rdelay = Hrtf->delays[idx[c]][1] - min_delay;
247 if(NUM_BANDS == 1)
249 for(i = 0;i < NumChannels;++i)
251 ALdouble mult = (ALdouble)AmbiOrderHFGain[(ALsizei)sqrt(i)] * AmbiMatrix[c][i];
252 ALsizei lidx = ldelay, ridx = rdelay;
253 ALsizei j = 0;
254 while(lidx < HRIR_LENGTH && ridx < HRIR_LENGTH && j < Hrtf->irSize)
256 tmpres[i][lidx++][0] += fir[j][0] * mult;
257 tmpres[i][ridx++][1] += fir[j][1] * mult;
258 j++;
262 else
264 /* Band-split left HRIR into low and high frequency responses. */
265 bandsplit_clear(&splitter);
266 for(i = 0;i < Hrtf->irSize;i++)
267 temps[2][i] = fir[i][0];
268 bandsplit_process(&splitter, temps[0], temps[1], temps[2], HRIR_LENGTH);
270 /* Apply left ear response with delay. */
271 for(i = 0;i < NumChannels;++i)
273 ALfloat hfgain = AmbiOrderHFGain[(ALsizei)sqrt(i)];
274 for(b = 0;b < NUM_BANDS;b++)
276 ALdouble mult = AmbiMatrix[c][i] * (ALdouble)((b==0) ? hfgain : 1.0);
277 ALsizei lidx = ldelay;
278 ALsizei j = 0;
279 while(lidx < HRIR_LENGTH)
280 tmpres[i][lidx++][0] += temps[b][j++] * mult;
284 /* Band-split right HRIR into low and high frequency responses. */
285 bandsplit_clear(&splitter);
286 for(i = 0;i < Hrtf->irSize;i++)
287 temps[2][i] = fir[i][1];
288 bandsplit_process(&splitter, temps[0], temps[1], temps[2], HRIR_LENGTH);
290 /* Apply right ear response with delay. */
291 for(i = 0;i < NumChannels;++i)
293 ALfloat hfgain = AmbiOrderHFGain[(ALsizei)sqrt(i)];
294 for(b = 0;b < NUM_BANDS;b++)
296 ALdouble mult = AmbiMatrix[c][i] * (ALdouble)((b==0) ? hfgain : 1.0);
297 ALsizei ridx = rdelay;
298 ALsizei j = 0;
299 while(ridx < HRIR_LENGTH)
300 tmpres[i][ridx++][1] += temps[b][j++] * mult;
306 for(i = 0;i < NumChannels;++i)
308 int idx;
309 for(idx = 0;idx < HRIR_LENGTH;idx++)
311 state->Chan[i].Coeffs[idx][0] = (ALfloat)tmpres[i][idx][0];
312 state->Chan[i].Coeffs[idx][1] = (ALfloat)tmpres[i][idx][1];
315 al_free(tmpres);
316 tmpres = NULL;
317 al_free(idx);
318 idx = NULL;
320 if(NUM_BANDS == 1)
321 max_length = mini(max_delay-min_delay + Hrtf->irSize, HRIR_LENGTH);
322 else
324 /* Increase the IR size by 2/3rds to account for the tail generated by
325 * the band-split filter.
327 const ALsizei irsize = mini(Hrtf->irSize*5/3, HRIR_LENGTH);
328 max_length = mini(max_delay-min_delay + irsize, HRIR_LENGTH);
330 /* Round up to the next IR size multiple. */
331 max_length += MOD_IR_SIZE-1;
332 max_length -= max_length%MOD_IR_SIZE;
334 TRACE("Skipped delay: %d, max delay: %d, new FIR length: %d\n",
335 min_delay, max_delay-min_delay, max_length);
336 state->IrSize = max_length;
337 #undef NUM_BANDS
341 static struct Hrtf *CreateHrtfStore(ALuint rate, ALsizei irSize,
342 ALfloat distance, ALsizei evCount, ALsizei irCount, const ALubyte *azCount,
343 const ALushort *evOffset, const ALfloat (*coeffs)[2], const ALubyte (*delays)[2],
344 const char *filename)
346 struct Hrtf *Hrtf;
347 size_t total;
349 total = sizeof(struct Hrtf);
350 total += sizeof(Hrtf->azCount[0])*evCount;
351 total = RoundUp(total, sizeof(ALushort)); /* Align for ushort fields */
352 total += sizeof(Hrtf->evOffset[0])*evCount;
353 total = RoundUp(total, 16); /* Align for coefficients using SIMD */
354 total += sizeof(Hrtf->coeffs[0])*irSize*irCount;
355 total += sizeof(Hrtf->delays[0])*irCount;
357 Hrtf = al_calloc(16, total);
358 if(Hrtf == NULL)
359 ERR("Out of memory allocating storage for %s.\n", filename);
360 else
362 uintptr_t offset = sizeof(struct Hrtf);
363 char *base = (char*)Hrtf;
364 ALushort *_evOffset;
365 ALubyte *_azCount;
366 ALubyte (*_delays)[2];
367 ALfloat (*_coeffs)[2];
368 ALsizei i;
370 InitRef(&Hrtf->ref, 0);
371 Hrtf->sampleRate = rate;
372 Hrtf->irSize = irSize;
373 Hrtf->distance = distance;
374 Hrtf->evCount = evCount;
376 /* Set up pointers to storage following the main HRTF struct. */
377 _azCount = (ALubyte*)(base + offset);
378 offset += sizeof(_azCount[0])*evCount;
380 offset = RoundUp(offset, sizeof(ALushort)); /* Align for ushort fields */
381 _evOffset = (ALushort*)(base + offset);
382 offset += sizeof(_evOffset[0])*evCount;
384 offset = RoundUp(offset, 16); /* Align for coefficients using SIMD */
385 _coeffs = (ALfloat(*)[2])(base + offset);
386 offset += sizeof(_coeffs[0])*irSize*irCount;
388 _delays = (ALubyte(*)[2])(base + offset);
389 offset += sizeof(_delays[0])*irCount;
391 assert(offset == total);
393 /* Copy input data to storage. */
394 for(i = 0;i < evCount;i++) _azCount[i] = azCount[i];
395 for(i = 0;i < evCount;i++) _evOffset[i] = evOffset[i];
396 for(i = 0;i < irSize*irCount;i++)
398 _coeffs[i][0] = coeffs[i][0];
399 _coeffs[i][1] = coeffs[i][1];
401 for(i = 0;i < irCount;i++)
403 _delays[i][0] = delays[i][0];
404 _delays[i][1] = delays[i][1];
407 /* Finally, assign the storage pointers. */
408 Hrtf->azCount = _azCount;
409 Hrtf->evOffset = _evOffset;
410 Hrtf->coeffs = _coeffs;
411 Hrtf->delays = _delays;
414 return Hrtf;
417 static ALubyte GetLE_ALubyte(const ALubyte **data, size_t *len)
419 ALubyte ret = (*data)[0];
420 *data += 1; *len -= 1;
421 return ret;
424 static ALshort GetLE_ALshort(const ALubyte **data, size_t *len)
426 ALshort ret = (*data)[0] | ((*data)[1]<<8);
427 *data += 2; *len -= 2;
428 return ret;
431 static ALushort GetLE_ALushort(const ALubyte **data, size_t *len)
433 ALushort ret = (*data)[0] | ((*data)[1]<<8);
434 *data += 2; *len -= 2;
435 return ret;
438 static ALint GetLE_ALint24(const ALubyte **data, size_t *len)
440 ALint ret = (*data)[0] | ((*data)[1]<<8) | ((*data)[2]<<16);
441 *data += 3; *len -= 3;
442 return (ret^0x800000) - 0x800000;
445 static ALuint GetLE_ALuint(const ALubyte **data, size_t *len)
447 ALuint ret = (*data)[0] | ((*data)[1]<<8) | ((*data)[2]<<16) | ((*data)[3]<<24);
448 *data += 4; *len -= 4;
449 return ret;
452 static const ALubyte *Get_ALubytePtr(const ALubyte **data, size_t *len, size_t size)
454 const ALubyte *ret = *data;
455 *data += size; *len -= size;
456 return ret;
459 static struct Hrtf *LoadHrtf00(const ALubyte *data, size_t datalen, const char *filename)
461 struct Hrtf *Hrtf = NULL;
462 ALboolean failed = AL_FALSE;
463 ALuint rate = 0;
464 ALushort irCount = 0;
465 ALushort irSize = 0;
466 ALubyte evCount = 0;
467 ALubyte *azCount = NULL;
468 ALushort *evOffset = NULL;
469 ALfloat (*coeffs)[2] = NULL;
470 ALubyte (*delays)[2] = NULL;
471 ALsizei i, j;
473 if(datalen < 9)
475 ERR("Unexpected end of %s data (req %d, rem "SZFMT")\n", filename, 9, datalen);
476 return NULL;
479 rate = GetLE_ALuint(&data, &datalen);
481 irCount = GetLE_ALushort(&data, &datalen);
483 irSize = GetLE_ALushort(&data, &datalen);
485 evCount = GetLE_ALubyte(&data, &datalen);
487 if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
489 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
490 irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
491 failed = AL_TRUE;
493 if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
495 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
496 evCount, MIN_EV_COUNT, MAX_EV_COUNT);
497 failed = AL_TRUE;
499 if(failed)
500 return NULL;
502 if(datalen < evCount*2u)
504 ERR("Unexpected end of %s data (req %d, rem "SZFMT")\n", filename, evCount*2, datalen);
505 return NULL;
508 azCount = malloc(sizeof(azCount[0])*evCount);
509 evOffset = malloc(sizeof(evOffset[0])*evCount);
510 if(azCount == NULL || evOffset == NULL)
512 ERR("Out of memory.\n");
513 failed = AL_TRUE;
516 if(!failed)
518 evOffset[0] = GetLE_ALushort(&data, &datalen);
519 for(i = 1;i < evCount;i++)
521 evOffset[i] = GetLE_ALushort(&data, &datalen);
522 if(evOffset[i] <= evOffset[i-1])
524 ERR("Invalid evOffset: evOffset[%d]=%d (last=%d)\n",
525 i, evOffset[i], evOffset[i-1]);
526 failed = AL_TRUE;
529 azCount[i-1] = evOffset[i] - evOffset[i-1];
530 if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
532 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
533 i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
534 failed = AL_TRUE;
537 if(irCount <= evOffset[i-1])
539 ERR("Invalid evOffset: evOffset[%d]=%d (irCount=%d)\n",
540 i-1, evOffset[i-1], irCount);
541 failed = AL_TRUE;
544 azCount[i-1] = irCount - evOffset[i-1];
545 if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
547 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
548 i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
549 failed = AL_TRUE;
553 if(!failed)
555 coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
556 delays = malloc(sizeof(delays[0])*irCount);
557 if(coeffs == NULL || delays == NULL)
559 ERR("Out of memory.\n");
560 failed = AL_TRUE;
564 if(!failed)
566 size_t reqsize = 2*irSize*irCount + irCount;
567 if(datalen < reqsize)
569 ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT")\n",
570 filename, reqsize, datalen);
571 failed = AL_TRUE;
575 if(!failed)
577 for(i = 0;i < irCount;i++)
579 for(j = 0;j < irSize;j++)
580 coeffs[i*irSize + j][0] = GetLE_ALshort(&data, &datalen) / 32768.0f;
583 for(i = 0;i < irCount;i++)
585 delays[i][0] = GetLE_ALubyte(&data, &datalen);
586 if(delays[i][0] > MAX_HRIR_DELAY)
588 ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i][0], MAX_HRIR_DELAY);
589 failed = AL_TRUE;
594 if(!failed)
596 /* Mirror the left ear responses to the right ear. */
597 for(i = 0;i < evCount;i++)
599 ALushort evoffset = evOffset[i];
600 ALubyte azcount = azCount[i];
601 for(j = 0;j < azcount;j++)
603 ALsizei lidx = evoffset + j;
604 ALsizei ridx = evoffset + ((azcount-j) % azcount);
605 ALsizei k;
607 for(k = 0;k < irSize;k++)
608 coeffs[ridx*irSize + k][1] = coeffs[lidx*irSize + k][0];
609 delays[ridx][1] = delays[lidx][0];
613 Hrtf = CreateHrtfStore(rate, irSize, 0.0f, evCount, irCount, azCount,
614 evOffset, coeffs, delays, filename);
617 free(azCount);
618 free(evOffset);
619 free(coeffs);
620 free(delays);
621 return Hrtf;
624 static struct Hrtf *LoadHrtf01(const ALubyte *data, size_t datalen, const char *filename)
626 struct Hrtf *Hrtf = NULL;
627 ALboolean failed = AL_FALSE;
628 ALuint rate = 0;
629 ALushort irCount = 0;
630 ALushort irSize = 0;
631 ALubyte evCount = 0;
632 const ALubyte *azCount = NULL;
633 ALushort *evOffset = NULL;
634 ALfloat (*coeffs)[2] = NULL;
635 ALubyte (*delays)[2] = NULL;
636 ALsizei i, j;
638 if(datalen < 6)
640 ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, 6, datalen);
641 return NULL;
644 rate = GetLE_ALuint(&data, &datalen);
646 irSize = GetLE_ALubyte(&data, &datalen);
648 evCount = GetLE_ALubyte(&data, &datalen);
650 if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
652 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
653 irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
654 failed = AL_TRUE;
656 if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
658 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
659 evCount, MIN_EV_COUNT, MAX_EV_COUNT);
660 failed = AL_TRUE;
662 if(failed)
663 return NULL;
665 if(datalen < evCount)
667 ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, evCount, datalen);
668 return NULL;
671 azCount = Get_ALubytePtr(&data, &datalen, evCount);
673 evOffset = malloc(sizeof(evOffset[0])*evCount);
674 if(azCount == NULL || evOffset == NULL)
676 ERR("Out of memory.\n");
677 failed = AL_TRUE;
680 if(!failed)
682 for(i = 0;i < evCount;i++)
684 if(azCount[i] < MIN_AZ_COUNT || azCount[i] > MAX_AZ_COUNT)
686 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
687 i, azCount[i], MIN_AZ_COUNT, MAX_AZ_COUNT);
688 failed = AL_TRUE;
693 if(!failed)
695 evOffset[0] = 0;
696 irCount = azCount[0];
697 for(i = 1;i < evCount;i++)
699 evOffset[i] = evOffset[i-1] + azCount[i-1];
700 irCount += azCount[i];
703 coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
704 delays = malloc(sizeof(delays[0])*irCount);
705 if(coeffs == NULL || delays == NULL)
707 ERR("Out of memory.\n");
708 failed = AL_TRUE;
712 if(!failed)
714 size_t reqsize = 2*irSize*irCount + irCount;
715 if(datalen < reqsize)
717 ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT"\n",
718 filename, reqsize, datalen);
719 failed = AL_TRUE;
723 if(!failed)
725 for(i = 0;i < irCount;i++)
727 for(j = 0;j < irSize;j++)
728 coeffs[i*irSize + j][0] = GetLE_ALshort(&data, &datalen) / 32768.0f;
731 for(i = 0;i < irCount;i++)
733 delays[i][0] = GetLE_ALubyte(&data, &datalen);
734 if(delays[i][0] > MAX_HRIR_DELAY)
736 ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i][0], MAX_HRIR_DELAY);
737 failed = AL_TRUE;
742 if(!failed)
744 /* Mirror the left ear responses to the right ear. */
745 for(i = 0;i < evCount;i++)
747 ALushort evoffset = evOffset[i];
748 ALubyte azcount = azCount[i];
749 for(j = 0;j < azcount;j++)
751 ALsizei lidx = evoffset + j;
752 ALsizei ridx = evoffset + ((azcount-j) % azcount);
753 ALsizei k;
755 for(k = 0;k < irSize;k++)
756 coeffs[ridx*irSize + k][1] = coeffs[lidx*irSize + k][0];
757 delays[ridx][1] = delays[lidx][0];
761 Hrtf = CreateHrtfStore(rate, irSize, 0.0f, evCount, irCount, azCount,
762 evOffset, coeffs, delays, filename);
765 free(evOffset);
766 free(coeffs);
767 free(delays);
768 return Hrtf;
771 #define SAMPLETYPE_S16 0
772 #define SAMPLETYPE_S24 1
774 #define CHANTYPE_LEFTONLY 0
775 #define CHANTYPE_LEFTRIGHT 1
777 static struct Hrtf *LoadHrtf02(const ALubyte *data, size_t datalen, const char *filename)
779 struct Hrtf *Hrtf = NULL;
780 ALboolean failed = AL_FALSE;
781 ALuint rate = 0;
782 ALubyte sampleType;
783 ALubyte channelType;
784 ALushort irCount = 0;
785 ALushort irSize = 0;
786 ALubyte fdCount = 0;
787 ALushort distance = 0;
788 ALubyte evCount = 0;
789 const ALubyte *azCount = NULL;
790 ALushort *evOffset = NULL;
791 ALfloat (*coeffs)[2] = NULL;
792 ALubyte (*delays)[2] = NULL;
793 ALsizei i, j;
795 if(datalen < 8)
797 ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, 8, datalen);
798 return NULL;
801 rate = GetLE_ALuint(&data, &datalen);
802 sampleType = GetLE_ALubyte(&data, &datalen);
803 channelType = GetLE_ALubyte(&data, &datalen);
805 irSize = GetLE_ALubyte(&data, &datalen);
807 fdCount = GetLE_ALubyte(&data, &datalen);
809 if(sampleType > SAMPLETYPE_S24)
811 ERR("Unsupported sample type: %d\n", sampleType);
812 failed = AL_TRUE;
814 if(channelType > CHANTYPE_LEFTRIGHT)
816 ERR("Unsupported channel type: %d\n", channelType);
817 failed = AL_TRUE;
820 if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
822 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
823 irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
824 failed = AL_TRUE;
826 if(fdCount != 1)
828 ERR("Multiple field-depths not supported: fdCount=%d (%d to %d)\n",
829 evCount, MIN_FD_COUNT, MAX_FD_COUNT);
830 failed = AL_TRUE;
832 if(failed)
833 return NULL;
835 for(i = 0;i < fdCount;i++)
837 if(datalen < 3)
839 ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, 3, datalen);
840 return NULL;
843 distance = GetLE_ALushort(&data, &datalen);
844 if(distance < MIN_FD_DISTANCE || distance > MAX_FD_DISTANCE)
846 ERR("Unsupported field distance: distance=%d (%dmm to %dmm)\n",
847 distance, MIN_FD_DISTANCE, MAX_FD_DISTANCE);
848 failed = AL_TRUE;
851 evCount = GetLE_ALubyte(&data, &datalen);
852 if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
854 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
855 evCount, MIN_EV_COUNT, MAX_EV_COUNT);
856 failed = AL_TRUE;
858 if(failed)
859 return NULL;
861 if(datalen < evCount)
863 ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n", filename, evCount, datalen);
864 return NULL;
867 azCount = Get_ALubytePtr(&data, &datalen, evCount);
868 for(j = 0;j < evCount;j++)
870 if(azCount[j] < MIN_AZ_COUNT || azCount[j] > MAX_AZ_COUNT)
872 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
873 j, azCount[j], MIN_AZ_COUNT, MAX_AZ_COUNT);
874 failed = AL_TRUE;
878 if(failed)
879 return NULL;
881 evOffset = malloc(sizeof(evOffset[0])*evCount);
882 if(azCount == NULL || evOffset == NULL)
884 ERR("Out of memory.\n");
885 failed = AL_TRUE;
888 if(!failed)
890 evOffset[0] = 0;
891 irCount = azCount[0];
892 for(i = 1;i < evCount;i++)
894 evOffset[i] = evOffset[i-1] + azCount[i-1];
895 irCount += azCount[i];
898 coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
899 delays = malloc(sizeof(delays[0])*irCount);
900 if(coeffs == NULL || delays == NULL)
902 ERR("Out of memory.\n");
903 failed = AL_TRUE;
907 if(!failed)
909 size_t reqsize = 2*irSize*irCount + irCount;
910 if(datalen < reqsize)
912 ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT"\n",
913 filename, reqsize, datalen);
914 failed = AL_TRUE;
918 if(!failed)
920 if(channelType == CHANTYPE_LEFTONLY)
922 if(sampleType == SAMPLETYPE_S16)
923 for(i = 0;i < irCount;i++)
925 for(j = 0;j < irSize;j++)
926 coeffs[i*irSize + j][0] = GetLE_ALshort(&data, &datalen) / 32768.0f;
928 else if(sampleType == SAMPLETYPE_S24)
929 for(i = 0;i < irCount;i++)
931 for(j = 0;j < irSize;j++)
932 coeffs[i*irSize + j][0] = GetLE_ALint24(&data, &datalen) / 8388608.0f;
935 for(i = 0;i < irCount;i++)
937 delays[i][0] = GetLE_ALubyte(&data, &datalen);
938 if(delays[i][0] > MAX_HRIR_DELAY)
940 ERR("Invalid delays[%d][0]: %d (%d)\n", i, delays[i][0], MAX_HRIR_DELAY);
941 failed = AL_TRUE;
945 else if(channelType == CHANTYPE_LEFTRIGHT)
947 if(sampleType == SAMPLETYPE_S16)
948 for(i = 0;i < irCount;i++)
950 for(j = 0;j < irSize;j++)
952 coeffs[i*irSize + j][0] = GetLE_ALshort(&data, &datalen) / 32768.0f;
953 coeffs[i*irSize + j][1] = GetLE_ALshort(&data, &datalen) / 32768.0f;
956 else if(sampleType == SAMPLETYPE_S24)
957 for(i = 0;i < irCount;i++)
959 for(j = 0;j < irSize;j++)
961 coeffs[i*irSize + j][0] = GetLE_ALint24(&data, &datalen) / 8388608.0f;
962 coeffs[i*irSize + j][1] = GetLE_ALint24(&data, &datalen) / 8388608.0f;
966 for(i = 0;i < irCount;i++)
968 delays[i][0] = GetLE_ALubyte(&data, &datalen);
969 if(delays[i][0] > MAX_HRIR_DELAY)
971 ERR("Invalid delays[%d][0]: %d (%d)\n", i, delays[i][0], MAX_HRIR_DELAY);
972 failed = AL_TRUE;
974 delays[i][1] = GetLE_ALubyte(&data, &datalen);
975 if(delays[i][1] > MAX_HRIR_DELAY)
977 ERR("Invalid delays[%d][1]: %d (%d)\n", i, delays[i][1], MAX_HRIR_DELAY);
978 failed = AL_TRUE;
984 if(!failed)
986 if(channelType == CHANTYPE_LEFTONLY)
988 /* Mirror the left ear responses to the right ear. */
989 for(i = 0;i < evCount;i++)
991 ALushort evoffset = evOffset[i];
992 ALubyte azcount = azCount[i];
993 for(j = 0;j < azcount;j++)
995 ALsizei lidx = evoffset + j;
996 ALsizei ridx = evoffset + ((azcount-j) % azcount);
997 ALsizei k;
999 for(k = 0;k < irSize;k++)
1000 coeffs[ridx*irSize + k][1] = coeffs[lidx*irSize + k][0];
1001 delays[ridx][1] = delays[lidx][0];
1006 Hrtf = CreateHrtfStore(rate, irSize,
1007 (ALfloat)distance / 1000.0f, evCount, irCount, azCount, evOffset,
1008 coeffs, delays, filename
1012 free(evOffset);
1013 free(coeffs);
1014 free(delays);
1015 return Hrtf;
1019 static void AddFileEntry(vector_EnumeratedHrtf *list, const_al_string filename)
1021 EnumeratedHrtf entry = { AL_STRING_INIT_STATIC(), NULL };
1022 struct HrtfEntry *loaded_entry;
1023 const EnumeratedHrtf *iter;
1024 const char *name;
1025 const char *ext;
1026 int i;
1028 /* Check if this file has already been loaded globally. */
1029 loaded_entry = LoadedHrtfs;
1030 while(loaded_entry)
1032 if(alstr_cmp_cstr(filename, loaded_entry->filename) == 0)
1034 /* Check if this entry has already been added to the list. */
1035 #define MATCH_ENTRY(i) (loaded_entry == (i)->hrtf)
1036 VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_ENTRY);
1037 #undef MATCH_ENTRY
1038 if(iter != VECTOR_END(*list))
1040 TRACE("Skipping duplicate file entry %s\n", alstr_get_cstr(filename));
1041 return;
1044 break;
1046 loaded_entry = loaded_entry->next;
1049 if(!loaded_entry)
1051 TRACE("Got new file \"%s\"\n", alstr_get_cstr(filename));
1053 loaded_entry = al_calloc(DEF_ALIGN,
1054 FAM_SIZE(struct HrtfEntry, filename, alstr_length(filename)+1)
1056 loaded_entry->next = LoadedHrtfs;
1057 loaded_entry->handle = NULL;
1058 strcpy(loaded_entry->filename, alstr_get_cstr(filename));
1059 LoadedHrtfs = loaded_entry;
1062 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1063 * format update). */
1064 name = strrchr(alstr_get_cstr(filename), '/');
1065 if(!name) name = strrchr(alstr_get_cstr(filename), '\\');
1066 if(!name) name = alstr_get_cstr(filename);
1067 else ++name;
1069 ext = strrchr(name, '.');
1071 i = 0;
1072 do {
1073 if(!ext)
1074 alstr_copy_cstr(&entry.name, name);
1075 else
1076 alstr_copy_range(&entry.name, name, ext);
1077 if(i != 0)
1079 char str[64];
1080 snprintf(str, sizeof(str), " #%d", i+1);
1081 alstr_append_cstr(&entry.name, str);
1083 ++i;
1085 #define MATCH_NAME(i) (alstr_cmp(entry.name, (i)->name) == 0)
1086 VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_NAME);
1087 #undef MATCH_NAME
1088 } while(iter != VECTOR_END(*list));
1089 entry.hrtf = loaded_entry;
1091 TRACE("Adding entry \"%s\" from file \"%s\"\n", alstr_get_cstr(entry.name),
1092 alstr_get_cstr(filename));
1093 VECTOR_PUSH_BACK(*list, entry);
1096 /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
1097 * for input instead of opening the given filename.
1099 static void AddBuiltInEntry(vector_EnumeratedHrtf *list, const_al_string filename, ALuint residx)
1101 EnumeratedHrtf entry = { AL_STRING_INIT_STATIC(), NULL };
1102 struct HrtfEntry *loaded_entry;
1103 struct Hrtf *hrtf = NULL;
1104 const EnumeratedHrtf *iter;
1105 const char *name;
1106 const char *ext;
1107 int i;
1109 loaded_entry = LoadedHrtfs;
1110 while(loaded_entry)
1112 if(alstr_cmp_cstr(filename, loaded_entry->filename) == 0)
1114 #define MATCH_ENTRY(i) (loaded_entry == (i)->hrtf)
1115 VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_ENTRY);
1116 #undef MATCH_ENTRY
1117 if(iter != VECTOR_END(*list))
1119 TRACE("Skipping duplicate file entry %s\n", alstr_get_cstr(filename));
1120 return;
1123 break;
1125 loaded_entry = loaded_entry->next;
1128 if(!loaded_entry)
1130 size_t namelen = alstr_length(filename)+32;
1132 TRACE("Got new file \"%s\"\n", alstr_get_cstr(filename));
1134 loaded_entry = al_calloc(DEF_ALIGN,
1135 FAM_SIZE(struct HrtfEntry, filename, namelen)
1137 loaded_entry->next = LoadedHrtfs;
1138 loaded_entry->handle = hrtf;
1139 snprintf(loaded_entry->filename, namelen, "!%u_%s",
1140 residx, alstr_get_cstr(filename));
1141 LoadedHrtfs = loaded_entry;
1144 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1145 * format update). */
1146 name = strrchr(alstr_get_cstr(filename), '/');
1147 if(!name) name = strrchr(alstr_get_cstr(filename), '\\');
1148 if(!name) name = alstr_get_cstr(filename);
1149 else ++name;
1151 ext = strrchr(name, '.');
1153 i = 0;
1154 do {
1155 if(!ext)
1156 alstr_copy_cstr(&entry.name, name);
1157 else
1158 alstr_copy_range(&entry.name, name, ext);
1159 if(i != 0)
1161 char str[64];
1162 snprintf(str, sizeof(str), " #%d", i+1);
1163 alstr_append_cstr(&entry.name, str);
1165 ++i;
1167 #define MATCH_NAME(i) (alstr_cmp(entry.name, (i)->name) == 0)
1168 VECTOR_FIND_IF(iter, const EnumeratedHrtf, *list, MATCH_NAME);
1169 #undef MATCH_NAME
1170 } while(iter != VECTOR_END(*list));
1171 entry.hrtf = loaded_entry;
1173 TRACE("Adding built-in entry \"%s\"\n", alstr_get_cstr(entry.name));
1174 VECTOR_PUSH_BACK(*list, entry);
1178 #define IDR_DEFAULT_44100_MHR 1
1179 #define IDR_DEFAULT_48000_MHR 2
1181 #ifndef ALSOFT_EMBED_HRTF_DATA
1183 static const ALubyte *GetResource(int UNUSED(name), size_t *size)
1185 *size = 0;
1186 return NULL;
1189 #else
1191 #include "default-44100.mhr.h"
1192 #include "default-48000.mhr.h"
1194 static const ALubyte *GetResource(int name, size_t *size)
1196 if(name == IDR_DEFAULT_44100_MHR)
1198 *size = sizeof(hrtf_default_44100);
1199 return hrtf_default_44100;
1201 if(name == IDR_DEFAULT_48000_MHR)
1203 *size = sizeof(hrtf_default_48000);
1204 return hrtf_default_48000;
1206 *size = 0;
1207 return NULL;
1209 #endif
1211 vector_EnumeratedHrtf EnumerateHrtf(const_al_string devname)
1213 vector_EnumeratedHrtf list = VECTOR_INIT_STATIC();
1214 const char *defaulthrtf = "";
1215 const char *pathlist = "";
1216 bool usedefaults = true;
1218 if(ConfigValueStr(alstr_get_cstr(devname), NULL, "hrtf-paths", &pathlist))
1220 al_string pname = AL_STRING_INIT_STATIC();
1221 while(pathlist && *pathlist)
1223 const char *next, *end;
1225 while(isspace(*pathlist) || *pathlist == ',')
1226 pathlist++;
1227 if(*pathlist == '\0')
1228 continue;
1230 next = strchr(pathlist, ',');
1231 if(next)
1232 end = next++;
1233 else
1235 end = pathlist + strlen(pathlist);
1236 usedefaults = false;
1239 while(end != pathlist && isspace(*(end-1)))
1240 --end;
1241 if(end != pathlist)
1243 vector_al_string flist;
1244 size_t i;
1246 alstr_copy_range(&pname, pathlist, end);
1248 flist = SearchDataFiles(".mhr", alstr_get_cstr(pname));
1249 for(i = 0;i < VECTOR_SIZE(flist);i++)
1250 AddFileEntry(&list, VECTOR_ELEM(flist, i));
1251 VECTOR_FOR_EACH(al_string, flist, alstr_reset);
1252 VECTOR_DEINIT(flist);
1255 pathlist = next;
1258 alstr_reset(&pname);
1260 else if(ConfigValueExists(alstr_get_cstr(devname), NULL, "hrtf_tables"))
1261 ERR("The hrtf_tables option is deprecated, please use hrtf-paths instead.\n");
1263 if(usedefaults)
1265 al_string ename = AL_STRING_INIT_STATIC();
1266 vector_al_string flist;
1267 const ALubyte *rdata;
1268 size_t rsize, i;
1270 flist = SearchDataFiles(".mhr", "openal/hrtf");
1271 for(i = 0;i < VECTOR_SIZE(flist);i++)
1272 AddFileEntry(&list, VECTOR_ELEM(flist, i));
1273 VECTOR_FOR_EACH(al_string, flist, alstr_reset);
1274 VECTOR_DEINIT(flist);
1276 rdata = GetResource(IDR_DEFAULT_44100_MHR, &rsize);
1277 if(rdata != NULL && rsize > 0)
1279 alstr_copy_cstr(&ename, "Built-In 44100hz");
1280 AddBuiltInEntry(&list, ename, IDR_DEFAULT_44100_MHR);
1283 rdata = GetResource(IDR_DEFAULT_48000_MHR, &rsize);
1284 if(rdata != NULL && rsize > 0)
1286 alstr_copy_cstr(&ename, "Built-In 48000hz");
1287 AddBuiltInEntry(&list, ename, IDR_DEFAULT_48000_MHR);
1289 alstr_reset(&ename);
1292 if(VECTOR_SIZE(list) > 1 && ConfigValueStr(alstr_get_cstr(devname), NULL, "default-hrtf", &defaulthrtf))
1294 const EnumeratedHrtf *iter;
1295 /* Find the preferred HRTF and move it to the front of the list. */
1296 #define FIND_ENTRY(i) (alstr_cmp_cstr((i)->name, defaulthrtf) == 0)
1297 VECTOR_FIND_IF(iter, const EnumeratedHrtf, list, FIND_ENTRY);
1298 #undef FIND_ENTRY
1299 if(iter == VECTOR_END(list))
1300 WARN("Failed to find default HRTF \"%s\"\n", defaulthrtf);
1301 else if(iter != VECTOR_BEGIN(list))
1303 EnumeratedHrtf entry = *iter;
1304 memmove(&VECTOR_ELEM(list,1), &VECTOR_ELEM(list,0),
1305 (iter-VECTOR_BEGIN(list))*sizeof(EnumeratedHrtf));
1306 VECTOR_ELEM(list,0) = entry;
1310 return list;
1313 void FreeHrtfList(vector_EnumeratedHrtf *list)
1315 #define CLEAR_ENTRY(i) alstr_reset(&(i)->name)
1316 VECTOR_FOR_EACH(EnumeratedHrtf, *list, CLEAR_ENTRY);
1317 VECTOR_DEINIT(*list);
1318 #undef CLEAR_ENTRY
1321 struct Hrtf *GetLoadedHrtf(struct HrtfEntry *entry)
1323 struct Hrtf *hrtf = NULL;
1324 struct FileMapping fmap;
1325 const ALubyte *rdata;
1326 const char *name;
1327 ALuint residx;
1328 size_t rsize;
1329 char ch;
1331 while(ATOMIC_FLAG_TEST_AND_SET(&LoadedHrtfLock, almemory_order_seq_cst))
1332 althrd_yield();
1334 if(entry->handle)
1336 hrtf = entry->handle;
1337 Hrtf_IncRef(hrtf);
1338 goto done;
1341 fmap.ptr = NULL;
1342 fmap.len = 0;
1343 if(sscanf(entry->filename, "!%u%c", &residx, &ch) == 2 && ch == '_')
1345 name = strchr(entry->filename, ch)+1;
1347 TRACE("Loading %s...\n", name);
1348 rdata = GetResource(residx, &rsize);
1349 if(rdata == NULL || rsize == 0)
1351 ERR("Could not get resource %u, %s\n", residx, name);
1352 goto done;
1355 else
1357 name = entry->filename;
1359 TRACE("Loading %s...\n", entry->filename);
1360 fmap = MapFileToMem(entry->filename);
1361 if(fmap.ptr == NULL)
1363 ERR("Could not open %s\n", entry->filename);
1364 goto done;
1367 rdata = fmap.ptr;
1368 rsize = fmap.len;
1371 if(rsize < sizeof(magicMarker02))
1372 ERR("%s data is too short ("SZFMT" bytes)\n", name, rsize);
1373 else if(memcmp(rdata, magicMarker02, sizeof(magicMarker02)) == 0)
1375 TRACE("Detected data set format v2\n");
1376 hrtf = LoadHrtf02(rdata+sizeof(magicMarker02),
1377 rsize-sizeof(magicMarker02), name
1380 else if(memcmp(rdata, magicMarker01, sizeof(magicMarker01)) == 0)
1382 TRACE("Detected data set format v1\n");
1383 hrtf = LoadHrtf01(rdata+sizeof(magicMarker01),
1384 rsize-sizeof(magicMarker01), name
1387 else if(memcmp(rdata, magicMarker00, sizeof(magicMarker00)) == 0)
1389 TRACE("Detected data set format v0\n");
1390 hrtf = LoadHrtf00(rdata+sizeof(magicMarker00),
1391 rsize-sizeof(magicMarker00), name
1394 else
1395 ERR("Invalid header in %s: \"%.8s\"\n", name, (const char*)rdata);
1396 if(fmap.ptr)
1397 UnmapFileMem(&fmap);
1399 if(!hrtf)
1401 ERR("Failed to load %s\n", name);
1402 goto done;
1404 entry->handle = hrtf;
1405 Hrtf_IncRef(hrtf);
1407 TRACE("Loaded HRTF support for format: %s %uhz\n",
1408 DevFmtChannelsString(DevFmtStereo), hrtf->sampleRate);
1410 done:
1411 ATOMIC_FLAG_CLEAR(&LoadedHrtfLock, almemory_order_seq_cst);
1412 return hrtf;
1416 void Hrtf_IncRef(struct Hrtf *hrtf)
1418 uint ref = IncrementRef(&hrtf->ref);
1419 TRACEREF("%p increasing refcount to %u\n", hrtf, ref);
1422 void Hrtf_DecRef(struct Hrtf *hrtf)
1424 struct HrtfEntry *Hrtf;
1425 uint ref = DecrementRef(&hrtf->ref);
1426 TRACEREF("%p decreasing refcount to %u\n", hrtf, ref);
1427 if(ref == 0)
1429 while(ATOMIC_FLAG_TEST_AND_SET(&LoadedHrtfLock, almemory_order_seq_cst))
1430 althrd_yield();
1432 Hrtf = LoadedHrtfs;
1433 while(Hrtf != NULL)
1435 /* Need to double-check that it's still unused, as another device
1436 * could've reacquired this HRTF after its reference went to 0 and
1437 * before the lock was taken.
1439 if(hrtf == Hrtf->handle && ReadRef(&hrtf->ref) == 0)
1441 al_free(Hrtf->handle);
1442 Hrtf->handle = NULL;
1443 TRACE("Unloaded unused HRTF %s\n", Hrtf->filename);
1445 Hrtf = Hrtf->next;
1448 ATOMIC_FLAG_CLEAR(&LoadedHrtfLock, almemory_order_seq_cst);
1453 void FreeHrtfs(void)
1455 struct HrtfEntry *Hrtf = LoadedHrtfs;
1456 LoadedHrtfs = NULL;
1458 while(Hrtf != NULL)
1460 struct HrtfEntry *next = Hrtf->next;
1461 al_free(Hrtf->handle);
1462 al_free(Hrtf);
1463 Hrtf = next;