1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
|
/**
* OpenAL cross platform audio library
* Copyright (C) 2011 by Chris Robinson
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
* Or go to http://www.gnu.org/copyleft/lgpl.html
*/
#include "config.h"
#include <stdlib.h>
#include <ctype.h>
#include "AL/al.h"
#include "AL/alc.h"
#include "alMain.h"
#include "alSource.h"
#include "alu.h"
#include "bformatdec.h"
#include "hrtf.h"
#include "compat.h"
#include "almalloc.h"
/* Current data set limits defined by the makehrtf utility. */
#define MIN_IR_SIZE (8)
#define MAX_IR_SIZE (128)
#define MOD_IR_SIZE (8)
#define MIN_EV_COUNT (5)
#define MAX_EV_COUNT (128)
#define MIN_AZ_COUNT (1)
#define MAX_AZ_COUNT (128)
static const ALchar magicMarker00[8] = "MinPHR00";
static const ALchar magicMarker01[8] = "MinPHR01";
/* First value for pass-through coefficients (remaining are 0), used for omni-
* directional sounds. */
static const ALfloat PassthruCoeff = 0.707106781187f/*sqrt(0.5)*/;
static struct Hrtf *LoadedHrtfs = NULL;
/* Calculate the elevation index given the polar elevation in radians. This
* will return an index between 0 and (evcount - 1). Assumes the FPU is in
* round-to-zero mode.
*/
static ALsizei CalcEvIndex(ALsizei evcount, ALfloat ev)
{
ev = (F_PI_2 + ev) * (evcount-1) / F_PI;
return mini(fastf2i(ev + 0.5f), evcount-1);
}
/* Calculate the azimuth index given the polar azimuth in radians. This will
* return an index between 0 and (azcount - 1). Assumes the FPU is in round-to-
* zero mode.
*/
static ALsizei CalcAzIndex(ALsizei azcount, ALfloat az)
{
az = (F_TAU + az) * azcount / F_TAU;
return fastf2i(az + 0.5f) % azcount;
}
/* Calculates static HRIR coefficients and delays for the given polar elevation
* and azimuth in radians. The coefficients are normalized.
*/
void GetHrtfCoeffs(const struct Hrtf *Hrtf, ALfloat elevation, ALfloat azimuth, ALfloat spread, ALfloat (*coeffs)[2], ALsizei *delays)
{
ALsizei evidx, azidx, lidx, ridx;
ALsizei azcount, evoffset;
ALfloat dirfact;
ALsizei i;
dirfact = 1.0f - (spread / F_TAU);
/* Claculate elevation index. */
evidx = CalcEvIndex(Hrtf->evCount, elevation);
azcount = Hrtf->azCount[evidx];
evoffset = Hrtf->evOffset[evidx];
/* Calculate azimuth index. */
azidx = CalcAzIndex(Hrtf->azCount[evidx], azimuth);
/* Calculate the HRIR indices for left and right channels. */
lidx = evoffset + azidx;
ridx = evoffset + ((azcount-azidx) % azcount);
/* Calculate the HRIR delays. */
delays[0] = fastf2i(Hrtf->delays[lidx]*dirfact + 0.5f);
delays[1] = fastf2i(Hrtf->delays[ridx]*dirfact + 0.5f);
/* Calculate the sample offsets for the HRIR indices. */
lidx *= Hrtf->irSize;
ridx *= Hrtf->irSize;
/* Calculate the normalized and attenuated HRIR coefficients. */
i = 0;
coeffs[i][0] = lerp(PassthruCoeff, Hrtf->coeffs[lidx+i], dirfact);
coeffs[i][1] = lerp(PassthruCoeff, Hrtf->coeffs[ridx+i], dirfact);
for(i = 1;i < Hrtf->irSize;i++)
{
coeffs[i][0] = Hrtf->coeffs[lidx+i] * dirfact;
coeffs[i][1] = Hrtf->coeffs[ridx+i] * dirfact;
}
}
ALsizei BuildBFormatHrtf(const struct Hrtf *Hrtf, DirectHrtfState *state, ALsizei NumChannels, const ALfloat (*restrict AmbiPoints)[2], const ALfloat (*restrict AmbiMatrix)[2][MAX_AMBI_COEFFS], ALsizei AmbiCount)
{
/* Set this to 2 for dual-band HRTF processing. May require a higher quality
* band-splitter, or better calculation of the new IR length to deal with the
* tail generated by the filter.
*/
#define NUM_BANDS 2
BandSplitter splitter;
ALsizei lidx[HRTF_AMBI_MAX_CHANNELS], ridx[HRTF_AMBI_MAX_CHANNELS];
ALsizei min_delay = HRTF_HISTORY_LENGTH;
ALfloat temps[3][HRIR_LENGTH];
ALsizei max_length = 0;
ALsizei i, c, b;
for(c = 0;c < AmbiCount;c++)
{
ALuint evidx, azidx;
ALuint evoffset;
ALuint azcount;
/* Calculate elevation index. */
evidx = (ALsizei)floorf((F_PI_2 + AmbiPoints[c][0]) *
(Hrtf->evCount-1)/F_PI + 0.5f);
evidx = mini(evidx, Hrtf->evCount-1);
azcount = Hrtf->azCount[evidx];
evoffset = Hrtf->evOffset[evidx];
/* Calculate azimuth index for this elevation. */
azidx = (ALsizei)floorf((F_TAU+AmbiPoints[c][1]) *
azcount/F_TAU + 0.5f) % azcount;
/* Calculate indices for left and right channels. */
lidx[c] = evoffset + azidx;
ridx[c] = evoffset + ((azcount-azidx) % azcount);
min_delay = mini(min_delay, mini(Hrtf->delays[lidx[c]], Hrtf->delays[ridx[c]]));
}
memset(temps, 0, sizeof(temps));
bandsplit_init(&splitter, 400.0f / (ALfloat)Hrtf->sampleRate);
for(c = 0;c < AmbiCount;c++)
{
const ALfloat *fir;
ALsizei delay;
/* Add to the left output coefficients with the specified delay. */
fir = &Hrtf->coeffs[lidx[c] * Hrtf->irSize];
delay = Hrtf->delays[lidx[c]] - min_delay;
if(NUM_BANDS == 1)
{
for(i = 0;i < NumChannels;++i)
{
ALsizei j = delay, k = 0;
while(j < HRIR_LENGTH && k < Hrtf->irSize)
state->Chan[i].Coeffs[j++][0] += fir[k++] * AmbiMatrix[c][0][i];
}
}
else
{
/* Band-split left HRIR into low and high frequency responses. */
bandsplit_clear(&splitter);
for(i = 0;i < Hrtf->irSize;i++)
temps[2][i] = fir[i];
bandsplit_process(&splitter, temps[0], temps[1], temps[2], HRIR_LENGTH);
for(i = 0;i < NumChannels;++i)
{
for(b = 0;b < NUM_BANDS;b++)
{
ALsizei j = delay, k = 0;
while(j < HRIR_LENGTH)
state->Chan[i].Coeffs[j++][0] += temps[b][k++] * AmbiMatrix[c][b][i];
}
}
}
max_length = maxi(max_length, mini(delay + Hrtf->irSize, HRIR_LENGTH));
/* Add to the right output coefficients with the specified delay. */
fir = &Hrtf->coeffs[ridx[c] * Hrtf->irSize];
delay = Hrtf->delays[ridx[c]] - min_delay;
if(NUM_BANDS == 1)
{
for(i = 0;i < NumChannels;++i)
{
ALsizei j = delay, k = 0;
while(j < HRIR_LENGTH && k < Hrtf->irSize)
state->Chan[i].Coeffs[j++][1] += fir[k++] * AmbiMatrix[c][0][i];
}
}
else
{
/* Band-split right HRIR into low and high frequency responses. */
bandsplit_clear(&splitter);
for(i = 0;i < Hrtf->irSize;i++)
temps[2][i] = fir[i];
bandsplit_process(&splitter, temps[0], temps[1], temps[2], HRIR_LENGTH);
for(i = 0;i < NumChannels;++i)
{
for(b = 0;b < NUM_BANDS;b++)
{
ALsizei j = delay, k = 0;
while(j < HRIR_LENGTH)
state->Chan[i].Coeffs[j++][1] += temps[b][k++] * AmbiMatrix[c][b][i];
}
}
}
max_length = maxi(max_length, mini(delay + Hrtf->irSize, HRIR_LENGTH));
}
TRACE("Skipped min delay: %d, new combined length: %d\n", min_delay, max_length);
return max_length;
#undef NUM_BANDS
}
static struct Hrtf *CreateHrtfStore(ALuint rate, ALsizei irSize, ALsizei evCount, ALsizei irCount,
const ALubyte *azCount, const ALushort *evOffset,
const ALshort *coeffs, const ALubyte *delays,
const_al_string filename)
{
struct Hrtf *Hrtf;
size_t total;
total = sizeof(struct Hrtf);
total += sizeof(Hrtf->azCount[0])*evCount;
total = RoundUp(total, sizeof(ALushort)); /* Align for ushort fields */
total += sizeof(Hrtf->evOffset[0])*evCount;
total = RoundUp(total, sizeof(ALfloat)); /* Align for float fields */
total += sizeof(Hrtf->coeffs[0])*irSize*irCount;
total += sizeof(Hrtf->delays[0])*irCount;
total += al_string_length(filename)+1;
Hrtf = al_calloc(16, total);
if(Hrtf == NULL)
ERR("Out of memory.\n");
else
{
uintptr_t offset = sizeof(struct Hrtf);
char *base = (char*)Hrtf;
ALushort *_evOffset;
ALubyte *_azCount;
ALubyte *_delays;
ALfloat *_coeffs;
char *_name;
ALsizei i;
Hrtf->sampleRate = rate;
Hrtf->irSize = irSize;
Hrtf->evCount = evCount;
/* Set up pointers to storage following the main HRTF struct. */
_azCount = (ALubyte*)(base + offset); Hrtf->azCount = _azCount;
offset += sizeof(_azCount[0])*evCount;
offset = RoundUp(offset, sizeof(ALushort)); /* Align for ushort fields */
_evOffset = (ALushort*)(base + offset); Hrtf->evOffset = _evOffset;
offset += sizeof(_evOffset[0])*evCount;
offset = RoundUp(offset, sizeof(ALfloat)); /* Align for float fields */
_coeffs = (ALfloat*)(base + offset); Hrtf->coeffs = _coeffs;
offset += sizeof(_coeffs[0])*irSize*irCount;
_delays = (ALubyte*)(base + offset); Hrtf->delays = _delays;
offset += sizeof(_delays[0])*irCount;
_name = (char*)(base + offset); Hrtf->filename = _name;
offset += sizeof(_name[0])*(al_string_length(filename)+1);
Hrtf->next = NULL;
/* Copy input data to storage. */
for(i = 0;i < evCount;i++) _azCount[i] = azCount[i];
for(i = 0;i < evCount;i++) _evOffset[i] = evOffset[i];
for(i = 0;i < irSize*irCount;i++)
_coeffs[i] = coeffs[i] / 32768.0f;
for(i = 0;i < irCount;i++) _delays[i] = delays[i];
for(i = 0;i < (ALsizei)al_string_length(filename);i++)
_name[i] = VECTOR_ELEM(filename, i);
_name[i] = '\0';
assert(offset == total);
}
return Hrtf;
}
static struct Hrtf *LoadHrtf00(const ALubyte *data, size_t datalen, const_al_string filename)
{
const ALubyte maxDelay = HRTF_HISTORY_LENGTH-1;
struct Hrtf *Hrtf = NULL;
ALboolean failed = AL_FALSE;
ALuint rate = 0, irCount = 0;
ALushort irSize = 0;
ALubyte evCount = 0;
ALubyte *azCount = NULL;
ALushort *evOffset = NULL;
ALshort *coeffs = NULL;
const ALubyte *delays = NULL;
ALuint i, j;
if(datalen < 9)
{
ERR("Unexpected end of %s data (req %d, rem "SZFMT")\n",
al_string_get_cstr(filename), 9, datalen);
return NULL;
}
rate = *(data++);
rate |= *(data++)<<8;
rate |= *(data++)<<16;
rate |= *(data++)<<24;
datalen -= 4;
irCount = *(data++);
irCount |= *(data++)<<8;
datalen -= 2;
irSize = *(data++);
irSize |= *(data++)<<8;
datalen -= 2;
evCount = *(data++);
datalen -= 1;
if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
{
ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
failed = AL_TRUE;
}
if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
{
ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
evCount, MIN_EV_COUNT, MAX_EV_COUNT);
failed = AL_TRUE;
}
if(failed)
return NULL;
if(datalen < evCount*2)
{
ERR("Unexpected end of %s data (req %d, rem "SZFMT")\n",
al_string_get_cstr(filename), evCount*2, datalen);
return NULL;
}
azCount = malloc(sizeof(azCount[0])*evCount);
evOffset = malloc(sizeof(evOffset[0])*evCount);
if(azCount == NULL || evOffset == NULL)
{
ERR("Out of memory.\n");
failed = AL_TRUE;
}
if(!failed)
{
evOffset[0] = *(data++);
evOffset[0] |= *(data++)<<8;
datalen -= 2;
for(i = 1;i < evCount;i++)
{
evOffset[i] = *(data++);
evOffset[i] |= *(data++)<<8;
datalen -= 2;
if(evOffset[i] <= evOffset[i-1])
{
ERR("Invalid evOffset: evOffset[%d]=%d (last=%d)\n",
i, evOffset[i], evOffset[i-1]);
failed = AL_TRUE;
}
azCount[i-1] = evOffset[i] - evOffset[i-1];
if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
{
ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
failed = AL_TRUE;
}
}
if(irCount <= evOffset[i-1])
{
ERR("Invalid evOffset: evOffset[%d]=%d (irCount=%d)\n",
i-1, evOffset[i-1], irCount);
failed = AL_TRUE;
}
azCount[i-1] = irCount - evOffset[i-1];
if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
{
ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
failed = AL_TRUE;
}
}
if(!failed)
{
coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
if(coeffs == NULL)
{
ERR("Out of memory.\n");
failed = AL_TRUE;
}
}
if(!failed)
{
size_t reqsize = 2*irSize*irCount + irCount;
if(datalen < reqsize)
{
ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT")\n",
al_string_get_cstr(filename), reqsize, datalen);
failed = AL_TRUE;
}
}
if(!failed)
{
for(i = 0;i < irCount*irSize;i+=irSize)
{
for(j = 0;j < irSize;j++)
{
coeffs[i+j] = *(data++);
coeffs[i+j] |= *(data++)<<8;
datalen -= 2;
}
}
delays = data;
data += irCount;
datalen -= irCount;
for(i = 0;i < irCount;i++)
{
if(delays[i] > maxDelay)
{
ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i], maxDelay);
failed = AL_TRUE;
}
}
}
if(!failed)
Hrtf = CreateHrtfStore(rate, irSize, evCount, irCount, azCount,
evOffset, coeffs, delays, filename);
free(azCount);
free(evOffset);
free(coeffs);
return Hrtf;
}
static struct Hrtf *LoadHrtf01(const ALubyte *data, size_t datalen, const_al_string filename)
{
const ALubyte maxDelay = HRTF_HISTORY_LENGTH-1;
struct Hrtf *Hrtf = NULL;
ALboolean failed = AL_FALSE;
ALuint rate = 0, irCount = 0;
ALubyte irSize = 0, evCount = 0;
const ALubyte *azCount = NULL;
ALushort *evOffset = NULL;
ALshort *coeffs = NULL;
const ALubyte *delays = NULL;
ALuint i, j;
if(datalen < 6)
{
ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n",
al_string_get_cstr(filename), 6, datalen);
return NULL;
}
rate = *(data++);
rate |= *(data++)<<8;
rate |= *(data++)<<16;
rate |= *(data++)<<24;
datalen -= 4;
irSize = *(data++);
datalen -= 1;
evCount = *(data++);
datalen -= 1;
if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
{
ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
failed = AL_TRUE;
}
if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
{
ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
evCount, MIN_EV_COUNT, MAX_EV_COUNT);
failed = AL_TRUE;
}
if(failed)
return NULL;
if(datalen < evCount)
{
ERR("Unexpected end of %s data (req %d, rem "SZFMT"\n",
al_string_get_cstr(filename), evCount, datalen);
return NULL;
}
azCount = data;
data += evCount;
datalen -= evCount;
evOffset = malloc(sizeof(evOffset[0])*evCount);
if(azCount == NULL || evOffset == NULL)
{
ERR("Out of memory.\n");
failed = AL_TRUE;
}
if(!failed)
{
for(i = 0;i < evCount;i++)
{
if(azCount[i] < MIN_AZ_COUNT || azCount[i] > MAX_AZ_COUNT)
{
ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
i, azCount[i], MIN_AZ_COUNT, MAX_AZ_COUNT);
failed = AL_TRUE;
}
}
}
if(!failed)
{
evOffset[0] = 0;
irCount = azCount[0];
for(i = 1;i < evCount;i++)
{
evOffset[i] = evOffset[i-1] + azCount[i-1];
irCount += azCount[i];
}
coeffs = malloc(sizeof(coeffs[0])*irSize*irCount);
if(coeffs == NULL)
{
ERR("Out of memory.\n");
failed = AL_TRUE;
}
}
if(!failed)
{
size_t reqsize = 2*irSize*irCount + irCount;
if(datalen < reqsize)
{
ERR("Unexpected end of %s data (req "SZFMT", rem "SZFMT"\n",
al_string_get_cstr(filename), reqsize, datalen);
failed = AL_TRUE;
}
}
if(!failed)
{
for(i = 0;i < irCount*irSize;i+=irSize)
{
for(j = 0;j < irSize;j++)
{
ALshort coeff;
coeff = *(data++);
coeff |= *(data++)<<8;
datalen -= 2;
coeffs[i+j] = coeff;
}
}
delays = data;
data += irCount;
datalen -= irCount;
for(i = 0;i < irCount;i++)
{
if(delays[i] > maxDelay)
{
ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i], maxDelay);
failed = AL_TRUE;
}
}
}
if(!failed)
Hrtf = CreateHrtfStore(rate, irSize, evCount, irCount, azCount,
evOffset, coeffs, delays, filename);
free(evOffset);
free(coeffs);
return Hrtf;
}
static void AddFileEntry(vector_HrtfEntry *list, al_string *filename)
{
HrtfEntry entry = { AL_STRING_INIT_STATIC(), NULL };
struct Hrtf *hrtf = NULL;
const HrtfEntry *iter;
struct FileMapping fmap;
const char *name;
const char *ext;
int i;
#define MATCH_FNAME(i) (al_string_cmp_cstr(*filename, (i)->hrtf->filename) == 0)
VECTOR_FIND_IF(iter, const HrtfEntry, *list, MATCH_FNAME);
if(iter != VECTOR_END(*list))
{
TRACE("Skipping duplicate file entry %s\n", al_string_get_cstr(*filename));
goto done;
}
#undef MATCH_FNAME
entry.hrtf = LoadedHrtfs;
while(entry.hrtf)
{
if(al_string_cmp_cstr(*filename, entry.hrtf->filename) == 0)
{
TRACE("Skipping load of already-loaded file %s\n", al_string_get_cstr(*filename));
goto skip_load;
}
entry.hrtf = entry.hrtf->next;
}
TRACE("Loading %s...\n", al_string_get_cstr(*filename));
fmap = MapFileToMem(al_string_get_cstr(*filename));
if(fmap.ptr == NULL)
{
ERR("Could not open %s\n", al_string_get_cstr(*filename));
goto done;
}
if(fmap.len < sizeof(magicMarker01))
ERR("%s data is too short ("SZFMT" bytes)\n", al_string_get_cstr(*filename), fmap.len);
else if(memcmp(fmap.ptr, magicMarker01, sizeof(magicMarker01)) == 0)
{
TRACE("Detected data set format v1\n");
hrtf = LoadHrtf01((const ALubyte*)fmap.ptr+sizeof(magicMarker01),
fmap.len-sizeof(magicMarker01), *filename
);
}
else if(memcmp(fmap.ptr, magicMarker00, sizeof(magicMarker00)) == 0)
{
TRACE("Detected data set format v0\n");
hrtf = LoadHrtf00((const ALubyte*)fmap.ptr+sizeof(magicMarker00),
fmap.len-sizeof(magicMarker00), *filename
);
}
else
ERR("Invalid header in %s: \"%.8s\"\n", al_string_get_cstr(*filename), (const char*)fmap.ptr);
UnmapFileMem(&fmap);
if(!hrtf)
{
ERR("Failed to load %s\n", al_string_get_cstr(*filename));
goto done;
}
hrtf->next = LoadedHrtfs;
LoadedHrtfs = hrtf;
TRACE("Loaded HRTF support for format: %s %uhz\n",
DevFmtChannelsString(DevFmtStereo), hrtf->sampleRate);
entry.hrtf = hrtf;
skip_load:
/* TODO: Get a human-readable name from the HRTF data (possibly coming in a
* format update). */
name = strrchr(al_string_get_cstr(*filename), '/');
if(!name) name = strrchr(al_string_get_cstr(*filename), '\\');
if(!name) name = al_string_get_cstr(*filename);
else ++name;
ext = strrchr(name, '.');
i = 0;
do {
if(!ext)
al_string_copy_cstr(&entry.name, name);
else
al_string_copy_range(&entry.name, name, ext);
if(i != 0)
{
char str[64];
snprintf(str, sizeof(str), " #%d", i+1);
al_string_append_cstr(&entry.name, str);
}
++i;
#define MATCH_NAME(i) (al_string_cmp(entry.name, (i)->name) == 0)
VECTOR_FIND_IF(iter, const HrtfEntry, *list, MATCH_NAME);
#undef MATCH_NAME
} while(iter != VECTOR_END(*list));
TRACE("Adding entry \"%s\" from file \"%s\"\n", al_string_get_cstr(entry.name),
al_string_get_cstr(*filename));
VECTOR_PUSH_BACK(*list, entry);
done:
al_string_deinit(filename);
}
/* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
* for input instead of opening the given filename.
*/
static void AddBuiltInEntry(vector_HrtfEntry *list, const ALubyte *data, size_t datalen, al_string *filename)
{
HrtfEntry entry = { AL_STRING_INIT_STATIC(), NULL };
struct Hrtf *hrtf = NULL;
const HrtfEntry *iter;
int i;
#define MATCH_FNAME(i) (al_string_cmp_cstr(*filename, (i)->hrtf->filename) == 0)
VECTOR_FIND_IF(iter, const HrtfEntry, *list, MATCH_FNAME);
if(iter != VECTOR_END(*list))
{
TRACE("Skipping duplicate file entry %s\n", al_string_get_cstr(*filename));
goto done;
}
#undef MATCH_FNAME
entry.hrtf = LoadedHrtfs;
while(entry.hrtf)
{
if(al_string_cmp_cstr(*filename, entry.hrtf->filename) == 0)
{
TRACE("Skipping load of already-loaded file %s\n", al_string_get_cstr(*filename));
goto skip_load;
}
entry.hrtf = entry.hrtf->next;
}
TRACE("Loading %s...\n", al_string_get_cstr(*filename));
if(datalen < sizeof(magicMarker01))
{
ERR("%s data is too short ("SZFMT" bytes)\n", al_string_get_cstr(*filename), datalen);
goto done;
}
if(memcmp(data, magicMarker01, sizeof(magicMarker01)) == 0)
{
TRACE("Detected data set format v1\n");
hrtf = LoadHrtf01(data+sizeof(magicMarker01),
datalen-sizeof(magicMarker01), *filename
);
}
else if(memcmp(data, magicMarker00, sizeof(magicMarker00)) == 0)
{
TRACE("Detected data set format v0\n");
hrtf = LoadHrtf00(data+sizeof(magicMarker00),
datalen-sizeof(magicMarker00), *filename
);
}
else
ERR("Invalid header in %s: \"%.8s\"\n", al_string_get_cstr(*filename), data);
if(!hrtf)
{
ERR("Failed to load %s\n", al_string_get_cstr(*filename));
goto done;
}
hrtf->next = LoadedHrtfs;
LoadedHrtfs = hrtf;
TRACE("Loaded HRTF support for format: %s %uhz\n",
DevFmtChannelsString(DevFmtStereo), hrtf->sampleRate);
entry.hrtf = hrtf;
skip_load:
i = 0;
do {
al_string_copy(&entry.name, *filename);
if(i != 0)
{
char str[64];
snprintf(str, sizeof(str), " #%d", i+1);
al_string_append_cstr(&entry.name, str);
}
++i;
#define MATCH_NAME(i) (al_string_cmp(entry.name, (i)->name) == 0)
VECTOR_FIND_IF(iter, const HrtfEntry, *list, MATCH_NAME);
#undef MATCH_NAME
} while(iter != VECTOR_END(*list));
TRACE("Adding built-in entry \"%s\"\n", al_string_get_cstr(entry.name));
VECTOR_PUSH_BACK(*list, entry);
done:
al_string_deinit(filename);
}
#ifndef ALSOFT_EMBED_HRTF_DATA
#define IDR_DEFAULT_44100_MHR 1
#define IDR_DEFAULT_48000_MHR 2
static const ALubyte *GetResource(int UNUSED(name), size_t *size)
{
*size = 0;
return NULL;
}
#else
#include "hrtf_res.h"
#ifdef _WIN32
static const ALubyte *GetResource(int name, size_t *size)
{
HMODULE handle;
HGLOBAL res;
HRSRC rc;
GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
(LPCWSTR)GetResource, &handle
);
rc = FindResourceW(handle, MAKEINTRESOURCEW(name), MAKEINTRESOURCEW(MHRTYPE));
res = LoadResource(handle, rc);
*size = SizeofResource(handle, rc);
return LockResource(res);
}
#elif defined(__APPLE__)
#include <Availability.h>
#include <mach-o/getsect.h>
#include <mach-o/ldsyms.h>
static const ALubyte *GetResource(int name, size_t *size)
{
#if defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && (__MAC_OS_X_VERSION_MAX_ALLOWED >= 1070)
/* NOTE: OSX 10.7 and up need to call getsectiondata(&_mh_dylib_header, ...). However, that
* call requires 10.7.
*/
if(name == IDR_DEFAULT_44100_MHR)
return getsectiondata(&_mh_dylib_header, "binary", "default_44100", size);
if(name == IDR_DEFAULT_48000_MHR)
return getsectiondata(&_mh_dylib_header, "binary", "default_48000", size);
#else
if(name == IDR_DEFAULT_44100_MHR)
return getsectdata("binary", "default_44100", size);
if(name == IDR_DEFAULT_48000_MHR)
return getsectdata("binary", "default_48000", size);
#endif
*size = 0;
return NULL;
}
#else
extern const ALubyte _binary_default_44100_mhr_start[] HIDDEN_DECL;
extern const ALubyte _binary_default_44100_mhr_end[] HIDDEN_DECL;
extern const ALubyte _binary_default_44100_mhr_size[] HIDDEN_DECL;
extern const ALubyte _binary_default_48000_mhr_start[] HIDDEN_DECL;
extern const ALubyte _binary_default_48000_mhr_end[] HIDDEN_DECL;
extern const ALubyte _binary_default_48000_mhr_size[] HIDDEN_DECL;
static const ALubyte *GetResource(int name, size_t *size)
{
if(name == IDR_DEFAULT_44100_MHR)
{
/* Make sure all symbols are referenced, to ensure the compiler won't
* ignore the declarations and lose the visibility attribute used to
* hide them (would be nice if ld or objcopy could automatically mark
* them as hidden when generating them, but apparently they can't).
*/
const void *volatile ptr =_binary_default_44100_mhr_size;
(void)ptr;
*size = _binary_default_44100_mhr_end - _binary_default_44100_mhr_start;
return _binary_default_44100_mhr_start;
}
if(name == IDR_DEFAULT_48000_MHR)
{
const void *volatile ptr =_binary_default_48000_mhr_size;
(void)ptr;
*size = _binary_default_48000_mhr_end - _binary_default_48000_mhr_start;
return _binary_default_48000_mhr_start;
}
*size = 0;
return NULL;
}
#endif
#endif
vector_HrtfEntry EnumerateHrtf(const_al_string devname)
{
vector_HrtfEntry list = VECTOR_INIT_STATIC();
const char *defaulthrtf = "";
const char *pathlist = "";
bool usedefaults = true;
if(ConfigValueStr(al_string_get_cstr(devname), NULL, "hrtf-paths", &pathlist))
{
while(pathlist && *pathlist)
{
const char *next, *end;
while(isspace(*pathlist) || *pathlist == ',')
pathlist++;
if(*pathlist == '\0')
continue;
next = strchr(pathlist, ',');
if(next)
end = next++;
else
{
end = pathlist + strlen(pathlist);
usedefaults = false;
}
while(end != pathlist && isspace(*(end-1)))
--end;
if(end != pathlist)
{
al_string pname = AL_STRING_INIT_STATIC();
vector_al_string flist;
al_string_append_range(&pname, pathlist, end);
flist = SearchDataFiles(".mhr", al_string_get_cstr(pname));
VECTOR_FOR_EACH_PARAMS(al_string, flist, AddFileEntry, &list);
VECTOR_DEINIT(flist);
al_string_deinit(&pname);
}
pathlist = next;
}
}
else if(ConfigValueExists(al_string_get_cstr(devname), NULL, "hrtf_tables"))
ERR("The hrtf_tables option is deprecated, please use hrtf-paths instead.\n");
if(usedefaults)
{
vector_al_string flist;
const ALubyte *rdata;
size_t rsize;
flist = SearchDataFiles(".mhr", "openal/hrtf");
VECTOR_FOR_EACH_PARAMS(al_string, flist, AddFileEntry, &list);
VECTOR_DEINIT(flist);
rdata = GetResource(IDR_DEFAULT_44100_MHR, &rsize);
if(rdata != NULL && rsize > 0)
{
al_string ename = AL_STRING_INIT_STATIC();
al_string_copy_cstr(&ename, "Built-In 44100hz");
AddBuiltInEntry(&list, rdata, rsize, &ename);
}
rdata = GetResource(IDR_DEFAULT_48000_MHR, &rsize);
if(rdata != NULL && rsize > 0)
{
al_string ename = AL_STRING_INIT_STATIC();
al_string_copy_cstr(&ename, "Built-In 48000hz");
AddBuiltInEntry(&list, rdata, rsize, &ename);
}
}
if(VECTOR_SIZE(list) > 1 && ConfigValueStr(al_string_get_cstr(devname), NULL, "default-hrtf", &defaulthrtf))
{
const HrtfEntry *iter;
/* Find the preferred HRTF and move it to the front of the list. */
#define FIND_ENTRY(i) (al_string_cmp_cstr((i)->name, defaulthrtf) == 0)
VECTOR_FIND_IF(iter, const HrtfEntry, list, FIND_ENTRY);
#undef FIND_ENTRY
if(iter == VECTOR_END(list))
WARN("Failed to find default HRTF \"%s\"\n", defaulthrtf);
else if(iter != VECTOR_BEGIN(list))
{
HrtfEntry entry = *iter;
memmove(&VECTOR_ELEM(list,1), &VECTOR_ELEM(list,0),
(iter-VECTOR_BEGIN(list))*sizeof(HrtfEntry));
VECTOR_ELEM(list,0) = entry;
}
}
return list;
}
void FreeHrtfList(vector_HrtfEntry *list)
{
#define CLEAR_ENTRY(i) do { \
al_string_deinit(&(i)->name); \
} while(0)
VECTOR_FOR_EACH(HrtfEntry, *list, CLEAR_ENTRY);
VECTOR_DEINIT(*list);
#undef CLEAR_ENTRY
}
void FreeHrtfs(void)
{
struct Hrtf *Hrtf = LoadedHrtfs;
LoadedHrtfs = NULL;
while(Hrtf != NULL)
{
struct Hrtf *next = Hrtf->next;
al_free(Hrtf);
Hrtf = next;
}
}
|