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 ALsizei idx
[HRTF_AMBI_MAX_CHANNELS
];
206 ALsizei min_delay
= HRTF_HISTORY_LENGTH
;
207 ALsizei max_delay
= 0;
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
;
234 memset(temps
, 0, sizeof(temps
));
235 bandsplit_init(&splitter
, 400.0f
/ (ALfloat
)Hrtf
->sampleRate
);
236 for(c
= 0;c
< AmbiCount
;c
++)
238 const ALfloat (*fir
)[2] = &Hrtf
->coeffs
[idx
[c
] * Hrtf
->irSize
];
239 const ALsizei res_delay
= mini(Hrtf
->delays
[idx
[c
]][0], Hrtf
->delays
[idx
[c
]][1]);
240 ALsizei ldelay
= Hrtf
->delays
[idx
[c
]][0] - res_delay
;
241 ALsizei rdelay
= Hrtf
->delays
[idx
[c
]][1] - res_delay
;
243 min_delay
= mini(min_delay
, res_delay
);
244 max_delay
= maxi(max_delay
, res_delay
);
246 max_length
= maxi(max_length
,
247 mini(maxi(ldelay
, rdelay
) + Hrtf
->irSize
, HRIR_LENGTH
)
252 for(i
= 0;i
< NumChannels
;++i
)
254 ALfloat hfgain
= AmbiOrderHFGain
[(ALsizei
)floor(sqrt(i
))];
255 ALsizei lidx
= ldelay
, ridx
= rdelay
;
257 while(lidx
< HRIR_LENGTH
&& ridx
< HRIR_LENGTH
&& j
< Hrtf
->irSize
)
259 state
->Chan
[i
].Coeffs
[lidx
++][0] += fir
[j
][0] * AmbiMatrix
[c
][i
] * hfgain
;
260 state
->Chan
[i
].Coeffs
[ridx
++][1] += fir
[j
][1] * AmbiMatrix
[c
][i
] * hfgain
;
267 /* Band-split left HRIR into low and high frequency responses. */
268 bandsplit_clear(&splitter
);
269 for(i
= 0;i
< Hrtf
->irSize
;i
++)
270 temps
[2][i
] = fir
[i
][0];
271 bandsplit_process(&splitter
, temps
[0], temps
[1], temps
[2], HRIR_LENGTH
);
273 /* Apply left ear response with delay. */
274 for(i
= 0;i
< NumChannels
;++i
)
276 ALfloat hfgain
= AmbiOrderHFGain
[(ALsizei
)floor(sqrt(i
))];
277 for(b
= 0;b
< NUM_BANDS
;b
++)
279 ALsizei lidx
= ldelay
;
281 while(lidx
< HRIR_LENGTH
)
282 state
->Chan
[i
].Coeffs
[lidx
++][0] += temps
[b
][j
++] * AmbiMatrix
[c
][i
] *
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 ALsizei ridx
= rdelay
;
302 while(ridx
< HRIR_LENGTH
)
303 state
->Chan
[i
].Coeffs
[ridx
++][1] += temps
[b
][j
++] * AmbiMatrix
[c
][i
] *
310 /* Round up to the next IR size multiple. */
311 max_length
+= MOD_IR_SIZE
-1;
312 max_length
-= max_length
%MOD_IR_SIZE
;
314 TRACE("Skipped delay min: %d, max: %d, new FIR length: %d\n", min_delay
, max_delay
,
316 state
->IrSize
= max_length
;
321 static struct Hrtf
*CreateHrtfStore(ALuint rate
, ALsizei irSize
,
322 ALfloat distance
, ALsizei evCount
, ALsizei irCount
, const ALubyte
*azCount
,
323 const ALushort
*evOffset
, const ALfloat (*coeffs
)[2], const ALubyte (*delays
)[2],
324 const char *filename
)
329 total
= sizeof(struct Hrtf
);
330 total
+= sizeof(Hrtf
->azCount
[0])*evCount
;
331 total
= RoundUp(total
, sizeof(ALushort
)); /* Align for ushort fields */
332 total
+= sizeof(Hrtf
->evOffset
[0])*evCount
;
333 total
= RoundUp(total
, 16); /* Align for coefficients using SIMD */
334 total
+= sizeof(Hrtf
->coeffs
[0])*irSize
*irCount
;
335 total
+= sizeof(Hrtf
->delays
[0])*irCount
;
337 Hrtf
= al_calloc(16, total
);
339 ERR("Out of memory allocating storage for %s.\n", filename
);
342 uintptr_t offset
= sizeof(struct Hrtf
);
343 char *base
= (char*)Hrtf
;
346 ALubyte (*_delays
)[2];
347 ALfloat (*_coeffs
)[2];
350 InitRef(&Hrtf
->ref
, 0);
351 Hrtf
->sampleRate
= rate
;
352 Hrtf
->irSize
= irSize
;
353 Hrtf
->distance
= distance
;
354 Hrtf
->evCount
= evCount
;
356 /* Set up pointers to storage following the main HRTF struct. */
357 _azCount
= (ALubyte
*)(base
+ offset
);
358 offset
+= sizeof(_azCount
[0])*evCount
;
360 offset
= RoundUp(offset
, sizeof(ALushort
)); /* Align for ushort fields */
361 _evOffset
= (ALushort
*)(base
+ offset
);
362 offset
+= sizeof(_evOffset
[0])*evCount
;
364 offset
= RoundUp(offset
, 16); /* Align for coefficients using SIMD */
365 _coeffs
= (ALfloat(*)[2])(base
+ offset
);
366 offset
+= sizeof(_coeffs
[0])*irSize
*irCount
;
368 _delays
= (ALubyte(*)[2])(base
+ offset
);
369 offset
+= sizeof(_delays
[0])*irCount
;
371 assert(offset
== total
);
373 /* Copy input data to storage. */
374 for(i
= 0;i
< evCount
;i
++) _azCount
[i
] = azCount
[i
];
375 for(i
= 0;i
< evCount
;i
++) _evOffset
[i
] = evOffset
[i
];
376 for(i
= 0;i
< irSize
*irCount
;i
++)
378 _coeffs
[i
][0] = coeffs
[i
][0];
379 _coeffs
[i
][1] = coeffs
[i
][1];
381 for(i
= 0;i
< irCount
;i
++)
383 _delays
[i
][0] = delays
[i
][0];
384 _delays
[i
][1] = delays
[i
][1];
387 /* Finally, assign the storage pointers. */
388 Hrtf
->azCount
= _azCount
;
389 Hrtf
->evOffset
= _evOffset
;
390 Hrtf
->coeffs
= _coeffs
;
391 Hrtf
->delays
= _delays
;
397 static ALubyte
GetLE_ALubyte(const ALubyte
**data
, size_t *len
)
399 ALubyte ret
= (*data
)[0];
400 *data
+= 1; *len
-= 1;
404 static ALshort
GetLE_ALshort(const ALubyte
**data
, size_t *len
)
406 ALshort ret
= (*data
)[0] | ((*data
)[1]<<8);
407 *data
+= 2; *len
-= 2;
411 static ALushort
GetLE_ALushort(const ALubyte
**data
, size_t *len
)
413 ALushort ret
= (*data
)[0] | ((*data
)[1]<<8);
414 *data
+= 2; *len
-= 2;
418 static ALint
GetLE_ALint24(const ALubyte
**data
, size_t *len
)
420 ALint ret
= (*data
)[0] | ((*data
)[1]<<8) | ((*data
)[2]<<16);
421 *data
+= 3; *len
-= 3;
422 return (ret
^0x800000) - 0x800000;
425 static ALuint
GetLE_ALuint(const ALubyte
**data
, size_t *len
)
427 ALuint ret
= (*data
)[0] | ((*data
)[1]<<8) | ((*data
)[2]<<16) | ((*data
)[3]<<24);
428 *data
+= 4; *len
-= 4;
432 static const ALubyte
*Get_ALubytePtr(const ALubyte
**data
, size_t *len
, size_t size
)
434 const ALubyte
*ret
= *data
;
435 *data
+= size
; *len
-= size
;
439 static struct Hrtf
*LoadHrtf00(const ALubyte
*data
, size_t datalen
, const char *filename
)
441 struct Hrtf
*Hrtf
= NULL
;
442 ALboolean failed
= AL_FALSE
;
444 ALushort irCount
= 0;
447 ALubyte
*azCount
= NULL
;
448 ALushort
*evOffset
= NULL
;
449 ALfloat (*coeffs
)[2] = NULL
;
450 ALubyte (*delays
)[2] = NULL
;
455 ERR("Unexpected end of %s data (req %d, rem "SZFMT
")\n", filename
, 9, datalen
);
459 rate
= GetLE_ALuint(&data
, &datalen
);
461 irCount
= GetLE_ALushort(&data
, &datalen
);
463 irSize
= GetLE_ALushort(&data
, &datalen
);
465 evCount
= GetLE_ALubyte(&data
, &datalen
);
467 if(irSize
< MIN_IR_SIZE
|| irSize
> MAX_IR_SIZE
|| (irSize
%MOD_IR_SIZE
))
469 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
470 irSize
, MIN_IR_SIZE
, MAX_IR_SIZE
, MOD_IR_SIZE
);
473 if(evCount
< MIN_EV_COUNT
|| evCount
> MAX_EV_COUNT
)
475 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
476 evCount
, MIN_EV_COUNT
, MAX_EV_COUNT
);
482 if(datalen
< evCount
*2u)
484 ERR("Unexpected end of %s data (req %d, rem "SZFMT
")\n", filename
, evCount
*2, datalen
);
488 azCount
= malloc(sizeof(azCount
[0])*evCount
);
489 evOffset
= malloc(sizeof(evOffset
[0])*evCount
);
490 if(azCount
== NULL
|| evOffset
== NULL
)
492 ERR("Out of memory.\n");
498 evOffset
[0] = GetLE_ALushort(&data
, &datalen
);
499 for(i
= 1;i
< evCount
;i
++)
501 evOffset
[i
] = GetLE_ALushort(&data
, &datalen
);
502 if(evOffset
[i
] <= evOffset
[i
-1])
504 ERR("Invalid evOffset: evOffset[%d]=%d (last=%d)\n",
505 i
, evOffset
[i
], evOffset
[i
-1]);
509 azCount
[i
-1] = evOffset
[i
] - evOffset
[i
-1];
510 if(azCount
[i
-1] < MIN_AZ_COUNT
|| azCount
[i
-1] > MAX_AZ_COUNT
)
512 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
513 i
-1, azCount
[i
-1], MIN_AZ_COUNT
, MAX_AZ_COUNT
);
517 if(irCount
<= evOffset
[i
-1])
519 ERR("Invalid evOffset: evOffset[%d]=%d (irCount=%d)\n",
520 i
-1, evOffset
[i
-1], irCount
);
524 azCount
[i
-1] = irCount
- evOffset
[i
-1];
525 if(azCount
[i
-1] < MIN_AZ_COUNT
|| azCount
[i
-1] > MAX_AZ_COUNT
)
527 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
528 i
-1, azCount
[i
-1], MIN_AZ_COUNT
, MAX_AZ_COUNT
);
535 coeffs
= malloc(sizeof(coeffs
[0])*irSize
*irCount
);
536 delays
= malloc(sizeof(delays
[0])*irCount
);
537 if(coeffs
== NULL
|| delays
== NULL
)
539 ERR("Out of memory.\n");
546 size_t reqsize
= 2*irSize
*irCount
+ irCount
;
547 if(datalen
< reqsize
)
549 ERR("Unexpected end of %s data (req "SZFMT
", rem "SZFMT
")\n",
550 filename
, reqsize
, datalen
);
557 for(i
= 0;i
< irCount
;i
++)
559 for(j
= 0;j
< irSize
;j
++)
560 coeffs
[i
*irSize
+ j
][0] = GetLE_ALshort(&data
, &datalen
) / 32768.0f
;
563 for(i
= 0;i
< irCount
;i
++)
565 delays
[i
][0] = GetLE_ALubyte(&data
, &datalen
);
566 if(delays
[i
][0] > MAX_HRIR_DELAY
)
568 ERR("Invalid delays[%d]: %d (%d)\n", i
, delays
[i
][0], MAX_HRIR_DELAY
);
576 /* Mirror the left ear responses to the right ear. */
577 for(i
= 0;i
< evCount
;i
++)
579 ALushort evoffset
= evOffset
[i
];
580 ALubyte azcount
= azCount
[i
];
581 for(j
= 0;j
< azcount
;j
++)
583 ALsizei lidx
= evoffset
+ j
;
584 ALsizei ridx
= evoffset
+ ((azcount
-j
) % azcount
);
587 for(k
= 0;k
< irSize
;k
++)
588 coeffs
[ridx
*irSize
+ k
][1] = coeffs
[lidx
*irSize
+ k
][0];
589 delays
[ridx
][1] = delays
[lidx
][0];
593 Hrtf
= CreateHrtfStore(rate
, irSize
, 0.0f
, evCount
, irCount
, azCount
,
594 evOffset
, coeffs
, delays
, filename
);
604 static struct Hrtf
*LoadHrtf01(const ALubyte
*data
, size_t datalen
, const char *filename
)
606 struct Hrtf
*Hrtf
= NULL
;
607 ALboolean failed
= AL_FALSE
;
609 ALushort irCount
= 0;
612 const ALubyte
*azCount
= NULL
;
613 ALushort
*evOffset
= NULL
;
614 ALfloat (*coeffs
)[2] = NULL
;
615 ALubyte (*delays
)[2] = NULL
;
620 ERR("Unexpected end of %s data (req %d, rem "SZFMT
"\n", filename
, 6, datalen
);
624 rate
= GetLE_ALuint(&data
, &datalen
);
626 irSize
= GetLE_ALubyte(&data
, &datalen
);
628 evCount
= GetLE_ALubyte(&data
, &datalen
);
630 if(irSize
< MIN_IR_SIZE
|| irSize
> MAX_IR_SIZE
|| (irSize
%MOD_IR_SIZE
))
632 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
633 irSize
, MIN_IR_SIZE
, MAX_IR_SIZE
, MOD_IR_SIZE
);
636 if(evCount
< MIN_EV_COUNT
|| evCount
> MAX_EV_COUNT
)
638 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
639 evCount
, MIN_EV_COUNT
, MAX_EV_COUNT
);
645 if(datalen
< evCount
)
647 ERR("Unexpected end of %s data (req %d, rem "SZFMT
"\n", filename
, evCount
, datalen
);
651 azCount
= Get_ALubytePtr(&data
, &datalen
, evCount
);
653 evOffset
= malloc(sizeof(evOffset
[0])*evCount
);
654 if(azCount
== NULL
|| evOffset
== NULL
)
656 ERR("Out of memory.\n");
662 for(i
= 0;i
< evCount
;i
++)
664 if(azCount
[i
] < MIN_AZ_COUNT
|| azCount
[i
] > MAX_AZ_COUNT
)
666 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
667 i
, azCount
[i
], MIN_AZ_COUNT
, MAX_AZ_COUNT
);
676 irCount
= azCount
[0];
677 for(i
= 1;i
< evCount
;i
++)
679 evOffset
[i
] = evOffset
[i
-1] + azCount
[i
-1];
680 irCount
+= azCount
[i
];
683 coeffs
= malloc(sizeof(coeffs
[0])*irSize
*irCount
);
684 delays
= malloc(sizeof(delays
[0])*irCount
);
685 if(coeffs
== NULL
|| delays
== NULL
)
687 ERR("Out of memory.\n");
694 size_t reqsize
= 2*irSize
*irCount
+ irCount
;
695 if(datalen
< reqsize
)
697 ERR("Unexpected end of %s data (req "SZFMT
", rem "SZFMT
"\n",
698 filename
, reqsize
, datalen
);
705 for(i
= 0;i
< irCount
;i
++)
707 for(j
= 0;j
< irSize
;j
++)
708 coeffs
[i
*irSize
+ j
][0] = GetLE_ALshort(&data
, &datalen
) / 32768.0f
;
711 for(i
= 0;i
< irCount
;i
++)
713 delays
[i
][0] = GetLE_ALubyte(&data
, &datalen
);
714 if(delays
[i
][0] > MAX_HRIR_DELAY
)
716 ERR("Invalid delays[%d]: %d (%d)\n", i
, delays
[i
][0], MAX_HRIR_DELAY
);
724 /* Mirror the left ear responses to the right ear. */
725 for(i
= 0;i
< evCount
;i
++)
727 ALushort evoffset
= evOffset
[i
];
728 ALubyte azcount
= azCount
[i
];
729 for(j
= 0;j
< azcount
;j
++)
731 ALsizei lidx
= evoffset
+ j
;
732 ALsizei ridx
= evoffset
+ ((azcount
-j
) % azcount
);
735 for(k
= 0;k
< irSize
;k
++)
736 coeffs
[ridx
*irSize
+ k
][1] = coeffs
[lidx
*irSize
+ k
][0];
737 delays
[ridx
][1] = delays
[lidx
][0];
741 Hrtf
= CreateHrtfStore(rate
, irSize
, 0.0f
, evCount
, irCount
, azCount
,
742 evOffset
, coeffs
, delays
, filename
);
751 #define SAMPLETYPE_S16 0
752 #define SAMPLETYPE_S24 1
754 #define CHANTYPE_LEFTONLY 0
755 #define CHANTYPE_LEFTRIGHT 1
757 static struct Hrtf
*LoadHrtf02(const ALubyte
*data
, size_t datalen
, const char *filename
)
759 struct Hrtf
*Hrtf
= NULL
;
760 ALboolean failed
= AL_FALSE
;
764 ALushort irCount
= 0;
767 ALushort distance
= 0;
769 const ALubyte
*azCount
= NULL
;
770 ALushort
*evOffset
= NULL
;
771 ALfloat (*coeffs
)[2] = NULL
;
772 ALubyte (*delays
)[2] = NULL
;
777 ERR("Unexpected end of %s data (req %d, rem "SZFMT
"\n", filename
, 8, datalen
);
781 rate
= GetLE_ALuint(&data
, &datalen
);
782 sampleType
= GetLE_ALubyte(&data
, &datalen
);
783 channelType
= GetLE_ALubyte(&data
, &datalen
);
785 irSize
= GetLE_ALubyte(&data
, &datalen
);
787 fdCount
= GetLE_ALubyte(&data
, &datalen
);
789 if(sampleType
> SAMPLETYPE_S24
)
791 ERR("Unsupported sample type: %d\n", sampleType
);
794 if(channelType
> CHANTYPE_LEFTRIGHT
)
796 ERR("Unsupported channel type: %d\n", channelType
);
800 if(irSize
< MIN_IR_SIZE
|| irSize
> MAX_IR_SIZE
|| (irSize
%MOD_IR_SIZE
))
802 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
803 irSize
, MIN_IR_SIZE
, MAX_IR_SIZE
, MOD_IR_SIZE
);
808 ERR("Multiple field-depths not supported: fdCount=%d (%d to %d)\n",
809 evCount
, MIN_FD_COUNT
, MAX_FD_COUNT
);
815 for(i
= 0;i
< fdCount
;i
++)
819 ERR("Unexpected end of %s data (req %d, rem "SZFMT
"\n", filename
, 3, datalen
);
823 distance
= GetLE_ALushort(&data
, &datalen
);
824 if(distance
< MIN_FD_DISTANCE
|| distance
> MAX_FD_DISTANCE
)
826 ERR("Unsupported field distance: distance=%d (%dmm to %dmm)\n",
827 distance
, MIN_FD_DISTANCE
, MAX_FD_DISTANCE
);
831 evCount
= GetLE_ALubyte(&data
, &datalen
);
832 if(evCount
< MIN_EV_COUNT
|| evCount
> MAX_EV_COUNT
)
834 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
835 evCount
, MIN_EV_COUNT
, MAX_EV_COUNT
);
841 if(datalen
< evCount
)
843 ERR("Unexpected end of %s data (req %d, rem "SZFMT
"\n", filename
, evCount
, datalen
);
847 azCount
= Get_ALubytePtr(&data
, &datalen
, evCount
);
848 for(j
= 0;j
< evCount
;j
++)
850 if(azCount
[j
] < MIN_AZ_COUNT
|| azCount
[j
] > MAX_AZ_COUNT
)
852 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
853 j
, azCount
[j
], MIN_AZ_COUNT
, MAX_AZ_COUNT
);
861 evOffset
= malloc(sizeof(evOffset
[0])*evCount
);
862 if(azCount
== NULL
|| evOffset
== NULL
)
864 ERR("Out of memory.\n");
871 irCount
= azCount
[0];
872 for(i
= 1;i
< evCount
;i
++)
874 evOffset
[i
] = evOffset
[i
-1] + azCount
[i
-1];
875 irCount
+= azCount
[i
];
878 coeffs
= malloc(sizeof(coeffs
[0])*irSize
*irCount
);
879 delays
= malloc(sizeof(delays
[0])*irCount
);
880 if(coeffs
== NULL
|| delays
== NULL
)
882 ERR("Out of memory.\n");
889 size_t reqsize
= 2*irSize
*irCount
+ irCount
;
890 if(datalen
< reqsize
)
892 ERR("Unexpected end of %s data (req "SZFMT
", rem "SZFMT
"\n",
893 filename
, reqsize
, datalen
);
900 if(channelType
== CHANTYPE_LEFTONLY
)
902 if(sampleType
== SAMPLETYPE_S16
)
903 for(i
= 0;i
< irCount
;i
++)
905 for(j
= 0;j
< irSize
;j
++)
906 coeffs
[i
*irSize
+ j
][0] = GetLE_ALshort(&data
, &datalen
) / 32768.0f
;
908 else if(sampleType
== SAMPLETYPE_S24
)
909 for(i
= 0;i
< irCount
;i
++)
911 for(j
= 0;j
< irSize
;j
++)
912 coeffs
[i
*irSize
+ j
][0] = GetLE_ALint24(&data
, &datalen
) / 8388608.0f
;
915 for(i
= 0;i
< irCount
;i
++)
917 delays
[i
][0] = GetLE_ALubyte(&data
, &datalen
);
918 if(delays
[i
][0] > MAX_HRIR_DELAY
)
920 ERR("Invalid delays[%d][0]: %d (%d)\n", i
, delays
[i
][0], MAX_HRIR_DELAY
);
925 else if(channelType
== CHANTYPE_LEFTRIGHT
)
927 if(sampleType
== SAMPLETYPE_S16
)
928 for(i
= 0;i
< irCount
;i
++)
930 for(j
= 0;j
< irSize
;j
++)
932 coeffs
[i
*irSize
+ j
][0] = GetLE_ALshort(&data
, &datalen
) / 32768.0f
;
933 coeffs
[i
*irSize
+ j
][1] = GetLE_ALshort(&data
, &datalen
) / 32768.0f
;
936 else if(sampleType
== SAMPLETYPE_S24
)
937 for(i
= 0;i
< irCount
;i
++)
939 for(j
= 0;j
< irSize
;j
++)
941 coeffs
[i
*irSize
+ j
][0] = GetLE_ALint24(&data
, &datalen
) / 8388608.0f
;
942 coeffs
[i
*irSize
+ j
][1] = GetLE_ALint24(&data
, &datalen
) / 8388608.0f
;
946 for(i
= 0;i
< irCount
;i
++)
948 delays
[i
][0] = GetLE_ALubyte(&data
, &datalen
);
949 if(delays
[i
][0] > MAX_HRIR_DELAY
)
951 ERR("Invalid delays[%d][0]: %d (%d)\n", i
, delays
[i
][0], MAX_HRIR_DELAY
);
954 delays
[i
][1] = GetLE_ALubyte(&data
, &datalen
);
955 if(delays
[i
][1] > MAX_HRIR_DELAY
)
957 ERR("Invalid delays[%d][1]: %d (%d)\n", i
, delays
[i
][1], MAX_HRIR_DELAY
);
966 if(channelType
== CHANTYPE_LEFTONLY
)
968 /* Mirror the left ear responses to the right ear. */
969 for(i
= 0;i
< evCount
;i
++)
971 ALushort evoffset
= evOffset
[i
];
972 ALubyte azcount
= azCount
[i
];
973 for(j
= 0;j
< azcount
;j
++)
975 ALsizei lidx
= evoffset
+ j
;
976 ALsizei ridx
= evoffset
+ ((azcount
-j
) % azcount
);
979 for(k
= 0;k
< irSize
;k
++)
980 coeffs
[ridx
*irSize
+ k
][1] = coeffs
[lidx
*irSize
+ k
][0];
981 delays
[ridx
][1] = delays
[lidx
][0];
986 Hrtf
= CreateHrtfStore(rate
, irSize
,
987 (ALfloat
)distance
/ 1000.0f
, evCount
, irCount
, azCount
, evOffset
,
988 coeffs
, delays
, filename
999 static void AddFileEntry(vector_EnumeratedHrtf
*list
, const_al_string filename
)
1001 EnumeratedHrtf entry
= { AL_STRING_INIT_STATIC(), NULL
};
1002 struct HrtfEntry
*loaded_entry
;
1003 const EnumeratedHrtf
*iter
;
1008 /* Check if this file has already been loaded globally. */
1009 loaded_entry
= LoadedHrtfs
;
1012 if(alstr_cmp_cstr(filename
, loaded_entry
->filename
) == 0)
1014 /* Check if this entry has already been added to the list. */
1015 #define MATCH_ENTRY(i) (loaded_entry == (i)->hrtf)
1016 VECTOR_FIND_IF(iter
, const EnumeratedHrtf
, *list
, MATCH_ENTRY
);
1017 if(iter
!= VECTOR_END(*list
))
1019 TRACE("Skipping duplicate file entry %s\n", alstr_get_cstr(filename
));
1026 loaded_entry
= loaded_entry
->next
;
1031 TRACE("Got new file \"%s\"\n", alstr_get_cstr(filename
));
1033 loaded_entry
= al_calloc(DEF_ALIGN
,
1034 FAM_SIZE(struct HrtfEntry
, filename
, alstr_length(filename
)+1)
1036 loaded_entry
->next
= LoadedHrtfs
;
1037 loaded_entry
->handle
= NULL
;
1038 strcpy(loaded_entry
->filename
, alstr_get_cstr(filename
));
1039 LoadedHrtfs
= loaded_entry
;
1042 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1043 * format update). */
1044 name
= strrchr(alstr_get_cstr(filename
), '/');
1045 if(!name
) name
= strrchr(alstr_get_cstr(filename
), '\\');
1046 if(!name
) name
= alstr_get_cstr(filename
);
1049 ext
= strrchr(name
, '.');
1054 alstr_copy_cstr(&entry
.name
, name
);
1056 alstr_copy_range(&entry
.name
, name
, ext
);
1060 snprintf(str
, sizeof(str
), " #%d", i
+1);
1061 alstr_append_cstr(&entry
.name
, str
);
1065 #define MATCH_NAME(i) (alstr_cmp(entry.name, (i)->name) == 0)
1066 VECTOR_FIND_IF(iter
, const EnumeratedHrtf
, *list
, MATCH_NAME
);
1068 } while(iter
!= VECTOR_END(*list
));
1069 entry
.hrtf
= loaded_entry
;
1071 TRACE("Adding entry \"%s\" from file \"%s\"\n", alstr_get_cstr(entry
.name
),
1072 alstr_get_cstr(filename
));
1073 VECTOR_PUSH_BACK(*list
, entry
);
1076 /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
1077 * for input instead of opening the given filename.
1079 static void AddBuiltInEntry(vector_EnumeratedHrtf
*list
, const_al_string filename
, ALuint residx
)
1081 EnumeratedHrtf entry
= { AL_STRING_INIT_STATIC(), NULL
};
1082 struct HrtfEntry
*loaded_entry
;
1083 struct Hrtf
*hrtf
= NULL
;
1084 const EnumeratedHrtf
*iter
;
1089 loaded_entry
= LoadedHrtfs
;
1092 if(alstr_cmp_cstr(filename
, loaded_entry
->filename
) == 0)
1094 #define MATCH_ENTRY(i) (loaded_entry == (i)->hrtf)
1095 VECTOR_FIND_IF(iter
, const EnumeratedHrtf
, *list
, MATCH_ENTRY
);
1096 if(iter
!= VECTOR_END(*list
))
1098 TRACE("Skipping duplicate file entry %s\n", alstr_get_cstr(filename
));
1105 loaded_entry
= loaded_entry
->next
;
1110 size_t namelen
= alstr_length(filename
)+32;
1112 TRACE("Got new file \"%s\"\n", alstr_get_cstr(filename
));
1114 loaded_entry
= al_calloc(DEF_ALIGN
,
1115 FAM_SIZE(struct HrtfEntry
, filename
, namelen
)
1117 loaded_entry
->next
= LoadedHrtfs
;
1118 loaded_entry
->handle
= hrtf
;
1119 snprintf(loaded_entry
->filename
, namelen
, "!%u_%s",
1120 residx
, alstr_get_cstr(filename
));
1121 LoadedHrtfs
= loaded_entry
;
1124 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1125 * format update). */
1126 name
= strrchr(alstr_get_cstr(filename
), '/');
1127 if(!name
) name
= strrchr(alstr_get_cstr(filename
), '\\');
1128 if(!name
) name
= alstr_get_cstr(filename
);
1131 ext
= strrchr(name
, '.');
1136 alstr_copy_cstr(&entry
.name
, name
);
1138 alstr_copy_range(&entry
.name
, name
, ext
);
1142 snprintf(str
, sizeof(str
), " #%d", i
+1);
1143 alstr_append_cstr(&entry
.name
, str
);
1147 #define MATCH_NAME(i) (alstr_cmp(entry.name, (i)->name) == 0)
1148 VECTOR_FIND_IF(iter
, const EnumeratedHrtf
, *list
, MATCH_NAME
);
1150 } while(iter
!= VECTOR_END(*list
));
1151 entry
.hrtf
= loaded_entry
;
1153 TRACE("Adding built-in entry \"%s\"\n", alstr_get_cstr(entry
.name
));
1154 VECTOR_PUSH_BACK(*list
, entry
);
1158 #define IDR_DEFAULT_44100_MHR 1
1159 #define IDR_DEFAULT_48000_MHR 2
1161 #ifndef ALSOFT_EMBED_HRTF_DATA
1163 static const ALubyte
*GetResource(int UNUSED(name
), size_t *size
)
1171 #include "default-44100.mhr.h"
1172 #include "default-48000.mhr.h"
1174 static const ALubyte
*GetResource(int name
, size_t *size
)
1176 if(name
== IDR_DEFAULT_44100_MHR
)
1178 *size
= sizeof(hrtf_default_44100
);
1179 return hrtf_default_44100
;
1181 if(name
== IDR_DEFAULT_48000_MHR
)
1183 *size
= sizeof(hrtf_default_48000
);
1184 return hrtf_default_48000
;
1191 vector_EnumeratedHrtf
EnumerateHrtf(const_al_string devname
)
1193 vector_EnumeratedHrtf list
= VECTOR_INIT_STATIC();
1194 const char *defaulthrtf
= "";
1195 const char *pathlist
= "";
1196 bool usedefaults
= true;
1198 if(ConfigValueStr(alstr_get_cstr(devname
), NULL
, "hrtf-paths", &pathlist
))
1200 al_string pname
= AL_STRING_INIT_STATIC();
1201 while(pathlist
&& *pathlist
)
1203 const char *next
, *end
;
1205 while(isspace(*pathlist
) || *pathlist
== ',')
1207 if(*pathlist
== '\0')
1210 next
= strchr(pathlist
, ',');
1215 end
= pathlist
+ strlen(pathlist
);
1216 usedefaults
= false;
1219 while(end
!= pathlist
&& isspace(*(end
-1)))
1223 vector_al_string flist
;
1226 alstr_copy_range(&pname
, pathlist
, end
);
1228 flist
= SearchDataFiles(".mhr", alstr_get_cstr(pname
));
1229 for(i
= 0;i
< VECTOR_SIZE(flist
);i
++)
1230 AddFileEntry(&list
, VECTOR_ELEM(flist
, i
));
1231 VECTOR_FOR_EACH(al_string
, flist
, alstr_reset
);
1232 VECTOR_DEINIT(flist
);
1238 alstr_reset(&pname
);
1240 else if(ConfigValueExists(alstr_get_cstr(devname
), NULL
, "hrtf_tables"))
1241 ERR("The hrtf_tables option is deprecated, please use hrtf-paths instead.\n");
1245 al_string ename
= AL_STRING_INIT_STATIC();
1246 vector_al_string flist
;
1247 const ALubyte
*rdata
;
1250 flist
= SearchDataFiles(".mhr", "openal/hrtf");
1251 for(i
= 0;i
< VECTOR_SIZE(flist
);i
++)
1252 AddFileEntry(&list
, VECTOR_ELEM(flist
, i
));
1253 VECTOR_FOR_EACH(al_string
, flist
, alstr_reset
);
1254 VECTOR_DEINIT(flist
);
1256 rdata
= GetResource(IDR_DEFAULT_44100_MHR
, &rsize
);
1257 if(rdata
!= NULL
&& rsize
> 0)
1259 alstr_copy_cstr(&ename
, "Built-In 44100hz");
1260 AddBuiltInEntry(&list
, ename
, IDR_DEFAULT_44100_MHR
);
1263 rdata
= GetResource(IDR_DEFAULT_48000_MHR
, &rsize
);
1264 if(rdata
!= NULL
&& rsize
> 0)
1266 alstr_copy_cstr(&ename
, "Built-In 48000hz");
1267 AddBuiltInEntry(&list
, ename
, IDR_DEFAULT_48000_MHR
);
1269 alstr_reset(&ename
);
1272 if(VECTOR_SIZE(list
) > 1 && ConfigValueStr(alstr_get_cstr(devname
), NULL
, "default-hrtf", &defaulthrtf
))
1274 const EnumeratedHrtf
*iter
;
1275 /* Find the preferred HRTF and move it to the front of the list. */
1276 #define FIND_ENTRY(i) (alstr_cmp_cstr((i)->name, defaulthrtf) == 0)
1277 VECTOR_FIND_IF(iter
, const EnumeratedHrtf
, list
, FIND_ENTRY
);
1279 if(iter
== VECTOR_END(list
))
1280 WARN("Failed to find default HRTF \"%s\"\n", defaulthrtf
);
1281 else if(iter
!= VECTOR_BEGIN(list
))
1283 EnumeratedHrtf entry
= *iter
;
1284 memmove(&VECTOR_ELEM(list
,1), &VECTOR_ELEM(list
,0),
1285 (iter
-VECTOR_BEGIN(list
))*sizeof(EnumeratedHrtf
));
1286 VECTOR_ELEM(list
,0) = entry
;
1293 void FreeHrtfList(vector_EnumeratedHrtf
*list
)
1295 #define CLEAR_ENTRY(i) alstr_reset(&(i)->name)
1296 VECTOR_FOR_EACH(EnumeratedHrtf
, *list
, CLEAR_ENTRY
);
1297 VECTOR_DEINIT(*list
);
1301 struct Hrtf
*GetLoadedHrtf(struct HrtfEntry
*entry
)
1303 struct Hrtf
*hrtf
= NULL
;
1304 struct FileMapping fmap
;
1305 const ALubyte
*rdata
;
1311 while(ATOMIC_FLAG_TEST_AND_SET(&LoadedHrtfLock
, almemory_order_seq_cst
))
1316 hrtf
= entry
->handle
;
1323 if(sscanf(entry
->filename
, "!%u%c", &residx
, &ch
) == 2 && ch
== '_')
1325 name
= strchr(entry
->filename
, ch
)+1;
1327 TRACE("Loading %s...\n", name
);
1328 rdata
= GetResource(residx
, &rsize
);
1329 if(rdata
== NULL
|| rsize
== 0)
1331 ERR("Could not get resource %u, %s\n", residx
, name
);
1337 name
= entry
->filename
;
1339 TRACE("Loading %s...\n", entry
->filename
);
1340 fmap
= MapFileToMem(entry
->filename
);
1341 if(fmap
.ptr
== NULL
)
1343 ERR("Could not open %s\n", entry
->filename
);
1351 if(rsize
< sizeof(magicMarker02
))
1352 ERR("%s data is too short ("SZFMT
" bytes)\n", name
, rsize
);
1353 else if(memcmp(rdata
, magicMarker02
, sizeof(magicMarker02
)) == 0)
1355 TRACE("Detected data set format v2\n");
1356 hrtf
= LoadHrtf02(rdata
+sizeof(magicMarker02
),
1357 rsize
-sizeof(magicMarker02
), name
1360 else if(memcmp(rdata
, magicMarker01
, sizeof(magicMarker01
)) == 0)
1362 TRACE("Detected data set format v1\n");
1363 hrtf
= LoadHrtf01(rdata
+sizeof(magicMarker01
),
1364 rsize
-sizeof(magicMarker01
), name
1367 else if(memcmp(rdata
, magicMarker00
, sizeof(magicMarker00
)) == 0)
1369 TRACE("Detected data set format v0\n");
1370 hrtf
= LoadHrtf00(rdata
+sizeof(magicMarker00
),
1371 rsize
-sizeof(magicMarker00
), name
1375 ERR("Invalid header in %s: \"%.8s\"\n", name
, (const char*)rdata
);
1377 UnmapFileMem(&fmap
);
1381 ERR("Failed to load %s\n", name
);
1384 entry
->handle
= hrtf
;
1387 TRACE("Loaded HRTF support for format: %s %uhz\n",
1388 DevFmtChannelsString(DevFmtStereo
), hrtf
->sampleRate
);
1391 ATOMIC_FLAG_CLEAR(&LoadedHrtfLock
, almemory_order_seq_cst
);
1396 void Hrtf_IncRef(struct Hrtf
*hrtf
)
1398 uint ref
= IncrementRef(&hrtf
->ref
);
1399 TRACEREF("%p increasing refcount to %u\n", hrtf
, ref
);
1402 void Hrtf_DecRef(struct Hrtf
*hrtf
)
1404 struct HrtfEntry
*Hrtf
;
1405 uint ref
= DecrementRef(&hrtf
->ref
);
1406 TRACEREF("%p decreasing refcount to %u\n", hrtf
, ref
);
1409 while(ATOMIC_FLAG_TEST_AND_SET(&LoadedHrtfLock
, almemory_order_seq_cst
))
1415 /* Need to double-check that it's still unused, as another device
1416 * could've reacquired this HRTF after its reference went to 0 and
1417 * before the lock was taken.
1419 if(hrtf
== Hrtf
->handle
&& ReadRef(&hrtf
->ref
) == 0)
1421 al_free(Hrtf
->handle
);
1422 Hrtf
->handle
= NULL
;
1423 TRACE("Unloaded unused HRTF %s\n", Hrtf
->filename
);
1428 ATOMIC_FLAG_CLEAR(&LoadedHrtfLock
, almemory_order_seq_cst
);
1433 void FreeHrtfs(void)
1435 struct HrtfEntry
*Hrtf
= LoadedHrtfs
;
1440 struct HrtfEntry
*next
= Hrtf
->next
;
1441 al_free(Hrtf
->handle
);