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"
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)
59 struct HrtfEntry
*next
;
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
80 static ALsizei
CalcEvIndex(ALsizei evcount
, ALfloat ev
, ALfloat
*mu
)
83 ev
= (F_PI_2
+ev
) * (evcount
-1) / F_PI
;
84 idx
= mini(fastf2i(ev
), evcount
-1);
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-
94 static ALsizei
CalcAzIndex(ALsizei azcount
, ALfloat az
, ALfloat
*mu
)
97 az
= (F_TAU
+az
) * azcount
/ F_TAU
;
99 idx
= fastf2i(az
) % azcount
;
100 *mu
= az
- floorf(az
);
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];
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. */
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
]);
144 /* If the lower elevation is the top index, the upper elevation is the
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. */
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
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
++)
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.
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;
212 for(c
= 0;c
< AmbiCount
;c
++)
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
)
252 for(i
= 0;i
< NumChannels
;++i
)
254 ALdouble mult
= (ALdouble
)AmbiOrderHFGain
[(ALsizei
)floor(sqrt(i
))] *
256 ALsizei lidx
= ldelay
, ridx
= rdelay
;
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
;
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
;
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
;
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
)
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];
326 TRACE("Skipped delay: %d, new FIR length: %d\n", min_delay
, max_length
);
327 state
->IrSize
= max_length
;
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
)
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
);
350 ERR("Out of memory allocating storage for %s.\n", filename
);
353 uintptr_t offset
= sizeof(struct Hrtf
);
354 char *base
= (char*)Hrtf
;
357 ALubyte (*_delays
)[2];
358 ALfloat (*_coeffs
)[2];
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
;
408 static ALubyte
GetLE_ALubyte(const ALubyte
**data
, size_t *len
)
410 ALubyte ret
= (*data
)[0];
411 *data
+= 1; *len
-= 1;
415 static ALshort
GetLE_ALshort(const ALubyte
**data
, size_t *len
)
417 ALshort ret
= (*data
)[0] | ((*data
)[1]<<8);
418 *data
+= 2; *len
-= 2;
422 static ALushort
GetLE_ALushort(const ALubyte
**data
, size_t *len
)
424 ALushort ret
= (*data
)[0] | ((*data
)[1]<<8);
425 *data
+= 2; *len
-= 2;
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;
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
;
450 static struct Hrtf
*LoadHrtf00(const ALubyte
*data
, size_t datalen
, const char *filename
)
452 struct Hrtf
*Hrtf
= NULL
;
453 ALboolean failed
= AL_FALSE
;
455 ALushort irCount
= 0;
458 ALubyte
*azCount
= NULL
;
459 ALushort
*evOffset
= NULL
;
460 ALfloat (*coeffs
)[2] = NULL
;
461 ALubyte (*delays
)[2] = NULL
;
466 ERR("Unexpected end of %s data (req %d, rem "SZFMT
")\n", filename
, 9, datalen
);
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
);
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
);
493 if(datalen
< evCount
*2u)
495 ERR("Unexpected end of %s data (req %d, rem "SZFMT
")\n", filename
, evCount
*2, datalen
);
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");
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]);
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
);
528 if(irCount
<= evOffset
[i
-1])
530 ERR("Invalid evOffset: evOffset[%d]=%d (irCount=%d)\n",
531 i
-1, evOffset
[i
-1], irCount
);
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
);
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");
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
);
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
);
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
);
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
);
615 static struct Hrtf
*LoadHrtf01(const ALubyte
*data
, size_t datalen
, const char *filename
)
617 struct Hrtf
*Hrtf
= NULL
;
618 ALboolean failed
= AL_FALSE
;
620 ALushort irCount
= 0;
623 const ALubyte
*azCount
= NULL
;
624 ALushort
*evOffset
= NULL
;
625 ALfloat (*coeffs
)[2] = NULL
;
626 ALubyte (*delays
)[2] = NULL
;
631 ERR("Unexpected end of %s data (req %d, rem "SZFMT
"\n", filename
, 6, datalen
);
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
);
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
);
656 if(datalen
< evCount
)
658 ERR("Unexpected end of %s data (req %d, rem "SZFMT
"\n", filename
, evCount
, datalen
);
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");
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
);
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");
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
);
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
);
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
);
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
);
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
;
775 ALushort irCount
= 0;
778 ALushort distance
= 0;
780 const ALubyte
*azCount
= NULL
;
781 ALushort
*evOffset
= NULL
;
782 ALfloat (*coeffs
)[2] = NULL
;
783 ALubyte (*delays
)[2] = NULL
;
788 ERR("Unexpected end of %s data (req %d, rem "SZFMT
"\n", filename
, 8, datalen
);
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
);
805 if(channelType
> CHANTYPE_LEFTRIGHT
)
807 ERR("Unsupported channel type: %d\n", channelType
);
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
);
819 ERR("Multiple field-depths not supported: fdCount=%d (%d to %d)\n",
820 evCount
, MIN_FD_COUNT
, MAX_FD_COUNT
);
826 for(i
= 0;i
< fdCount
;i
++)
830 ERR("Unexpected end of %s data (req %d, rem "SZFMT
"\n", filename
, 3, datalen
);
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
);
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
);
852 if(datalen
< evCount
)
854 ERR("Unexpected end of %s data (req %d, rem "SZFMT
"\n", filename
, evCount
, datalen
);
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
);
872 evOffset
= malloc(sizeof(evOffset
[0])*evCount
);
873 if(azCount
== NULL
|| evOffset
== NULL
)
875 ERR("Out of memory.\n");
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");
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
);
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
);
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
);
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
);
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
);
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
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
;
1019 /* Check if this file has already been loaded globally. */
1020 loaded_entry
= LoadedHrtfs
;
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
));
1037 loaded_entry
= loaded_entry
->next
;
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
);
1060 ext
= strrchr(name
, '.');
1065 alstr_copy_cstr(&entry
.name
, name
);
1067 alstr_copy_range(&entry
.name
, name
, ext
);
1071 snprintf(str
, sizeof(str
), " #%d", i
+1);
1072 alstr_append_cstr(&entry
.name
, str
);
1076 #define MATCH_NAME(i) (alstr_cmp(entry.name, (i)->name) == 0)
1077 VECTOR_FIND_IF(iter
, const EnumeratedHrtf
, *list
, 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
;
1100 loaded_entry
= LoadedHrtfs
;
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
));
1116 loaded_entry
= loaded_entry
->next
;
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
);
1142 ext
= strrchr(name
, '.');
1147 alstr_copy_cstr(&entry
.name
, name
);
1149 alstr_copy_range(&entry
.name
, name
, ext
);
1153 snprintf(str
, sizeof(str
), " #%d", i
+1);
1154 alstr_append_cstr(&entry
.name
, str
);
1158 #define MATCH_NAME(i) (alstr_cmp(entry.name, (i)->name) == 0)
1159 VECTOR_FIND_IF(iter
, const EnumeratedHrtf
, *list
, 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
)
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
;
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
== ',')
1218 if(*pathlist
== '\0')
1221 next
= strchr(pathlist
, ',');
1226 end
= pathlist
+ strlen(pathlist
);
1227 usedefaults
= false;
1230 while(end
!= pathlist
&& isspace(*(end
-1)))
1234 vector_al_string flist
;
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
);
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");
1256 al_string ename
= AL_STRING_INIT_STATIC();
1257 vector_al_string flist
;
1258 const ALubyte
*rdata
;
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
);
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
;
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
);
1312 struct Hrtf
*GetLoadedHrtf(struct HrtfEntry
*entry
)
1314 struct Hrtf
*hrtf
= NULL
;
1315 struct FileMapping fmap
;
1316 const ALubyte
*rdata
;
1322 while(ATOMIC_FLAG_TEST_AND_SET(&LoadedHrtfLock
, almemory_order_seq_cst
))
1327 hrtf
= entry
->handle
;
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
);
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
);
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
1386 ERR("Invalid header in %s: \"%.8s\"\n", name
, (const char*)rdata
);
1388 UnmapFileMem(&fmap
);
1392 ERR("Failed to load %s\n", name
);
1395 entry
->handle
= hrtf
;
1398 TRACE("Loaded HRTF support for format: %s %uhz\n",
1399 DevFmtChannelsString(DevFmtStereo
), hrtf
->sampleRate
);
1402 ATOMIC_FLAG_CLEAR(&LoadedHrtfLock
, almemory_order_seq_cst
);
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
);
1420 while(ATOMIC_FLAG_TEST_AND_SET(&LoadedHrtfLock
, almemory_order_seq_cst
))
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
);
1439 ATOMIC_FLAG_CLEAR(&LoadedHrtfLock
, almemory_order_seq_cst
);
1444 void FreeHrtfs(void)
1446 struct HrtfEntry
*Hrtf
= LoadedHrtfs
;
1451 struct HrtfEntry
*next
= Hrtf
->next
;
1452 al_free(Hrtf
->handle
);