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
40 #include <type_traits>
47 #include "alfstream.h"
49 #include "alnumeric.h"
50 #include "aloptional.h"
52 #include "filters/splitter.h"
54 #include "math_defs.h"
55 #include "opthelpers.h"
56 #include "polyphase_resampler.h"
61 using namespace std::placeholders
;
64 std::string mDispName
;
65 std::string mFilename
;
69 std::string mFilename
;
70 std::unique_ptr
<HrtfStore
> mEntry
;
73 /* Data set limits must be the same as or more flexible than those defined in
74 * the makemhr utility.
76 #define MIN_FD_COUNT 1
77 #define MAX_FD_COUNT 16
79 #define MIN_FD_DISTANCE 50
80 #define MAX_FD_DISTANCE 2500
82 #define MIN_EV_COUNT 5
83 #define MAX_EV_COUNT 181
85 #define MIN_AZ_COUNT 1
86 #define MAX_AZ_COUNT 255
88 #define MAX_HRIR_DELAY (HRTF_HISTORY_LENGTH-1)
90 #define HRIR_DELAY_FRACBITS 2
91 #define HRIR_DELAY_FRACONE (1<<HRIR_DELAY_FRACBITS)
92 #define HRIR_DELAY_FRACHALF (HRIR_DELAY_FRACONE>>1)
94 static_assert(MAX_HRIR_DELAY
*HRIR_DELAY_FRACONE
< 256, "MAX_HRIR_DELAY or DELAY_FRAC too large");
96 constexpr ALchar magicMarker00
[8]{'M','i','n','P','H','R','0','0'};
97 constexpr ALchar magicMarker01
[8]{'M','i','n','P','H','R','0','1'};
98 constexpr ALchar magicMarker02
[8]{'M','i','n','P','H','R','0','2'};
99 constexpr ALchar magicMarker03
[8]{'M','i','n','P','H','R','0','3'};
101 /* First value for pass-through coefficients (remaining are 0), used for omni-
102 * directional sounds. */
103 constexpr float PassthruCoeff
{0.707106781187f
/*sqrt(0.5)*/};
105 std::mutex LoadedHrtfLock
;
106 al::vector
<LoadedHrtf
> LoadedHrtfs
;
108 std::mutex EnumeratedHrtfLock
;
109 al::vector
<HrtfEntry
> EnumeratedHrtfs
;
112 class databuf final
: public std::streambuf
{
113 int_type
underflow() override
114 { return traits_type::eof(); }
116 pos_type
seekoff(off_type offset
, std::ios_base::seekdir whence
, std::ios_base::openmode mode
) override
118 if((mode
&std::ios_base::out
) || !(mode
&std::ios_base::in
))
119 return traits_type::eof();
124 case std::ios_base::beg
:
125 if(offset
< 0 || offset
> egptr()-eback())
126 return traits_type::eof();
127 cur
= eback() + offset
;
130 case std::ios_base::cur
:
131 if((offset
>= 0 && offset
> egptr()-gptr()) ||
132 (offset
< 0 && -offset
> gptr()-eback()))
133 return traits_type::eof();
134 cur
= gptr() + offset
;
137 case std::ios_base::end
:
138 if(offset
> 0 || -offset
> egptr()-eback())
139 return traits_type::eof();
140 cur
= egptr() + offset
;
144 return traits_type::eof();
147 setg(eback(), cur
, egptr());
148 return cur
- eback();
151 pos_type
seekpos(pos_type pos
, std::ios_base::openmode mode
) override
153 // Simplified version of seekoff
154 if((mode
&std::ios_base::out
) || !(mode
&std::ios_base::in
))
155 return traits_type::eof();
157 if(pos
< 0 || pos
> egptr()-eback())
158 return traits_type::eof();
160 setg(eback(), eback() + static_cast<size_t>(pos
), egptr());
165 databuf(const char_type
*start_
, const char_type
*end_
) noexcept
167 setg(const_cast<char_type
*>(start_
), const_cast<char_type
*>(start_
),
168 const_cast<char_type
*>(end_
));
172 class idstream final
: public std::istream
{
176 idstream(const char *start_
, const char *end_
)
177 : std::istream
{nullptr}, mStreamBuf
{start_
, end_
}
178 { init(&mStreamBuf
); }
182 struct IdxBlend
{ ALuint idx
; float blend
; };
183 /* Calculate the elevation index given the polar elevation in radians. This
184 * will return an index between 0 and (evcount - 1).
186 IdxBlend
CalcEvIndex(ALuint evcount
, float ev
)
188 ev
= (al::MathDefs
<float>::Pi()*0.5f
+ ev
) * static_cast<float>(evcount
-1) /
189 al::MathDefs
<float>::Pi();
190 ALuint idx
{float2uint(ev
)};
192 return IdxBlend
{minu(idx
, evcount
-1), ev
-static_cast<float>(idx
)};
195 /* Calculate the azimuth index given the polar azimuth in radians. This will
196 * return an index between 0 and (azcount - 1).
198 IdxBlend
CalcAzIndex(ALuint azcount
, float az
)
200 az
= (al::MathDefs
<float>::Tau()+az
) * static_cast<float>(azcount
) /
201 al::MathDefs
<float>::Tau();
202 ALuint idx
{float2uint(az
)};
204 return IdxBlend
{idx
%azcount
, az
-static_cast<float>(idx
)};
210 /* Calculates static HRIR coefficients and delays for the given polar elevation
211 * and azimuth in radians. The coefficients are normalized.
213 void GetHrtfCoeffs(const HrtfStore
*Hrtf
, float elevation
, float azimuth
, float distance
,
214 float spread
, HrirArray
&coeffs
, const al::span
<ALuint
,2> delays
)
216 const float dirfact
{1.0f
- (spread
/ al::MathDefs
<float>::Tau())};
218 const auto *field
= Hrtf
->field
;
219 const auto *field_end
= field
+ Hrtf
->fdCount
-1;
221 while(distance
< field
->distance
&& field
!= field_end
)
223 ebase
+= field
->evCount
;
227 /* Calculate the elevation indices. */
228 const auto elev0
= CalcEvIndex(field
->evCount
, elevation
);
229 const size_t elev1_idx
{minu(elev0
.idx
+1, field
->evCount
-1)};
230 const size_t ir0offset
{Hrtf
->elev
[ebase
+ elev0
.idx
].irOffset
};
231 const size_t ir1offset
{Hrtf
->elev
[ebase
+ elev1_idx
].irOffset
};
233 /* Calculate azimuth indices. */
234 const auto az0
= CalcAzIndex(Hrtf
->elev
[ebase
+ elev0
.idx
].azCount
, azimuth
);
235 const auto az1
= CalcAzIndex(Hrtf
->elev
[ebase
+ elev1_idx
].azCount
, azimuth
);
237 /* Calculate the HRIR indices to blend. */
240 ir0offset
+ ((az0
.idx
+1) % Hrtf
->elev
[ebase
+ elev0
.idx
].azCount
),
242 ir1offset
+ ((az1
.idx
+1) % Hrtf
->elev
[ebase
+ elev1_idx
].azCount
)
245 /* Calculate bilinear blending weights, attenuated according to the
246 * directional panning factor.
248 const float blend
[4]{
249 (1.0f
-elev0
.blend
) * (1.0f
-az0
.blend
) * dirfact
,
250 (1.0f
-elev0
.blend
) * ( az0
.blend
) * dirfact
,
251 ( elev0
.blend
) * (1.0f
-az1
.blend
) * dirfact
,
252 ( elev0
.blend
) * ( az1
.blend
) * dirfact
255 /* Calculate the blended HRIR delays. */
256 float d
{Hrtf
->delays
[idx
[0]][0]*blend
[0] + Hrtf
->delays
[idx
[1]][0]*blend
[1] +
257 Hrtf
->delays
[idx
[2]][0]*blend
[2] + Hrtf
->delays
[idx
[3]][0]*blend
[3]};
258 delays
[0] = fastf2u(d
* float{1.0f
/HRIR_DELAY_FRACONE
});
259 d
= Hrtf
->delays
[idx
[0]][1]*blend
[0] + Hrtf
->delays
[idx
[1]][1]*blend
[1] +
260 Hrtf
->delays
[idx
[2]][1]*blend
[2] + Hrtf
->delays
[idx
[3]][1]*blend
[3];
261 delays
[1] = fastf2u(d
* float{1.0f
/HRIR_DELAY_FRACONE
});
263 /* Calculate the blended HRIR coefficients. */
264 float *coeffout
{al::assume_aligned
<16>(&coeffs
[0][0])};
265 coeffout
[0] = PassthruCoeff
* (1.0f
-dirfact
);
266 coeffout
[1] = PassthruCoeff
* (1.0f
-dirfact
);
267 std::fill_n(coeffout
+2, size_t{HRIR_LENGTH
-1}*2, 0.0f
);
268 for(size_t c
{0};c
< 4;c
++)
270 const float *srccoeffs
{al::assume_aligned
<16>(Hrtf
->coeffs
[idx
[c
]][0].data())};
271 const float mult
{blend
[c
]};
272 auto blend_coeffs
= [mult
](const float src
, const float coeff
) noexcept
-> float
273 { return src
*mult
+ coeff
; };
274 std::transform(srccoeffs
, srccoeffs
+ HRIR_LENGTH
*2, coeffout
, coeffout
, blend_coeffs
);
279 std::unique_ptr
<DirectHrtfState
> DirectHrtfState::Create(size_t num_chans
)
280 { return std::unique_ptr
<DirectHrtfState
>{new(FamCount(num_chans
)) DirectHrtfState
{num_chans
}}; }
282 void DirectHrtfState::build(const HrtfStore
*Hrtf
, const al::span
<const AngularPoint
> AmbiPoints
,
283 const float (*AmbiMatrix
)[MAX_AMBI_CHANNELS
],
284 const al::span
<const float,MAX_AMBI_ORDER
+1> AmbiOrderHFGain
)
286 using double2
= std::array
<double,2>;
287 struct ImpulseResponse
{
288 const HrirArray
&hrir
;
289 ALuint ldelay
, rdelay
;
292 const double xover_norm
{400.0 / Hrtf
->sampleRate
};
293 for(size_t i
{0};i
< mChannels
.size();++i
)
295 const size_t order
{AmbiIndex::OrderFromChannel
[i
]};
296 mChannels
[i
].mSplitter
.init(static_cast<float>(xover_norm
));
297 mChannels
[i
].mHfScale
= AmbiOrderHFGain
[order
];
300 ALuint min_delay
{HRTF_HISTORY_LENGTH
*HRIR_DELAY_FRACONE
}, max_delay
{0};
301 al::vector
<ImpulseResponse
> impres
; impres
.reserve(AmbiPoints
.size());
302 auto calc_res
= [Hrtf
,&max_delay
,&min_delay
](const AngularPoint
&pt
) -> ImpulseResponse
304 auto &field
= Hrtf
->field
[0];
305 const auto elev0
= CalcEvIndex(field
.evCount
, pt
.Elev
.value
);
306 const size_t elev1_idx
{minu(elev0
.idx
+1, field
.evCount
-1)};
307 const size_t ir0offset
{Hrtf
->elev
[elev0
.idx
].irOffset
};
308 const size_t ir1offset
{Hrtf
->elev
[elev1_idx
].irOffset
};
310 const auto az0
= CalcAzIndex(Hrtf
->elev
[elev0
.idx
].azCount
, pt
.Azim
.value
);
311 const auto az1
= CalcAzIndex(Hrtf
->elev
[elev1_idx
].azCount
, pt
.Azim
.value
);
315 ir0offset
+ ((az0
.idx
+1) % Hrtf
->elev
[elev0
.idx
].azCount
),
317 ir1offset
+ ((az1
.idx
+1) % Hrtf
->elev
[elev1_idx
].azCount
)
320 const std::array
<double,4> blend
{{
321 (1.0-elev0
.blend
) * (1.0-az0
.blend
),
322 (1.0-elev0
.blend
) * ( az0
.blend
),
323 ( elev0
.blend
) * (1.0-az1
.blend
),
324 ( elev0
.blend
) * ( az1
.blend
)
327 /* The largest blend factor serves as the closest HRIR. */
328 const size_t irOffset
{idx
[std::max_element(blend
.begin(), blend
.end()) - blend
.begin()]};
329 ImpulseResponse res
{Hrtf
->coeffs
[irOffset
],
330 Hrtf
->delays
[irOffset
][0], Hrtf
->delays
[irOffset
][1]};
332 min_delay
= minu(min_delay
, minu(res
.ldelay
, res
.rdelay
));
333 max_delay
= maxu(max_delay
, maxu(res
.ldelay
, res
.rdelay
));
337 std::transform(AmbiPoints
.begin(), AmbiPoints
.end(), std::back_inserter(impres
), calc_res
);
338 auto hrir_delay_round
= [](const ALuint d
) noexcept
-> ALuint
339 { return (d
+HRIR_DELAY_FRACHALF
) >> HRIR_DELAY_FRACBITS
; };
341 auto tmpres
= al::vector
<std::array
<double2
,HRIR_LENGTH
>>(mChannels
.size());
342 for(size_t c
{0u};c
< AmbiPoints
.size();++c
)
344 const HrirArray
&hrir
{impres
[c
].hrir
};
345 const ALuint ldelay
{hrir_delay_round(impres
[c
].ldelay
- min_delay
)};
346 const ALuint rdelay
{hrir_delay_round(impres
[c
].rdelay
- min_delay
)};
348 for(size_t i
{0u};i
< mChannels
.size();++i
)
350 const double mult
{AmbiMatrix
[c
][i
]};
351 const size_t numirs
{HRIR_LENGTH
- maxz(ldelay
, rdelay
)};
352 size_t lidx
{ldelay
}, ridx
{rdelay
};
353 for(size_t j
{0};j
< numirs
;++j
)
355 tmpres
[i
][lidx
++][0] += hrir
[j
][0] * mult
;
356 tmpres
[i
][ridx
++][1] += hrir
[j
][1] * mult
;
362 for(size_t i
{0u};i
< mChannels
.size();++i
)
364 auto copy_arr
= [](const double2
&in
) noexcept
-> float2
365 { return float2
{{static_cast<float>(in
[0]), static_cast<float>(in
[1])}}; };
366 std::transform(tmpres
[i
].cbegin(), tmpres
[i
].cend(), mChannels
[i
].mCoeffs
.begin(),
371 max_delay
= hrir_delay_round(max_delay
- min_delay
);
372 const ALuint max_length
{minu(max_delay
+ Hrtf
->irSize
, HRIR_LENGTH
)};
374 TRACE("Skipped delay: %.2f, new max delay: %.2f, FIR length: %u\n",
375 min_delay
/double{HRIR_DELAY_FRACONE
}, max_delay
/double{HRIR_DELAY_FRACONE
},
377 mIrSize
= max_length
;
383 std::unique_ptr
<HrtfStore
> CreateHrtfStore(ALuint rate
, ALushort irSize
,
384 const al::span
<const HrtfStore::Field
> fields
,
385 const al::span
<const HrtfStore::Elevation
> elevs
, const HrirArray
*coeffs
,
386 const ubyte2
*delays
, const char *filename
)
388 std::unique_ptr
<HrtfStore
> Hrtf
;
390 const size_t irCount
{size_t{elevs
.back().azCount
} + elevs
.back().irOffset
};
391 size_t total
{sizeof(HrtfStore
)};
392 total
= RoundUp(total
, alignof(HrtfStore::Field
)); /* Align for field infos */
393 total
+= sizeof(HrtfStore::Field
)*fields
.size();
394 total
= RoundUp(total
, alignof(HrtfStore::Elevation
)); /* Align for elevation infos */
395 total
+= sizeof(Hrtf
->elev
[0])*elevs
.size();
396 total
= RoundUp(total
, 16); /* Align for coefficients using SIMD */
397 total
+= sizeof(Hrtf
->coeffs
[0])*irCount
;
398 total
+= sizeof(Hrtf
->delays
[0])*irCount
;
400 Hrtf
.reset(new (al_calloc(16, total
)) HrtfStore
{});
402 ERR("Out of memory allocating storage for %s.\n", filename
);
405 InitRef(Hrtf
->mRef
, 1u);
406 Hrtf
->sampleRate
= rate
;
407 Hrtf
->irSize
= irSize
;
408 Hrtf
->fdCount
= static_cast<ALuint
>(fields
.size());
410 /* Set up pointers to storage following the main HRTF struct. */
411 char *base
= reinterpret_cast<char*>(Hrtf
.get());
412 uintptr_t offset
= sizeof(HrtfStore
);
414 offset
= RoundUp(offset
, alignof(HrtfStore::Field
)); /* Align for field infos */
415 auto field_
= reinterpret_cast<HrtfStore::Field
*>(base
+ offset
);
416 offset
+= sizeof(field_
[0])*fields
.size();
418 offset
= RoundUp(offset
, alignof(HrtfStore::Elevation
)); /* Align for elevation infos */
419 auto elev_
= reinterpret_cast<HrtfStore::Elevation
*>(base
+ offset
);
420 offset
+= sizeof(elev_
[0])*elevs
.size();
422 offset
= RoundUp(offset
, 16); /* Align for coefficients using SIMD */
423 auto coeffs_
= reinterpret_cast<HrirArray
*>(base
+ offset
);
424 offset
+= sizeof(coeffs_
[0])*irCount
;
426 auto delays_
= reinterpret_cast<ubyte2
*>(base
+ offset
);
427 offset
+= sizeof(delays_
[0])*irCount
;
429 assert(offset
== total
);
431 /* Copy input data to storage. */
432 std::copy(fields
.cbegin(), fields
.cend(), field_
);
433 std::copy(elevs
.cbegin(), elevs
.cend(), elev_
);
434 std::copy_n(coeffs
, irCount
, coeffs_
);
435 std::copy_n(delays
, irCount
, delays_
);
437 /* Finally, assign the storage pointers. */
438 Hrtf
->field
= field_
;
440 Hrtf
->coeffs
= coeffs_
;
441 Hrtf
->delays
= delays_
;
447 void MirrorLeftHrirs(const al::span
<const HrtfStore::Elevation
> elevs
, HrirArray
*coeffs
,
450 for(const auto &elev
: elevs
)
452 const ALushort evoffset
{elev
.irOffset
};
453 const ALushort azcount
{elev
.azCount
};
454 for(size_t j
{0};j
< azcount
;j
++)
456 const size_t lidx
{evoffset
+ j
};
457 const size_t ridx
{evoffset
+ ((azcount
-j
) % azcount
)};
459 const size_t irSize
{coeffs
[ridx
].size()};
460 for(size_t k
{0};k
< irSize
;k
++)
461 coeffs
[ridx
][k
][1] = coeffs
[lidx
][k
][0];
462 delays
[ridx
][1] = delays
[lidx
][0];
467 ALubyte
GetLE_ALubyte(std::istream
&data
)
469 return static_cast<ALubyte
>(data
.get());
472 ALshort
GetLE_ALshort(std::istream
&data
)
474 int ret
= data
.get();
475 ret
|= data
.get() << 8;
476 return static_cast<ALshort
>((ret
^32768) - 32768);
479 ALushort
GetLE_ALushort(std::istream
&data
)
481 int ret
= data
.get();
482 ret
|= data
.get() << 8;
483 return static_cast<ALushort
>(ret
);
486 int GetLE_ALint24(std::istream
&data
)
488 int ret
= data
.get();
489 ret
|= data
.get() << 8;
490 ret
|= data
.get() << 16;
491 return (ret
^8388608) - 8388608;
494 ALuint
GetLE_ALuint(std::istream
&data
)
496 ALuint ret
{static_cast<ALuint
>(data
.get())};
497 ret
|= static_cast<ALuint
>(data
.get()) << 8;
498 ret
|= static_cast<ALuint
>(data
.get()) << 16;
499 ret
|= static_cast<ALuint
>(data
.get()) << 24;
503 std::unique_ptr
<HrtfStore
> LoadHrtf00(std::istream
&data
, const char *filename
)
505 ALuint rate
{GetLE_ALuint(data
)};
506 ALushort irCount
{GetLE_ALushort(data
)};
507 ALushort irSize
{GetLE_ALushort(data
)};
508 ALubyte evCount
{GetLE_ALubyte(data
)};
509 if(!data
|| data
.eof())
511 ERR("Failed reading %s\n", filename
);
515 if(irSize
< MIN_IR_LENGTH
|| irSize
> HRIR_LENGTH
)
517 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize
, MIN_IR_LENGTH
, HRIR_LENGTH
);
520 if(evCount
< MIN_EV_COUNT
|| evCount
> MAX_EV_COUNT
)
522 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
523 evCount
, MIN_EV_COUNT
, MAX_EV_COUNT
);
527 auto elevs
= al::vector
<HrtfStore::Elevation
>(evCount
);
528 for(auto &elev
: elevs
)
529 elev
.irOffset
= GetLE_ALushort(data
);
530 if(!data
|| data
.eof())
532 ERR("Failed reading %s\n", filename
);
535 for(size_t i
{1};i
< evCount
;i
++)
537 if(elevs
[i
].irOffset
<= elevs
[i
-1].irOffset
)
539 ERR("Invalid evOffset: evOffset[%zu]=%d (last=%d)\n", i
, elevs
[i
].irOffset
,
540 elevs
[i
-1].irOffset
);
544 if(irCount
<= elevs
.back().irOffset
)
546 ERR("Invalid evOffset: evOffset[%zu]=%d (irCount=%d)\n",
547 elevs
.size()-1, elevs
.back().irOffset
, irCount
);
551 for(size_t i
{1};i
< evCount
;i
++)
553 elevs
[i
-1].azCount
= static_cast<ALushort
>(elevs
[i
].irOffset
- elevs
[i
-1].irOffset
);
554 if(elevs
[i
-1].azCount
< MIN_AZ_COUNT
|| elevs
[i
-1].azCount
> MAX_AZ_COUNT
)
556 ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n",
557 i
-1, elevs
[i
-1].azCount
, MIN_AZ_COUNT
, MAX_AZ_COUNT
);
561 elevs
.back().azCount
= static_cast<ALushort
>(irCount
- elevs
.back().irOffset
);
562 if(elevs
.back().azCount
< MIN_AZ_COUNT
|| elevs
.back().azCount
> MAX_AZ_COUNT
)
564 ERR("Unsupported azimuth count: azCount[%zu]=%d (%d to %d)\n",
565 elevs
.size()-1, elevs
.back().azCount
, MIN_AZ_COUNT
, MAX_AZ_COUNT
);
569 auto coeffs
= al::vector
<HrirArray
>(irCount
, HrirArray
{});
570 auto delays
= al::vector
<ubyte2
>(irCount
);
571 for(auto &hrir
: coeffs
)
573 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
574 val
[0] = GetLE_ALshort(data
) / 32768.0f
;
576 for(auto &val
: delays
)
577 val
[0] = GetLE_ALubyte(data
);
578 if(!data
|| data
.eof())
580 ERR("Failed reading %s\n", filename
);
583 for(size_t i
{0};i
< irCount
;i
++)
585 if(delays
[i
][0] > MAX_HRIR_DELAY
)
587 ERR("Invalid delays[%zd]: %d (%d)\n", i
, delays
[i
][0], MAX_HRIR_DELAY
);
590 delays
[i
][0] <<= HRIR_DELAY_FRACBITS
;
593 /* Mirror the left ear responses to the right ear. */
594 MirrorLeftHrirs({elevs
.data(), elevs
.size()}, coeffs
.data(), delays
.data());
596 const HrtfStore::Field field
[1]{{0.0f
, evCount
}};
597 return CreateHrtfStore(rate
, irSize
, field
, {elevs
.data(), elevs
.size()}, coeffs
.data(),
598 delays
.data(), filename
);
601 std::unique_ptr
<HrtfStore
> LoadHrtf01(std::istream
&data
, const char *filename
)
603 ALuint rate
{GetLE_ALuint(data
)};
604 ALushort irSize
{GetLE_ALubyte(data
)};
605 ALubyte evCount
{GetLE_ALubyte(data
)};
606 if(!data
|| data
.eof())
608 ERR("Failed reading %s\n", filename
);
612 if(irSize
< MIN_IR_LENGTH
|| irSize
> HRIR_LENGTH
)
614 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize
, MIN_IR_LENGTH
, HRIR_LENGTH
);
617 if(evCount
< MIN_EV_COUNT
|| evCount
> MAX_EV_COUNT
)
619 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
620 evCount
, MIN_EV_COUNT
, MAX_EV_COUNT
);
624 auto elevs
= al::vector
<HrtfStore::Elevation
>(evCount
);
625 for (auto &elev
: elevs
) elev
.azCount
= GetLE_ALubyte(data
);
626 if(!data
|| data
.eof())
628 ERR("Failed reading %s\n", filename
);
631 for(size_t i
{0};i
< evCount
;++i
)
633 if(elevs
[i
].azCount
< MIN_AZ_COUNT
|| elevs
[i
].azCount
> MAX_AZ_COUNT
)
635 ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n", i
, elevs
[i
].azCount
,
636 MIN_AZ_COUNT
, MAX_AZ_COUNT
);
641 elevs
[0].irOffset
= 0;
642 for(size_t i
{1};i
< evCount
;i
++)
643 elevs
[i
].irOffset
= static_cast<ALushort
>(elevs
[i
-1].irOffset
+ elevs
[i
-1].azCount
);
644 const ALushort irCount
{static_cast<ALushort
>(elevs
.back().irOffset
+ elevs
.back().azCount
)};
646 auto coeffs
= al::vector
<HrirArray
>(irCount
, HrirArray
{});
647 auto delays
= al::vector
<ubyte2
>(irCount
);
648 for(auto &hrir
: coeffs
)
650 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
651 val
[0] = GetLE_ALshort(data
) / 32768.0f
;
653 for(auto &val
: delays
)
654 val
[0] = GetLE_ALubyte(data
);
655 if(!data
|| data
.eof())
657 ERR("Failed reading %s\n", filename
);
660 for(size_t i
{0};i
< irCount
;i
++)
662 if(delays
[i
][0] > MAX_HRIR_DELAY
)
664 ERR("Invalid delays[%zd]: %d (%d)\n", i
, delays
[i
][0], MAX_HRIR_DELAY
);
667 delays
[i
][0] <<= HRIR_DELAY_FRACBITS
;
670 /* Mirror the left ear responses to the right ear. */
671 MirrorLeftHrirs({elevs
.data(), elevs
.size()}, coeffs
.data(), delays
.data());
673 const HrtfStore::Field field
[1]{{0.0f
, evCount
}};
674 return CreateHrtfStore(rate
, irSize
, field
, {elevs
.data(), elevs
.size()}, coeffs
.data(),
675 delays
.data(), filename
);
678 std::unique_ptr
<HrtfStore
> LoadHrtf02(std::istream
&data
, const char *filename
)
680 constexpr ALubyte SampleType_S16
{0};
681 constexpr ALubyte SampleType_S24
{1};
682 constexpr ALubyte ChanType_LeftOnly
{0};
683 constexpr ALubyte ChanType_LeftRight
{1};
685 ALuint rate
{GetLE_ALuint(data
)};
686 ALubyte sampleType
{GetLE_ALubyte(data
)};
687 ALubyte channelType
{GetLE_ALubyte(data
)};
688 ALushort irSize
{GetLE_ALubyte(data
)};
689 ALubyte fdCount
{GetLE_ALubyte(data
)};
690 if(!data
|| data
.eof())
692 ERR("Failed reading %s\n", filename
);
696 if(sampleType
> SampleType_S24
)
698 ERR("Unsupported sample type: %d\n", sampleType
);
701 if(channelType
> ChanType_LeftRight
)
703 ERR("Unsupported channel type: %d\n", channelType
);
707 if(irSize
< MIN_IR_LENGTH
|| irSize
> HRIR_LENGTH
)
709 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize
, MIN_IR_LENGTH
, HRIR_LENGTH
);
712 if(fdCount
< 1 || fdCount
> MAX_FD_COUNT
)
714 ERR("Unsupported number of field-depths: fdCount=%d (%d to %d)\n", fdCount
, MIN_FD_COUNT
,
719 auto fields
= al::vector
<HrtfStore::Field
>(fdCount
);
720 auto elevs
= al::vector
<HrtfStore::Elevation
>{};
721 for(size_t f
{0};f
< fdCount
;f
++)
723 const ALushort distance
{GetLE_ALushort(data
)};
724 const ALubyte evCount
{GetLE_ALubyte(data
)};
725 if(!data
|| data
.eof())
727 ERR("Failed reading %s\n", filename
);
731 if(distance
< MIN_FD_DISTANCE
|| distance
> MAX_FD_DISTANCE
)
733 ERR("Unsupported field distance[%zu]=%d (%d to %d millimeters)\n", f
, distance
,
734 MIN_FD_DISTANCE
, MAX_FD_DISTANCE
);
737 if(evCount
< MIN_EV_COUNT
|| evCount
> MAX_EV_COUNT
)
739 ERR("Unsupported elevation count: evCount[%zu]=%d (%d to %d)\n", f
, evCount
,
740 MIN_EV_COUNT
, MAX_EV_COUNT
);
744 fields
[f
].distance
= distance
/ 1000.0f
;
745 fields
[f
].evCount
= evCount
;
746 if(f
> 0 && fields
[f
].distance
<= fields
[f
-1].distance
)
748 ERR("Field distance[%zu] is not after previous (%f > %f)\n", f
, fields
[f
].distance
,
749 fields
[f
-1].distance
);
753 const size_t ebase
{elevs
.size()};
754 elevs
.resize(ebase
+ evCount
);
755 for(auto &elev
: al::span
<HrtfStore::Elevation
>(elevs
.data()+ebase
, evCount
))
756 elev
.azCount
= GetLE_ALubyte(data
);
757 if(!data
|| data
.eof())
759 ERR("Failed reading %s\n", filename
);
763 for(size_t e
{0};e
< evCount
;e
++)
765 if(elevs
[ebase
+e
].azCount
< MIN_AZ_COUNT
|| elevs
[ebase
+e
].azCount
> MAX_AZ_COUNT
)
767 ERR("Unsupported azimuth count: azCount[%zu][%zu]=%d (%d to %d)\n", f
, e
,
768 elevs
[ebase
+e
].azCount
, MIN_AZ_COUNT
, MAX_AZ_COUNT
);
774 elevs
[0].irOffset
= 0;
775 std::partial_sum(elevs
.cbegin(), elevs
.cend(), elevs
.begin(),
776 [](const HrtfStore::Elevation
&last
, const HrtfStore::Elevation
&cur
)
777 -> HrtfStore::Elevation
779 return HrtfStore::Elevation
{cur
.azCount
,
780 static_cast<ALushort
>(last
.azCount
+ last
.irOffset
)};
782 const auto irTotal
= static_cast<ALushort
>(elevs
.back().azCount
+ elevs
.back().irOffset
);
784 auto coeffs
= al::vector
<HrirArray
>(irTotal
, HrirArray
{});
785 auto delays
= al::vector
<ubyte2
>(irTotal
);
786 if(channelType
== ChanType_LeftOnly
)
788 if(sampleType
== SampleType_S16
)
790 for(auto &hrir
: coeffs
)
792 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
793 val
[0] = GetLE_ALshort(data
) / 32768.0f
;
796 else if(sampleType
== SampleType_S24
)
798 for(auto &hrir
: coeffs
)
800 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
801 val
[0] = static_cast<float>(GetLE_ALint24(data
)) / 8388608.0f
;
804 for(auto &val
: delays
)
805 val
[0] = GetLE_ALubyte(data
);
806 if(!data
|| data
.eof())
808 ERR("Failed reading %s\n", filename
);
811 for(size_t i
{0};i
< irTotal
;++i
)
813 if(delays
[i
][0] > MAX_HRIR_DELAY
)
815 ERR("Invalid delays[%zu][0]: %d (%d)\n", i
, delays
[i
][0], MAX_HRIR_DELAY
);
818 delays
[i
][0] <<= HRIR_DELAY_FRACBITS
;
821 /* Mirror the left ear responses to the right ear. */
822 MirrorLeftHrirs({elevs
.data(), elevs
.size()}, coeffs
.data(), delays
.data());
824 else if(channelType
== ChanType_LeftRight
)
826 if(sampleType
== SampleType_S16
)
828 for(auto &hrir
: coeffs
)
830 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
832 val
[0] = GetLE_ALshort(data
) / 32768.0f
;
833 val
[1] = GetLE_ALshort(data
) / 32768.0f
;
837 else if(sampleType
== SampleType_S24
)
839 for(auto &hrir
: coeffs
)
841 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
843 val
[0] = static_cast<float>(GetLE_ALint24(data
)) / 8388608.0f
;
844 val
[1] = static_cast<float>(GetLE_ALint24(data
)) / 8388608.0f
;
848 for(auto &val
: delays
)
850 val
[0] = GetLE_ALubyte(data
);
851 val
[1] = GetLE_ALubyte(data
);
853 if(!data
|| data
.eof())
855 ERR("Failed reading %s\n", filename
);
859 for(size_t i
{0};i
< irTotal
;++i
)
861 if(delays
[i
][0] > MAX_HRIR_DELAY
)
863 ERR("Invalid delays[%zu][0]: %d (%d)\n", i
, delays
[i
][0], MAX_HRIR_DELAY
);
866 if(delays
[i
][1] > MAX_HRIR_DELAY
)
868 ERR("Invalid delays[%zu][1]: %d (%d)\n", i
, delays
[i
][1], MAX_HRIR_DELAY
);
871 delays
[i
][0] <<= HRIR_DELAY_FRACBITS
;
872 delays
[i
][1] <<= HRIR_DELAY_FRACBITS
;
878 auto fields_
= al::vector
<HrtfStore::Field
>(fields
.size());
879 auto elevs_
= al::vector
<HrtfStore::Elevation
>(elevs
.size());
880 auto coeffs_
= al::vector
<HrirArray
>(coeffs
.size());
881 auto delays_
= al::vector
<ubyte2
>(delays
.size());
883 /* Simple reverse for the per-field elements. */
884 std::reverse_copy(fields
.cbegin(), fields
.cend(), fields_
.begin());
886 /* Each field has a group of elevations, which each have an azimuth
887 * count. Reverse the order of the groups, keeping the relative order
888 * of per-group azimuth counts.
890 auto elevs__end
= elevs_
.end();
891 auto copy_azs
= [&elevs
,&elevs__end
](const ptrdiff_t ebase
, const HrtfStore::Field
&field
)
894 auto elevs_src
= elevs
.begin()+ebase
;
895 elevs__end
= std::copy_backward(elevs_src
, elevs_src
+field
.evCount
, elevs__end
);
896 return ebase
+ field
.evCount
;
898 (void)std::accumulate(fields
.cbegin(), fields
.cend(), ptrdiff_t{0}, copy_azs
);
899 assert(elevs_
.begin() == elevs__end
);
901 /* Reestablish the IR offset for each elevation index, given the new
902 * ordering of elevations.
904 elevs_
[0].irOffset
= 0;
905 std::partial_sum(elevs_
.cbegin(), elevs_
.cend(), elevs_
.begin(),
906 [](const HrtfStore::Elevation
&last
, const HrtfStore::Elevation
&cur
)
907 -> HrtfStore::Elevation
909 return HrtfStore::Elevation
{cur
.azCount
,
910 static_cast<ALushort
>(last
.azCount
+ last
.irOffset
)};
913 /* Reverse the order of each field's group of IRs. */
914 auto coeffs_end
= coeffs_
.end();
915 auto delays_end
= delays_
.end();
916 auto copy_irs
= [&elevs
,&coeffs
,&delays
,&coeffs_end
,&delays_end
](
917 const ptrdiff_t ebase
, const HrtfStore::Field
&field
) -> ptrdiff_t
919 auto accum_az
= [](ALsizei count
, const HrtfStore::Elevation
&elev
) noexcept
-> ALsizei
920 { return count
+ elev
.azCount
; };
921 const auto elevs_mid
= elevs
.cbegin() + ebase
;
922 const auto elevs_end
= elevs_mid
+ field
.evCount
;
923 const ALsizei abase
{std::accumulate(elevs
.cbegin(), elevs_mid
, 0, accum_az
)};
924 const ALsizei num_azs
{std::accumulate(elevs_mid
, elevs_end
, 0, accum_az
)};
926 coeffs_end
= std::copy_backward(coeffs
.cbegin() + abase
,
927 coeffs
.cbegin() + (abase
+num_azs
), coeffs_end
);
928 delays_end
= std::copy_backward(delays
.cbegin() + abase
,
929 delays
.cbegin() + (abase
+num_azs
), delays_end
);
931 return ebase
+ field
.evCount
;
933 (void)std::accumulate(fields
.cbegin(), fields
.cend(), ptrdiff_t{0}, copy_irs
);
934 assert(coeffs_
.begin() == coeffs_end
);
935 assert(delays_
.begin() == delays_end
);
937 fields
= std::move(fields_
);
938 elevs
= std::move(elevs_
);
939 coeffs
= std::move(coeffs_
);
940 delays
= std::move(delays_
);
943 return CreateHrtfStore(rate
, irSize
, {fields
.data(), fields
.size()},
944 {elevs
.data(), elevs
.size()}, coeffs
.data(), delays
.data(), filename
);
947 std::unique_ptr
<HrtfStore
> LoadHrtf03(std::istream
&data
, const char *filename
)
949 constexpr ALubyte ChanType_LeftOnly
{0};
950 constexpr ALubyte ChanType_LeftRight
{1};
952 ALuint rate
{GetLE_ALuint(data
)};
953 ALubyte channelType
{GetLE_ALubyte(data
)};
954 ALushort irSize
{GetLE_ALubyte(data
)};
955 ALubyte fdCount
{GetLE_ALubyte(data
)};
956 if(!data
|| data
.eof())
958 ERR("Failed reading %s\n", filename
);
962 if(channelType
> ChanType_LeftRight
)
964 ERR("Unsupported channel type: %d\n", channelType
);
968 if(irSize
< MIN_IR_LENGTH
|| irSize
> HRIR_LENGTH
)
970 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize
, MIN_IR_LENGTH
, HRIR_LENGTH
);
973 if(fdCount
< 1 || fdCount
> MAX_FD_COUNT
)
975 ERR("Unsupported number of field-depths: fdCount=%d (%d to %d)\n", fdCount
, MIN_FD_COUNT
,
980 auto fields
= al::vector
<HrtfStore::Field
>(fdCount
);
981 auto elevs
= al::vector
<HrtfStore::Elevation
>{};
982 for(size_t f
{0};f
< fdCount
;f
++)
984 const ALushort distance
{GetLE_ALushort(data
)};
985 const ALubyte evCount
{GetLE_ALubyte(data
)};
986 if(!data
|| data
.eof())
988 ERR("Failed reading %s\n", filename
);
992 if(distance
< MIN_FD_DISTANCE
|| distance
> MAX_FD_DISTANCE
)
994 ERR("Unsupported field distance[%zu]=%d (%d to %d millimeters)\n", f
, distance
,
995 MIN_FD_DISTANCE
, MAX_FD_DISTANCE
);
998 if(evCount
< MIN_EV_COUNT
|| evCount
> MAX_EV_COUNT
)
1000 ERR("Unsupported elevation count: evCount[%zu]=%d (%d to %d)\n", f
, evCount
,
1001 MIN_EV_COUNT
, MAX_EV_COUNT
);
1005 fields
[f
].distance
= distance
/ 1000.0f
;
1006 fields
[f
].evCount
= evCount
;
1007 if(f
> 0 && fields
[f
].distance
> fields
[f
-1].distance
)
1009 ERR("Field distance[%zu] is not before previous (%f <= %f)\n", f
, fields
[f
].distance
,
1010 fields
[f
-1].distance
);
1014 const size_t ebase
{elevs
.size()};
1015 elevs
.resize(ebase
+ evCount
);
1016 for(auto &elev
: al::span
<HrtfStore::Elevation
>(elevs
.data()+ebase
, evCount
))
1017 elev
.azCount
= GetLE_ALubyte(data
);
1018 if(!data
|| data
.eof())
1020 ERR("Failed reading %s\n", filename
);
1024 for(size_t e
{0};e
< evCount
;e
++)
1026 if(elevs
[ebase
+e
].azCount
< MIN_AZ_COUNT
|| elevs
[ebase
+e
].azCount
> MAX_AZ_COUNT
)
1028 ERR("Unsupported azimuth count: azCount[%zu][%zu]=%d (%d to %d)\n", f
, e
,
1029 elevs
[ebase
+e
].azCount
, MIN_AZ_COUNT
, MAX_AZ_COUNT
);
1035 elevs
[0].irOffset
= 0;
1036 std::partial_sum(elevs
.cbegin(), elevs
.cend(), elevs
.begin(),
1037 [](const HrtfStore::Elevation
&last
, const HrtfStore::Elevation
&cur
)
1038 -> HrtfStore::Elevation
1040 return HrtfStore::Elevation
{cur
.azCount
,
1041 static_cast<ALushort
>(last
.azCount
+ last
.irOffset
)};
1043 const auto irTotal
= static_cast<ALushort
>(elevs
.back().azCount
+ elevs
.back().irOffset
);
1045 auto coeffs
= al::vector
<HrirArray
>(irTotal
, HrirArray
{});
1046 auto delays
= al::vector
<ubyte2
>(irTotal
);
1047 if(channelType
== ChanType_LeftOnly
)
1049 for(auto &hrir
: coeffs
)
1051 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
1052 val
[0] = static_cast<float>(GetLE_ALint24(data
)) / 8388608.0f
;
1054 for(auto &val
: delays
)
1055 val
[0] = GetLE_ALubyte(data
);
1056 if(!data
|| data
.eof())
1058 ERR("Failed reading %s\n", filename
);
1061 for(size_t i
{0};i
< irTotal
;++i
)
1063 if(delays
[i
][0] > MAX_HRIR_DELAY
<<HRIR_DELAY_FRACBITS
)
1065 ERR("Invalid delays[%zu][0]: %f (%d)\n", i
,
1066 delays
[i
][0] / float{HRIR_DELAY_FRACONE
}, MAX_HRIR_DELAY
);
1071 /* Mirror the left ear responses to the right ear. */
1072 MirrorLeftHrirs({elevs
.data(), elevs
.size()}, coeffs
.data(), delays
.data());
1074 else if(channelType
== ChanType_LeftRight
)
1076 for(auto &hrir
: coeffs
)
1078 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
1080 val
[0] = static_cast<float>(GetLE_ALint24(data
)) / 8388608.0f
;
1081 val
[1] = static_cast<float>(GetLE_ALint24(data
)) / 8388608.0f
;
1084 for(auto &val
: delays
)
1086 val
[0] = GetLE_ALubyte(data
);
1087 val
[1] = GetLE_ALubyte(data
);
1089 if(!data
|| data
.eof())
1091 ERR("Failed reading %s\n", filename
);
1095 for(size_t i
{0};i
< irTotal
;++i
)
1097 if(delays
[i
][0] > MAX_HRIR_DELAY
<<HRIR_DELAY_FRACBITS
)
1099 ERR("Invalid delays[%zu][0]: %f (%d)\n", i
,
1100 delays
[i
][0] / float{HRIR_DELAY_FRACONE
}, MAX_HRIR_DELAY
);
1103 if(delays
[i
][1] > MAX_HRIR_DELAY
<<HRIR_DELAY_FRACBITS
)
1105 ERR("Invalid delays[%zu][1]: %f (%d)\n", i
,
1106 delays
[i
][1] / float{HRIR_DELAY_FRACONE
}, MAX_HRIR_DELAY
);
1112 return CreateHrtfStore(rate
, irSize
, {fields
.data(), fields
.size()},
1113 {elevs
.data(), elevs
.size()}, coeffs
.data(), delays
.data(), filename
);
1117 bool checkName(const std::string
&name
)
1119 auto match_name
= [&name
](const HrtfEntry
&entry
) -> bool { return name
== entry
.mDispName
; };
1120 auto &enum_names
= EnumeratedHrtfs
;
1121 return std::find_if(enum_names
.cbegin(), enum_names
.cend(), match_name
) != enum_names
.cend();
1124 void AddFileEntry(const std::string
&filename
)
1126 /* Check if this file has already been enumerated. */
1127 auto enum_iter
= std::find_if(EnumeratedHrtfs
.cbegin(), EnumeratedHrtfs
.cend(),
1128 [&filename
](const HrtfEntry
&entry
) -> bool
1129 { return entry
.mFilename
== filename
; });
1130 if(enum_iter
!= EnumeratedHrtfs
.cend())
1132 TRACE("Skipping duplicate file entry %s\n", filename
.c_str());
1136 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1137 * format update). */
1138 size_t namepos
= filename
.find_last_of('/')+1;
1139 if(!namepos
) namepos
= filename
.find_last_of('\\')+1;
1141 size_t extpos
{filename
.find_last_of('.')};
1142 if(extpos
<= namepos
) extpos
= std::string::npos
;
1144 const std::string basename
{(extpos
== std::string::npos
) ?
1145 filename
.substr(namepos
) : filename
.substr(namepos
, extpos
-namepos
)};
1146 std::string newname
{basename
};
1148 while(checkName(newname
))
1152 newname
+= std::to_string(++count
);
1154 EnumeratedHrtfs
.emplace_back(HrtfEntry
{newname
, filename
});
1155 const HrtfEntry
&entry
= EnumeratedHrtfs
.back();
1157 TRACE("Adding file entry \"%s\"\n", entry
.mFilename
.c_str());
1160 /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
1161 * for input instead of opening the given filename.
1163 void AddBuiltInEntry(const std::string
&dispname
, ALuint residx
)
1165 const std::string filename
{'!'+std::to_string(residx
)+'_'+dispname
};
1167 auto enum_iter
= std::find_if(EnumeratedHrtfs
.cbegin(), EnumeratedHrtfs
.cend(),
1168 [&filename
](const HrtfEntry
&entry
) -> bool
1169 { return entry
.mFilename
== filename
; });
1170 if(enum_iter
!= EnumeratedHrtfs
.cend())
1172 TRACE("Skipping duplicate file entry %s\n", filename
.c_str());
1176 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1177 * format update). */
1179 std::string newname
{dispname
};
1181 while(checkName(newname
))
1185 newname
+= std::to_string(++count
);
1187 EnumeratedHrtfs
.emplace_back(HrtfEntry
{newname
, filename
});
1188 const HrtfEntry
&entry
= EnumeratedHrtfs
.back();
1190 TRACE("Adding built-in entry \"%s\"\n", entry
.mFilename
.c_str());
1194 #define IDR_DEFAULT_HRTF_MHR 1
1196 #ifndef ALSOFT_EMBED_HRTF_DATA
1198 al::span
<const char> GetResource(int /*name*/)
1203 #include "hrtf_default.h"
1205 al::span
<const char> GetResource(int name
)
1207 if(name
== IDR_DEFAULT_HRTF_MHR
)
1208 return {reinterpret_cast<const char*>(hrtf_default
), sizeof(hrtf_default
)};
1216 al::vector
<std::string
> EnumerateHrtf(const char *devname
)
1218 std::lock_guard
<std::mutex
> _
{EnumeratedHrtfLock
};
1219 EnumeratedHrtfs
.clear();
1221 bool usedefaults
{true};
1222 if(auto pathopt
= ConfigValueStr(devname
, nullptr, "hrtf-paths"))
1224 const char *pathlist
{pathopt
->c_str()};
1225 while(pathlist
&& *pathlist
)
1227 const char *next
, *end
;
1229 while(isspace(*pathlist
) || *pathlist
== ',')
1231 if(*pathlist
== '\0')
1234 next
= strchr(pathlist
, ',');
1239 end
= pathlist
+ strlen(pathlist
);
1240 usedefaults
= false;
1243 while(end
!= pathlist
&& isspace(*(end
-1)))
1247 const std::string pname
{pathlist
, end
};
1248 for(const auto &fname
: SearchDataFiles(".mhr", pname
.c_str()))
1249 AddFileEntry(fname
);
1258 for(const auto &fname
: SearchDataFiles(".mhr", "openal/hrtf"))
1259 AddFileEntry(fname
);
1261 if(!GetResource(IDR_DEFAULT_HRTF_MHR
).empty())
1262 AddBuiltInEntry("Built-In HRTF", IDR_DEFAULT_HRTF_MHR
);
1265 al::vector
<std::string
> list
;
1266 list
.reserve(EnumeratedHrtfs
.size());
1267 for(auto &entry
: EnumeratedHrtfs
)
1268 list
.emplace_back(entry
.mDispName
);
1270 if(auto defhrtfopt
= ConfigValueStr(devname
, nullptr, "default-hrtf"))
1272 auto iter
= std::find(list
.begin(), list
.end(), *defhrtfopt
);
1273 if(iter
== list
.end())
1274 WARN("Failed to find default HRTF \"%s\"\n", defhrtfopt
->c_str());
1275 else if(iter
!= list
.begin())
1276 std::rotate(list
.begin(), iter
, iter
+1);
1282 HrtfStorePtr
GetLoadedHrtf(const std::string
&name
, const char *devname
, const ALuint devrate
)
1284 std::lock_guard
<std::mutex
> _
{EnumeratedHrtfLock
};
1285 auto entry_iter
= std::find_if(EnumeratedHrtfs
.cbegin(), EnumeratedHrtfs
.cend(),
1286 [&name
](const HrtfEntry
&entry
) -> bool { return entry
.mDispName
== name
; }
1288 if(entry_iter
== EnumeratedHrtfs
.cend())
1290 const std::string
&fname
= entry_iter
->mFilename
;
1292 std::lock_guard
<std::mutex
> __
{LoadedHrtfLock
};
1293 auto hrtf_lt_fname
= [](LoadedHrtf
&hrtf
, const std::string
&filename
) -> bool
1294 { return hrtf
.mFilename
< filename
; };
1295 auto handle
= std::lower_bound(LoadedHrtfs
.begin(), LoadedHrtfs
.end(), fname
, hrtf_lt_fname
);
1296 while(handle
!= LoadedHrtfs
.end() && handle
->mFilename
== fname
)
1298 HrtfStore
*hrtf
{handle
->mEntry
.get()};
1299 if(hrtf
&& hrtf
->sampleRate
== devrate
)
1302 return HrtfStorePtr
{hrtf
};
1307 std::unique_ptr
<std::istream
> stream
;
1310 if(sscanf(fname
.c_str(), "!%d%c", &residx
, &ch
) == 2 && ch
== '_')
1312 TRACE("Loading %s...\n", fname
.c_str());
1313 al::span
<const char> res
{GetResource(residx
)};
1316 ERR("Could not get resource %u, %s\n", residx
, name
.c_str());
1319 stream
= std::make_unique
<idstream
>(res
.begin(), res
.end());
1323 TRACE("Loading %s...\n", fname
.c_str());
1324 auto fstr
= std::make_unique
<al::ifstream
>(fname
.c_str(), std::ios::binary
);
1325 if(!fstr
->is_open())
1327 ERR("Could not open %s\n", fname
.c_str());
1330 stream
= std::move(fstr
);
1333 std::unique_ptr
<HrtfStore
> hrtf
;
1334 char magic
[sizeof(magicMarker03
)];
1335 stream
->read(magic
, sizeof(magic
));
1336 if(stream
->gcount() < static_cast<std::streamsize
>(sizeof(magicMarker03
)))
1337 ERR("%s data is too short (%zu bytes)\n", name
.c_str(), stream
->gcount());
1338 else if(memcmp(magic
, magicMarker03
, sizeof(magicMarker03
)) == 0)
1340 TRACE("Detected data set format v3\n");
1341 hrtf
= LoadHrtf03(*stream
, name
.c_str());
1343 else if(memcmp(magic
, magicMarker02
, sizeof(magicMarker02
)) == 0)
1345 TRACE("Detected data set format v2\n");
1346 hrtf
= LoadHrtf02(*stream
, name
.c_str());
1348 else if(memcmp(magic
, magicMarker01
, sizeof(magicMarker01
)) == 0)
1350 TRACE("Detected data set format v1\n");
1351 hrtf
= LoadHrtf01(*stream
, name
.c_str());
1353 else if(memcmp(magic
, magicMarker00
, sizeof(magicMarker00
)) == 0)
1355 TRACE("Detected data set format v0\n");
1356 hrtf
= LoadHrtf00(*stream
, name
.c_str());
1359 ERR("Invalid header in %s: \"%.8s\"\n", name
.c_str(), magic
);
1364 ERR("Failed to load %s\n", name
.c_str());
1368 if(hrtf
->sampleRate
!= devrate
)
1370 TRACE("Resampling HRTF %s (%uhz -> %uhz)\n", name
.c_str(), hrtf
->sampleRate
, devrate
);
1372 /* Calculate the last elevation's index and get the total IR count. */
1373 const size_t lastEv
{std::accumulate(hrtf
->field
, hrtf
->field
+hrtf
->fdCount
, size_t{0},
1374 [](const size_t curval
, const HrtfStore::Field
&field
) noexcept
-> size_t
1375 { return curval
+ field
.evCount
; }
1377 const size_t irCount
{size_t{hrtf
->elev
[lastEv
].irOffset
} + hrtf
->elev
[lastEv
].azCount
};
1379 /* Resample all the IRs. */
1380 std::array
<std::array
<double,HRIR_LENGTH
>,2> inout
;
1382 rs
.init(hrtf
->sampleRate
, devrate
);
1383 for(size_t i
{0};i
< irCount
;++i
)
1385 HrirArray
&coeffs
= const_cast<HrirArray
&>(hrtf
->coeffs
[i
]);
1386 for(size_t j
{0};j
< 2;++j
)
1388 std::transform(coeffs
.cbegin(), coeffs
.cend(), inout
[0].begin(),
1389 [j
](const float2
&in
) noexcept
-> double { return in
[j
]; });
1390 rs
.process(HRIR_LENGTH
, inout
[0].data(), HRIR_LENGTH
, inout
[1].data());
1391 for(size_t k
{0};k
< HRIR_LENGTH
;++k
)
1392 coeffs
[k
][j
] = static_cast<float>(inout
[1][k
]);
1397 /* Scale the delays for the new sample rate. */
1398 float max_delay
{0.0f
};
1399 auto new_delays
= al::vector
<float2
>(irCount
);
1400 const float rate_scale
{static_cast<float>(devrate
)/static_cast<float>(hrtf
->sampleRate
)};
1401 for(size_t i
{0};i
< irCount
;++i
)
1403 for(size_t j
{0};j
< 2;++j
)
1405 const float new_delay
{std::round(hrtf
->delays
[i
][j
] * rate_scale
) /
1406 float{HRIR_DELAY_FRACONE
}};
1407 max_delay
= maxf(max_delay
, new_delay
);
1408 new_delays
[i
][j
] = new_delay
;
1412 /* If the new delays exceed the max, scale it down to fit (essentially
1413 * shrinking the head radius; not ideal but better than a per-delay
1416 float delay_scale
{HRIR_DELAY_FRACONE
};
1417 if(max_delay
> MAX_HRIR_DELAY
)
1419 WARN("Resampled delay exceeds max (%.2f > %d)\n", max_delay
, MAX_HRIR_DELAY
);
1420 delay_scale
*= float{MAX_HRIR_DELAY
} / max_delay
;
1423 for(size_t i
{0};i
< irCount
;++i
)
1425 ubyte2
&delays
= const_cast<ubyte2
&>(hrtf
->delays
[i
]);
1426 for(size_t j
{0};j
< 2;++j
)
1427 delays
[j
] = static_cast<ALubyte
>(float2int(new_delays
[i
][j
]*delay_scale
+ 0.5f
));
1430 /* Scale the IR size for the new sample rate and update the stored
1433 const float newIrSize
{std::round(static_cast<float>(hrtf
->irSize
) * rate_scale
)};
1434 hrtf
->irSize
= static_cast<ALuint
>(minf(HRIR_LENGTH
, newIrSize
));
1435 hrtf
->sampleRate
= devrate
;
1438 if(auto hrtfsizeopt
= ConfigValueUInt(devname
, nullptr, "hrtf-size"))
1440 if(*hrtfsizeopt
> 0 && *hrtfsizeopt
< hrtf
->irSize
)
1441 hrtf
->irSize
= maxu(*hrtfsizeopt
, MIN_IR_LENGTH
);
1444 TRACE("Loaded HRTF %s for sample rate %uhz, %u-sample filter\n", name
.c_str(),
1445 hrtf
->sampleRate
, hrtf
->irSize
);
1446 handle
= LoadedHrtfs
.emplace(handle
, LoadedHrtf
{fname
, std::move(hrtf
)});
1448 return HrtfStorePtr
{handle
->mEntry
.get()};
1452 void HrtfStore::add_ref()
1454 auto ref
= IncrementRef(mRef
);
1455 TRACE("HrtfStore %p increasing refcount to %u\n", decltype(std::declval
<void*>()){this}, ref
);
1458 void HrtfStore::release()
1460 auto ref
= DecrementRef(mRef
);
1461 TRACE("HrtfStore %p decreasing refcount to %u\n", decltype(std::declval
<void*>()){this}, ref
);
1464 std::lock_guard
<std::mutex
> _
{LoadedHrtfLock
};
1466 /* Go through and remove all unused HRTFs. */
1467 auto remove_unused
= [](LoadedHrtf
&hrtf
) -> bool
1469 HrtfStore
*entry
{hrtf
.mEntry
.get()};
1470 if(entry
&& ReadRef(entry
->mRef
) == 0)
1472 TRACE("Unloading unused HRTF %s\n", hrtf
.mFilename
.data());
1473 hrtf
.mEntry
= nullptr;
1478 auto iter
= std::remove_if(LoadedHrtfs
.begin(), LoadedHrtfs
.end(), remove_unused
);
1479 LoadedHrtfs
.erase(iter
, LoadedHrtfs
.end());