Update the B-Format HRTF coefficients to use the pseudo-inverse matrix
[openal-soft.git] / Alc / hrtf.c
blob3249868d22e91b1141ffe5667b3ca01f6018eb20
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 2011 by Chris Robinson
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
21 #include "config.h"
23 #include <stdlib.h>
24 #include <ctype.h>
26 #include "AL/al.h"
27 #include "AL/alc.h"
28 #include "alMain.h"
29 #include "alSource.h"
30 #include "alu.h"
31 #include "bformatdec.h"
32 #include "hrtf.h"
34 #include "compat.h"
35 #include "almalloc.h"
38 /* Current data set limits defined by the makehrtf utility. */
39 #define MIN_IR_SIZE (8)
40 #define MAX_IR_SIZE (128)
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)
49 static const ALchar magicMarker00[8] = "MinPHR00";
50 static const ALchar magicMarker01[8] = "MinPHR01";
52 /* First value for pass-through coefficients (remaining are 0), used for omni-
53 * directional sounds. */
54 static const ALfloat PassthruCoeff = 32767.0f * 0.707106781187f/*sqrt(0.5)*/;
56 static struct Hrtf *LoadedHrtfs = NULL;
59 /* Calculate the elevation index given the polar elevation in radians. This
60 * will return an index between 0 and (evcount - 1). Assumes the FPU is in
61 * round-to-zero mode.
63 static ALuint CalcEvIndex(ALuint evcount, ALfloat ev)
65 ev = (F_PI_2 + ev) * (evcount-1) / F_PI;
66 return minu(fastf2u(ev + 0.5f), evcount-1);
69 /* Calculate the azimuth index given the polar azimuth in radians. This will
70 * return an index between 0 and (azcount - 1). Assumes the FPU is in round-to-
71 * zero mode.
73 static ALuint CalcAzIndex(ALuint azcount, ALfloat az)
75 az = (F_TAU + az) * azcount / F_TAU;
76 return fastf2u(az + 0.5f) % azcount;
79 /* Calculates static HRIR coefficients and delays for the given polar elevation
80 * and azimuth in radians. The coefficients are normalized and attenuated by
81 * the specified gain.
83 void GetHrtfCoeffs(const struct Hrtf *Hrtf, ALfloat elevation, ALfloat azimuth, ALfloat spread, ALfloat gain, ALfloat (*coeffs)[2], ALuint *delays)
85 ALuint evidx, azidx, lidx, ridx;
86 ALuint azcount, evoffset;
87 ALfloat dirfact;
88 ALuint i;
90 dirfact = 1.0f - (spread / F_TAU);
92 /* Claculate elevation index. */
93 evidx = CalcEvIndex(Hrtf->evCount, elevation);
94 azcount = Hrtf->azCount[evidx];
95 evoffset = Hrtf->evOffset[evidx];
97 /* Calculate azimuth index. */
98 azidx = CalcAzIndex(Hrtf->azCount[evidx], azimuth);
100 /* Calculate the HRIR indices for left and right channels. */
101 lidx = evoffset + azidx;
102 ridx = evoffset + ((azcount-azidx) % azcount);
104 /* Calculate the HRIR delays. */
105 delays[0] = fastf2u(Hrtf->delays[lidx]*dirfact + 0.5f) << HRTFDELAY_BITS;
106 delays[1] = fastf2u(Hrtf->delays[ridx]*dirfact + 0.5f) << HRTFDELAY_BITS;
108 /* Calculate the sample offsets for the HRIR indices. */
109 lidx *= Hrtf->irSize;
110 ridx *= Hrtf->irSize;
112 /* Calculate the normalized and attenuated HRIR coefficients. Zero the
113 * coefficients if gain is too low.
115 if(gain > 0.0001f)
117 gain /= 32767.0f;
119 i = 0;
120 coeffs[i][0] = lerp(PassthruCoeff, Hrtf->coeffs[lidx+i], dirfact)*gain;
121 coeffs[i][1] = lerp(PassthruCoeff, Hrtf->coeffs[ridx+i], dirfact)*gain;
122 for(i = 1;i < Hrtf->irSize;i++)
124 coeffs[i][0] = Hrtf->coeffs[lidx+i]*gain * dirfact;
125 coeffs[i][1] = Hrtf->coeffs[ridx+i]*gain * dirfact;
128 else
130 for(i = 0;i < Hrtf->irSize;i++)
132 coeffs[i][0] = 0.0f;
133 coeffs[i][1] = 0.0f;
139 ALuint BuildBFormatHrtf(const struct Hrtf *Hrtf, ALfloat (*coeffs)[HRIR_LENGTH][2], ALuint NumChannels)
141 static const struct {
142 ALfloat elevation;
143 ALfloat azimuth;
144 } Ambi3DPoints[14] = {
145 { DEG2RAD( 90.0f), DEG2RAD( 0.0f) },
146 { DEG2RAD( 35.0f), DEG2RAD( -45.0f) },
147 { DEG2RAD( 35.0f), DEG2RAD( 45.0f) },
148 { DEG2RAD( 35.0f), DEG2RAD( 135.0f) },
149 { DEG2RAD( 35.0f), DEG2RAD(-135.0f) },
150 { DEG2RAD( 0.0f), DEG2RAD( 0.0f) },
151 { DEG2RAD( 0.0f), DEG2RAD( 90.0f) },
152 { DEG2RAD( 0.0f), DEG2RAD( 180.0f) },
153 { DEG2RAD( 0.0f), DEG2RAD( -90.0f) },
154 { DEG2RAD(-35.0f), DEG2RAD( -45.0f) },
155 { DEG2RAD(-35.0f), DEG2RAD( 45.0f) },
156 { DEG2RAD(-35.0f), DEG2RAD( 135.0f) },
157 { DEG2RAD(-35.0f), DEG2RAD(-135.0f) },
158 { DEG2RAD(-90.0f), DEG2RAD( 0.0f) },
160 static const ALfloat Ambi3DMatrix[14][2][MAX_AMBI_COEFFS] = {
161 { { 0.1889822365f, 0.0000000000f, 0.1889822365f, 0.0000000000f }, { 0.0714285714f, 0.0000000000f, 0.1237180798f, 0.0000000000f } },
162 { { 0.1889822365f, 0.1091089451f, 0.1091089451f, 0.1091089451f }, { 0.0714285714f, 0.0714285714f, 0.0714285714f, 0.0714285714f } },
163 { { 0.1889822365f, -0.1091089451f, 0.1091089451f, 0.1091089451f }, { 0.0714285714f, -0.0714285714f, 0.0714285714f, 0.0714285714f } },
164 { { 0.1889822365f, -0.1091089451f, 0.1091089451f, -0.1091089451f }, { 0.0714285714f, -0.0714285714f, 0.0714285714f, -0.0714285714f } },
165 { { 0.1889822365f, 0.1091089451f, 0.1091089451f, -0.1091089451f }, { 0.0714285714f, 0.0714285714f, 0.0714285714f, -0.0714285714f } },
166 { { 0.1889822365f, 0.0000000000f, 0.0000000000f, 0.1889822365f }, { 0.0714285714f, 0.0000000000f, 0.0000000000f, 0.1237180798f } },
167 { { 0.1889822365f, -0.1889822365f, 0.0000000000f, 0.0000000000f }, { 0.0714285714f, -0.1237180798f, 0.0000000000f, 0.0000000000f } },
168 { { 0.1889822365f, 0.0000000000f, 0.0000000000f, -0.1889822365f }, { 0.0714285714f, 0.0000000000f, 0.0000000000f, -0.1237180798f } },
169 { { 0.1889822365f, 0.1889822365f, 0.0000000000f, 0.0000000000f }, { 0.0714285714f, 0.1237180798f, 0.0000000000f, 0.0000000000f } },
170 { { 0.1889822365f, 0.1091089451f, -0.1091089451f, 0.1091089451f }, { 0.0714285714f, 0.0714285714f, -0.0714285714f, 0.0714285714f } },
171 { { 0.1889822365f, -0.1091089451f, -0.1091089451f, 0.1091089451f }, { 0.0714285714f, -0.0714285714f, -0.0714285714f, 0.0714285714f } },
172 { { 0.1889822365f, -0.1091089451f, -0.1091089451f, -0.1091089451f }, { 0.0714285714f, -0.0714285714f, -0.0714285714f, -0.0714285714f } },
173 { { 0.1889822365f, 0.1091089451f, -0.1091089451f, -0.1091089451f }, { 0.0714285714f, 0.0714285714f, -0.0714285714f, -0.0714285714f } },
174 { { 0.1889822365f, 0.0000000000f, -0.1889822365f, 0.0000000000f }, { 0.0714285714f, 0.0000000000f, -0.1237180798f, 0.0000000000f } },
177 /* Change this to 2 for dual-band HRTF processing. May require a higher quality
178 * band-splitter, or better calculation of the new IR length to deal with the
179 * tail generated by the filter.
181 #define NUM_BANDS 2
182 BandSplitter splitter;
183 ALfloat temps[3][HRIR_LENGTH];
184 ALuint lidx[14], ridx[14];
185 ALuint min_delay = HRTF_HISTORY_LENGTH;
186 ALuint max_length = 0;
187 ALuint i, j, c, b;
189 assert(NumChannels == 4);
191 for(c = 0;c < COUNTOF(Ambi3DPoints);c++)
193 ALuint evidx, azidx;
194 ALuint evoffset;
195 ALuint azcount;
197 /* Calculate elevation index. */
198 evidx = (ALuint)floorf((F_PI_2 + Ambi3DPoints[c].elevation) *
199 (Hrtf->evCount-1)/F_PI + 0.5f);
200 evidx = minu(evidx, Hrtf->evCount-1);
202 azcount = Hrtf->azCount[evidx];
203 evoffset = Hrtf->evOffset[evidx];
205 /* Calculate azimuth index for this elevation. */
206 azidx = (ALuint)floorf((F_TAU+Ambi3DPoints[c].azimuth) *
207 azcount/F_TAU + 0.5f) % azcount;
209 /* Calculate indices for left and right channels. */
210 lidx[c] = evoffset + azidx;
211 ridx[c] = evoffset + ((azcount-azidx) % azcount);
213 min_delay = minu(min_delay, minu(Hrtf->delays[lidx[c]], Hrtf->delays[ridx[c]]));
216 memset(temps, 0, sizeof(temps));
217 bandsplit_init(&splitter, 400.0f / (ALfloat)Hrtf->sampleRate);
218 for(c = 0;c < COUNTOF(Ambi3DMatrix);c++)
220 const ALshort *fir;
221 ALuint delay;
223 /* Convert the left FIR from shorts to float */
224 fir = &Hrtf->coeffs[lidx[c] * Hrtf->irSize];
225 if(NUM_BANDS == 1)
227 for(i = 0;i < Hrtf->irSize;i++)
228 temps[0][i] = fir[i] / 32767.0f;
230 else
232 /* Band-split left HRIR into low and high frequency responses. */
233 bandsplit_clear(&splitter);
234 for(i = 0;i < Hrtf->irSize;i++)
235 temps[2][i] = fir[i] / 32767.0f;
236 bandsplit_process(&splitter, temps[0], temps[1], temps[2], HRIR_LENGTH);
239 /* Add to the left output coefficients with the specified delay. */
240 delay = Hrtf->delays[lidx[c]] - min_delay;
241 for(i = 0;i < NumChannels;++i)
243 for(b = 0;b < NUM_BANDS;b++)
245 ALuint k = 0;
246 for(j = delay;j < HRIR_LENGTH;++j)
247 coeffs[i][j][0] += temps[b][k++] * Ambi3DMatrix[c][b][i];
250 max_length = maxu(max_length, minu(delay + Hrtf->irSize, HRIR_LENGTH));
252 /* Convert the right FIR from shorts to float */
253 fir = &Hrtf->coeffs[ridx[c] * Hrtf->irSize];
254 if(NUM_BANDS == 1)
256 for(i = 0;i < Hrtf->irSize;i++)
257 temps[0][i] = fir[i] / 32767.0f;
259 else
261 /* Band-split right HRIR into low and high frequency responses. */
262 bandsplit_clear(&splitter);
263 for(i = 0;i < Hrtf->irSize;i++)
264 temps[2][i] = fir[i] / 32767.0f;
265 bandsplit_process(&splitter, temps[0], temps[1], temps[2], HRIR_LENGTH);
268 /* Add to the right output coefficients with the specified delay. */
269 delay = Hrtf->delays[ridx[c]] - min_delay;
270 for(i = 0;i < NumChannels;++i)
272 for(b = 0;b < NUM_BANDS;b++)
274 ALuint k = 0;
275 for(j = delay;j < HRIR_LENGTH;++j)
276 coeffs[i][j][1] += temps[b][k++] * Ambi3DMatrix[c][b][i];
279 max_length = maxu(max_length, minu(delay + Hrtf->irSize, HRIR_LENGTH));
281 TRACE("Skipped min delay: %u, new combined length: %u\n", min_delay, max_length);
282 #undef NUM_BANDS
284 return max_length;
288 static struct Hrtf *LoadHrtf00(const ALubyte *data, size_t datalen, const_al_string filename)
290 const ALubyte maxDelay = HRTF_HISTORY_LENGTH-1;
291 struct Hrtf *Hrtf = NULL;
292 ALboolean failed = AL_FALSE;
293 ALuint rate = 0, irCount = 0;
294 ALushort irSize = 0;
295 ALubyte evCount = 0;
296 ALubyte *azCount = NULL;
297 ALushort *evOffset = NULL;
298 ALshort *coeffs = NULL;
299 const ALubyte *delays = NULL;
300 ALuint i, j;
302 if(datalen < 9)
304 ERR("Unexpected end of %s data (req %d, rem "SZFMT")\n",
305 al_string_get_cstr(filename), 9, datalen);
306 return NULL;
309 rate = *(data++);
310 rate |= *(data++)<<8;
311 rate |= *(data++)<<16;
312 rate |= *(data++)<<24;
313 datalen -= 4;
315 irCount = *(data++);
316 irCount |= *(data++)<<8;
317 datalen -= 2;
319 irSize = *(data++);
320 irSize |= *(data++)<<8;
321 datalen -= 2;
323 evCount = *(data++);
324 datalen -= 1;
326 if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
328 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
329 irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
330 failed = AL_TRUE;
332 if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
334 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
335 evCount, MIN_EV_COUNT, MAX_EV_COUNT);
336 failed = AL_TRUE;
338 if(failed)
339 return NULL;
341 if(datalen < evCount*2)
343 ERR("Unexpected end of %s data (req %d, rem "SZFMT")\n",
344 al_string_get_cstr(filename), evCount*2, datalen);
345 return NULL;
348 azCount = malloc(sizeof(azCount[0])*evCount);
349 evOffset = malloc(sizeof(evOffset[0])*evCount);
350 if(azCount == NULL || evOffset == NULL)
352 ERR("Out of memory.\n");
353 failed = AL_TRUE;
356 if(!failed)
358 evOffset[0] = *(data++);
359 evOffset[0] |= *(data++)<<8;
360 datalen -= 2;
361 for(i = 1;i < evCount;i++)
363 evOffset[i] = *(data++);
364 evOffset[i] |= *(data++)<<8;
365 datalen -= 2;
366 if(evOffset[i] <= evOffset[i-1])
368 ERR("Invalid evOffset: evOffset[%d]=%d (last=%d)\n",
369 i, evOffset[i], evOffset[i-1]);
370 failed = AL_TRUE;
373 azCount[i-1] = evOffset[i] - evOffset[i-1];
374 if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
376 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
377 i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
378 failed = AL_TRUE;
381 if(irCount <= evOffset[i-1])
383 ERR("Invalid evOffset: evOffset[%d]=%d (irCount=%d)\n",
384 i-1, evOffset[i-1], irCount);
385 failed = AL_TRUE;
388 azCount[i-1] = irCount - evOffset[i-1];
389 if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
391 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
392 i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
393 failed = AL_TRUE;
397 if(!failed)
399 coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
400 if(coeffs == NULL)
402 ERR("Out of memory.\n");
403 failed = AL_TRUE;
407 if(!failed)
409 size_t reqsize = 2*irSize*irCount + irCount;
410 if(datalen < reqsize)
412 ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT")\n",
413 al_string_get_cstr(filename), reqsize, datalen);
414 failed = AL_TRUE;
418 if(!failed)
420 for(i = 0;i < irCount*irSize;i+=irSize)
422 for(j = 0;j < irSize;j++)
424 coeffs[i+j] = *(data++);
425 coeffs[i+j] |= *(data++)<<8;
426 datalen -= 2;
430 delays = data;
431 data += irCount;
432 datalen -= irCount;
433 for(i = 0;i < irCount;i++)
435 if(delays[i] > maxDelay)
437 ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i], maxDelay);
438 failed = AL_TRUE;
443 if(!failed)
445 size_t total = sizeof(struct Hrtf);
446 total += sizeof(azCount[0])*evCount;
447 total = (total+1)&~1; /* Align for (u)short fields */
448 total += sizeof(evOffset[0])*evCount;
449 total += sizeof(coeffs[0])*irSize*irCount;
450 total += sizeof(delays[0])*irCount;
451 total += al_string_length(filename)+1;
453 Hrtf = al_calloc(16, total);
454 if(Hrtf == NULL)
456 ERR("Out of memory.\n");
457 failed = AL_TRUE;
461 if(!failed)
463 char *base = (char*)Hrtf;
464 uintptr_t offset = sizeof(*Hrtf);
466 Hrtf->sampleRate = rate;
467 Hrtf->irSize = irSize;
468 Hrtf->evCount = evCount;
469 Hrtf->azCount = ((ALubyte*)(base + offset)); offset += evCount*sizeof(Hrtf->azCount[0]);
470 offset = (offset+1)&~1; /* Align for (u)short fields */
471 Hrtf->evOffset = ((ALushort*)(base + offset)); offset += evCount*sizeof(Hrtf->evOffset[0]);
472 Hrtf->coeffs = ((ALshort*)(base + offset)); offset += irSize*irCount*sizeof(Hrtf->coeffs[0]);
473 Hrtf->delays = ((ALubyte*)(base + offset)); offset += irCount*sizeof(Hrtf->delays[0]);
474 Hrtf->filename = ((char*)(base + offset));
475 Hrtf->next = NULL;
477 memcpy((void*)Hrtf->azCount, azCount, sizeof(azCount[0])*evCount);
478 memcpy((void*)Hrtf->evOffset, evOffset, sizeof(evOffset[0])*evCount);
479 memcpy((void*)Hrtf->coeffs, coeffs, sizeof(coeffs[0])*irSize*irCount);
480 memcpy((void*)Hrtf->delays, delays, sizeof(delays[0])*irCount);
481 memcpy((void*)Hrtf->filename, al_string_get_cstr(filename), al_string_length(filename)+1);
484 free(azCount);
485 free(evOffset);
486 free(coeffs);
487 return Hrtf;
490 static struct Hrtf *LoadHrtf01(const ALubyte *data, size_t datalen, const_al_string filename)
492 const ALubyte maxDelay = HRTF_HISTORY_LENGTH-1;
493 struct Hrtf *Hrtf = NULL;
494 ALboolean failed = AL_FALSE;
495 ALuint rate = 0, irCount = 0;
496 ALubyte irSize = 0, evCount = 0;
497 const ALubyte *azCount = NULL;
498 ALushort *evOffset = NULL;
499 ALshort *coeffs = NULL;
500 const ALubyte *delays = NULL;
501 ALuint i, j;
503 if(datalen < 6)
505 ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n",
506 al_string_get_cstr(filename), 6, datalen);
507 return NULL;
510 rate = *(data++);
511 rate |= *(data++)<<8;
512 rate |= *(data++)<<16;
513 rate |= *(data++)<<24;
514 datalen -= 4;
516 irSize = *(data++);
517 datalen -= 1;
519 evCount = *(data++);
520 datalen -= 1;
522 if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
524 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
525 irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
526 failed = AL_TRUE;
528 if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
530 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
531 evCount, MIN_EV_COUNT, MAX_EV_COUNT);
532 failed = AL_TRUE;
534 if(failed)
535 return NULL;
537 if(datalen < evCount)
539 ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n",
540 al_string_get_cstr(filename), evCount, datalen);
541 return NULL;
544 azCount = data;
545 data += evCount;
546 datalen -= evCount;
548 evOffset = malloc(sizeof(evOffset[0])*evCount);
549 if(azCount == NULL || evOffset == NULL)
551 ERR("Out of memory.\n");
552 failed = AL_TRUE;
555 if(!failed)
557 for(i = 0;i < evCount;i++)
559 if(azCount[i] < MIN_AZ_COUNT || azCount[i] > MAX_AZ_COUNT)
561 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
562 i, azCount[i], MIN_AZ_COUNT, MAX_AZ_COUNT);
563 failed = AL_TRUE;
568 if(!failed)
570 evOffset[0] = 0;
571 irCount = azCount[0];
572 for(i = 1;i < evCount;i++)
574 evOffset[i] = evOffset[i-1] + azCount[i-1];
575 irCount += azCount[i];
578 coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
579 if(coeffs == NULL)
581 ERR("Out of memory.\n");
582 failed = AL_TRUE;
586 if(!failed)
588 size_t reqsize = 2*irSize*irCount + irCount;
589 if(datalen < reqsize)
591 ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT"\n",
592 al_string_get_cstr(filename), reqsize, datalen);
593 failed = AL_TRUE;
597 if(!failed)
599 for(i = 0;i < irCount*irSize;i+=irSize)
601 for(j = 0;j < irSize;j++)
603 ALshort coeff;
604 coeff = *(data++);
605 coeff |= *(data++)<<8;
606 datalen -= 2;
607 coeffs[i+j] = coeff;
611 delays = data;
612 data += irCount;
613 datalen -= irCount;
614 for(i = 0;i < irCount;i++)
616 if(delays[i] > maxDelay)
618 ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i], maxDelay);
619 failed = AL_TRUE;
624 if(!failed)
626 size_t total = sizeof(struct Hrtf);
627 total += sizeof(azCount[0])*evCount;
628 total = (total+1)&~1; /* Align for (u)short fields */
629 total += sizeof(evOffset[0])*evCount;
630 total += sizeof(coeffs[0])*irSize*irCount;
631 total += sizeof(delays[0])*irCount;
632 total += al_string_length(filename)+1;
634 Hrtf = al_calloc(16, total);
635 if(Hrtf == NULL)
637 ERR("Out of memory.\n");
638 failed = AL_TRUE;
642 if(!failed)
644 char *base = (char*)Hrtf;
645 uintptr_t offset = sizeof(*Hrtf);
647 Hrtf->sampleRate = rate;
648 Hrtf->irSize = irSize;
649 Hrtf->evCount = evCount;
650 Hrtf->azCount = ((ALubyte*)(base + offset)); offset += evCount*sizeof(Hrtf->azCount[0]);
651 offset = (offset+1)&~1; /* Align for (u)short fields */
652 Hrtf->evOffset = ((ALushort*)(base + offset)); offset += evCount*sizeof(Hrtf->evOffset[0]);
653 Hrtf->coeffs = ((ALshort*)(base + offset)); offset += irSize*irCount*sizeof(Hrtf->coeffs[0]);
654 Hrtf->delays = ((ALubyte*)(base + offset)); offset += irCount*sizeof(Hrtf->delays[0]);
655 Hrtf->filename = ((char*)(base + offset));
656 Hrtf->next = NULL;
658 memcpy((void*)Hrtf->azCount, azCount, sizeof(azCount[0])*evCount);
659 memcpy((void*)Hrtf->evOffset, evOffset, sizeof(evOffset[0])*evCount);
660 memcpy((void*)Hrtf->coeffs, coeffs, sizeof(coeffs[0])*irSize*irCount);
661 memcpy((void*)Hrtf->delays, delays, sizeof(delays[0])*irCount);
662 memcpy((void*)Hrtf->filename, al_string_get_cstr(filename), al_string_length(filename)+1);
665 free(evOffset);
666 free(coeffs);
667 return Hrtf;
670 static void AddFileEntry(vector_HrtfEntry *list, al_string *filename)
672 HrtfEntry entry = { AL_STRING_INIT_STATIC(), NULL };
673 struct Hrtf *hrtf = NULL;
674 const HrtfEntry *iter;
675 struct FileMapping fmap;
676 const char *name;
677 const char *ext;
678 int i;
680 #define MATCH_FNAME(i) (al_string_cmp_cstr(*filename, (i)->hrtf->filename) == 0)
681 VECTOR_FIND_IF(iter, const HrtfEntry, *list, MATCH_FNAME);
682 if(iter != VECTOR_END(*list))
684 TRACE("Skipping duplicate file entry %s\n", al_string_get_cstr(*filename));
685 goto done;
687 #undef MATCH_FNAME
689 entry.hrtf = LoadedHrtfs;
690 while(entry.hrtf)
692 if(al_string_cmp_cstr(*filename, entry.hrtf->filename) == 0)
694 TRACE("Skipping load of already-loaded file %s\n", al_string_get_cstr(*filename));
695 goto skip_load;
697 entry.hrtf = entry.hrtf->next;
700 TRACE("Loading %s...\n", al_string_get_cstr(*filename));
701 fmap = MapFileToMem(al_string_get_cstr(*filename));
702 if(fmap.ptr == NULL)
704 ERR("Could not open %s\n", al_string_get_cstr(*filename));
705 goto done;
708 if(fmap.len < sizeof(magicMarker01))
709 ERR("%s data is too short ("SZFMT" bytes)\n", al_string_get_cstr(*filename), fmap.len);
710 else if(memcmp(fmap.ptr, magicMarker01, sizeof(magicMarker01)) == 0)
712 TRACE("Detected data set format v1\n");
713 hrtf = LoadHrtf01((const ALubyte*)fmap.ptr+sizeof(magicMarker01),
714 fmap.len-sizeof(magicMarker01), *filename
717 else if(memcmp(fmap.ptr, magicMarker00, sizeof(magicMarker00)) == 0)
719 TRACE("Detected data set format v0\n");
720 hrtf = LoadHrtf00((const ALubyte*)fmap.ptr+sizeof(magicMarker00),
721 fmap.len-sizeof(magicMarker00), *filename
724 else
725 ERR("Invalid header in %s: \"%.8s\"\n", al_string_get_cstr(*filename), (const char*)fmap.ptr);
726 UnmapFileMem(&fmap);
728 if(!hrtf)
730 ERR("Failed to load %s\n", al_string_get_cstr(*filename));
731 goto done;
734 hrtf->next = LoadedHrtfs;
735 LoadedHrtfs = hrtf;
736 TRACE("Loaded HRTF support for format: %s %uhz\n",
737 DevFmtChannelsString(DevFmtStereo), hrtf->sampleRate);
738 entry.hrtf = hrtf;
740 skip_load:
741 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
742 * format update). */
743 name = strrchr(al_string_get_cstr(*filename), '/');
744 if(!name) name = strrchr(al_string_get_cstr(*filename), '\\');
745 if(!name) name = al_string_get_cstr(*filename);
746 else ++name;
748 ext = strrchr(name, '.');
750 i = 0;
751 do {
752 if(!ext)
753 al_string_copy_cstr(&entry.name, name);
754 else
755 al_string_copy_range(&entry.name, name, ext);
756 if(i != 0)
758 char str[64];
759 snprintf(str, sizeof(str), " #%d", i+1);
760 al_string_append_cstr(&entry.name, str);
762 ++i;
764 #define MATCH_NAME(i) (al_string_cmp(entry.name, (i)->name) == 0)
765 VECTOR_FIND_IF(iter, const HrtfEntry, *list, MATCH_NAME);
766 #undef MATCH_NAME
767 } while(iter != VECTOR_END(*list));
769 TRACE("Adding entry \"%s\" from file \"%s\"\n", al_string_get_cstr(entry.name),
770 al_string_get_cstr(*filename));
771 VECTOR_PUSH_BACK(*list, entry);
773 done:
774 al_string_deinit(filename);
777 /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
778 * for input instead of opening the given filename.
780 static void AddBuiltInEntry(vector_HrtfEntry *list, const ALubyte *data, size_t datalen, al_string *filename)
782 HrtfEntry entry = { AL_STRING_INIT_STATIC(), NULL };
783 struct Hrtf *hrtf = NULL;
784 const HrtfEntry *iter;
785 int i;
787 #define MATCH_FNAME(i) (al_string_cmp_cstr(*filename, (i)->hrtf->filename) == 0)
788 VECTOR_FIND_IF(iter, const HrtfEntry, *list, MATCH_FNAME);
789 if(iter != VECTOR_END(*list))
791 TRACE("Skipping duplicate file entry %s\n", al_string_get_cstr(*filename));
792 goto done;
794 #undef MATCH_FNAME
796 entry.hrtf = LoadedHrtfs;
797 while(entry.hrtf)
799 if(al_string_cmp_cstr(*filename, entry.hrtf->filename) == 0)
801 TRACE("Skipping load of already-loaded file %s\n", al_string_get_cstr(*filename));
802 goto skip_load;
804 entry.hrtf = entry.hrtf->next;
807 TRACE("Loading %s...\n", al_string_get_cstr(*filename));
808 if(datalen < sizeof(magicMarker01))
810 ERR("%s data is too short ("SZFMT" bytes)\n", al_string_get_cstr(*filename), datalen);
811 goto done;
814 if(memcmp(data, magicMarker01, sizeof(magicMarker01)) == 0)
816 TRACE("Detected data set format v1\n");
817 hrtf = LoadHrtf01(data+sizeof(magicMarker01),
818 datalen-sizeof(magicMarker01), *filename
821 else if(memcmp(data, magicMarker00, sizeof(magicMarker00)) == 0)
823 TRACE("Detected data set format v0\n");
824 hrtf = LoadHrtf00(data+sizeof(magicMarker00),
825 datalen-sizeof(magicMarker00), *filename
828 else
829 ERR("Invalid header in %s: \"%.8s\"\n", al_string_get_cstr(*filename), data);
831 if(!hrtf)
833 ERR("Failed to load %s\n", al_string_get_cstr(*filename));
834 goto done;
837 hrtf->next = LoadedHrtfs;
838 LoadedHrtfs = hrtf;
839 TRACE("Loaded HRTF support for format: %s %uhz\n",
840 DevFmtChannelsString(DevFmtStereo), hrtf->sampleRate);
841 entry.hrtf = hrtf;
843 skip_load:
844 i = 0;
845 do {
846 al_string_copy(&entry.name, *filename);
847 if(i != 0)
849 char str[64];
850 snprintf(str, sizeof(str), " #%d", i+1);
851 al_string_append_cstr(&entry.name, str);
853 ++i;
855 #define MATCH_NAME(i) (al_string_cmp(entry.name, (i)->name) == 0)
856 VECTOR_FIND_IF(iter, const HrtfEntry, *list, MATCH_NAME);
857 #undef MATCH_NAME
858 } while(iter != VECTOR_END(*list));
860 TRACE("Adding built-in entry \"%s\"\n", al_string_get_cstr(entry.name));
861 VECTOR_PUSH_BACK(*list, entry);
863 done:
864 al_string_deinit(filename);
868 #ifndef ALSOFT_EMBED_HRTF_DATA
869 #define IDR_DEFAULT_44100_MHR 1
870 #define IDR_DEFAULT_48000_MHR 2
872 static const ALubyte *GetResource(int UNUSED(name), size_t *size)
874 *size = 0;
875 return NULL;
878 #else
879 #include "hrtf_res.h"
881 #ifdef _WIN32
882 static const ALubyte *GetResource(int name, size_t *size)
884 HMODULE handle;
885 HGLOBAL res;
886 HRSRC rc;
888 GetModuleHandleExW(
889 GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
890 (LPCWSTR)GetResource, &handle
892 rc = FindResourceW(handle, MAKEINTRESOURCEW(name), MAKEINTRESOURCEW(MHRTYPE));
893 res = LoadResource(handle, rc);
895 *size = SizeofResource(handle, rc);
896 return LockResource(res);
899 #elif defined(__APPLE__)
901 #include <Availability.h>
902 #include <mach-o/getsect.h>
903 #include <mach-o/ldsyms.h>
905 static const ALubyte *GetResource(int name, size_t *size)
907 #if defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && (__MAC_OS_X_VERSION_MAX_ALLOWED >= 1070)
908 /* NOTE: OSX 10.7 and up need to call getsectiondata(&_mh_dylib_header, ...). However, that
909 * call requires 10.7.
911 if(name == IDR_DEFAULT_44100_MHR)
912 return getsectiondata(&_mh_dylib_header, "binary", "default_44100", size);
913 if(name == IDR_DEFAULT_48000_MHR)
914 return getsectiondata(&_mh_dylib_header, "binary", "default_48000", size);
915 #else
916 if(name == IDR_DEFAULT_44100_MHR)
917 return getsectdata("binary", "default_44100", size);
918 if(name == IDR_DEFAULT_48000_MHR)
919 return getsectdata("binary", "default_48000", size);
920 #endif
921 *size = 0;
922 return NULL;
925 #else
927 extern const ALubyte _binary_default_44100_mhr_start[] HIDDEN_DECL;
928 extern const ALubyte _binary_default_44100_mhr_end[] HIDDEN_DECL;
929 extern const ALubyte _binary_default_44100_mhr_size[] HIDDEN_DECL;
931 extern const ALubyte _binary_default_48000_mhr_start[] HIDDEN_DECL;
932 extern const ALubyte _binary_default_48000_mhr_end[] HIDDEN_DECL;
933 extern const ALubyte _binary_default_48000_mhr_size[] HIDDEN_DECL;
935 static const ALubyte *GetResource(int name, size_t *size)
937 if(name == IDR_DEFAULT_44100_MHR)
939 /* Make sure all symbols are referenced, to ensure the compiler won't
940 * ignore the declarations and lose the visibility attribute used to
941 * hide them (would be nice if ld or objcopy could automatically mark
942 * them as hidden when generating them, but apparently they can't).
944 const void *volatile ptr =_binary_default_44100_mhr_size;
945 (void)ptr;
946 *size = _binary_default_44100_mhr_end - _binary_default_44100_mhr_start;
947 return _binary_default_44100_mhr_start;
949 if(name == IDR_DEFAULT_48000_MHR)
951 const void *volatile ptr =_binary_default_48000_mhr_size;
952 (void)ptr;
953 *size = _binary_default_48000_mhr_end - _binary_default_48000_mhr_start;
954 return _binary_default_48000_mhr_start;
956 *size = 0;
957 return NULL;
959 #endif
960 #endif
962 vector_HrtfEntry EnumerateHrtf(const_al_string devname)
964 vector_HrtfEntry list = VECTOR_INIT_STATIC();
965 const char *defaulthrtf = "";
966 const char *pathlist = "";
967 bool usedefaults = true;
969 if(ConfigValueStr(al_string_get_cstr(devname), NULL, "hrtf-paths", &pathlist))
971 while(pathlist && *pathlist)
973 const char *next, *end;
975 while(isspace(*pathlist) || *pathlist == ',')
976 pathlist++;
977 if(*pathlist == '\0')
978 continue;
980 next = strchr(pathlist, ',');
981 if(next)
982 end = next++;
983 else
985 end = pathlist + strlen(pathlist);
986 usedefaults = false;
989 while(end != pathlist && isspace(*(end-1)))
990 --end;
991 if(end != pathlist)
993 al_string pname = AL_STRING_INIT_STATIC();
994 vector_al_string flist;
996 al_string_append_range(&pname, pathlist, end);
998 flist = SearchDataFiles(".mhr", al_string_get_cstr(pname));
999 VECTOR_FOR_EACH_PARAMS(al_string, flist, AddFileEntry, &list);
1000 VECTOR_DEINIT(flist);
1002 al_string_deinit(&pname);
1005 pathlist = next;
1008 else if(ConfigValueExists(al_string_get_cstr(devname), NULL, "hrtf_tables"))
1009 ERR("The hrtf_tables option is deprecated, please use hrtf-paths instead.\n");
1011 if(usedefaults)
1013 vector_al_string flist;
1014 const ALubyte *rdata;
1015 size_t rsize;
1017 flist = SearchDataFiles(".mhr", "openal/hrtf");
1018 VECTOR_FOR_EACH_PARAMS(al_string, flist, AddFileEntry, &list);
1019 VECTOR_DEINIT(flist);
1021 rdata = GetResource(IDR_DEFAULT_44100_MHR, &rsize);
1022 if(rdata != NULL && rsize > 0)
1024 al_string ename = AL_STRING_INIT_STATIC();
1025 al_string_copy_cstr(&ename, "Built-In 44100hz");
1026 AddBuiltInEntry(&list, rdata, rsize, &ename);
1029 rdata = GetResource(IDR_DEFAULT_48000_MHR, &rsize);
1030 if(rdata != NULL && rsize > 0)
1032 al_string ename = AL_STRING_INIT_STATIC();
1033 al_string_copy_cstr(&ename, "Built-In 48000hz");
1034 AddBuiltInEntry(&list, rdata, rsize, &ename);
1038 if(VECTOR_SIZE(list) > 1 && ConfigValueStr(al_string_get_cstr(devname), NULL, "default-hrtf", &defaulthrtf))
1040 const HrtfEntry *iter;
1041 /* Find the preferred HRTF and move it to the front of the list. */
1042 #define FIND_ENTRY(i) (al_string_cmp_cstr((i)->name, defaulthrtf) == 0)
1043 VECTOR_FIND_IF(iter, const HrtfEntry, list, FIND_ENTRY);
1044 #undef FIND_ENTRY
1045 if(iter == VECTOR_END(list))
1046 WARN("Failed to find default HRTF \"%s\"\n", defaulthrtf);
1047 else if(iter != VECTOR_BEGIN(list))
1049 HrtfEntry entry = *iter;
1050 memmove(&VECTOR_ELEM(list,1), &VECTOR_ELEM(list,0),
1051 (iter-VECTOR_BEGIN(list))*sizeof(HrtfEntry));
1052 VECTOR_ELEM(list,0) = entry;
1056 return list;
1059 void FreeHrtfList(vector_HrtfEntry *list)
1061 #define CLEAR_ENTRY(i) do { \
1062 al_string_deinit(&(i)->name); \
1063 } while(0)
1064 VECTOR_FOR_EACH(HrtfEntry, *list, CLEAR_ENTRY);
1065 VECTOR_DEINIT(*list);
1066 #undef CLEAR_ENTRY
1070 void FreeHrtfs(void)
1072 struct Hrtf *Hrtf = LoadedHrtfs;
1073 LoadedHrtfs = NULL;
1075 while(Hrtf != NULL)
1077 struct Hrtf *next = Hrtf->next;
1078 al_free(Hrtf);
1079 Hrtf = next;