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
31 #include "bformatdec.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)
50 struct HrtfEntry
*next
;
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
72 static ALsizei
CalcEvIndex(ALsizei evcount
, ALfloat ev
, ALfloat
*mu
)
75 ev
= (F_PI_2
+ev
) * (evcount
-1) / F_PI
;
76 idx
= mini(fastf2i(ev
), evcount
-1);
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-
86 static ALsizei
CalcAzIndex(ALsizei azcount
, ALfloat az
, ALfloat
*mu
)
89 az
= (F_TAU
+az
) * azcount
/ F_TAU
;
91 idx
= fastf2i(az
) % azcount
;
92 *mu
= az
- floorf(az
);
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
,
100 ALfloat (*restrict coeffs
)[2], ALsizei
*delays
)
102 ALsizei evidx
, azidx
, idx
[4];
109 dirfact
= 1.0f
- (spread
/ F_TAU
);
111 /* Claculate the lower elevation index. */
112 evidx
= CalcEvIndex(Hrtf
->evCount
, elevation
, &emu
);
113 evoffset
= Hrtf
->evOffset
[evidx
];
115 /* Calculate lower azimuth index. */
116 azidx
= CalcAzIndex(Hrtf
->azCount
[evidx
], azimuth
, &amu
[0]);
118 /* Calculate the lower HRIR indices. */
119 idx
[0] = evoffset
+ azidx
;
120 idx
[1] = evoffset
+ ((azidx
+1) % Hrtf
->azCount
[evidx
]);
121 if(evidx
< Hrtf
->evCount
-1)
123 /* Increment elevation to the next (upper) index. */
125 evoffset
= Hrtf
->evOffset
[evidx
];
127 /* Calculate upper azimuth index. */
128 azidx
= CalcAzIndex(Hrtf
->azCount
[evidx
], azimuth
, &amu
[1]);
130 /* Calculate the upper HRIR indices. */
131 idx
[2] = evoffset
+ azidx
;
132 idx
[3] = evoffset
+ ((azidx
+1) % Hrtf
->azCount
[evidx
]);
136 /* If the lower elevation is the top index, the upper elevation is the
144 /* Calculate bilinear blending weights, attenuated according to the
145 * directional panning factor.
147 blend
[0] = (1.0f
-emu
) * (1.0f
-amu
[0]) * dirfact
;
148 blend
[1] = (1.0f
-emu
) * ( amu
[0]) * dirfact
;
149 blend
[2] = ( emu
) * (1.0f
-amu
[1]) * dirfact
;
150 blend
[3] = ( emu
) * ( amu
[1]) * dirfact
;
152 /* Calculate the blended HRIR delays. */
154 Hrtf
->delays
[idx
[0]][0]*blend
[0] + Hrtf
->delays
[idx
[1]][0]*blend
[1] +
155 Hrtf
->delays
[idx
[2]][0]*blend
[2] + Hrtf
->delays
[idx
[3]][0]*blend
[3] + 0.5f
158 Hrtf
->delays
[idx
[0]][1]*blend
[0] + Hrtf
->delays
[idx
[1]][1]*blend
[1] +
159 Hrtf
->delays
[idx
[2]][1]*blend
[2] + Hrtf
->delays
[idx
[3]][1]*blend
[3] + 0.5f
162 /* Calculate the sample offsets for the HRIR indices. */
163 idx
[0] *= Hrtf
->irSize
;
164 idx
[1] *= Hrtf
->irSize
;
165 idx
[2] *= Hrtf
->irSize
;
166 idx
[3] *= Hrtf
->irSize
;
168 coeffs
= ASSUME_ALIGNED(coeffs
, 16);
169 /* Calculate the blended HRIR coefficients. */
170 coeffs
[0][0] = PassthruCoeff
* (1.0f
-dirfact
);
171 coeffs
[0][1] = PassthruCoeff
* (1.0f
-dirfact
);
172 for(i
= 1;i
< Hrtf
->irSize
;i
++)
179 const ALfloat (*restrict srccoeffs
)[2] = ASSUME_ALIGNED(Hrtf
->coeffs
+idx
[c
], 16);
180 for(i
= 0;i
< Hrtf
->irSize
;i
++)
182 coeffs
[i
][0] += srccoeffs
[i
][0] * blend
[c
];
183 coeffs
[i
][1] += srccoeffs
[i
][1] * blend
[c
];
189 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
)
191 /* Set this to 2 for dual-band HRTF processing. May require a higher quality
192 * band-splitter, or better calculation of the new IR length to deal with the
193 * tail generated by the filter.
196 BandSplitter splitter
;
197 ALsizei idx
[HRTF_AMBI_MAX_CHANNELS
];
198 ALsizei min_delay
= HRTF_HISTORY_LENGTH
;
199 ALfloat temps
[3][HRIR_LENGTH
];
200 ALsizei max_length
= 0;
203 for(c
= 0;c
< AmbiCount
;c
++)
209 /* Calculate elevation index. */
210 evidx
= (ALsizei
)floorf((F_PI_2
+ AmbiPoints
[c
][0]) *
211 (Hrtf
->evCount
-1)/F_PI
+ 0.5f
);
212 evidx
= mini(evidx
, Hrtf
->evCount
-1);
214 azcount
= Hrtf
->azCount
[evidx
];
215 evoffset
= Hrtf
->evOffset
[evidx
];
217 /* Calculate azimuth index for this elevation. */
218 azidx
= (ALsizei
)floorf((F_TAU
+AmbiPoints
[c
][1]) *
219 azcount
/F_TAU
+ 0.5f
) % azcount
;
221 /* Calculate indices for left and right channels. */
222 idx
[c
] = evoffset
+ azidx
;
224 min_delay
= mini(min_delay
, mini(Hrtf
->delays
[idx
[c
]][0], Hrtf
->delays
[idx
[c
]][1]));
227 memset(temps
, 0, sizeof(temps
));
228 bandsplit_init(&splitter
, 400.0f
/ (ALfloat
)Hrtf
->sampleRate
);
229 for(c
= 0;c
< AmbiCount
;c
++)
231 const ALfloat (*fir
)[2] = &Hrtf
->coeffs
[idx
[c
] * Hrtf
->irSize
];
232 ALsizei ldelay
= Hrtf
->delays
[idx
[c
]][0] - min_delay
;
233 ALsizei rdelay
= Hrtf
->delays
[idx
[c
]][1] - min_delay
;
235 max_length
= maxi(max_length
,
236 mini(maxi(ldelay
, rdelay
) + Hrtf
->irSize
, HRIR_LENGTH
)
241 for(i
= 0;i
< NumChannels
;++i
)
243 ALsizei lidx
= ldelay
, ridx
= rdelay
;
245 while(lidx
< HRIR_LENGTH
&& ridx
< HRIR_LENGTH
&& j
< Hrtf
->irSize
)
247 state
->Chan
[i
].Coeffs
[lidx
++][0] += fir
[j
][0] * AmbiMatrix
[c
][0][i
];
248 state
->Chan
[i
].Coeffs
[ridx
++][1] += fir
[j
][1] * AmbiMatrix
[c
][0][i
];
255 /* Band-split left HRIR into low and high frequency responses. */
256 bandsplit_clear(&splitter
);
257 for(i
= 0;i
< Hrtf
->irSize
;i
++)
258 temps
[2][i
] = fir
[i
][0];
259 bandsplit_process(&splitter
, temps
[0], temps
[1], temps
[2], HRIR_LENGTH
);
261 /* Apply left ear response with delay. */
262 for(i
= 0;i
< NumChannels
;++i
)
264 for(b
= 0;b
< NUM_BANDS
;b
++)
266 ALsizei lidx
= ldelay
;
268 while(lidx
< HRIR_LENGTH
)
269 state
->Chan
[i
].Coeffs
[lidx
++][0] += temps
[b
][j
++] * AmbiMatrix
[c
][b
][i
];
273 /* Band-split right HRIR into low and high frequency responses. */
274 bandsplit_clear(&splitter
);
275 for(i
= 0;i
< Hrtf
->irSize
;i
++)
276 temps
[2][i
] = fir
[i
][1];
277 bandsplit_process(&splitter
, temps
[0], temps
[1], temps
[2], HRIR_LENGTH
);
279 /* Apply right ear response with delay. */
280 for(i
= 0;i
< NumChannels
;++i
)
282 for(b
= 0;b
< NUM_BANDS
;b
++)
284 ALsizei ridx
= rdelay
;
286 while(ridx
< HRIR_LENGTH
)
287 state
->Chan
[i
].Coeffs
[ridx
++][1] += temps
[b
][j
++] * AmbiMatrix
[c
][b
][i
];
292 /* Round up to the next IR size multiple. */
293 max_length
= RoundUp(max_length
, MOD_IR_SIZE
);
295 TRACE("Skipped min delay: %d, new combined length: %d\n", min_delay
, max_length
);
296 state
->IrSize
= max_length
;
301 static struct Hrtf
*CreateHrtfStore(ALuint rate
, ALsizei irSize
, ALsizei evCount
, ALsizei irCount
,
302 const ALubyte
*azCount
, const ALushort
*evOffset
,
303 const ALfloat (*coeffs
)[2], const ALubyte (*delays
)[2],
304 const char *filename
)
309 total
= sizeof(struct Hrtf
);
310 total
+= sizeof(Hrtf
->azCount
[0])*evCount
;
311 total
= RoundUp(total
, sizeof(ALushort
)); /* Align for ushort fields */
312 total
+= sizeof(Hrtf
->evOffset
[0])*evCount
;
313 total
= RoundUp(total
, 16); /* Align for coefficients using SIMD */
314 total
+= sizeof(Hrtf
->coeffs
[0])*irSize
*irCount
;
315 total
+= sizeof(Hrtf
->delays
[0])*irCount
;
317 Hrtf
= al_calloc(16, total
);
319 ERR("Out of memory allocating storage for %s.\n", filename
);
322 uintptr_t offset
= sizeof(struct Hrtf
);
323 char *base
= (char*)Hrtf
;
326 ALubyte (*_delays
)[2];
327 ALfloat (*_coeffs
)[2];
330 InitRef(&Hrtf
->ref
, 0);
331 Hrtf
->sampleRate
= rate
;
332 Hrtf
->irSize
= irSize
;
333 Hrtf
->evCount
= evCount
;
335 /* Set up pointers to storage following the main HRTF struct. */
336 _azCount
= (ALubyte
*)(base
+ offset
); Hrtf
->azCount
= _azCount
;
337 offset
+= sizeof(_azCount
[0])*evCount
;
339 offset
= RoundUp(offset
, sizeof(ALushort
)); /* Align for ushort fields */
340 _evOffset
= (ALushort
*)(base
+ offset
); Hrtf
->evOffset
= _evOffset
;
341 offset
+= sizeof(_evOffset
[0])*evCount
;
343 offset
= RoundUp(offset
, 16); /* Align for coefficients using SIMD */
344 _coeffs
= (ALfloat(*)[2])(base
+ offset
); Hrtf
->coeffs
= _coeffs
;
345 offset
+= sizeof(_coeffs
[0])*irSize
*irCount
;
347 _delays
= (ALubyte(*)[2])(base
+ offset
); Hrtf
->delays
= _delays
;
348 offset
+= sizeof(_delays
[0])*irCount
;
350 /* Copy input data to storage. */
351 for(i
= 0;i
< evCount
;i
++) _azCount
[i
] = azCount
[i
];
352 for(i
= 0;i
< evCount
;i
++) _evOffset
[i
] = evOffset
[i
];
353 for(i
= 0;i
< irSize
*irCount
;i
++)
355 _coeffs
[i
][0] = coeffs
[i
][0];
356 _coeffs
[i
][1] = coeffs
[i
][1];
358 for(i
= 0;i
< irCount
;i
++)
360 _delays
[i
][0] = delays
[i
][0];
361 _delays
[i
][1] = delays
[i
][1];
364 assert(offset
== total
);
370 static ALubyte
GetLE_ALubyte(const ALubyte
**data
, size_t *len
)
372 ALubyte ret
= (*data
)[0];
373 *data
+= 1; *len
-= 1;
377 static ALshort
GetLE_ALshort(const ALubyte
**data
, size_t *len
)
379 ALshort ret
= (*data
)[0] | ((*data
)[1]<<8);
380 *data
+= 2; *len
-= 2;
384 static ALushort
GetLE_ALushort(const ALubyte
**data
, size_t *len
)
386 ALushort ret
= (*data
)[0] | ((*data
)[1]<<8);
387 *data
+= 2; *len
-= 2;
391 static ALint
GetLE_ALint24(const ALubyte
**data
, size_t *len
)
393 ALint ret
= (*data
)[0] | ((*data
)[1]<<8) | ((*data
)[2]<<16);
394 *data
+= 3; *len
-= 3;
395 return (ret
^0x800000) - 0x800000;
398 static ALuint
GetLE_ALuint(const ALubyte
**data
, size_t *len
)
400 ALuint ret
= (*data
)[0] | ((*data
)[1]<<8) | ((*data
)[2]<<16) | ((*data
)[3]<<24);
401 *data
+= 4; *len
-= 4;
405 static const ALubyte
*Get_ALubytePtr(const ALubyte
**data
, size_t *len
, size_t size
)
407 const ALubyte
*ret
= *data
;
408 *data
+= size
; *len
-= size
;
412 static struct Hrtf
*LoadHrtf00(const ALubyte
*data
, size_t datalen
, const char *filename
)
414 const ALubyte maxDelay
= HRTF_HISTORY_LENGTH
-1;
415 struct Hrtf
*Hrtf
= NULL
;
416 ALboolean failed
= AL_FALSE
;
418 ALushort irCount
= 0;
421 ALubyte
*azCount
= NULL
;
422 ALushort
*evOffset
= NULL
;
423 ALfloat (*coeffs
)[2] = NULL
;
424 ALubyte (*delays
)[2] = NULL
;
429 ERR("Unexpected end of %s data (req %d, rem "SZFMT
")\n", filename
, 9, datalen
);
433 rate
= GetLE_ALuint(&data
, &datalen
);
435 irCount
= GetLE_ALushort(&data
, &datalen
);
437 irSize
= GetLE_ALushort(&data
, &datalen
);
439 evCount
= GetLE_ALubyte(&data
, &datalen
);
441 if(irSize
< MIN_IR_SIZE
|| irSize
> MAX_IR_SIZE
|| (irSize
%MOD_IR_SIZE
))
443 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
444 irSize
, MIN_IR_SIZE
, MAX_IR_SIZE
, MOD_IR_SIZE
);
447 if(evCount
< MIN_EV_COUNT
|| evCount
> MAX_EV_COUNT
)
449 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
450 evCount
, MIN_EV_COUNT
, MAX_EV_COUNT
);
456 if(datalen
< evCount
*2u)
458 ERR("Unexpected end of %s data (req %d, rem "SZFMT
")\n", filename
, evCount
*2, datalen
);
462 azCount
= malloc(sizeof(azCount
[0])*evCount
);
463 evOffset
= malloc(sizeof(evOffset
[0])*evCount
);
464 if(azCount
== NULL
|| evOffset
== NULL
)
466 ERR("Out of memory.\n");
472 evOffset
[0] = GetLE_ALushort(&data
, &datalen
);
473 for(i
= 1;i
< evCount
;i
++)
475 evOffset
[i
] = GetLE_ALushort(&data
, &datalen
);
476 if(evOffset
[i
] <= evOffset
[i
-1])
478 ERR("Invalid evOffset: evOffset[%d]=%d (last=%d)\n",
479 i
, evOffset
[i
], evOffset
[i
-1]);
483 azCount
[i
-1] = evOffset
[i
] - evOffset
[i
-1];
484 if(azCount
[i
-1] < MIN_AZ_COUNT
|| azCount
[i
-1] > MAX_AZ_COUNT
)
486 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
487 i
-1, azCount
[i
-1], MIN_AZ_COUNT
, MAX_AZ_COUNT
);
491 if(irCount
<= evOffset
[i
-1])
493 ERR("Invalid evOffset: evOffset[%d]=%d (irCount=%d)\n",
494 i
-1, evOffset
[i
-1], irCount
);
498 azCount
[i
-1] = irCount
- evOffset
[i
-1];
499 if(azCount
[i
-1] < MIN_AZ_COUNT
|| azCount
[i
-1] > MAX_AZ_COUNT
)
501 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
502 i
-1, azCount
[i
-1], MIN_AZ_COUNT
, MAX_AZ_COUNT
);
509 coeffs
= malloc(sizeof(coeffs
[0])*irSize
*irCount
);
510 delays
= malloc(sizeof(delays
[0])*irCount
);
511 if(coeffs
== NULL
|| delays
== NULL
)
513 ERR("Out of memory.\n");
520 size_t reqsize
= 2*irSize
*irCount
+ irCount
;
521 if(datalen
< reqsize
)
523 ERR("Unexpected end of %s data (req "SZFMT
", rem "SZFMT
")\n",
524 filename
, reqsize
, datalen
);
531 for(i
= 0;i
< irCount
;i
++)
533 for(j
= 0;j
< irSize
;j
++)
534 coeffs
[i
*irSize
+ j
][0] = GetLE_ALshort(&data
, &datalen
) / 32768.0f
;
537 for(i
= 0;i
< irCount
;i
++)
539 delays
[i
][0] = GetLE_ALubyte(&data
, &datalen
);
540 if(delays
[i
][0] > maxDelay
)
542 ERR("Invalid delays[%d]: %d (%d)\n", i
, delays
[i
][0], maxDelay
);
550 /* Mirror the left ear responses to the right ear. */
551 for(i
= 0;i
< evCount
;i
++)
553 ALushort evoffset
= evOffset
[i
];
554 ALubyte azcount
= azCount
[i
];
555 for(j
= 0;j
< azcount
;j
++)
557 ALsizei lidx
= evoffset
+ j
;
558 ALsizei ridx
= evoffset
+ ((azcount
-j
) % azcount
);
561 for(k
= 0;k
< irSize
;k
++)
562 coeffs
[ridx
*irSize
+ k
][1] = coeffs
[lidx
*irSize
+ k
][0];
563 delays
[ridx
][1] = delays
[lidx
][0];
567 Hrtf
= CreateHrtfStore(rate
, irSize
, evCount
, irCount
, azCount
,
568 evOffset
, coeffs
, delays
, filename
);
578 static struct Hrtf
*LoadHrtf01(const ALubyte
*data
, size_t datalen
, const char *filename
)
580 const ALubyte maxDelay
= HRTF_HISTORY_LENGTH
-1;
581 struct Hrtf
*Hrtf
= NULL
;
582 ALboolean failed
= AL_FALSE
;
584 ALushort irCount
= 0;
587 const ALubyte
*azCount
= NULL
;
588 ALushort
*evOffset
= NULL
;
589 ALfloat (*coeffs
)[2] = NULL
;
590 ALubyte (*delays
)[2] = NULL
;
595 ERR("Unexpected end of %s data (req %d, rem "SZFMT
"\n", filename
, 6, datalen
);
599 rate
= GetLE_ALuint(&data
, &datalen
);
601 irSize
= GetLE_ALubyte(&data
, &datalen
);
603 evCount
= GetLE_ALubyte(&data
, &datalen
);
605 if(irSize
< MIN_IR_SIZE
|| irSize
> MAX_IR_SIZE
|| (irSize
%MOD_IR_SIZE
))
607 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
608 irSize
, MIN_IR_SIZE
, MAX_IR_SIZE
, MOD_IR_SIZE
);
611 if(evCount
< MIN_EV_COUNT
|| evCount
> MAX_EV_COUNT
)
613 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
614 evCount
, MIN_EV_COUNT
, MAX_EV_COUNT
);
620 if(datalen
< evCount
)
622 ERR("Unexpected end of %s data (req %d, rem "SZFMT
"\n", filename
, evCount
, datalen
);
626 azCount
= Get_ALubytePtr(&data
, &datalen
, evCount
);
628 evOffset
= malloc(sizeof(evOffset
[0])*evCount
);
629 if(azCount
== NULL
|| evOffset
== NULL
)
631 ERR("Out of memory.\n");
637 for(i
= 0;i
< evCount
;i
++)
639 if(azCount
[i
] < MIN_AZ_COUNT
|| azCount
[i
] > MAX_AZ_COUNT
)
641 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
642 i
, azCount
[i
], MIN_AZ_COUNT
, MAX_AZ_COUNT
);
651 irCount
= azCount
[0];
652 for(i
= 1;i
< evCount
;i
++)
654 evOffset
[i
] = evOffset
[i
-1] + azCount
[i
-1];
655 irCount
+= azCount
[i
];
658 coeffs
= malloc(sizeof(coeffs
[0])*irSize
*irCount
);
659 delays
= malloc(sizeof(delays
[0])*irCount
);
660 if(coeffs
== NULL
|| delays
== NULL
)
662 ERR("Out of memory.\n");
669 size_t reqsize
= 2*irSize
*irCount
+ irCount
;
670 if(datalen
< reqsize
)
672 ERR("Unexpected end of %s data (req "SZFMT
", rem "SZFMT
"\n",
673 filename
, reqsize
, datalen
);
680 for(i
= 0;i
< irCount
;i
++)
682 for(j
= 0;j
< irSize
;j
++)
683 coeffs
[i
*irSize
+ j
][0] = GetLE_ALshort(&data
, &datalen
) / 32768.0f
;
686 for(i
= 0;i
< irCount
;i
++)
688 delays
[i
][0] = GetLE_ALubyte(&data
, &datalen
);
689 if(delays
[i
][0] > maxDelay
)
691 ERR("Invalid delays[%d]: %d (%d)\n", i
, delays
[i
][0], maxDelay
);
699 /* Mirror the left ear responses to the right ear. */
700 for(i
= 0;i
< evCount
;i
++)
702 ALushort evoffset
= evOffset
[i
];
703 ALubyte azcount
= azCount
[i
];
704 for(j
= 0;j
< azcount
;j
++)
706 ALsizei lidx
= evoffset
+ j
;
707 ALsizei ridx
= evoffset
+ ((azcount
-j
) % azcount
);
710 for(k
= 0;k
< irSize
;k
++)
711 coeffs
[ridx
*irSize
+ k
][1] = coeffs
[lidx
*irSize
+ k
][0];
712 delays
[ridx
][1] = delays
[lidx
][0];
716 Hrtf
= CreateHrtfStore(rate
, irSize
, evCount
, irCount
, azCount
,
717 evOffset
, coeffs
, delays
, filename
);
726 #define SAMPLETYPE_S16 0
727 #define SAMPLETYPE_S24 1
729 #define CHANTYPE_LEFTONLY 0
730 #define CHANTYPE_LEFTRIGHT 1
732 static struct Hrtf
*LoadHrtf02(const ALubyte
*data
, size_t datalen
, const char *filename
)
734 const ALubyte maxDelay
= HRTF_HISTORY_LENGTH
-1;
735 struct Hrtf
*Hrtf
= NULL
;
736 ALboolean failed
= AL_FALSE
;
740 ALushort irCount
= 0;
743 const ALubyte
*azCount
= NULL
;
744 ALushort
*evOffset
= NULL
;
745 ALfloat (*coeffs
)[2] = NULL
;
746 ALubyte (*delays
)[2] = NULL
;
751 ERR("Unexpected end of %s data (req %d, rem "SZFMT
"\n", filename
, 8, datalen
);
755 rate
= GetLE_ALuint(&data
, &datalen
);
756 sampleType
= GetLE_ALubyte(&data
, &datalen
);
757 channelType
= GetLE_ALubyte(&data
, &datalen
);
759 irSize
= GetLE_ALubyte(&data
, &datalen
);
761 evCount
= GetLE_ALubyte(&data
, &datalen
);
763 if(sampleType
> SAMPLETYPE_S24
)
765 ERR("Unsupported sample type: %d\n", sampleType
);
768 if(channelType
> CHANTYPE_LEFTRIGHT
)
770 ERR("Unsupported channel type: %d\n", channelType
);
774 if(irSize
< MIN_IR_SIZE
|| irSize
> MAX_IR_SIZE
|| (irSize
%MOD_IR_SIZE
))
776 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
777 irSize
, MIN_IR_SIZE
, MAX_IR_SIZE
, MOD_IR_SIZE
);
780 if(evCount
< MIN_EV_COUNT
|| evCount
> MAX_EV_COUNT
)
782 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
783 evCount
, MIN_EV_COUNT
, MAX_EV_COUNT
);
789 if(datalen
< evCount
)
791 ERR("Unexpected end of %s data (req %d, rem "SZFMT
"\n", filename
, evCount
, datalen
);
795 azCount
= Get_ALubytePtr(&data
, &datalen
, evCount
);
797 evOffset
= malloc(sizeof(evOffset
[0])*evCount
);
798 if(azCount
== NULL
|| evOffset
== NULL
)
800 ERR("Out of memory.\n");
806 for(i
= 0;i
< evCount
;i
++)
808 if(azCount
[i
] < MIN_AZ_COUNT
|| azCount
[i
] > MAX_AZ_COUNT
)
810 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
811 i
, azCount
[i
], MIN_AZ_COUNT
, MAX_AZ_COUNT
);
820 irCount
= azCount
[0];
821 for(i
= 1;i
< evCount
;i
++)
823 evOffset
[i
] = evOffset
[i
-1] + azCount
[i
-1];
824 irCount
+= azCount
[i
];
827 coeffs
= malloc(sizeof(coeffs
[0])*irSize
*irCount
);
828 delays
= malloc(sizeof(delays
[0])*irCount
);
829 if(coeffs
== NULL
|| delays
== NULL
)
831 ERR("Out of memory.\n");
838 size_t reqsize
= 2*irSize
*irCount
+ irCount
;
839 if(datalen
< reqsize
)
841 ERR("Unexpected end of %s data (req "SZFMT
", rem "SZFMT
"\n",
842 filename
, reqsize
, datalen
);
849 if(channelType
== CHANTYPE_LEFTONLY
|| channelType
== CHANTYPE_LEFTRIGHT
)
851 if(sampleType
== SAMPLETYPE_S16
)
852 for(i
= 0;i
< irCount
;i
++)
854 for(j
= 0;j
< irSize
;j
++)
855 coeffs
[i
*irSize
+ j
][0] = GetLE_ALshort(&data
, &datalen
) / 32768.0f
;
857 else if(sampleType
== SAMPLETYPE_S24
)
858 for(i
= 0;i
< irCount
;i
++)
860 for(j
= 0;j
< irSize
;j
++)
861 coeffs
[i
*irSize
+ j
][0] = GetLE_ALint24(&data
, &datalen
) / 8388608.0f
;
864 if(channelType
== CHANTYPE_LEFTRIGHT
)
866 if(sampleType
== SAMPLETYPE_S16
)
867 for(i
= 0;i
< irCount
;i
++)
869 for(j
= 0;j
< irSize
;j
++)
870 coeffs
[i
*irSize
+ j
][1] = GetLE_ALshort(&data
, &datalen
) / 32768.0f
;
872 else if(sampleType
== SAMPLETYPE_S24
)
873 for(i
= 0;i
< irCount
;i
++)
875 for(j
= 0;j
< irSize
;j
++)
876 coeffs
[i
*irSize
+ j
][1] = GetLE_ALint24(&data
, &datalen
) / 8388608.0f
;
879 if(channelType
== CHANTYPE_LEFTONLY
|| channelType
== CHANTYPE_LEFTRIGHT
)
881 for(i
= 0;i
< irCount
;i
++)
883 delays
[i
][0] = GetLE_ALubyte(&data
, &datalen
);
884 if(delays
[i
][0] > maxDelay
)
886 ERR("Invalid delays[%d][0]: %d (%d)\n", i
, delays
[i
][0], maxDelay
);
891 if(channelType
== CHANTYPE_LEFTRIGHT
)
893 for(i
= 0;i
< irCount
;i
++)
895 delays
[i
][1] = GetLE_ALubyte(&data
, &datalen
);
896 if(delays
[i
][1] > maxDelay
)
898 ERR("Invalid delays[%d][1]: %d (%d)\n", i
, delays
[i
][1], maxDelay
);
907 if(channelType
== CHANTYPE_LEFTONLY
)
909 /* Mirror the left ear responses to the right ear. */
910 for(i
= 0;i
< evCount
;i
++)
912 ALushort evoffset
= evOffset
[i
];
913 ALubyte azcount
= azCount
[i
];
914 for(j
= 0;j
< azcount
;j
++)
916 ALsizei lidx
= evoffset
+ j
;
917 ALsizei ridx
= evoffset
+ ((azcount
-j
) % azcount
);
920 for(k
= 0;k
< irSize
;k
++)
921 coeffs
[ridx
*irSize
+ k
][1] = coeffs
[lidx
*irSize
+ k
][0];
922 delays
[ridx
][1] = delays
[lidx
][0];
927 Hrtf
= CreateHrtfStore(rate
, irSize
, evCount
, irCount
, azCount
,
928 evOffset
, coeffs
, delays
, filename
);
938 static void AddFileEntry(vector_EnumeratedHrtf
*list
, const_al_string filename
)
940 EnumeratedHrtf entry
= { AL_STRING_INIT_STATIC(), NULL
};
941 struct HrtfEntry
*loaded_entry
;
942 const EnumeratedHrtf
*iter
;
947 /* Check if this file has already been loaded globally. */
948 loaded_entry
= LoadedHrtfs
;
951 if(alstr_cmp_cstr(filename
, loaded_entry
->filename
) == 0)
953 /* Check if this entry has already been added to the list. */
954 #define MATCH_ENTRY(i) (loaded_entry == (i)->hrtf)
955 VECTOR_FIND_IF(iter
, const EnumeratedHrtf
, *list
, MATCH_ENTRY
);
956 if(iter
!= VECTOR_END(*list
))
958 TRACE("Skipping duplicate file entry %s\n", alstr_get_cstr(filename
));
965 loaded_entry
= loaded_entry
->next
;
970 TRACE("Got new file \"%s\"\n", alstr_get_cstr(filename
));
972 loaded_entry
= al_calloc(DEF_ALIGN
,
973 FAM_SIZE(struct HrtfEntry
, filename
, alstr_length(filename
)+1)
975 loaded_entry
->next
= LoadedHrtfs
;
976 loaded_entry
->handle
= NULL
;
977 strcpy(loaded_entry
->filename
, alstr_get_cstr(filename
));
978 LoadedHrtfs
= loaded_entry
;
981 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
983 name
= strrchr(alstr_get_cstr(filename
), '/');
984 if(!name
) name
= strrchr(alstr_get_cstr(filename
), '\\');
985 if(!name
) name
= alstr_get_cstr(filename
);
988 ext
= strrchr(name
, '.');
993 alstr_copy_cstr(&entry
.name
, name
);
995 alstr_copy_range(&entry
.name
, name
, ext
);
999 snprintf(str
, sizeof(str
), " #%d", i
+1);
1000 alstr_append_cstr(&entry
.name
, str
);
1004 #define MATCH_NAME(i) (alstr_cmp(entry.name, (i)->name) == 0)
1005 VECTOR_FIND_IF(iter
, const EnumeratedHrtf
, *list
, MATCH_NAME
);
1007 } while(iter
!= VECTOR_END(*list
));
1008 entry
.hrtf
= loaded_entry
;
1010 TRACE("Adding entry \"%s\" from file \"%s\"\n", alstr_get_cstr(entry
.name
),
1011 alstr_get_cstr(filename
));
1012 VECTOR_PUSH_BACK(*list
, entry
);
1015 /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
1016 * for input instead of opening the given filename.
1018 static void AddBuiltInEntry(vector_EnumeratedHrtf
*list
, const_al_string filename
, size_t residx
)
1020 EnumeratedHrtf entry
= { AL_STRING_INIT_STATIC(), NULL
};
1021 struct HrtfEntry
*loaded_entry
;
1022 struct Hrtf
*hrtf
= NULL
;
1023 const EnumeratedHrtf
*iter
;
1028 loaded_entry
= LoadedHrtfs
;
1031 if(alstr_cmp_cstr(filename
, loaded_entry
->filename
) == 0)
1033 #define MATCH_ENTRY(i) (loaded_entry == (i)->hrtf)
1034 VECTOR_FIND_IF(iter
, const EnumeratedHrtf
, *list
, MATCH_ENTRY
);
1035 if(iter
!= VECTOR_END(*list
))
1037 TRACE("Skipping duplicate file entry %s\n", alstr_get_cstr(filename
));
1044 loaded_entry
= loaded_entry
->next
;
1049 size_t namelen
= alstr_length(filename
)+32;
1051 TRACE("Got new file \"%s\"\n", alstr_get_cstr(filename
));
1053 loaded_entry
= al_calloc(DEF_ALIGN
,
1054 FAM_SIZE(struct HrtfEntry
, filename
, namelen
)
1056 loaded_entry
->next
= LoadedHrtfs
;
1057 loaded_entry
->handle
= hrtf
;
1058 snprintf(loaded_entry
->filename
, namelen
, "!"SZFMT
"_%s",
1059 residx
, alstr_get_cstr(filename
));
1060 LoadedHrtfs
= loaded_entry
;
1063 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1064 * format update). */
1065 name
= strrchr(alstr_get_cstr(filename
), '/');
1066 if(!name
) name
= strrchr(alstr_get_cstr(filename
), '\\');
1067 if(!name
) name
= alstr_get_cstr(filename
);
1070 ext
= strrchr(name
, '.');
1075 alstr_copy_cstr(&entry
.name
, name
);
1077 alstr_copy_range(&entry
.name
, name
, ext
);
1081 snprintf(str
, sizeof(str
), " #%d", i
+1);
1082 alstr_append_cstr(&entry
.name
, str
);
1086 #define MATCH_NAME(i) (alstr_cmp(entry.name, (i)->name) == 0)
1087 VECTOR_FIND_IF(iter
, const EnumeratedHrtf
, *list
, MATCH_NAME
);
1089 } while(iter
!= VECTOR_END(*list
));
1090 entry
.hrtf
= loaded_entry
;
1092 TRACE("Adding built-in entry \"%s\"\n", alstr_get_cstr(entry
.name
));
1093 VECTOR_PUSH_BACK(*list
, entry
);
1097 #define IDR_DEFAULT_44100_MHR 1
1098 #define IDR_DEFAULT_48000_MHR 2
1100 #ifndef ALSOFT_EMBED_HRTF_DATA
1102 static const ALubyte
*GetResource(int UNUSED(name
), size_t *size
)
1110 #include "default-44100.mhr.h"
1111 #include "default-48000.mhr.h"
1113 static const ALubyte
*GetResource(int name
, size_t *size
)
1115 if(name
== IDR_DEFAULT_44100_MHR
)
1117 *size
= sizeof(hrtf_default_44100
);
1118 return hrtf_default_44100
;
1120 if(name
== IDR_DEFAULT_48000_MHR
)
1122 *size
= sizeof(hrtf_default_48000
);
1123 return hrtf_default_48000
;
1130 vector_EnumeratedHrtf
EnumerateHrtf(const_al_string devname
)
1132 vector_EnumeratedHrtf list
= VECTOR_INIT_STATIC();
1133 const char *defaulthrtf
= "";
1134 const char *pathlist
= "";
1135 bool usedefaults
= true;
1137 if(ConfigValueStr(alstr_get_cstr(devname
), NULL
, "hrtf-paths", &pathlist
))
1139 al_string pname
= AL_STRING_INIT_STATIC();
1140 while(pathlist
&& *pathlist
)
1142 const char *next
, *end
;
1144 while(isspace(*pathlist
) || *pathlist
== ',')
1146 if(*pathlist
== '\0')
1149 next
= strchr(pathlist
, ',');
1154 end
= pathlist
+ strlen(pathlist
);
1155 usedefaults
= false;
1158 while(end
!= pathlist
&& isspace(*(end
-1)))
1162 vector_al_string flist
;
1165 alstr_copy_range(&pname
, pathlist
, end
);
1167 flist
= SearchDataFiles(".mhr", alstr_get_cstr(pname
));
1168 for(i
= 0;i
< VECTOR_SIZE(flist
);i
++)
1169 AddFileEntry(&list
, VECTOR_ELEM(flist
, i
));
1170 VECTOR_FOR_EACH(al_string
, flist
, alstr_reset
);
1171 VECTOR_DEINIT(flist
);
1177 alstr_reset(&pname
);
1179 else if(ConfigValueExists(alstr_get_cstr(devname
), NULL
, "hrtf_tables"))
1180 ERR("The hrtf_tables option is deprecated, please use hrtf-paths instead.\n");
1184 al_string ename
= AL_STRING_INIT_STATIC();
1185 vector_al_string flist
;
1186 const ALubyte
*rdata
;
1189 flist
= SearchDataFiles(".mhr", "openal/hrtf");
1190 for(i
= 0;i
< VECTOR_SIZE(flist
);i
++)
1191 AddFileEntry(&list
, VECTOR_ELEM(flist
, i
));
1192 VECTOR_FOR_EACH(al_string
, flist
, alstr_reset
);
1193 VECTOR_DEINIT(flist
);
1195 rdata
= GetResource(IDR_DEFAULT_44100_MHR
, &rsize
);
1196 if(rdata
!= NULL
&& rsize
> 0)
1198 alstr_copy_cstr(&ename
, "Built-In 44100hz");
1199 AddBuiltInEntry(&list
, ename
, IDR_DEFAULT_44100_MHR
);
1202 rdata
= GetResource(IDR_DEFAULT_48000_MHR
, &rsize
);
1203 if(rdata
!= NULL
&& rsize
> 0)
1205 alstr_copy_cstr(&ename
, "Built-In 48000hz");
1206 AddBuiltInEntry(&list
, ename
, IDR_DEFAULT_48000_MHR
);
1208 alstr_reset(&ename
);
1211 if(VECTOR_SIZE(list
) > 1 && ConfigValueStr(alstr_get_cstr(devname
), NULL
, "default-hrtf", &defaulthrtf
))
1213 const EnumeratedHrtf
*iter
;
1214 /* Find the preferred HRTF and move it to the front of the list. */
1215 #define FIND_ENTRY(i) (alstr_cmp_cstr((i)->name, defaulthrtf) == 0)
1216 VECTOR_FIND_IF(iter
, const EnumeratedHrtf
, list
, FIND_ENTRY
);
1218 if(iter
== VECTOR_END(list
))
1219 WARN("Failed to find default HRTF \"%s\"\n", defaulthrtf
);
1220 else if(iter
!= VECTOR_BEGIN(list
))
1222 EnumeratedHrtf entry
= *iter
;
1223 memmove(&VECTOR_ELEM(list
,1), &VECTOR_ELEM(list
,0),
1224 (iter
-VECTOR_BEGIN(list
))*sizeof(EnumeratedHrtf
));
1225 VECTOR_ELEM(list
,0) = entry
;
1232 void FreeHrtfList(vector_EnumeratedHrtf
*list
)
1234 #define CLEAR_ENTRY(i) alstr_reset(&(i)->name)
1235 VECTOR_FOR_EACH(EnumeratedHrtf
, *list
, CLEAR_ENTRY
);
1236 VECTOR_DEINIT(*list
);
1240 struct Hrtf
*GetLoadedHrtf(struct HrtfEntry
*entry
)
1242 struct Hrtf
*hrtf
= NULL
;
1243 struct FileMapping fmap
;
1244 const ALubyte
*rdata
;
1250 while(ATOMIC_FLAG_TEST_AND_SET(&LoadedHrtfLock
, almemory_order_seq_cst
))
1255 hrtf
= entry
->handle
;
1262 if(sscanf(entry
->filename
, "!"SZFMT
"%c", &residx
, &ch
) == 2 && ch
== '_')
1264 name
= strchr(entry
->filename
, ch
)+1;
1266 TRACE("Loading %s...\n", name
);
1267 rdata
= GetResource(residx
, &rsize
);
1268 if(rdata
== NULL
|| rsize
== 0)
1270 ERR("Could not get resource "SZFMT
", %s\n", residx
, name
);
1276 name
= entry
->filename
;
1278 TRACE("Loading %s...\n", entry
->filename
);
1279 fmap
= MapFileToMem(entry
->filename
);
1280 if(fmap
.ptr
== NULL
)
1282 ERR("Could not open %s\n", entry
->filename
);
1290 if(rsize
< sizeof(magicMarker02
))
1291 ERR("%s data is too short ("SZFMT
" bytes)\n", name
, rsize
);
1292 else if(memcmp(rdata
, magicMarker02
, sizeof(magicMarker02
)) == 0)
1294 TRACE("Detected data set format v2\n");
1295 hrtf
= LoadHrtf02(rdata
+sizeof(magicMarker02
),
1296 rsize
-sizeof(magicMarker02
), name
1299 else if(memcmp(rdata
, magicMarker01
, sizeof(magicMarker01
)) == 0)
1301 TRACE("Detected data set format v1\n");
1302 hrtf
= LoadHrtf01(rdata
+sizeof(magicMarker01
),
1303 rsize
-sizeof(magicMarker01
), name
1306 else if(memcmp(rdata
, magicMarker00
, sizeof(magicMarker00
)) == 0)
1308 TRACE("Detected data set format v0\n");
1309 hrtf
= LoadHrtf00(rdata
+sizeof(magicMarker00
),
1310 rsize
-sizeof(magicMarker00
), name
1314 ERR("Invalid header in %s: \"%.8s\"\n", name
, (const char*)rdata
);
1316 UnmapFileMem(&fmap
);
1320 ERR("Failed to load %s\n", name
);
1323 entry
->handle
= hrtf
;
1326 TRACE("Loaded HRTF support for format: %s %uhz\n",
1327 DevFmtChannelsString(DevFmtStereo
), hrtf
->sampleRate
);
1330 ATOMIC_FLAG_CLEAR(&LoadedHrtfLock
, almemory_order_seq_cst
);
1335 void Hrtf_IncRef(struct Hrtf
*hrtf
)
1337 uint ref
= IncrementRef(&hrtf
->ref
);
1338 TRACEREF("%p increasing refcount to %u\n", hrtf
, ref
);
1341 void Hrtf_DecRef(struct Hrtf
*hrtf
)
1343 struct HrtfEntry
*Hrtf
;
1344 uint ref
= DecrementRef(&hrtf
->ref
);
1345 TRACEREF("%p decreasing refcount to %u\n", hrtf
, ref
);
1348 while(ATOMIC_FLAG_TEST_AND_SET(&LoadedHrtfLock
, almemory_order_seq_cst
))
1354 /* Need to double-check that it's still unused, as another device
1355 * could've reacquired this HRTF after its reference went to 0 and
1356 * before the lock was taken.
1358 if(hrtf
== Hrtf
->handle
&& ReadRef(&hrtf
->ref
) == 0)
1360 al_free(Hrtf
->handle
);
1361 Hrtf
->handle
= NULL
;
1362 TRACE("Unloaded unused HRTF %s\n", Hrtf
->filename
);
1367 ATOMIC_FLAG_CLEAR(&LoadedHrtfLock
, almemory_order_seq_cst
);
1372 void FreeHrtfs(void)
1374 struct HrtfEntry
*Hrtf
= LoadedHrtfs
;
1379 struct HrtfEntry
*next
= Hrtf
->next
;
1380 al_free(Hrtf
->handle
);