Better organize the reverb code into separate labeled sections
[openal-soft.git] / Alc / hrtf.c
blob467232d7568dd03dec82952f7f8fcf0f1cdb75a9
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 "hrtf.h"
33 #include "compat.h"
36 /* Current data set limits defined by the makehrtf utility. */
37 #define MIN_IR_SIZE (8)
38 #define MAX_IR_SIZE (128)
39 #define MOD_IR_SIZE (8)
41 #define MIN_EV_COUNT (5)
42 #define MAX_EV_COUNT (128)
44 #define MIN_AZ_COUNT (1)
45 #define MAX_AZ_COUNT (128)
47 struct Hrtf {
48 ALuint sampleRate;
49 ALuint irSize;
50 ALubyte evCount;
52 const ALubyte *azCount;
53 const ALushort *evOffset;
54 const ALshort *coeffs;
55 const ALubyte *delays;
57 al_string filename;
58 struct Hrtf *next;
61 static const ALchar magicMarker00[8] = "MinPHR00";
62 static const ALchar magicMarker01[8] = "MinPHR01";
64 /* First value for pass-through coefficients (remaining are 0), used for omni-
65 * directional sounds. */
66 static const ALfloat PassthruCoeff = 32767.0f * 0.707106781187f/*sqrt(0.5)*/;
68 static struct Hrtf *LoadedHrtfs = NULL;
70 /* Calculate the elevation indices given the polar elevation in radians.
71 * This will return two indices between 0 and (evcount - 1) and an
72 * interpolation factor between 0.0 and 1.0.
74 static void CalcEvIndices(ALuint evcount, ALfloat ev, ALuint *evidx, ALfloat *evmu)
76 ev = (F_PI_2 + ev) * (evcount-1) / F_PI;
77 evidx[0] = fastf2u(ev);
78 evidx[1] = minu(evidx[0] + 1, evcount-1);
79 *evmu = ev - evidx[0];
82 /* Calculate the azimuth indices given the polar azimuth in radians. This
83 * will return two indices between 0 and (azcount - 1) and an interpolation
84 * factor between 0.0 and 1.0.
86 static void CalcAzIndices(ALuint azcount, ALfloat az, ALuint *azidx, ALfloat *azmu)
88 az = (F_TAU + az) * azcount / F_TAU;
89 azidx[0] = fastf2u(az) % azcount;
90 azidx[1] = (azidx[0] + 1) % azcount;
91 *azmu = az - floorf(az);
94 /* Calculates static HRIR coefficients and delays for the given polar
95 * elevation and azimuth in radians. Linear interpolation is used to
96 * increase the apparent resolution of the HRIR data set. The coefficients
97 * are also normalized and attenuated by the specified gain.
99 void GetLerpedHrtfCoeffs(const struct Hrtf *Hrtf, ALfloat elevation, ALfloat azimuth, ALfloat dirfact, ALfloat gain, ALfloat (*coeffs)[2], ALuint *delays)
101 ALuint evidx[2], lidx[4], ridx[4];
102 ALfloat mu[3], blend[4];
103 ALuint i;
105 /* Claculate elevation indices and interpolation factor. */
106 CalcEvIndices(Hrtf->evCount, elevation, evidx, &mu[2]);
108 for(i = 0;i < 2;i++)
110 ALuint azcount = Hrtf->azCount[evidx[i]];
111 ALuint evoffset = Hrtf->evOffset[evidx[i]];
112 ALuint azidx[2];
114 /* Calculate azimuth indices and interpolation factor for this elevation. */
115 CalcAzIndices(azcount, azimuth, azidx, &mu[i]);
117 /* Calculate a set of linear HRIR indices for left and right channels. */
118 lidx[i*2 + 0] = evoffset + azidx[0];
119 lidx[i*2 + 1] = evoffset + azidx[1];
120 ridx[i*2 + 0] = evoffset + ((azcount-azidx[0]) % azcount);
121 ridx[i*2 + 1] = evoffset + ((azcount-azidx[1]) % azcount);
124 /* Calculate 4 blending weights for 2D bilinear interpolation. */
125 blend[0] = (1.0f-mu[0]) * (1.0f-mu[2]);
126 blend[1] = ( mu[0]) * (1.0f-mu[2]);
127 blend[2] = (1.0f-mu[1]) * ( mu[2]);
128 blend[3] = ( mu[1]) * ( mu[2]);
130 /* Calculate the HRIR delays using linear interpolation. */
131 delays[0] = fastf2u((Hrtf->delays[lidx[0]]*blend[0] + Hrtf->delays[lidx[1]]*blend[1] +
132 Hrtf->delays[lidx[2]]*blend[2] + Hrtf->delays[lidx[3]]*blend[3]) *
133 dirfact + 0.5f) << HRTFDELAY_BITS;
134 delays[1] = fastf2u((Hrtf->delays[ridx[0]]*blend[0] + Hrtf->delays[ridx[1]]*blend[1] +
135 Hrtf->delays[ridx[2]]*blend[2] + Hrtf->delays[ridx[3]]*blend[3]) *
136 dirfact + 0.5f) << HRTFDELAY_BITS;
138 /* Calculate the sample offsets for the HRIR indices. */
139 lidx[0] *= Hrtf->irSize;
140 lidx[1] *= Hrtf->irSize;
141 lidx[2] *= Hrtf->irSize;
142 lidx[3] *= Hrtf->irSize;
143 ridx[0] *= Hrtf->irSize;
144 ridx[1] *= Hrtf->irSize;
145 ridx[2] *= Hrtf->irSize;
146 ridx[3] *= Hrtf->irSize;
148 /* Calculate the normalized and attenuated HRIR coefficients using linear
149 * interpolation when there is enough gain to warrant it. Zero the
150 * coefficients if gain is too low.
152 if(gain > 0.0001f)
154 ALfloat c;
156 i = 0;
157 c = (Hrtf->coeffs[lidx[0]+i]*blend[0] + Hrtf->coeffs[lidx[1]+i]*blend[1] +
158 Hrtf->coeffs[lidx[2]+i]*blend[2] + Hrtf->coeffs[lidx[3]+i]*blend[3]);
159 coeffs[i][0] = lerp(PassthruCoeff, c, dirfact) * gain * (1.0f/32767.0f);
160 c = (Hrtf->coeffs[ridx[0]+i]*blend[0] + Hrtf->coeffs[ridx[1]+i]*blend[1] +
161 Hrtf->coeffs[ridx[2]+i]*blend[2] + Hrtf->coeffs[ridx[3]+i]*blend[3]);
162 coeffs[i][1] = lerp(PassthruCoeff, c, dirfact) * gain * (1.0f/32767.0f);
164 for(i = 1;i < Hrtf->irSize;i++)
166 c = (Hrtf->coeffs[lidx[0]+i]*blend[0] + Hrtf->coeffs[lidx[1]+i]*blend[1] +
167 Hrtf->coeffs[lidx[2]+i]*blend[2] + Hrtf->coeffs[lidx[3]+i]*blend[3]);
168 coeffs[i][0] = lerp(0.0f, c, dirfact) * gain * (1.0f/32767.0f);
169 c = (Hrtf->coeffs[ridx[0]+i]*blend[0] + Hrtf->coeffs[ridx[1]+i]*blend[1] +
170 Hrtf->coeffs[ridx[2]+i]*blend[2] + Hrtf->coeffs[ridx[3]+i]*blend[3]);
171 coeffs[i][1] = lerp(0.0f, c, dirfact) * gain * (1.0f/32767.0f);
174 else
176 for(i = 0;i < Hrtf->irSize;i++)
178 coeffs[i][0] = 0.0f;
179 coeffs[i][1] = 0.0f;
184 /* Calculates the moving HRIR target coefficients, target delays, and
185 * stepping values for the given polar elevation and azimuth in radians.
186 * Linear interpolation is used to increase the apparent resolution of the
187 * HRIR data set. The coefficients are also normalized and attenuated by the
188 * specified gain. Stepping resolution and count is determined using the
189 * given delta factor between 0.0 and 1.0.
191 ALuint GetMovingHrtfCoeffs(const struct Hrtf *Hrtf, ALfloat elevation, ALfloat azimuth, ALfloat dirfact, ALfloat gain, ALfloat delta, ALint counter, ALfloat (*coeffs)[2], ALuint *delays, ALfloat (*coeffStep)[2], ALint *delayStep)
193 ALuint evidx[2], lidx[4], ridx[4];
194 ALfloat mu[3], blend[4];
195 ALfloat left, right;
196 ALfloat steps;
197 ALuint i;
199 /* Claculate elevation indices and interpolation factor. */
200 CalcEvIndices(Hrtf->evCount, elevation, evidx, &mu[2]);
202 for(i = 0;i < 2;i++)
204 ALuint azcount = Hrtf->azCount[evidx[i]];
205 ALuint evoffset = Hrtf->evOffset[evidx[i]];
206 ALuint azidx[2];
208 /* Calculate azimuth indices and interpolation factor for this elevation. */
209 CalcAzIndices(azcount, azimuth, azidx, &mu[i]);
211 /* Calculate a set of linear HRIR indices for left and right channels. */
212 lidx[i*2 + 0] = evoffset + azidx[0];
213 lidx[i*2 + 1] = evoffset + azidx[1];
214 ridx[i*2 + 0] = evoffset + ((azcount-azidx[0]) % azcount);
215 ridx[i*2 + 1] = evoffset + ((azcount-azidx[1]) % azcount);
218 // Calculate the stepping parameters.
219 steps = maxf(floorf(delta*Hrtf->sampleRate + 0.5f), 1.0f);
220 delta = 1.0f / steps;
222 /* Calculate 4 blending weights for 2D bilinear interpolation. */
223 blend[0] = (1.0f-mu[0]) * (1.0f-mu[2]);
224 blend[1] = ( mu[0]) * (1.0f-mu[2]);
225 blend[2] = (1.0f-mu[1]) * ( mu[2]);
226 blend[3] = ( mu[1]) * ( mu[2]);
228 /* Calculate the HRIR delays using linear interpolation. Then calculate
229 * the delay stepping values using the target and previous running
230 * delays.
232 left = (ALfloat)(delays[0] - (delayStep[0] * counter));
233 right = (ALfloat)(delays[1] - (delayStep[1] * counter));
235 delays[0] = fastf2u((Hrtf->delays[lidx[0]]*blend[0] + Hrtf->delays[lidx[1]]*blend[1] +
236 Hrtf->delays[lidx[2]]*blend[2] + Hrtf->delays[lidx[3]]*blend[3]) *
237 dirfact + 0.5f) << HRTFDELAY_BITS;
238 delays[1] = fastf2u((Hrtf->delays[ridx[0]]*blend[0] + Hrtf->delays[ridx[1]]*blend[1] +
239 Hrtf->delays[ridx[2]]*blend[2] + Hrtf->delays[ridx[3]]*blend[3]) *
240 dirfact + 0.5f) << HRTFDELAY_BITS;
242 delayStep[0] = fastf2i(delta * (delays[0] - left));
243 delayStep[1] = fastf2i(delta * (delays[1] - right));
245 /* Calculate the sample offsets for the HRIR indices. */
246 lidx[0] *= Hrtf->irSize;
247 lidx[1] *= Hrtf->irSize;
248 lidx[2] *= Hrtf->irSize;
249 lidx[3] *= Hrtf->irSize;
250 ridx[0] *= Hrtf->irSize;
251 ridx[1] *= Hrtf->irSize;
252 ridx[2] *= Hrtf->irSize;
253 ridx[3] *= Hrtf->irSize;
255 /* Calculate the normalized and attenuated target HRIR coefficients using
256 * linear interpolation when there is enough gain to warrant it. Zero
257 * the target coefficients if gain is too low. Then calculate the
258 * coefficient stepping values using the target and previous running
259 * coefficients.
261 if(gain > 0.0001f)
263 ALfloat c;
265 i = 0;
266 left = coeffs[i][0] - (coeffStep[i][0] * counter);
267 right = coeffs[i][1] - (coeffStep[i][1] * counter);
269 c = (Hrtf->coeffs[lidx[0]+i]*blend[0] + Hrtf->coeffs[lidx[1]+i]*blend[1] +
270 Hrtf->coeffs[lidx[2]+i]*blend[2] + Hrtf->coeffs[lidx[3]+i]*blend[3]);
271 coeffs[i][0] = lerp(PassthruCoeff, c, dirfact) * gain * (1.0f/32767.0f);
272 c = (Hrtf->coeffs[ridx[0]+i]*blend[0] + Hrtf->coeffs[ridx[1]+i]*blend[1] +
273 Hrtf->coeffs[ridx[2]+i]*blend[2] + Hrtf->coeffs[ridx[3]+i]*blend[3]);
274 coeffs[i][1] = lerp(PassthruCoeff, c, dirfact) * gain * (1.0f/32767.0f);
276 coeffStep[i][0] = delta * (coeffs[i][0] - left);
277 coeffStep[i][1] = delta * (coeffs[i][1] - right);
279 for(i = 1;i < Hrtf->irSize;i++)
281 left = coeffs[i][0] - (coeffStep[i][0] * counter);
282 right = coeffs[i][1] - (coeffStep[i][1] * counter);
284 c = (Hrtf->coeffs[lidx[0]+i]*blend[0] + Hrtf->coeffs[lidx[1]+i]*blend[1] +
285 Hrtf->coeffs[lidx[2]+i]*blend[2] + Hrtf->coeffs[lidx[3]+i]*blend[3]);
286 coeffs[i][0] = lerp(0.0f, c, dirfact) * gain * (1.0f/32767.0f);
287 c = (Hrtf->coeffs[ridx[0]+i]*blend[0] + Hrtf->coeffs[ridx[1]+i]*blend[1] +
288 Hrtf->coeffs[ridx[2]+i]*blend[2] + Hrtf->coeffs[ridx[3]+i]*blend[3]);
289 coeffs[i][1] = lerp(0.0f, c, dirfact) * gain * (1.0f/32767.0f);
291 coeffStep[i][0] = delta * (coeffs[i][0] - left);
292 coeffStep[i][1] = delta * (coeffs[i][1] - right);
295 else
297 for(i = 0;i < Hrtf->irSize;i++)
299 left = coeffs[i][0] - (coeffStep[i][0] * counter);
300 right = coeffs[i][1] - (coeffStep[i][1] * counter);
302 coeffs[i][0] = 0.0f;
303 coeffs[i][1] = 0.0f;
305 coeffStep[i][0] = delta * -left;
306 coeffStep[i][1] = delta * -right;
310 /* The stepping count is the number of samples necessary for the HRIR to
311 * complete its transition. The mixer will only apply stepping for this
312 * many samples.
314 return fastf2u(steps);
318 /* Calculates HRTF coefficients for B-Format channels (only up to first-order).
319 * Note that these will decode a B-Format output mix, which uses FuMa ordering
320 * and scaling, not N3D!
322 void GetBFormatHrtfCoeffs(const struct Hrtf *Hrtf, const ALuint num_chans, ALfloat (**coeffs_list)[2], ALuint **delay_list)
324 ALuint elev_idx, azi_idx;
325 ALfloat scale;
326 ALuint i, c;
328 assert(num_chans <= 4);
330 for(c = 0;c < num_chans;c++)
332 ALfloat (*coeffs)[2] = coeffs_list[c];
333 ALuint *delay = delay_list[c];
335 for(i = 0;i < Hrtf->irSize;i++)
337 coeffs[i][0] = 0.0f;
338 coeffs[i][1] = 0.0f;
340 delay[0] = 0;
341 delay[1] = 0;
344 /* NOTE: HRTF coefficients are generated by combining all the HRIRs in the
345 * dataset, with each entry scaled according to how much it contributes to
346 * the given B-Format channel based on its direction (including negative
347 * contributions!).
349 scale = 0.0f;
350 for(elev_idx = 0;elev_idx < Hrtf->evCount;elev_idx++)
352 ALfloat elev = (ALfloat)elev_idx/(ALfloat)(Hrtf->evCount-1)*F_PI - F_PI_2;
353 ALuint evoffset = Hrtf->evOffset[elev_idx];
354 ALuint azcount = Hrtf->azCount[elev_idx];
356 scale += (ALfloat)azcount;
358 for(azi_idx = 0;azi_idx < azcount;azi_idx++)
360 ALuint lidx, ridx;
361 ALfloat ambi_coeffs[4];
362 ALfloat az, gain;
363 ALfloat x, y, z;
365 lidx = evoffset + azi_idx;
366 ridx = evoffset + ((azcount-azi_idx) % azcount);
368 az = (ALfloat)azi_idx / (ALfloat)azcount * F_TAU;
369 if(az > F_PI) az -= F_TAU;
371 x = cosf(-az) * cosf(elev);
372 y = sinf(-az) * cosf(elev);
373 z = sinf(elev);
375 ambi_coeffs[0] = 1.414213562f;
376 ambi_coeffs[1] = x;
377 ambi_coeffs[2] = y;
378 ambi_coeffs[3] = z;
380 for(c = 0;c < num_chans;c++)
382 ALfloat (*coeffs)[2] = coeffs_list[c];
383 ALuint *delay = delay_list[c];
385 /* NOTE: Always include the total delay average since the
386 * channels need to have matching delays. */
387 delay[0] += Hrtf->delays[lidx];
388 delay[1] += Hrtf->delays[ridx];
390 gain = ambi_coeffs[c];
391 if(!(fabsf(gain) > GAIN_SILENCE_THRESHOLD))
392 continue;
394 for(i = 0;i < Hrtf->irSize;i++)
396 coeffs[i][0] += Hrtf->coeffs[lidx*Hrtf->irSize + i]*(1.0f/32767.0f) * gain;
397 coeffs[i][1] += Hrtf->coeffs[ridx*Hrtf->irSize + i]*(1.0f/32767.0f) * gain;
403 scale = 1.0f/scale;
405 for(c = 0;c < num_chans;c++)
407 ALfloat (*coeffs)[2] = coeffs_list[c];
408 ALuint *delay = delay_list[c];
410 for(i = 0;i < Hrtf->irSize;i++)
412 coeffs[i][0] *= scale;
413 coeffs[i][1] *= scale;
415 delay[0] = minu((ALuint)((ALfloat)delay[0] * scale), HRTF_HISTORY_LENGTH-1);
416 delay[0] <<= HRTFDELAY_BITS;
417 delay[1] = minu((ALuint)((ALfloat)delay[1] * scale), HRTF_HISTORY_LENGTH-1);
418 delay[1] <<= HRTFDELAY_BITS;
423 static struct Hrtf *LoadHrtf00(FILE *f)
425 const ALubyte maxDelay = HRTF_HISTORY_LENGTH-1;
426 struct Hrtf *Hrtf = NULL;
427 ALboolean failed = AL_FALSE;
428 ALuint rate = 0, irCount = 0;
429 ALushort irSize = 0;
430 ALubyte evCount = 0;
431 ALubyte *azCount = NULL;
432 ALushort *evOffset = NULL;
433 ALshort *coeffs = NULL;
434 ALubyte *delays = NULL;
435 ALuint i, j;
437 rate = fgetc(f);
438 rate |= fgetc(f)<<8;
439 rate |= fgetc(f)<<16;
440 rate |= fgetc(f)<<24;
442 irCount = fgetc(f);
443 irCount |= fgetc(f)<<8;
445 irSize = fgetc(f);
446 irSize |= fgetc(f)<<8;
448 evCount = fgetc(f);
450 if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
452 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
453 irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
454 failed = AL_TRUE;
456 if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
458 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
459 evCount, MIN_EV_COUNT, MAX_EV_COUNT);
460 failed = AL_TRUE;
463 if(failed)
464 return NULL;
466 azCount = malloc(sizeof(azCount[0])*evCount);
467 evOffset = malloc(sizeof(evOffset[0])*evCount);
468 if(azCount == NULL || evOffset == NULL)
470 ERR("Out of memory.\n");
471 failed = AL_TRUE;
474 if(!failed)
476 evOffset[0] = fgetc(f);
477 evOffset[0] |= fgetc(f)<<8;
478 for(i = 1;i < evCount;i++)
480 evOffset[i] = fgetc(f);
481 evOffset[i] |= fgetc(f)<<8;
482 if(evOffset[i] <= evOffset[i-1])
484 ERR("Invalid evOffset: evOffset[%d]=%d (last=%d)\n",
485 i, evOffset[i], evOffset[i-1]);
486 failed = AL_TRUE;
489 azCount[i-1] = evOffset[i] - evOffset[i-1];
490 if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
492 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
493 i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
494 failed = AL_TRUE;
497 if(irCount <= evOffset[i-1])
499 ERR("Invalid evOffset: evOffset[%d]=%d (irCount=%d)\n",
500 i-1, evOffset[i-1], irCount);
501 failed = AL_TRUE;
504 azCount[i-1] = irCount - evOffset[i-1];
505 if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
507 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
508 i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
509 failed = AL_TRUE;
513 if(!failed)
515 coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
516 delays = malloc(sizeof(delays[0])*irCount);
517 if(coeffs == NULL || delays == NULL)
519 ERR("Out of memory.\n");
520 failed = AL_TRUE;
524 if(!failed)
526 for(i = 0;i < irCount*irSize;i+=irSize)
528 for(j = 0;j < irSize;j++)
530 ALshort coeff;
531 coeff = fgetc(f);
532 coeff |= fgetc(f)<<8;
533 coeffs[i+j] = coeff;
536 for(i = 0;i < irCount;i++)
538 delays[i] = fgetc(f);
539 if(delays[i] > maxDelay)
541 ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i], maxDelay);
542 failed = AL_TRUE;
546 if(feof(f))
548 ERR("Premature end of data\n");
549 failed = AL_TRUE;
553 if(!failed)
555 Hrtf = malloc(sizeof(struct Hrtf));
556 if(Hrtf == NULL)
558 ERR("Out of memory.\n");
559 failed = AL_TRUE;
563 if(!failed)
565 Hrtf->sampleRate = rate;
566 Hrtf->irSize = irSize;
567 Hrtf->evCount = evCount;
568 Hrtf->azCount = azCount;
569 Hrtf->evOffset = evOffset;
570 Hrtf->coeffs = coeffs;
571 Hrtf->delays = delays;
572 AL_STRING_INIT(Hrtf->filename);
573 Hrtf->next = NULL;
574 return Hrtf;
577 free(azCount);
578 free(evOffset);
579 free(coeffs);
580 free(delays);
581 return NULL;
585 static struct Hrtf *LoadHrtf01(FILE *f)
587 const ALubyte maxDelay = HRTF_HISTORY_LENGTH-1;
588 struct Hrtf *Hrtf = NULL;
589 ALboolean failed = AL_FALSE;
590 ALuint rate = 0, irCount = 0;
591 ALubyte irSize = 0, evCount = 0;
592 ALubyte *azCount = NULL;
593 ALushort *evOffset = NULL;
594 ALshort *coeffs = NULL;
595 ALubyte *delays = NULL;
596 ALuint i, j;
598 rate = fgetc(f);
599 rate |= fgetc(f)<<8;
600 rate |= fgetc(f)<<16;
601 rate |= fgetc(f)<<24;
603 irSize = fgetc(f);
605 evCount = fgetc(f);
607 if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
609 ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
610 irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
611 failed = AL_TRUE;
613 if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
615 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
616 evCount, MIN_EV_COUNT, MAX_EV_COUNT);
617 failed = AL_TRUE;
620 if(failed)
621 return NULL;
623 azCount = malloc(sizeof(azCount[0])*evCount);
624 evOffset = malloc(sizeof(evOffset[0])*evCount);
625 if(azCount == NULL || evOffset == NULL)
627 ERR("Out of memory.\n");
628 failed = AL_TRUE;
631 if(!failed)
633 for(i = 0;i < evCount;i++)
635 azCount[i] = fgetc(f);
636 if(azCount[i] < MIN_AZ_COUNT || azCount[i] > MAX_AZ_COUNT)
638 ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
639 i, azCount[i], MIN_AZ_COUNT, MAX_AZ_COUNT);
640 failed = AL_TRUE;
645 if(!failed)
647 evOffset[0] = 0;
648 irCount = azCount[0];
649 for(i = 1;i < evCount;i++)
651 evOffset[i] = evOffset[i-1] + azCount[i-1];
652 irCount += azCount[i];
655 coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
656 delays = malloc(sizeof(delays[0])*irCount);
657 if(coeffs == NULL || delays == NULL)
659 ERR("Out of memory.\n");
660 failed = AL_TRUE;
664 if(!failed)
666 for(i = 0;i < irCount*irSize;i+=irSize)
668 for(j = 0;j < irSize;j++)
670 ALshort coeff;
671 coeff = fgetc(f);
672 coeff |= fgetc(f)<<8;
673 coeffs[i+j] = coeff;
676 for(i = 0;i < irCount;i++)
678 delays[i] = fgetc(f);
679 if(delays[i] > maxDelay)
681 ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i], maxDelay);
682 failed = AL_TRUE;
686 if(feof(f))
688 ERR("Premature end of data\n");
689 failed = AL_TRUE;
693 if(!failed)
695 Hrtf = malloc(sizeof(struct Hrtf));
696 if(Hrtf == NULL)
698 ERR("Out of memory.\n");
699 failed = AL_TRUE;
703 if(!failed)
705 Hrtf->sampleRate = rate;
706 Hrtf->irSize = irSize;
707 Hrtf->evCount = evCount;
708 Hrtf->azCount = azCount;
709 Hrtf->evOffset = evOffset;
710 Hrtf->coeffs = coeffs;
711 Hrtf->delays = delays;
712 AL_STRING_INIT(Hrtf->filename);
713 Hrtf->next = NULL;
714 return Hrtf;
717 free(azCount);
718 free(evOffset);
719 free(coeffs);
720 free(delays);
721 return NULL;
725 static void AddFileEntry(vector_HrtfEntry *list, al_string *filename)
727 HrtfEntry entry = { AL_STRING_INIT_STATIC(), *filename, NULL };
728 HrtfEntry *iter;
729 const char *name;
730 int i;
732 name = strrchr(al_string_get_cstr(entry.filename), '/');
733 if(!name) name = strrchr(al_string_get_cstr(entry.filename), '\\');
734 if(!name) name = al_string_get_cstr(entry.filename);
735 else ++name;
737 entry.hrtf = LoadedHrtfs;
738 while(entry.hrtf)
740 if(al_string_cmp(entry.filename, entry.hrtf->filename) == 0)
741 break;
742 entry.hrtf = entry.hrtf->next;
745 if(!entry.hrtf)
747 struct Hrtf *hrtf = NULL;
748 ALchar magic[8];
749 FILE *f;
751 TRACE("Loading %s...\n", al_string_get_cstr(entry.filename));
752 f = al_fopen(al_string_get_cstr(entry.filename), "rb");
753 if(f == NULL)
755 ERR("Could not open %s\n", al_string_get_cstr(entry.filename));
756 goto error;
759 if(fread(magic, 1, sizeof(magic), f) != sizeof(magic))
760 ERR("Failed to read header from %s\n", al_string_get_cstr(entry.filename));
761 else
763 if(memcmp(magic, magicMarker00, sizeof(magicMarker00)) == 0)
765 TRACE("Detected data set format v0\n");
766 hrtf = LoadHrtf00(f);
768 else if(memcmp(magic, magicMarker01, sizeof(magicMarker01)) == 0)
770 TRACE("Detected data set format v1\n");
771 hrtf = LoadHrtf01(f);
773 else
774 ERR("Invalid header in %s: \"%.8s\"\n", al_string_get_cstr(entry.filename), magic);
776 fclose(f);
778 if(!hrtf)
780 ERR("Failed to load %s\n", al_string_get_cstr(entry.filename));
781 goto error;
784 al_string_copy(&hrtf->filename, entry.filename);
785 hrtf->next = LoadedHrtfs;
786 LoadedHrtfs = hrtf;
787 TRACE("Loaded HRTF support for format: %s %uhz\n",
788 DevFmtChannelsString(DevFmtStereo), hrtf->sampleRate);
789 entry.hrtf = hrtf;
792 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
793 * format update). */
795 i = 0;
796 do {
797 al_string_copy_cstr(&entry.name, name);
798 if(i != 0)
800 char str[64];
801 snprintf(str, sizeof(str), " #%d", i+1);
802 al_string_append_cstr(&entry.name, str);
804 ++i;
806 #define MATCH_NAME(i) (al_string_cmp(entry.name, (i)->name) == 0)
807 VECTOR_FIND_IF(iter, HrtfEntry, *list, MATCH_NAME);
808 #undef MATCH_NAME
809 } while(iter != VECTOR_ITER_END(*list));
811 TRACE("Adding entry \"%s\" from file \"%s\"\n", al_string_get_cstr(entry.name),
812 al_string_get_cstr(entry.filename));
813 VECTOR_PUSH_BACK(*list, entry);
814 return;
816 error:
817 al_string_deinit(&entry.filename);
820 vector_HrtfEntry EnumerateHrtf(const_al_string devname)
822 vector_HrtfEntry list = VECTOR_INIT_STATIC();
823 const char *fnamelist = "%s.mhr";
825 ConfigValueStr(al_string_get_cstr(devname), NULL, "hrtf_tables", &fnamelist);
826 while(fnamelist && *fnamelist)
828 while(isspace(*fnamelist) || *fnamelist == ',')
829 fnamelist++;
830 if(*fnamelist != '\0')
832 const char *next, *end;
834 next = strchr(fnamelist, ',');
835 if(!next)
836 end = fnamelist + strlen(fnamelist);
837 else
838 end = next++;
840 while(end != fnamelist && isspace(*(end-1)))
841 --end;
842 if(end != fnamelist)
844 al_string fname = AL_STRING_INIT_STATIC();
845 vector_al_string flist;
847 al_string_append_range(&fname, fnamelist, end);
849 flist = SearchDataFiles(al_string_get_cstr(fname), "openal/hrtf");
850 VECTOR_FOR_EACH_PARAMS(al_string, flist, AddFileEntry, &list);
851 VECTOR_DEINIT(flist);
853 al_string_deinit(&fname);
856 fnamelist = next;
860 return list;
863 void FreeHrtfList(vector_HrtfEntry *list)
865 #define CLEAR_ENTRY(i) do { \
866 al_string_deinit(&(i)->name); \
867 al_string_deinit(&(i)->filename); \
868 } while(0)
869 VECTOR_FOR_EACH(HrtfEntry, *list, CLEAR_ENTRY);
870 VECTOR_DEINIT(*list);
871 #undef CLEAR_ENTRY
875 ALuint GetHrtfSampleRate(const struct Hrtf *Hrtf)
877 return Hrtf->sampleRate;
880 ALuint GetHrtfIrSize(const struct Hrtf *Hrtf)
882 return Hrtf->irSize;
886 void FreeHrtfs(void)
888 struct Hrtf *Hrtf = NULL;
890 while((Hrtf=LoadedHrtfs) != NULL)
892 LoadedHrtfs = Hrtf->next;
893 free((void*)Hrtf->azCount);
894 free((void*)Hrtf->evOffset);
895 free((void*)Hrtf->coeffs);
896 free((void*)Hrtf->delays);
897 al_string_deinit(&Hrtf->filename);
898 free(Hrtf);