Support environment variables in the hrtf_tables config value
[openal-soft.git] / Alc / hrtf.c
blobd326191a082ba1a2496e3c309e2b90b74e3c3405
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., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
21 #ifdef _WIN32
22 #ifdef __MINGW32__
23 #define _WIN32_IE 0x501
24 #else
25 #define _WIN32_IE 0x400
26 #endif
27 #endif
29 #include "config.h"
31 #include <stdlib.h>
32 #include <ctype.h>
33 #include <limits.h>
35 #ifdef _WIN32_IE
36 #include <shlobj.h>
37 #endif
39 #include "AL/al.h"
40 #include "AL/alc.h"
41 #include "alMain.h"
42 #include "alSource.h"
43 #include "alu.h"
44 #include "hrtf.h"
47 #ifndef PATH_MAX
48 #ifdef MAX_PATH
49 #define PATH_MAX MAX_PATH
50 #else
51 #define PATH_MAX 4096
52 #endif
53 #endif
56 /* Current data set limits defined by the makehrtf utility. */
57 #define MIN_IR_SIZE (8)
58 #define MAX_IR_SIZE (128)
59 #define MOD_IR_SIZE (8)
61 #define MIN_EV_COUNT (5)
62 #define MAX_EV_COUNT (128)
64 #define MIN_AZ_COUNT (1)
65 #define MAX_AZ_COUNT (128)
67 struct Hrtf {
68 ALuint sampleRate;
69 ALuint irSize;
70 ALubyte evCount;
72 const ALubyte *azCount;
73 const ALushort *evOffset;
74 const ALshort *coeffs;
75 const ALubyte *delays;
77 struct Hrtf *next;
80 static const ALchar magicMarker00[8] = "MinPHR00";
81 static const ALchar magicMarker01[8] = "MinPHR01";
83 static struct Hrtf *LoadedHrtfs = NULL;
85 /* Calculate the elevation indices given the polar elevation in radians.
86 * This will return two indices between 0 and (Hrtf->evCount - 1) and an
87 * interpolation factor between 0.0 and 1.0.
89 static void CalcEvIndices(const struct Hrtf *Hrtf, ALfloat ev, ALuint *evidx, ALfloat *evmu)
91 ev = (F_PI_2 + ev) * (Hrtf->evCount-1) / F_PI;
92 evidx[0] = fastf2u(ev);
93 evidx[1] = minu(evidx[0] + 1, Hrtf->evCount-1);
94 *evmu = ev - evidx[0];
97 /* Calculate the azimuth indices given the polar azimuth in radians. This
98 * will return two indices between 0 and (Hrtf->azCount[ei] - 1) and an
99 * interpolation factor between 0.0 and 1.0.
101 static void CalcAzIndices(const struct Hrtf *Hrtf, ALuint evidx, ALfloat az, ALuint *azidx, ALfloat *azmu)
103 az = (F_2PI + az) * Hrtf->azCount[evidx] / (F_2PI);
104 azidx[0] = fastf2u(az) % Hrtf->azCount[evidx];
105 azidx[1] = (azidx[0] + 1) % Hrtf->azCount[evidx];
106 *azmu = az - floorf(az);
109 /* Calculates the normalized HRTF transition factor (delta) from the changes
110 * in gain and listener to source angle between updates. The result is a
111 * normalized delta factor that can be used to calculate moving HRIR stepping
112 * values.
114 ALfloat CalcHrtfDelta(ALfloat oldGain, ALfloat newGain, const ALfloat olddir[3], const ALfloat newdir[3])
116 ALfloat gainChange, angleChange, change;
118 // Calculate the normalized dB gain change.
119 newGain = maxf(newGain, 0.0001f);
120 oldGain = maxf(oldGain, 0.0001f);
121 gainChange = fabsf(log10f(newGain / oldGain) / log10f(0.0001f));
123 // Calculate the normalized listener to source angle change when there is
124 // enough gain to notice it.
125 angleChange = 0.0f;
126 if(gainChange > 0.0001f || newGain > 0.0001f)
128 // No angle change when the directions are equal or degenerate (when
129 // both have zero length).
130 if(newdir[0]-olddir[0] || newdir[1]-olddir[1] || newdir[2]-olddir[2])
131 angleChange = acosf(olddir[0]*newdir[0] +
132 olddir[1]*newdir[1] +
133 olddir[2]*newdir[2]) / F_PI;
137 // Use the largest of the two changes for the delta factor, and apply a
138 // significance shaping function to it.
139 change = maxf(angleChange * 25.0f, gainChange) * 2.0f;
140 return minf(change, 1.0f);
143 /* Calculates static HRIR coefficients and delays for the given polar
144 * elevation and azimuth in radians. Linear interpolation is used to
145 * increase the apparent resolution of the HRIR data set. The coefficients
146 * are also normalized and attenuated by the specified gain.
148 void GetLerpedHrtfCoeffs(const struct Hrtf *Hrtf, ALfloat elevation, ALfloat azimuth, ALfloat gain, ALfloat (*coeffs)[2], ALuint *delays)
150 ALuint evidx[2], azidx[2];
151 ALuint lidx[4], ridx[4];
152 ALfloat mu[3], blend[4];
153 ALuint i;
155 // Claculate elevation indices and interpolation factor.
156 CalcEvIndices(Hrtf, elevation, evidx, &mu[2]);
158 // Calculate azimuth indices and interpolation factor for the first
159 // elevation.
160 CalcAzIndices(Hrtf, evidx[0], azimuth, azidx, &mu[0]);
162 // Calculate the first set of linear HRIR indices for left and right
163 // channels.
164 lidx[0] = Hrtf->evOffset[evidx[0]] + azidx[0];
165 lidx[1] = Hrtf->evOffset[evidx[0]] + azidx[1];
166 ridx[0] = Hrtf->evOffset[evidx[0]] + ((Hrtf->azCount[evidx[0]]-azidx[0]) % Hrtf->azCount[evidx[0]]);
167 ridx[1] = Hrtf->evOffset[evidx[0]] + ((Hrtf->azCount[evidx[0]]-azidx[1]) % Hrtf->azCount[evidx[0]]);
169 // Calculate azimuth indices and interpolation factor for the second
170 // elevation.
171 CalcAzIndices(Hrtf, evidx[1], azimuth, azidx, &mu[1]);
173 // Calculate the second set of linear HRIR indices for left and right
174 // channels.
175 lidx[2] = Hrtf->evOffset[evidx[1]] + azidx[0];
176 lidx[3] = Hrtf->evOffset[evidx[1]] + azidx[1];
177 ridx[2] = Hrtf->evOffset[evidx[1]] + ((Hrtf->azCount[evidx[1]]-azidx[0]) % Hrtf->azCount[evidx[1]]);
178 ridx[3] = Hrtf->evOffset[evidx[1]] + ((Hrtf->azCount[evidx[1]]-azidx[1]) % Hrtf->azCount[evidx[1]]);
180 /* Calculate 4 blending weights for 2D bilinear interpolation. */
181 blend[0] = (1.0f-mu[0]) * (1.0f-mu[2]);
182 blend[1] = ( mu[0]) * (1.0f-mu[2]);
183 blend[2] = (1.0f-mu[1]) * ( mu[2]);
184 blend[3] = ( mu[1]) * ( mu[2]);
186 /* Calculate the HRIR delays using linear interpolation. */
187 delays[0] = fastf2u(Hrtf->delays[lidx[0]]*blend[0] + Hrtf->delays[lidx[1]]*blend[1] +
188 Hrtf->delays[lidx[2]]*blend[2] + Hrtf->delays[lidx[3]]*blend[3] +
189 0.5f) << HRTFDELAY_BITS;
190 delays[1] = fastf2u(Hrtf->delays[ridx[0]]*blend[0] + Hrtf->delays[ridx[1]]*blend[1] +
191 Hrtf->delays[ridx[2]]*blend[2] + Hrtf->delays[ridx[3]]*blend[3] +
192 0.5f) << HRTFDELAY_BITS;
194 /* Calculate the sample offsets for the HRIR indices. */
195 lidx[0] *= Hrtf->irSize;
196 lidx[1] *= Hrtf->irSize;
197 lidx[2] *= Hrtf->irSize;
198 lidx[3] *= Hrtf->irSize;
199 ridx[0] *= Hrtf->irSize;
200 ridx[1] *= Hrtf->irSize;
201 ridx[2] *= Hrtf->irSize;
202 ridx[3] *= Hrtf->irSize;
204 /* Calculate the normalized and attenuated HRIR coefficients using linear
205 * interpolation when there is enough gain to warrant it. Zero the
206 * coefficients if gain is too low.
208 if(gain > 0.0001f)
210 gain *= 1.0f/32767.0f;
211 for(i = 0;i < Hrtf->irSize;i++)
213 coeffs[i][0] = (Hrtf->coeffs[lidx[0]+i]*blend[0] +
214 Hrtf->coeffs[lidx[1]+i]*blend[1] +
215 Hrtf->coeffs[lidx[2]+i]*blend[2] +
216 Hrtf->coeffs[lidx[3]+i]*blend[3]) * gain;
217 coeffs[i][1] = (Hrtf->coeffs[ridx[0]+i]*blend[0] +
218 Hrtf->coeffs[ridx[1]+i]*blend[1] +
219 Hrtf->coeffs[ridx[2]+i]*blend[2] +
220 Hrtf->coeffs[ridx[3]+i]*blend[3]) * gain;
223 else
225 for(i = 0;i < Hrtf->irSize;i++)
227 coeffs[i][0] = 0.0f;
228 coeffs[i][1] = 0.0f;
233 /* Calculates the moving HRIR target coefficients, target delays, and
234 * stepping values for the given polar elevation and azimuth in radians.
235 * Linear interpolation is used to increase the apparent resolution of the
236 * HRIR data set. The coefficients are also normalized and attenuated by the
237 * specified gain. Stepping resolution and count is determined using the
238 * given delta factor between 0.0 and 1.0.
240 ALuint GetMovingHrtfCoeffs(const struct Hrtf *Hrtf, ALfloat elevation, ALfloat azimuth, ALfloat gain, ALfloat delta, ALint counter, ALfloat (*coeffs)[2], ALuint *delays, ALfloat (*coeffStep)[2], ALint *delayStep)
242 ALuint evidx[2], azidx[2];
243 ALuint lidx[4], ridx[4];
244 ALfloat mu[3], blend[4];
245 ALfloat left, right;
246 ALfloat step;
247 ALuint i;
249 // Claculate elevation indices and interpolation factor.
250 CalcEvIndices(Hrtf, elevation, evidx, &mu[2]);
252 // Calculate azimuth indices and interpolation factor for the first
253 // elevation.
254 CalcAzIndices(Hrtf, evidx[0], azimuth, azidx, &mu[0]);
256 // Calculate the first set of linear HRIR indices for left and right
257 // channels.
258 lidx[0] = Hrtf->evOffset[evidx[0]] + azidx[0];
259 lidx[1] = Hrtf->evOffset[evidx[0]] + azidx[1];
260 ridx[0] = Hrtf->evOffset[evidx[0]] + ((Hrtf->azCount[evidx[0]]-azidx[0]) % Hrtf->azCount[evidx[0]]);
261 ridx[1] = Hrtf->evOffset[evidx[0]] + ((Hrtf->azCount[evidx[0]]-azidx[1]) % Hrtf->azCount[evidx[0]]);
263 // Calculate azimuth indices and interpolation factor for the second
264 // elevation.
265 CalcAzIndices(Hrtf, evidx[1], azimuth, azidx, &mu[1]);
267 // Calculate the second set of linear HRIR indices for left and right
268 // channels.
269 lidx[2] = Hrtf->evOffset[evidx[1]] + azidx[0];
270 lidx[3] = Hrtf->evOffset[evidx[1]] + azidx[1];
271 ridx[2] = Hrtf->evOffset[evidx[1]] + ((Hrtf->azCount[evidx[1]]-azidx[0]) % Hrtf->azCount[evidx[1]]);
272 ridx[3] = Hrtf->evOffset[evidx[1]] + ((Hrtf->azCount[evidx[1]]-azidx[1]) % Hrtf->azCount[evidx[1]]);
274 // Calculate the stepping parameters.
275 delta = maxf(floorf(delta*(Hrtf->sampleRate*0.015f) + 0.5f), 1.0f);
276 step = 1.0f / delta;
278 /* Calculate 4 blending weights for 2D bilinear interpolation. */
279 blend[0] = (1.0f-mu[0]) * (1.0f-mu[2]);
280 blend[1] = ( mu[0]) * (1.0f-mu[2]);
281 blend[2] = (1.0f-mu[1]) * ( mu[2]);
282 blend[3] = ( mu[1]) * ( mu[2]);
284 /* Calculate the HRIR delays using linear interpolation. Then calculate
285 * the delay stepping values using the target and previous running
286 * delays.
288 left = (ALfloat)(delays[0] - (delayStep[0] * counter));
289 right = (ALfloat)(delays[1] - (delayStep[1] * counter));
291 delays[0] = fastf2u(Hrtf->delays[lidx[0]]*blend[0] + Hrtf->delays[lidx[1]]*blend[1] +
292 Hrtf->delays[lidx[2]]*blend[2] + Hrtf->delays[lidx[3]]*blend[3] +
293 0.5f) << HRTFDELAY_BITS;
294 delays[1] = fastf2u(Hrtf->delays[ridx[0]]*blend[0] + Hrtf->delays[ridx[1]]*blend[1] +
295 Hrtf->delays[ridx[2]]*blend[2] + Hrtf->delays[ridx[3]]*blend[3] +
296 0.5f) << HRTFDELAY_BITS;
298 delayStep[0] = fastf2i(step * (delays[0] - left));
299 delayStep[1] = fastf2i(step * (delays[1] - right));
301 /* Calculate the sample offsets for the HRIR indices. */
302 lidx[0] *= Hrtf->irSize;
303 lidx[1] *= Hrtf->irSize;
304 lidx[2] *= Hrtf->irSize;
305 lidx[3] *= Hrtf->irSize;
306 ridx[0] *= Hrtf->irSize;
307 ridx[1] *= Hrtf->irSize;
308 ridx[2] *= Hrtf->irSize;
309 ridx[3] *= Hrtf->irSize;
311 /* Calculate the normalized and attenuated target HRIR coefficients using
312 * linear interpolation when there is enough gain to warrant it. Zero
313 * the target coefficients if gain is too low. Then calculate the
314 * coefficient stepping values using the target and previous running
315 * coefficients.
317 if(gain > 0.0001f)
319 gain *= 1.0f/32767.0f;
320 for(i = 0;i < HRIR_LENGTH;i++)
322 left = coeffs[i][0] - (coeffStep[i][0] * counter);
323 right = coeffs[i][1] - (coeffStep[i][1] * counter);
325 coeffs[i][0] = (Hrtf->coeffs[lidx[0]+i]*blend[0] +
326 Hrtf->coeffs[lidx[1]+i]*blend[1] +
327 Hrtf->coeffs[lidx[2]+i]*blend[2] +
328 Hrtf->coeffs[lidx[3]+i]*blend[3]) * gain;
329 coeffs[i][1] = (Hrtf->coeffs[ridx[0]+i]*blend[0] +
330 Hrtf->coeffs[ridx[1]+i]*blend[1] +
331 Hrtf->coeffs[ridx[2]+i]*blend[2] +
332 Hrtf->coeffs[ridx[3]+i]*blend[3]) * gain;
334 coeffStep[i][0] = step * (coeffs[i][0] - left);
335 coeffStep[i][1] = step * (coeffs[i][1] - right);
338 else
340 for(i = 0;i < HRIR_LENGTH;i++)
342 left = coeffs[i][0] - (coeffStep[i][0] * counter);
343 right = coeffs[i][1] - (coeffStep[i][1] * counter);
345 coeffs[i][0] = 0.0f;
346 coeffs[i][1] = 0.0f;
348 coeffStep[i][0] = step * -left;
349 coeffStep[i][1] = step * -right;
353 /* The stepping count is the number of samples necessary for the HRIR to
354 * complete its transition. The mixer will only apply stepping for this
355 * many samples.
357 return fastf2u(delta);
361 static struct Hrtf *LoadHrtf00(FILE *f, ALuint deviceRate)
363 const ALubyte maxDelay = SRC_HISTORY_LENGTH-1;
364 struct Hrtf *Hrtf = NULL;
365 ALboolean failed = AL_FALSE;
366 ALuint rate = 0, irCount = 0;
367 ALushort irSize = 0;
368 ALubyte evCount = 0;
369 ALubyte *azCount = NULL;
370 ALushort *evOffset = NULL;
371 ALshort *coeffs = NULL;
372 ALubyte *delays = NULL;
373 ALuint i, j;
375 rate = fgetc(f);
376 rate |= fgetc(f)<<8;
377 rate |= fgetc(f)<<16;
378 rate |= fgetc(f)<<24;
380 irCount = fgetc(f);
381 irCount |= fgetc(f)<<8;
383 irSize = fgetc(f);
384 irSize |= fgetc(f)<<8;
386 evCount = fgetc(f);
388 if(rate != deviceRate)
390 ERR("HRIR rate does not match device rate: rate=%d (%d)\n",
391 rate, deviceRate);
392 failed = AL_TRUE;
394 if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
396 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
397 irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
398 failed = AL_TRUE;
400 if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
402 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
403 evCount, MIN_EV_COUNT, MAX_EV_COUNT);
404 failed = AL_TRUE;
407 if(failed)
408 return NULL;
410 azCount = malloc(sizeof(azCount[0])*evCount);
411 evOffset = malloc(sizeof(evOffset[0])*evCount);
412 if(azCount == NULL || evOffset == NULL)
414 ERR("Out of memory.\n");
415 failed = AL_TRUE;
418 if(!failed)
420 evOffset[0] = fgetc(f);
421 evOffset[0] |= fgetc(f)<<8;
422 for(i = 1;i < evCount;i++)
424 evOffset[i] = fgetc(f);
425 evOffset[i] |= fgetc(f)<<8;
426 if(evOffset[i] <= evOffset[i-1])
428 ERR("Invalid evOffset: evOffset[%d]=%d (last=%d)\n",
429 i, evOffset[i], evOffset[i-1]);
430 failed = AL_TRUE;
433 azCount[i-1] = evOffset[i] - evOffset[i-1];
434 if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
436 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
437 i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
438 failed = AL_TRUE;
441 if(irCount <= evOffset[i-1])
443 ERR("Invalid evOffset: evOffset[%d]=%d (irCount=%d)\n",
444 i-1, evOffset[i-1], irCount);
445 failed = AL_TRUE;
448 azCount[i-1] = irCount - evOffset[i-1];
449 if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
451 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
452 i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
453 failed = AL_TRUE;
457 if(!failed)
459 coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
460 delays = malloc(sizeof(delays[0])*irCount);
461 if(coeffs == NULL || delays == NULL)
463 ERR("Out of memory.\n");
464 failed = AL_TRUE;
468 if(!failed)
470 for(i = 0;i < irCount*irSize;i+=irSize)
472 for(j = 0;j < irSize;j++)
474 ALshort coeff;
475 coeff = fgetc(f);
476 coeff |= fgetc(f)<<8;
477 coeffs[i+j] = coeff;
480 for(i = 0;i < irCount;i++)
482 delays[i] = fgetc(f);
483 if(delays[i] > maxDelay)
485 ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i], maxDelay);
486 failed = AL_TRUE;
490 if(feof(f))
492 ERR("Premature end of data\n");
493 failed = AL_TRUE;
497 if(!failed)
499 Hrtf = malloc(sizeof(struct Hrtf));
500 if(Hrtf == NULL)
502 ERR("Out of memory.\n");
503 failed = AL_TRUE;
507 if(!failed)
509 Hrtf->sampleRate = rate;
510 Hrtf->irSize = irSize;
511 Hrtf->evCount = evCount;
512 Hrtf->azCount = azCount;
513 Hrtf->evOffset = evOffset;
514 Hrtf->coeffs = coeffs;
515 Hrtf->delays = delays;
516 Hrtf->next = NULL;
517 return Hrtf;
520 free(azCount);
521 free(evOffset);
522 free(coeffs);
523 free(delays);
524 return NULL;
528 static struct Hrtf *LoadHrtf01(FILE *f, ALuint deviceRate)
530 const ALubyte maxDelay = SRC_HISTORY_LENGTH-1;
531 struct Hrtf *Hrtf = NULL;
532 ALboolean failed = AL_FALSE;
533 ALuint rate = 0, irCount = 0;
534 ALubyte irSize = 0, evCount = 0;
535 ALubyte *azCount = NULL;
536 ALushort *evOffset = NULL;
537 ALshort *coeffs = NULL;
538 ALubyte *delays = NULL;
539 ALuint i, j;
541 rate = fgetc(f);
542 rate |= fgetc(f)<<8;
543 rate |= fgetc(f)<<16;
544 rate |= fgetc(f)<<24;
546 irSize = fgetc(f);
548 evCount = fgetc(f);
550 if(rate != deviceRate)
552 ERR("HRIR rate does not match device rate: rate=%d (%d)\n",
553 rate, deviceRate);
554 failed = AL_TRUE;
556 if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
558 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
559 irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
560 failed = AL_TRUE;
562 if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
564 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
565 evCount, MIN_EV_COUNT, MAX_EV_COUNT);
566 failed = AL_TRUE;
569 if(failed)
570 return NULL;
572 azCount = malloc(sizeof(azCount[0])*evCount);
573 evOffset = malloc(sizeof(evOffset[0])*evCount);
574 if(azCount == NULL || evOffset == NULL)
576 ERR("Out of memory.\n");
577 failed = AL_TRUE;
580 if(!failed)
582 for(i = 0;i < evCount;i++)
584 azCount[i] = fgetc(f);
585 if(azCount[i] < MIN_AZ_COUNT || azCount[i] > MAX_AZ_COUNT)
587 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
588 i, azCount[i], MIN_AZ_COUNT, MAX_AZ_COUNT);
589 failed = AL_TRUE;
594 if(!failed)
596 evOffset[0] = 0;
597 irCount = azCount[0];
598 for(i = 1;i < evCount;i++)
600 evOffset[i] = evOffset[i-1] + azCount[i-1];
601 irCount += azCount[i];
604 coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
605 delays = malloc(sizeof(delays[0])*irCount);
606 if(coeffs == NULL || delays == NULL)
608 ERR("Out of memory.\n");
609 failed = AL_TRUE;
613 if(!failed)
615 for(i = 0;i < irCount*irSize;i+=irSize)
617 for(j = 0;j < irSize;j++)
619 ALshort coeff;
620 coeff = fgetc(f);
621 coeff |= fgetc(f)<<8;
622 coeffs[i+j] = coeff;
625 for(i = 0;i < irCount;i++)
627 delays[i] = fgetc(f);
628 if(delays[i] > maxDelay)
630 ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i], maxDelay);
631 failed = AL_TRUE;
635 if(feof(f))
637 ERR("Premature end of data\n");
638 failed = AL_TRUE;
642 if(!failed)
644 Hrtf = malloc(sizeof(struct Hrtf));
645 if(Hrtf == NULL)
647 ERR("Out of memory.\n");
648 failed = AL_TRUE;
652 if(!failed)
654 Hrtf->sampleRate = rate;
655 Hrtf->irSize = irSize;
656 Hrtf->evCount = evCount;
657 Hrtf->azCount = azCount;
658 Hrtf->evOffset = evOffset;
659 Hrtf->coeffs = coeffs;
660 Hrtf->delays = delays;
661 Hrtf->next = NULL;
662 return Hrtf;
665 free(azCount);
666 free(evOffset);
667 free(coeffs);
668 free(delays);
669 return NULL;
672 static FILE *OpenDataFile(const char *fname, const char *subdir)
674 char buffer[PATH_MAX] = "";
675 FILE *f;
677 #ifdef _WIN32
678 /* If the path is absolute, open it directly. */
679 if(fname[0] != '\0' && fname[1] == ':' && (fname[2] == '\\' || fname[2] == '/'))
681 if((f=fopen(fname, "rb")) != NULL)
683 TRACE("Opened %s\n", fname);
684 return f;
686 WARN("Could not open %s\n", fname);
688 else
690 static const int ids[2] = { CSIDL_APPDATA, CSIDL_COMMON_APPDATA };
691 int i;
693 for(i = 0;i < 2;i++)
695 size_t len;
697 if(SHGetSpecialFolderPathA(NULL, buffer, ids[i], FALSE) == FALSE)
698 continue;
700 len = strlen(buffer);
701 if(len > 0 && (buffer[len-1] == '\\' || buffer[len-1] == '/'))
702 buffer[--len] = '\0';
703 snprintf(buffer+len, sizeof(buffer)-len, "/%s/%s", subdir, fname);
704 len = strlen(buffer);
705 while(len > 0)
707 --len;
708 if(buffer[len] == '/')
709 buffer[len] = '\\';
712 if((f=fopen(buffer, "rb")) != NULL)
714 TRACE("Opened %s\n", buffer);
715 return f;
717 WARN("Could not open %s\n", buffer);
720 #else
721 const char *str, *next;
723 if(fname[0] == '/')
725 if((f=fopen(fname, "rb")) != NULL)
727 TRACE("Opened %s\n", fname);
728 return f;
730 WARN("Could not open %s\n", fname);
732 if((str=getenv("XDG_DATA_HOME")) != NULL && str[0] != '\0')
733 snprintf(buffer, sizeof(buffer), "%s/%s/%s", str, subdir, fname);
734 else if((str=getenv("HOME")) != NULL && str[0] != '\0')
735 snprintf(buffer, sizeof(buffer), "%s/.local/share/%s/%s", str, subdir, fname);
736 if(buffer[0])
738 if((f=fopen(buffer, "rb")) != NULL)
740 TRACE("Opened %s\n", buffer);
741 return f;
743 WARN("Could not open %s\n", buffer);
746 if((str=getenv("XDG_DATA_DIRS")) == NULL || str[0] == '\0')
747 str = " /usr/local/share/:/usr/share/";
749 next = str;
750 while((str=next) != NULL && str[0] != '\0')
752 size_t len;
753 next = strchr(str, ':');
755 if(!next)
756 len = strlen(str);
757 else
759 len = next - str;
760 next++;
763 if(len > sizeof(buffer)-1)
764 len = sizeof(buffer)-1;
765 strncpy(buffer, str, len);
766 buffer[len] = '\0';
767 snprintf(buffer+len, sizeof(buffer)-len, "/%s/%s", subdir, fname);
769 if((f=fopen(buffer, "rb")) != NULL)
771 TRACE("Opened %s\n", buffer);
772 return f;
774 WARN("Could not open %s\n", buffer);
776 #endif
778 return NULL;
781 static struct Hrtf *LoadHrtf(ALuint deviceRate)
783 const char *fnamelist = "default-%r.mhr";
785 ConfigValueStr(NULL, "hrtf_tables", &fnamelist);
786 while(*fnamelist != '\0')
788 struct Hrtf *Hrtf = NULL;
789 char fname[PATH_MAX];
790 const char *next;
791 ALchar magic[8];
792 ALuint i;
793 FILE *f;
795 i = 0;
796 while(isspace(*fnamelist) || *fnamelist == ',')
797 fnamelist++;
798 next = fnamelist;
799 while(*(fnamelist=next) != '\0' && *fnamelist != ',')
801 next = strpbrk(fnamelist, "%,$");
802 while(fnamelist != next && *fnamelist && i < sizeof(fname))
803 fname[i++] = *(fnamelist++);
805 if(!next || *next == ',')
806 break;
808 if(*next == '$')
810 next++;
811 if(*next == '$')
813 /* '$$' becomes a single '$'. */
814 if(i < sizeof(fname))
815 fname[i++] = '$';
816 next++;
818 else
820 const char *str;
821 char envname[1024];
822 size_t k = 0;
824 while((isalnum(*next) || *next == '_') && k < sizeof(envname)-1)
825 envname[k++] = *(next++);
826 envname[k++] = '\0';
828 if((str=getenv(envname)) != NULL)
830 int wrote = snprintf(&fname[i], sizeof(fname)-i, "%s", str);
831 i += minu(wrote, sizeof(fname)-i);
834 continue;
837 /* *next == '%' */
838 next++;
839 if(*next == 'r')
841 int wrote = snprintf(&fname[i], sizeof(fname)-i, "%u", deviceRate);
842 i += minu(wrote, sizeof(fname)-i);
843 next++;
845 else if(*next == '%')
847 if(i < sizeof(fname))
848 fname[i++] = '%';
849 next++;
851 else
852 ERR("Invalid marker '%%%c'\n", *next);
854 i = minu(i, sizeof(fname)-1);
855 fname[i] = '\0';
856 while(i > 0 && isspace(fname[i-1]))
857 i--;
858 fname[i] = '\0';
860 if(fname[0] == '\0')
861 continue;
863 TRACE("Loading %s...\n", fname);
864 f = OpenDataFile(fname, "openal/hrtf");
865 if(f == NULL)
867 ERR("Could not open %s\n", fname);
868 continue;
871 if(fread(magic, 1, sizeof(magic), f) != sizeof(magic))
872 ERR("Failed to read header from %s\n", fname);
873 else
875 if(memcmp(magic, magicMarker00, sizeof(magicMarker00)) == 0)
877 TRACE("Detected data set format v0\n");
878 Hrtf = LoadHrtf00(f, deviceRate);
880 else if(memcmp(magic, magicMarker01, sizeof(magicMarker01)) == 0)
882 TRACE("Detected data set format v1\n");
883 Hrtf = LoadHrtf01(f, deviceRate);
885 else
886 ERR("Invalid header in %s: \"%.8s\"\n", fname, magic);
889 fclose(f);
890 f = NULL;
892 if(Hrtf)
894 Hrtf->next = LoadedHrtfs;
895 LoadedHrtfs = Hrtf;
896 TRACE("Loaded HRTF support for format: %s %uhz\n",
897 DevFmtChannelsString(DevFmtStereo), Hrtf->sampleRate);
898 return Hrtf;
901 ERR("Failed to load %s\n", fname);
904 return NULL;
907 const struct Hrtf *GetHrtf(ALCdevice *device)
909 if(device->FmtChans == DevFmtStereo)
911 struct Hrtf *Hrtf = LoadedHrtfs;
912 while(Hrtf != NULL)
914 if(device->Frequency == Hrtf->sampleRate)
915 return Hrtf;
916 Hrtf = Hrtf->next;
919 Hrtf = LoadHrtf(device->Frequency);
920 if(Hrtf != NULL)
921 return Hrtf;
923 ERR("Incompatible format: %s %uhz\n",
924 DevFmtChannelsString(device->FmtChans), device->Frequency);
925 return NULL;
928 ALCboolean FindHrtfFormat(const ALCdevice *device, enum DevFmtChannels *chans, ALCuint *srate)
930 const struct Hrtf *hrtf = LoadedHrtfs;
931 while(hrtf != NULL)
933 if(device->Frequency == hrtf->sampleRate)
934 break;
935 hrtf = hrtf->next;
938 if(hrtf == NULL)
940 hrtf = LoadHrtf(device->Frequency);
941 if(hrtf == NULL) return ALC_FALSE;
944 *chans = DevFmtStereo;
945 *srate = hrtf->sampleRate;
946 return ALC_TRUE;
949 void FreeHrtfs(void)
951 struct Hrtf *Hrtf = NULL;
953 while((Hrtf=LoadedHrtfs) != NULL)
955 LoadedHrtfs = Hrtf->next;
956 free((void*)Hrtf->azCount);
957 free((void*)Hrtf->evOffset);
958 free((void*)Hrtf->coeffs);
959 free((void*)Hrtf->delays);
960 free(Hrtf);
964 ALuint GetHrtfIrSize (const struct Hrtf *Hrtf)
966 return Hrtf->irSize;