19 #include <type_traits>
24 #include "alfstream.h"
26 #include "alnumbers.h"
27 #include "alnumeric.h"
28 #include "aloptional.h"
31 #include "filters/splitter.h"
34 #include "mixer/hrtfdefs.h"
35 #include "opthelpers.h"
36 #include "polyphase_resampler.h"
43 std::string mDispName
;
44 std::string mFilename
;
48 std::string mFilename
;
49 std::unique_ptr
<HrtfStore
> mEntry
;
52 /* Data set limits must be the same as or more flexible than those defined in
53 * the makemhr utility.
55 constexpr uint MinFdCount
{1};
56 constexpr uint MaxFdCount
{16};
58 constexpr uint MinFdDistance
{50};
59 constexpr uint MaxFdDistance
{2500};
61 constexpr uint MinEvCount
{5};
62 constexpr uint MaxEvCount
{181};
64 constexpr uint MinAzCount
{1};
65 constexpr uint MaxAzCount
{255};
67 constexpr uint MaxHrirDelay
{HrtfHistoryLength
- 1};
69 constexpr uint HrirDelayFracBits
{2};
70 constexpr uint HrirDelayFracOne
{1 << HrirDelayFracBits
};
71 constexpr uint HrirDelayFracHalf
{HrirDelayFracOne
>> 1};
73 static_assert(MaxHrirDelay
*HrirDelayFracOne
< 256, "MAX_HRIR_DELAY or DELAY_FRAC too large");
75 constexpr char magicMarker00
[8]{'M','i','n','P','H','R','0','0'};
76 constexpr char magicMarker01
[8]{'M','i','n','P','H','R','0','1'};
77 constexpr char magicMarker02
[8]{'M','i','n','P','H','R','0','2'};
78 constexpr char magicMarker03
[8]{'M','i','n','P','H','R','0','3'};
80 /* First value for pass-through coefficients (remaining are 0), used for omni-
81 * directional sounds. */
82 constexpr auto PassthruCoeff
= static_cast<float>(1.0/al::numbers::sqrt2
);
84 std::mutex LoadedHrtfLock
;
85 al::vector
<LoadedHrtf
> LoadedHrtfs
;
87 std::mutex EnumeratedHrtfLock
;
88 al::vector
<HrtfEntry
> EnumeratedHrtfs
;
91 class databuf final
: public std::streambuf
{
92 int_type
underflow() override
93 { return traits_type::eof(); }
95 pos_type
seekoff(off_type offset
, std::ios_base::seekdir whence
, std::ios_base::openmode mode
) override
97 if((mode
&std::ios_base::out
) || !(mode
&std::ios_base::in
))
98 return traits_type::eof();
103 case std::ios_base::beg
:
104 if(offset
< 0 || offset
> egptr()-eback())
105 return traits_type::eof();
106 cur
= eback() + offset
;
109 case std::ios_base::cur
:
110 if((offset
>= 0 && offset
> egptr()-gptr()) ||
111 (offset
< 0 && -offset
> gptr()-eback()))
112 return traits_type::eof();
113 cur
= gptr() + offset
;
116 case std::ios_base::end
:
117 if(offset
> 0 || -offset
> egptr()-eback())
118 return traits_type::eof();
119 cur
= egptr() + offset
;
123 return traits_type::eof();
126 setg(eback(), cur
, egptr());
127 return cur
- eback();
130 pos_type
seekpos(pos_type pos
, std::ios_base::openmode mode
) override
132 // Simplified version of seekoff
133 if((mode
&std::ios_base::out
) || !(mode
&std::ios_base::in
))
134 return traits_type::eof();
136 if(pos
< 0 || pos
> egptr()-eback())
137 return traits_type::eof();
139 setg(eback(), eback() + static_cast<size_t>(pos
), egptr());
144 databuf(const char_type
*start_
, const char_type
*end_
) noexcept
146 setg(const_cast<char_type
*>(start_
), const_cast<char_type
*>(start_
),
147 const_cast<char_type
*>(end_
));
151 class idstream final
: public std::istream
{
155 idstream(const char *start_
, const char *end_
)
156 : std::istream
{nullptr}, mStreamBuf
{start_
, end_
}
157 { init(&mStreamBuf
); }
161 struct IdxBlend
{ uint idx
; float blend
; };
162 /* Calculate the elevation index given the polar elevation in radians. This
163 * will return an index between 0 and (evcount - 1).
165 IdxBlend
CalcEvIndex(uint evcount
, float ev
)
167 ev
= (al::numbers::pi_v
<float>*0.5f
+ ev
) * static_cast<float>(evcount
-1) /
168 al::numbers::pi_v
<float>;
169 uint idx
{float2uint(ev
)};
171 return IdxBlend
{minu(idx
, evcount
-1), ev
-static_cast<float>(idx
)};
174 /* Calculate the azimuth index given the polar azimuth in radians. This will
175 * return an index between 0 and (azcount - 1).
177 IdxBlend
CalcAzIndex(uint azcount
, float az
)
179 az
= (al::numbers::pi_v
<float>*2.0f
+ az
) * static_cast<float>(azcount
) /
180 (al::numbers::pi_v
<float>*2.0f
);
181 uint idx
{float2uint(az
)};
183 return IdxBlend
{idx
%azcount
, az
-static_cast<float>(idx
)};
189 /* Calculates static HRIR coefficients and delays for the given polar elevation
190 * and azimuth in radians. The coefficients are normalized.
192 void GetHrtfCoeffs(const HrtfStore
*Hrtf
, float elevation
, float azimuth
, float distance
,
193 float spread
, HrirArray
&coeffs
, const al::span
<uint
,2> delays
)
195 const float dirfact
{1.0f
- (al::numbers::inv_pi_v
<float>/2.0f
* spread
)};
197 const auto *field
= Hrtf
->field
;
198 const auto *field_end
= field
+ Hrtf
->fdCount
-1;
200 while(distance
< field
->distance
&& field
!= field_end
)
202 ebase
+= field
->evCount
;
206 /* Calculate the elevation indices. */
207 const auto elev0
= CalcEvIndex(field
->evCount
, elevation
);
208 const size_t elev1_idx
{minu(elev0
.idx
+1, field
->evCount
-1)};
209 const size_t ir0offset
{Hrtf
->elev
[ebase
+ elev0
.idx
].irOffset
};
210 const size_t ir1offset
{Hrtf
->elev
[ebase
+ elev1_idx
].irOffset
};
212 /* Calculate azimuth indices. */
213 const auto az0
= CalcAzIndex(Hrtf
->elev
[ebase
+ elev0
.idx
].azCount
, azimuth
);
214 const auto az1
= CalcAzIndex(Hrtf
->elev
[ebase
+ elev1_idx
].azCount
, azimuth
);
216 /* Calculate the HRIR indices to blend. */
219 ir0offset
+ ((az0
.idx
+1) % Hrtf
->elev
[ebase
+ elev0
.idx
].azCount
),
221 ir1offset
+ ((az1
.idx
+1) % Hrtf
->elev
[ebase
+ elev1_idx
].azCount
)
224 /* Calculate bilinear blending weights, attenuated according to the
225 * directional panning factor.
227 const float blend
[4]{
228 (1.0f
-elev0
.blend
) * (1.0f
-az0
.blend
) * dirfact
,
229 (1.0f
-elev0
.blend
) * ( az0
.blend
) * dirfact
,
230 ( elev0
.blend
) * (1.0f
-az1
.blend
) * dirfact
,
231 ( elev0
.blend
) * ( az1
.blend
) * dirfact
234 /* Calculate the blended HRIR delays. */
235 float d
{Hrtf
->delays
[idx
[0]][0]*blend
[0] + Hrtf
->delays
[idx
[1]][0]*blend
[1] +
236 Hrtf
->delays
[idx
[2]][0]*blend
[2] + Hrtf
->delays
[idx
[3]][0]*blend
[3]};
237 delays
[0] = fastf2u(d
* float{1.0f
/HrirDelayFracOne
});
238 d
= Hrtf
->delays
[idx
[0]][1]*blend
[0] + Hrtf
->delays
[idx
[1]][1]*blend
[1] +
239 Hrtf
->delays
[idx
[2]][1]*blend
[2] + Hrtf
->delays
[idx
[3]][1]*blend
[3];
240 delays
[1] = fastf2u(d
* float{1.0f
/HrirDelayFracOne
});
242 /* Calculate the blended HRIR coefficients. */
243 float *coeffout
{al::assume_aligned
<16>(&coeffs
[0][0])};
244 coeffout
[0] = PassthruCoeff
* (1.0f
-dirfact
);
245 coeffout
[1] = PassthruCoeff
* (1.0f
-dirfact
);
246 std::fill_n(coeffout
+2, size_t{HrirLength
-1}*2, 0.0f
);
247 for(size_t c
{0};c
< 4;c
++)
249 const float *srccoeffs
{al::assume_aligned
<16>(Hrtf
->coeffs
[idx
[c
]][0].data())};
250 const float mult
{blend
[c
]};
251 auto blend_coeffs
= [mult
](const float src
, const float coeff
) noexcept
-> float
252 { return src
*mult
+ coeff
; };
253 std::transform(srccoeffs
, srccoeffs
+ HrirLength
*2, coeffout
, coeffout
, blend_coeffs
);
258 std::unique_ptr
<DirectHrtfState
> DirectHrtfState::Create(size_t num_chans
)
259 { return std::unique_ptr
<DirectHrtfState
>{new(FamCount(num_chans
)) DirectHrtfState
{num_chans
}}; }
261 void DirectHrtfState::build(const HrtfStore
*Hrtf
, const uint irSize
,
262 const al::span
<const AngularPoint
> AmbiPoints
, const float (*AmbiMatrix
)[MaxAmbiChannels
],
263 const float XOverFreq
, const al::span
<const float,MaxAmbiOrder
+1> AmbiOrderHFGain
)
265 using double2
= std::array
<double,2>;
266 struct ImpulseResponse
{
267 const ConstHrirSpan hrir
;
271 const double xover_norm
{double{XOverFreq
} / Hrtf
->sampleRate
};
272 for(size_t i
{0};i
< mChannels
.size();++i
)
274 const size_t order
{AmbiIndex::OrderFromChannel()[i
]};
275 mChannels
[i
].mSplitter
.init(static_cast<float>(xover_norm
));
276 mChannels
[i
].mHfScale
= AmbiOrderHFGain
[order
];
279 uint min_delay
{HrtfHistoryLength
*HrirDelayFracOne
}, max_delay
{0};
280 al::vector
<ImpulseResponse
> impres
; impres
.reserve(AmbiPoints
.size());
281 auto calc_res
= [Hrtf
,&max_delay
,&min_delay
](const AngularPoint
&pt
) -> ImpulseResponse
283 auto &field
= Hrtf
->field
[0];
284 const auto elev0
= CalcEvIndex(field
.evCount
, pt
.Elev
.value
);
285 const size_t elev1_idx
{minu(elev0
.idx
+1, field
.evCount
-1)};
286 const size_t ir0offset
{Hrtf
->elev
[elev0
.idx
].irOffset
};
287 const size_t ir1offset
{Hrtf
->elev
[elev1_idx
].irOffset
};
289 const auto az0
= CalcAzIndex(Hrtf
->elev
[elev0
.idx
].azCount
, pt
.Azim
.value
);
290 const auto az1
= CalcAzIndex(Hrtf
->elev
[elev1_idx
].azCount
, pt
.Azim
.value
);
294 ir0offset
+ ((az0
.idx
+1) % Hrtf
->elev
[elev0
.idx
].azCount
),
296 ir1offset
+ ((az1
.idx
+1) % Hrtf
->elev
[elev1_idx
].azCount
)
299 const std::array
<double,4> blend
{{
300 (1.0-elev0
.blend
) * (1.0-az0
.blend
),
301 (1.0-elev0
.blend
) * ( az0
.blend
),
302 ( elev0
.blend
) * (1.0-az1
.blend
),
303 ( elev0
.blend
) * ( az1
.blend
)
306 /* The largest blend factor serves as the closest HRIR. */
307 const size_t irOffset
{idx
[std::max_element(blend
.begin(), blend
.end()) - blend
.begin()]};
308 ImpulseResponse res
{Hrtf
->coeffs
[irOffset
],
309 Hrtf
->delays
[irOffset
][0], Hrtf
->delays
[irOffset
][1]};
311 min_delay
= minu(min_delay
, minu(res
.ldelay
, res
.rdelay
));
312 max_delay
= maxu(max_delay
, maxu(res
.ldelay
, res
.rdelay
));
316 std::transform(AmbiPoints
.begin(), AmbiPoints
.end(), std::back_inserter(impres
), calc_res
);
317 auto hrir_delay_round
= [](const uint d
) noexcept
-> uint
318 { return (d
+HrirDelayFracHalf
) >> HrirDelayFracBits
; };
320 TRACE("Min delay: %.2f, max delay: %.2f, FIR length: %u\n",
321 min_delay
/double{HrirDelayFracOne
}, max_delay
/double{HrirDelayFracOne
}, irSize
);
323 const bool per_hrir_min
{mChannels
.size() > AmbiChannelsFromOrder(1)};
324 auto tmpres
= al::vector
<std::array
<double2
,HrirLength
>>(mChannels
.size());
326 for(size_t c
{0u};c
< AmbiPoints
.size();++c
)
328 const ConstHrirSpan hrir
{impres
[c
].hrir
};
329 const uint base_delay
{per_hrir_min
? minu(impres
[c
].ldelay
, impres
[c
].rdelay
) : min_delay
};
330 const uint ldelay
{hrir_delay_round(impres
[c
].ldelay
- base_delay
)};
331 const uint rdelay
{hrir_delay_round(impres
[c
].rdelay
- base_delay
)};
332 max_delay
= maxu(max_delay
, maxu(impres
[c
].ldelay
, impres
[c
].rdelay
) - base_delay
);
334 for(size_t i
{0u};i
< mChannels
.size();++i
)
336 const double mult
{AmbiMatrix
[c
][i
]};
337 const size_t numirs
{HrirLength
- maxz(ldelay
, rdelay
)};
338 size_t lidx
{ldelay
}, ridx
{rdelay
};
339 for(size_t j
{0};j
< numirs
;++j
)
341 tmpres
[i
][lidx
++][0] += hrir
[j
][0] * mult
;
342 tmpres
[i
][ridx
++][1] += hrir
[j
][1] * mult
;
348 for(size_t i
{0u};i
< mChannels
.size();++i
)
350 auto copy_arr
= [](const double2
&in
) noexcept
-> float2
351 { return float2
{{static_cast<float>(in
[0]), static_cast<float>(in
[1])}}; };
352 std::transform(tmpres
[i
].cbegin(), tmpres
[i
].cend(), mChannels
[i
].mCoeffs
.begin(),
357 const uint max_length
{minu(hrir_delay_round(max_delay
) + irSize
, HrirLength
)};
358 TRACE("New max delay: %.2f, FIR length: %u\n", max_delay
/double{HrirDelayFracOne
},
360 mIrSize
= max_length
;
366 std::unique_ptr
<HrtfStore
> CreateHrtfStore(uint rate
, ushort irSize
,
367 const al::span
<const HrtfStore::Field
> fields
,
368 const al::span
<const HrtfStore::Elevation
> elevs
, const HrirArray
*coeffs
,
369 const ubyte2
*delays
, const char *filename
)
371 const size_t irCount
{size_t{elevs
.back().azCount
} + elevs
.back().irOffset
};
372 size_t total
{sizeof(HrtfStore
)};
373 total
= RoundUp(total
, alignof(HrtfStore::Field
)); /* Align for field infos */
374 total
+= sizeof(std::declval
<HrtfStore
&>().field
[0])*fields
.size();
375 total
= RoundUp(total
, alignof(HrtfStore::Elevation
)); /* Align for elevation infos */
376 total
+= sizeof(std::declval
<HrtfStore
&>().elev
[0])*elevs
.size();
377 total
= RoundUp(total
, 16); /* Align for coefficients using SIMD */
378 total
+= sizeof(std::declval
<HrtfStore
&>().coeffs
[0])*irCount
;
379 total
+= sizeof(std::declval
<HrtfStore
&>().delays
[0])*irCount
;
381 void *ptr
{al_calloc(16, total
)};
382 std::unique_ptr
<HrtfStore
> Hrtf
{al::construct_at(static_cast<HrtfStore
*>(ptr
))};
384 ERR("Out of memory allocating storage for %s.\n", filename
);
387 InitRef(Hrtf
->mRef
, 1u);
388 Hrtf
->sampleRate
= rate
;
389 Hrtf
->irSize
= irSize
;
390 Hrtf
->fdCount
= static_cast<uint
>(fields
.size());
392 /* Set up pointers to storage following the main HRTF struct. */
393 char *base
= reinterpret_cast<char*>(Hrtf
.get());
394 size_t offset
{sizeof(HrtfStore
)};
396 offset
= RoundUp(offset
, alignof(HrtfStore::Field
)); /* Align for field infos */
397 auto field_
= reinterpret_cast<HrtfStore::Field
*>(base
+ offset
);
398 offset
+= sizeof(field_
[0])*fields
.size();
400 offset
= RoundUp(offset
, alignof(HrtfStore::Elevation
)); /* Align for elevation infos */
401 auto elev_
= reinterpret_cast<HrtfStore::Elevation
*>(base
+ offset
);
402 offset
+= sizeof(elev_
[0])*elevs
.size();
404 offset
= RoundUp(offset
, 16); /* Align for coefficients using SIMD */
405 auto coeffs_
= reinterpret_cast<HrirArray
*>(base
+ offset
);
406 offset
+= sizeof(coeffs_
[0])*irCount
;
408 auto delays_
= reinterpret_cast<ubyte2
*>(base
+ offset
);
409 offset
+= sizeof(delays_
[0])*irCount
;
411 if(unlikely(offset
!= total
))
412 throw std::runtime_error
{"HrtfStore allocation size mismatch"};
414 /* Copy input data to storage. */
415 std::uninitialized_copy(fields
.cbegin(), fields
.cend(), field_
);
416 std::uninitialized_copy(elevs
.cbegin(), elevs
.cend(), elev_
);
417 std::uninitialized_copy_n(coeffs
, irCount
, coeffs_
);
418 std::uninitialized_copy_n(delays
, irCount
, delays_
);
420 /* Finally, assign the storage pointers. */
421 Hrtf
->field
= field_
;
423 Hrtf
->coeffs
= coeffs_
;
424 Hrtf
->delays
= delays_
;
430 void MirrorLeftHrirs(const al::span
<const HrtfStore::Elevation
> elevs
, HrirArray
*coeffs
,
433 for(const auto &elev
: elevs
)
435 const ushort evoffset
{elev
.irOffset
};
436 const ushort azcount
{elev
.azCount
};
437 for(size_t j
{0};j
< azcount
;j
++)
439 const size_t lidx
{evoffset
+ j
};
440 const size_t ridx
{evoffset
+ ((azcount
-j
) % azcount
)};
442 const size_t irSize
{coeffs
[ridx
].size()};
443 for(size_t k
{0};k
< irSize
;k
++)
444 coeffs
[ridx
][k
][1] = coeffs
[lidx
][k
][0];
445 delays
[ridx
][1] = delays
[lidx
][0];
451 template<size_t num_bits
, typename T
>
452 constexpr std::enable_if_t
<std::is_signed
<T
>::value
&& num_bits
< sizeof(T
)*8,
453 T
> fixsign(T value
) noexcept
455 constexpr auto signbit
= static_cast<T
>(1u << (num_bits
-1));
456 return static_cast<T
>((value
^signbit
) - signbit
);
459 template<size_t num_bits
, typename T
>
460 constexpr std::enable_if_t
<!std::is_signed
<T
>::value
|| num_bits
== sizeof(T
)*8,
461 T
> fixsign(T value
) noexcept
464 template<typename T
, size_t num_bits
=sizeof(T
)*8>
465 inline std::enable_if_t
<al::endian::native
== al::endian::little
,
466 T
> readle(std::istream
&data
)
468 static_assert((num_bits
&7) == 0, "num_bits must be a multiple of 8");
469 static_assert(num_bits
<= sizeof(T
)*8, "num_bits is too large for the type");
472 if(!data
.read(reinterpret_cast<char*>(&ret
), num_bits
/8))
473 return static_cast<T
>(EOF
);
475 return fixsign
<num_bits
>(ret
);
478 template<typename T
, size_t num_bits
=sizeof(T
)*8>
479 inline std::enable_if_t
<al::endian::native
== al::endian::big
,
480 T
> readle(std::istream
&data
)
482 static_assert((num_bits
&7) == 0, "num_bits must be a multiple of 8");
483 static_assert(num_bits
<= sizeof(T
)*8, "num_bits is too large for the type");
486 al::byte b
[sizeof(T
)]{};
487 if(!data
.read(reinterpret_cast<char*>(b
), num_bits
/8))
488 return static_cast<T
>(EOF
);
489 std::reverse_copy(std::begin(b
), std::end(b
), reinterpret_cast<al::byte
*>(&ret
));
491 return fixsign
<num_bits
>(ret
);
495 inline uint8_t readle
<uint8_t,8>(std::istream
&data
)
496 { return static_cast<uint8_t>(data
.get()); }
499 std::unique_ptr
<HrtfStore
> LoadHrtf00(std::istream
&data
, const char *filename
)
501 uint rate
{readle
<uint32_t>(data
)};
502 ushort irCount
{readle
<uint16_t>(data
)};
503 ushort irSize
{readle
<uint16_t>(data
)};
504 ubyte evCount
{readle
<uint8_t>(data
)};
505 if(!data
|| data
.eof())
507 ERR("Failed reading %s\n", filename
);
511 if(irSize
< MinIrLength
|| irSize
> HrirLength
)
513 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize
, MinIrLength
, HrirLength
);
516 if(evCount
< MinEvCount
|| evCount
> MaxEvCount
)
518 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
519 evCount
, MinEvCount
, MaxEvCount
);
523 auto elevs
= al::vector
<HrtfStore::Elevation
>(evCount
);
524 for(auto &elev
: elevs
)
525 elev
.irOffset
= readle
<uint16_t>(data
);
526 if(!data
|| data
.eof())
528 ERR("Failed reading %s\n", filename
);
531 for(size_t i
{1};i
< evCount
;i
++)
533 if(elevs
[i
].irOffset
<= elevs
[i
-1].irOffset
)
535 ERR("Invalid evOffset: evOffset[%zu]=%d (last=%d)\n", i
, elevs
[i
].irOffset
,
536 elevs
[i
-1].irOffset
);
540 if(irCount
<= elevs
.back().irOffset
)
542 ERR("Invalid evOffset: evOffset[%zu]=%d (irCount=%d)\n",
543 elevs
.size()-1, elevs
.back().irOffset
, irCount
);
547 for(size_t i
{1};i
< evCount
;i
++)
549 elevs
[i
-1].azCount
= static_cast<ushort
>(elevs
[i
].irOffset
- elevs
[i
-1].irOffset
);
550 if(elevs
[i
-1].azCount
< MinAzCount
|| elevs
[i
-1].azCount
> MaxAzCount
)
552 ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n",
553 i
-1, elevs
[i
-1].azCount
, MinAzCount
, MaxAzCount
);
557 elevs
.back().azCount
= static_cast<ushort
>(irCount
- elevs
.back().irOffset
);
558 if(elevs
.back().azCount
< MinAzCount
|| elevs
.back().azCount
> MaxAzCount
)
560 ERR("Unsupported azimuth count: azCount[%zu]=%d (%d to %d)\n",
561 elevs
.size()-1, elevs
.back().azCount
, MinAzCount
, MaxAzCount
);
565 auto coeffs
= al::vector
<HrirArray
>(irCount
, HrirArray
{});
566 auto delays
= al::vector
<ubyte2
>(irCount
);
567 for(auto &hrir
: coeffs
)
569 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
570 val
[0] = readle
<int16_t>(data
) / 32768.0f
;
572 for(auto &val
: delays
)
573 val
[0] = readle
<uint8_t>(data
);
574 if(!data
|| data
.eof())
576 ERR("Failed reading %s\n", filename
);
579 for(size_t i
{0};i
< irCount
;i
++)
581 if(delays
[i
][0] > MaxHrirDelay
)
583 ERR("Invalid delays[%zd]: %d (%d)\n", i
, delays
[i
][0], MaxHrirDelay
);
586 delays
[i
][0] <<= HrirDelayFracBits
;
589 /* Mirror the left ear responses to the right ear. */
590 MirrorLeftHrirs({elevs
.data(), elevs
.size()}, coeffs
.data(), delays
.data());
592 const HrtfStore::Field field
[1]{{0.0f
, evCount
}};
593 return CreateHrtfStore(rate
, irSize
, field
, {elevs
.data(), elevs
.size()}, coeffs
.data(),
594 delays
.data(), filename
);
597 std::unique_ptr
<HrtfStore
> LoadHrtf01(std::istream
&data
, const char *filename
)
599 uint rate
{readle
<uint32_t>(data
)};
600 ushort irSize
{readle
<uint8_t>(data
)};
601 ubyte evCount
{readle
<uint8_t>(data
)};
602 if(!data
|| data
.eof())
604 ERR("Failed reading %s\n", filename
);
608 if(irSize
< MinIrLength
|| irSize
> HrirLength
)
610 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize
, MinIrLength
, HrirLength
);
613 if(evCount
< MinEvCount
|| evCount
> MaxEvCount
)
615 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
616 evCount
, MinEvCount
, MaxEvCount
);
620 auto elevs
= al::vector
<HrtfStore::Elevation
>(evCount
);
621 for(auto &elev
: elevs
)
622 elev
.azCount
= readle
<uint8_t>(data
);
623 if(!data
|| data
.eof())
625 ERR("Failed reading %s\n", filename
);
628 for(size_t i
{0};i
< evCount
;++i
)
630 if(elevs
[i
].azCount
< MinAzCount
|| elevs
[i
].azCount
> MaxAzCount
)
632 ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n", i
, elevs
[i
].azCount
,
633 MinAzCount
, MaxAzCount
);
638 elevs
[0].irOffset
= 0;
639 for(size_t i
{1};i
< evCount
;i
++)
640 elevs
[i
].irOffset
= static_cast<ushort
>(elevs
[i
-1].irOffset
+ elevs
[i
-1].azCount
);
641 const ushort irCount
{static_cast<ushort
>(elevs
.back().irOffset
+ elevs
.back().azCount
)};
643 auto coeffs
= al::vector
<HrirArray
>(irCount
, HrirArray
{});
644 auto delays
= al::vector
<ubyte2
>(irCount
);
645 for(auto &hrir
: coeffs
)
647 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
648 val
[0] = readle
<int16_t>(data
) / 32768.0f
;
650 for(auto &val
: delays
)
651 val
[0] = readle
<uint8_t>(data
);
652 if(!data
|| data
.eof())
654 ERR("Failed reading %s\n", filename
);
657 for(size_t i
{0};i
< irCount
;i
++)
659 if(delays
[i
][0] > MaxHrirDelay
)
661 ERR("Invalid delays[%zd]: %d (%d)\n", i
, delays
[i
][0], MaxHrirDelay
);
664 delays
[i
][0] <<= HrirDelayFracBits
;
667 /* Mirror the left ear responses to the right ear. */
668 MirrorLeftHrirs({elevs
.data(), elevs
.size()}, coeffs
.data(), delays
.data());
670 const HrtfStore::Field field
[1]{{0.0f
, evCount
}};
671 return CreateHrtfStore(rate
, irSize
, field
, {elevs
.data(), elevs
.size()}, coeffs
.data(),
672 delays
.data(), filename
);
675 std::unique_ptr
<HrtfStore
> LoadHrtf02(std::istream
&data
, const char *filename
)
677 constexpr ubyte SampleType_S16
{0};
678 constexpr ubyte SampleType_S24
{1};
679 constexpr ubyte ChanType_LeftOnly
{0};
680 constexpr ubyte ChanType_LeftRight
{1};
682 uint rate
{readle
<uint32_t>(data
)};
683 ubyte sampleType
{readle
<uint8_t>(data
)};
684 ubyte channelType
{readle
<uint8_t>(data
)};
685 ushort irSize
{readle
<uint8_t>(data
)};
686 ubyte fdCount
{readle
<uint8_t>(data
)};
687 if(!data
|| data
.eof())
689 ERR("Failed reading %s\n", filename
);
693 if(sampleType
> SampleType_S24
)
695 ERR("Unsupported sample type: %d\n", sampleType
);
698 if(channelType
> ChanType_LeftRight
)
700 ERR("Unsupported channel type: %d\n", channelType
);
704 if(irSize
< MinIrLength
|| irSize
> HrirLength
)
706 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize
, MinIrLength
, HrirLength
);
709 if(fdCount
< 1 || fdCount
> MaxFdCount
)
711 ERR("Unsupported number of field-depths: fdCount=%d (%d to %d)\n", fdCount
, MinFdCount
,
716 auto fields
= al::vector
<HrtfStore::Field
>(fdCount
);
717 auto elevs
= al::vector
<HrtfStore::Elevation
>{};
718 for(size_t f
{0};f
< fdCount
;f
++)
720 const ushort distance
{readle
<uint16_t>(data
)};
721 const ubyte evCount
{readle
<uint8_t>(data
)};
722 if(!data
|| data
.eof())
724 ERR("Failed reading %s\n", filename
);
728 if(distance
< MinFdDistance
|| distance
> MaxFdDistance
)
730 ERR("Unsupported field distance[%zu]=%d (%d to %d millimeters)\n", f
, distance
,
731 MinFdDistance
, MaxFdDistance
);
734 if(evCount
< MinEvCount
|| evCount
> MaxEvCount
)
736 ERR("Unsupported elevation count: evCount[%zu]=%d (%d to %d)\n", f
, evCount
,
737 MinEvCount
, MaxEvCount
);
741 fields
[f
].distance
= distance
/ 1000.0f
;
742 fields
[f
].evCount
= evCount
;
743 if(f
> 0 && fields
[f
].distance
<= fields
[f
-1].distance
)
745 ERR("Field distance[%zu] is not after previous (%f > %f)\n", f
, fields
[f
].distance
,
746 fields
[f
-1].distance
);
750 const size_t ebase
{elevs
.size()};
751 elevs
.resize(ebase
+ evCount
);
752 for(auto &elev
: al::span
<HrtfStore::Elevation
>(elevs
.data()+ebase
, evCount
))
753 elev
.azCount
= readle
<uint8_t>(data
);
754 if(!data
|| data
.eof())
756 ERR("Failed reading %s\n", filename
);
760 for(size_t e
{0};e
< evCount
;e
++)
762 if(elevs
[ebase
+e
].azCount
< MinAzCount
|| elevs
[ebase
+e
].azCount
> MaxAzCount
)
764 ERR("Unsupported azimuth count: azCount[%zu][%zu]=%d (%d to %d)\n", f
, e
,
765 elevs
[ebase
+e
].azCount
, MinAzCount
, MaxAzCount
);
771 elevs
[0].irOffset
= 0;
772 std::partial_sum(elevs
.cbegin(), elevs
.cend(), elevs
.begin(),
773 [](const HrtfStore::Elevation
&last
, const HrtfStore::Elevation
&cur
)
774 -> HrtfStore::Elevation
776 return HrtfStore::Elevation
{cur
.azCount
,
777 static_cast<ushort
>(last
.azCount
+ last
.irOffset
)};
779 const auto irTotal
= static_cast<ushort
>(elevs
.back().azCount
+ elevs
.back().irOffset
);
781 auto coeffs
= al::vector
<HrirArray
>(irTotal
, HrirArray
{});
782 auto delays
= al::vector
<ubyte2
>(irTotal
);
783 if(channelType
== ChanType_LeftOnly
)
785 if(sampleType
== SampleType_S16
)
787 for(auto &hrir
: coeffs
)
789 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
790 val
[0] = readle
<int16_t>(data
) / 32768.0f
;
793 else if(sampleType
== SampleType_S24
)
795 for(auto &hrir
: coeffs
)
797 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
798 val
[0] = static_cast<float>(readle
<int,24>(data
)) / 8388608.0f
;
801 for(auto &val
: delays
)
802 val
[0] = readle
<uint8_t>(data
);
803 if(!data
|| data
.eof())
805 ERR("Failed reading %s\n", filename
);
808 for(size_t i
{0};i
< irTotal
;++i
)
810 if(delays
[i
][0] > MaxHrirDelay
)
812 ERR("Invalid delays[%zu][0]: %d (%d)\n", i
, delays
[i
][0], MaxHrirDelay
);
815 delays
[i
][0] <<= HrirDelayFracBits
;
818 /* Mirror the left ear responses to the right ear. */
819 MirrorLeftHrirs({elevs
.data(), elevs
.size()}, coeffs
.data(), delays
.data());
821 else if(channelType
== ChanType_LeftRight
)
823 if(sampleType
== SampleType_S16
)
825 for(auto &hrir
: coeffs
)
827 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
829 val
[0] = readle
<int16_t>(data
) / 32768.0f
;
830 val
[1] = readle
<int16_t>(data
) / 32768.0f
;
834 else if(sampleType
== SampleType_S24
)
836 for(auto &hrir
: coeffs
)
838 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
840 val
[0] = static_cast<float>(readle
<int,24>(data
)) / 8388608.0f
;
841 val
[1] = static_cast<float>(readle
<int,24>(data
)) / 8388608.0f
;
845 for(auto &val
: delays
)
847 val
[0] = readle
<uint8_t>(data
);
848 val
[1] = readle
<uint8_t>(data
);
850 if(!data
|| data
.eof())
852 ERR("Failed reading %s\n", filename
);
856 for(size_t i
{0};i
< irTotal
;++i
)
858 if(delays
[i
][0] > MaxHrirDelay
)
860 ERR("Invalid delays[%zu][0]: %d (%d)\n", i
, delays
[i
][0], MaxHrirDelay
);
863 if(delays
[i
][1] > MaxHrirDelay
)
865 ERR("Invalid delays[%zu][1]: %d (%d)\n", i
, delays
[i
][1], MaxHrirDelay
);
868 delays
[i
][0] <<= HrirDelayFracBits
;
869 delays
[i
][1] <<= HrirDelayFracBits
;
875 auto fields_
= al::vector
<HrtfStore::Field
>(fields
.size());
876 auto elevs_
= al::vector
<HrtfStore::Elevation
>(elevs
.size());
877 auto coeffs_
= al::vector
<HrirArray
>(coeffs
.size());
878 auto delays_
= al::vector
<ubyte2
>(delays
.size());
880 /* Simple reverse for the per-field elements. */
881 std::reverse_copy(fields
.cbegin(), fields
.cend(), fields_
.begin());
883 /* Each field has a group of elevations, which each have an azimuth
884 * count. Reverse the order of the groups, keeping the relative order
885 * of per-group azimuth counts.
887 auto elevs__end
= elevs_
.end();
888 auto copy_azs
= [&elevs
,&elevs__end
](const ptrdiff_t ebase
, const HrtfStore::Field
&field
)
891 auto elevs_src
= elevs
.begin()+ebase
;
892 elevs__end
= std::copy_backward(elevs_src
, elevs_src
+field
.evCount
, elevs__end
);
893 return ebase
+ field
.evCount
;
895 (void)std::accumulate(fields
.cbegin(), fields
.cend(), ptrdiff_t{0}, copy_azs
);
896 assert(elevs_
.begin() == elevs__end
);
898 /* Reestablish the IR offset for each elevation index, given the new
899 * ordering of elevations.
901 elevs_
[0].irOffset
= 0;
902 std::partial_sum(elevs_
.cbegin(), elevs_
.cend(), elevs_
.begin(),
903 [](const HrtfStore::Elevation
&last
, const HrtfStore::Elevation
&cur
)
904 -> HrtfStore::Elevation
906 return HrtfStore::Elevation
{cur
.azCount
,
907 static_cast<ushort
>(last
.azCount
+ last
.irOffset
)};
910 /* Reverse the order of each field's group of IRs. */
911 auto coeffs_end
= coeffs_
.end();
912 auto delays_end
= delays_
.end();
913 auto copy_irs
= [&elevs
,&coeffs
,&delays
,&coeffs_end
,&delays_end
](
914 const ptrdiff_t ebase
, const HrtfStore::Field
&field
) -> ptrdiff_t
916 auto accum_az
= [](int count
, const HrtfStore::Elevation
&elev
) noexcept
-> int
917 { return count
+ elev
.azCount
; };
918 const auto elevs_mid
= elevs
.cbegin() + ebase
;
919 const auto elevs_end
= elevs_mid
+ field
.evCount
;
920 const int abase
{std::accumulate(elevs
.cbegin(), elevs_mid
, 0, accum_az
)};
921 const int num_azs
{std::accumulate(elevs_mid
, elevs_end
, 0, accum_az
)};
923 coeffs_end
= std::copy_backward(coeffs
.cbegin() + abase
,
924 coeffs
.cbegin() + (abase
+num_azs
), coeffs_end
);
925 delays_end
= std::copy_backward(delays
.cbegin() + abase
,
926 delays
.cbegin() + (abase
+num_azs
), delays_end
);
928 return ebase
+ field
.evCount
;
930 (void)std::accumulate(fields
.cbegin(), fields
.cend(), ptrdiff_t{0}, copy_irs
);
931 assert(coeffs_
.begin() == coeffs_end
);
932 assert(delays_
.begin() == delays_end
);
934 fields
= std::move(fields_
);
935 elevs
= std::move(elevs_
);
936 coeffs
= std::move(coeffs_
);
937 delays
= std::move(delays_
);
940 return CreateHrtfStore(rate
, irSize
, {fields
.data(), fields
.size()},
941 {elevs
.data(), elevs
.size()}, coeffs
.data(), delays
.data(), filename
);
944 std::unique_ptr
<HrtfStore
> LoadHrtf03(std::istream
&data
, const char *filename
)
946 constexpr ubyte ChanType_LeftOnly
{0};
947 constexpr ubyte ChanType_LeftRight
{1};
949 uint rate
{readle
<uint32_t>(data
)};
950 ubyte channelType
{readle
<uint8_t>(data
)};
951 ushort irSize
{readle
<uint8_t>(data
)};
952 ubyte fdCount
{readle
<uint8_t>(data
)};
953 if(!data
|| data
.eof())
955 ERR("Failed reading %s\n", filename
);
959 if(channelType
> ChanType_LeftRight
)
961 ERR("Unsupported channel type: %d\n", channelType
);
965 if(irSize
< MinIrLength
|| irSize
> HrirLength
)
967 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize
, MinIrLength
, HrirLength
);
970 if(fdCount
< 1 || fdCount
> MaxFdCount
)
972 ERR("Unsupported number of field-depths: fdCount=%d (%d to %d)\n", fdCount
, MinFdCount
,
977 auto fields
= al::vector
<HrtfStore::Field
>(fdCount
);
978 auto elevs
= al::vector
<HrtfStore::Elevation
>{};
979 for(size_t f
{0};f
< fdCount
;f
++)
981 const ushort distance
{readle
<uint16_t>(data
)};
982 const ubyte evCount
{readle
<uint8_t>(data
)};
983 if(!data
|| data
.eof())
985 ERR("Failed reading %s\n", filename
);
989 if(distance
< MinFdDistance
|| distance
> MaxFdDistance
)
991 ERR("Unsupported field distance[%zu]=%d (%d to %d millimeters)\n", f
, distance
,
992 MinFdDistance
, MaxFdDistance
);
995 if(evCount
< MinEvCount
|| evCount
> MaxEvCount
)
997 ERR("Unsupported elevation count: evCount[%zu]=%d (%d to %d)\n", f
, evCount
,
998 MinEvCount
, MaxEvCount
);
1002 fields
[f
].distance
= distance
/ 1000.0f
;
1003 fields
[f
].evCount
= evCount
;
1004 if(f
> 0 && fields
[f
].distance
> fields
[f
-1].distance
)
1006 ERR("Field distance[%zu] is not before previous (%f <= %f)\n", f
, fields
[f
].distance
,
1007 fields
[f
-1].distance
);
1011 const size_t ebase
{elevs
.size()};
1012 elevs
.resize(ebase
+ evCount
);
1013 for(auto &elev
: al::span
<HrtfStore::Elevation
>(elevs
.data()+ebase
, evCount
))
1014 elev
.azCount
= readle
<uint8_t>(data
);
1015 if(!data
|| data
.eof())
1017 ERR("Failed reading %s\n", filename
);
1021 for(size_t e
{0};e
< evCount
;e
++)
1023 if(elevs
[ebase
+e
].azCount
< MinAzCount
|| elevs
[ebase
+e
].azCount
> MaxAzCount
)
1025 ERR("Unsupported azimuth count: azCount[%zu][%zu]=%d (%d to %d)\n", f
, e
,
1026 elevs
[ebase
+e
].azCount
, MinAzCount
, MaxAzCount
);
1032 elevs
[0].irOffset
= 0;
1033 std::partial_sum(elevs
.cbegin(), elevs
.cend(), elevs
.begin(),
1034 [](const HrtfStore::Elevation
&last
, const HrtfStore::Elevation
&cur
)
1035 -> HrtfStore::Elevation
1037 return HrtfStore::Elevation
{cur
.azCount
,
1038 static_cast<ushort
>(last
.azCount
+ last
.irOffset
)};
1040 const auto irTotal
= static_cast<ushort
>(elevs
.back().azCount
+ elevs
.back().irOffset
);
1042 auto coeffs
= al::vector
<HrirArray
>(irTotal
, HrirArray
{});
1043 auto delays
= al::vector
<ubyte2
>(irTotal
);
1044 if(channelType
== ChanType_LeftOnly
)
1046 for(auto &hrir
: coeffs
)
1048 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
1049 val
[0] = static_cast<float>(readle
<int,24>(data
)) / 8388608.0f
;
1051 for(auto &val
: delays
)
1052 val
[0] = readle
<uint8_t>(data
);
1053 if(!data
|| data
.eof())
1055 ERR("Failed reading %s\n", filename
);
1058 for(size_t i
{0};i
< irTotal
;++i
)
1060 if(delays
[i
][0] > MaxHrirDelay
<<HrirDelayFracBits
)
1062 ERR("Invalid delays[%zu][0]: %f (%d)\n", i
,
1063 delays
[i
][0] / float{HrirDelayFracOne
}, MaxHrirDelay
);
1068 /* Mirror the left ear responses to the right ear. */
1069 MirrorLeftHrirs({elevs
.data(), elevs
.size()}, coeffs
.data(), delays
.data());
1071 else if(channelType
== ChanType_LeftRight
)
1073 for(auto &hrir
: coeffs
)
1075 for(auto &val
: al::span
<float2
>{hrir
.data(), irSize
})
1077 val
[0] = static_cast<float>(readle
<int,24>(data
)) / 8388608.0f
;
1078 val
[1] = static_cast<float>(readle
<int,24>(data
)) / 8388608.0f
;
1081 for(auto &val
: delays
)
1083 val
[0] = readle
<uint8_t>(data
);
1084 val
[1] = readle
<uint8_t>(data
);
1086 if(!data
|| data
.eof())
1088 ERR("Failed reading %s\n", filename
);
1092 for(size_t i
{0};i
< irTotal
;++i
)
1094 if(delays
[i
][0] > MaxHrirDelay
<<HrirDelayFracBits
)
1096 ERR("Invalid delays[%zu][0]: %f (%d)\n", i
,
1097 delays
[i
][0] / float{HrirDelayFracOne
}, MaxHrirDelay
);
1100 if(delays
[i
][1] > MaxHrirDelay
<<HrirDelayFracBits
)
1102 ERR("Invalid delays[%zu][1]: %f (%d)\n", i
,
1103 delays
[i
][1] / float{HrirDelayFracOne
}, MaxHrirDelay
);
1109 return CreateHrtfStore(rate
, irSize
, {fields
.data(), fields
.size()},
1110 {elevs
.data(), elevs
.size()}, coeffs
.data(), delays
.data(), filename
);
1114 bool checkName(const std::string
&name
)
1116 auto match_name
= [&name
](const HrtfEntry
&entry
) -> bool { return name
== entry
.mDispName
; };
1117 auto &enum_names
= EnumeratedHrtfs
;
1118 return std::find_if(enum_names
.cbegin(), enum_names
.cend(), match_name
) != enum_names
.cend();
1121 void AddFileEntry(const std::string
&filename
)
1123 /* Check if this file has already been enumerated. */
1124 auto enum_iter
= std::find_if(EnumeratedHrtfs
.cbegin(), EnumeratedHrtfs
.cend(),
1125 [&filename
](const HrtfEntry
&entry
) -> bool
1126 { return entry
.mFilename
== filename
; });
1127 if(enum_iter
!= EnumeratedHrtfs
.cend())
1129 TRACE("Skipping duplicate file entry %s\n", filename
.c_str());
1133 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1134 * format update). */
1135 size_t namepos
{filename
.find_last_of('/')+1};
1136 if(!namepos
) namepos
= filename
.find_last_of('\\')+1;
1138 size_t extpos
{filename
.find_last_of('.')};
1139 if(extpos
<= namepos
) extpos
= std::string::npos
;
1141 const std::string basename
{(extpos
== std::string::npos
) ?
1142 filename
.substr(namepos
) : filename
.substr(namepos
, extpos
-namepos
)};
1143 std::string newname
{basename
};
1145 while(checkName(newname
))
1149 newname
+= std::to_string(++count
);
1151 EnumeratedHrtfs
.emplace_back(HrtfEntry
{newname
, filename
});
1152 const HrtfEntry
&entry
= EnumeratedHrtfs
.back();
1154 TRACE("Adding file entry \"%s\"\n", entry
.mFilename
.c_str());
1157 /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
1158 * for input instead of opening the given filename.
1160 void AddBuiltInEntry(const std::string
&dispname
, uint residx
)
1162 const std::string filename
{'!'+std::to_string(residx
)+'_'+dispname
};
1164 auto enum_iter
= std::find_if(EnumeratedHrtfs
.cbegin(), EnumeratedHrtfs
.cend(),
1165 [&filename
](const HrtfEntry
&entry
) -> bool
1166 { return entry
.mFilename
== filename
; });
1167 if(enum_iter
!= EnumeratedHrtfs
.cend())
1169 TRACE("Skipping duplicate file entry %s\n", filename
.c_str());
1173 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1174 * format update). */
1176 std::string newname
{dispname
};
1178 while(checkName(newname
))
1182 newname
+= std::to_string(++count
);
1184 EnumeratedHrtfs
.emplace_back(HrtfEntry
{newname
, filename
});
1185 const HrtfEntry
&entry
= EnumeratedHrtfs
.back();
1187 TRACE("Adding built-in entry \"%s\"\n", entry
.mFilename
.c_str());
1191 #define IDR_DEFAULT_HRTF_MHR 1
1193 #ifndef ALSOFT_EMBED_HRTF_DATA
1195 al::span
<const char> GetResource(int /*name*/)
1200 #include "hrtf_default.h"
1202 al::span
<const char> GetResource(int name
)
1204 if(name
== IDR_DEFAULT_HRTF_MHR
)
1205 return {reinterpret_cast<const char*>(hrtf_default
), sizeof(hrtf_default
)};
1213 al::vector
<std::string
> EnumerateHrtf(al::optional
<std::string
> pathopt
)
1215 std::lock_guard
<std::mutex
> _
{EnumeratedHrtfLock
};
1216 EnumeratedHrtfs
.clear();
1218 bool usedefaults
{true};
1221 const char *pathlist
{pathopt
->c_str()};
1222 while(pathlist
&& *pathlist
)
1224 const char *next
, *end
;
1226 while(isspace(*pathlist
) || *pathlist
== ',')
1228 if(*pathlist
== '\0')
1231 next
= strchr(pathlist
, ',');
1236 end
= pathlist
+ strlen(pathlist
);
1237 usedefaults
= false;
1240 while(end
!= pathlist
&& isspace(*(end
-1)))
1244 const std::string pname
{pathlist
, end
};
1245 for(const auto &fname
: SearchDataFiles(".mhr", pname
.c_str()))
1246 AddFileEntry(fname
);
1255 for(const auto &fname
: SearchDataFiles(".mhr", "openal/hrtf"))
1256 AddFileEntry(fname
);
1258 if(!GetResource(IDR_DEFAULT_HRTF_MHR
).empty())
1259 AddBuiltInEntry("Built-In HRTF", IDR_DEFAULT_HRTF_MHR
);
1262 al::vector
<std::string
> list
;
1263 list
.reserve(EnumeratedHrtfs
.size());
1264 for(auto &entry
: EnumeratedHrtfs
)
1265 list
.emplace_back(entry
.mDispName
);
1270 HrtfStorePtr
GetLoadedHrtf(const std::string
&name
, const uint devrate
)
1272 std::lock_guard
<std::mutex
> _
{EnumeratedHrtfLock
};
1273 auto entry_iter
= std::find_if(EnumeratedHrtfs
.cbegin(), EnumeratedHrtfs
.cend(),
1274 [&name
](const HrtfEntry
&entry
) -> bool { return entry
.mDispName
== name
; });
1275 if(entry_iter
== EnumeratedHrtfs
.cend())
1277 const std::string
&fname
= entry_iter
->mFilename
;
1279 std::lock_guard
<std::mutex
> __
{LoadedHrtfLock
};
1280 auto hrtf_lt_fname
= [](LoadedHrtf
&hrtf
, const std::string
&filename
) -> bool
1281 { return hrtf
.mFilename
< filename
; };
1282 auto handle
= std::lower_bound(LoadedHrtfs
.begin(), LoadedHrtfs
.end(), fname
, hrtf_lt_fname
);
1283 while(handle
!= LoadedHrtfs
.end() && handle
->mFilename
== fname
)
1285 HrtfStore
*hrtf
{handle
->mEntry
.get()};
1286 if(hrtf
&& hrtf
->sampleRate
== devrate
)
1289 return HrtfStorePtr
{hrtf
};
1294 std::unique_ptr
<std::istream
> stream
;
1297 if(sscanf(fname
.c_str(), "!%d%c", &residx
, &ch
) == 2 && ch
== '_')
1299 TRACE("Loading %s...\n", fname
.c_str());
1300 al::span
<const char> res
{GetResource(residx
)};
1303 ERR("Could not get resource %u, %s\n", residx
, name
.c_str());
1306 stream
= std::make_unique
<idstream
>(res
.begin(), res
.end());
1310 TRACE("Loading %s...\n", fname
.c_str());
1311 auto fstr
= std::make_unique
<al::ifstream
>(fname
.c_str(), std::ios::binary
);
1312 if(!fstr
->is_open())
1314 ERR("Could not open %s\n", fname
.c_str());
1317 stream
= std::move(fstr
);
1320 std::unique_ptr
<HrtfStore
> hrtf
;
1321 char magic
[sizeof(magicMarker03
)];
1322 stream
->read(magic
, sizeof(magic
));
1323 if(stream
->gcount() < static_cast<std::streamsize
>(sizeof(magicMarker03
)))
1324 ERR("%s data is too short (%zu bytes)\n", name
.c_str(), stream
->gcount());
1325 else if(memcmp(magic
, magicMarker03
, sizeof(magicMarker03
)) == 0)
1327 TRACE("Detected data set format v3\n");
1328 hrtf
= LoadHrtf03(*stream
, name
.c_str());
1330 else if(memcmp(magic
, magicMarker02
, sizeof(magicMarker02
)) == 0)
1332 TRACE("Detected data set format v2\n");
1333 hrtf
= LoadHrtf02(*stream
, name
.c_str());
1335 else if(memcmp(magic
, magicMarker01
, sizeof(magicMarker01
)) == 0)
1337 TRACE("Detected data set format v1\n");
1338 hrtf
= LoadHrtf01(*stream
, name
.c_str());
1340 else if(memcmp(magic
, magicMarker00
, sizeof(magicMarker00
)) == 0)
1342 TRACE("Detected data set format v0\n");
1343 hrtf
= LoadHrtf00(*stream
, name
.c_str());
1346 ERR("Invalid header in %s: \"%.8s\"\n", name
.c_str(), magic
);
1351 ERR("Failed to load %s\n", name
.c_str());
1355 if(hrtf
->sampleRate
!= devrate
)
1357 TRACE("Resampling HRTF %s (%uhz -> %uhz)\n", name
.c_str(), hrtf
->sampleRate
, devrate
);
1359 /* Calculate the last elevation's index and get the total IR count. */
1360 const size_t lastEv
{std::accumulate(hrtf
->field
, hrtf
->field
+hrtf
->fdCount
, size_t{0},
1361 [](const size_t curval
, const HrtfStore::Field
&field
) noexcept
-> size_t
1362 { return curval
+ field
.evCount
; }
1364 const size_t irCount
{size_t{hrtf
->elev
[lastEv
].irOffset
} + hrtf
->elev
[lastEv
].azCount
};
1366 /* Resample all the IRs. */
1367 std::array
<std::array
<double,HrirLength
>,2> inout
;
1369 rs
.init(hrtf
->sampleRate
, devrate
);
1370 for(size_t i
{0};i
< irCount
;++i
)
1372 HrirArray
&coeffs
= const_cast<HrirArray
&>(hrtf
->coeffs
[i
]);
1373 for(size_t j
{0};j
< 2;++j
)
1375 std::transform(coeffs
.cbegin(), coeffs
.cend(), inout
[0].begin(),
1376 [j
](const float2
&in
) noexcept
-> double { return in
[j
]; });
1377 rs
.process(HrirLength
, inout
[0].data(), HrirLength
, inout
[1].data());
1378 for(size_t k
{0};k
< HrirLength
;++k
)
1379 coeffs
[k
][j
] = static_cast<float>(inout
[1][k
]);
1384 /* Scale the delays for the new sample rate. */
1385 float max_delay
{0.0f
};
1386 auto new_delays
= al::vector
<float2
>(irCount
);
1387 const float rate_scale
{static_cast<float>(devrate
)/static_cast<float>(hrtf
->sampleRate
)};
1388 for(size_t i
{0};i
< irCount
;++i
)
1390 for(size_t j
{0};j
< 2;++j
)
1392 const float new_delay
{std::round(hrtf
->delays
[i
][j
] * rate_scale
) /
1393 float{HrirDelayFracOne
}};
1394 max_delay
= maxf(max_delay
, new_delay
);
1395 new_delays
[i
][j
] = new_delay
;
1399 /* If the new delays exceed the max, scale it down to fit (essentially
1400 * shrinking the head radius; not ideal but better than a per-delay
1403 float delay_scale
{HrirDelayFracOne
};
1404 if(max_delay
> MaxHrirDelay
)
1406 WARN("Resampled delay exceeds max (%.2f > %d)\n", max_delay
, MaxHrirDelay
);
1407 delay_scale
*= float{MaxHrirDelay
} / max_delay
;
1410 for(size_t i
{0};i
< irCount
;++i
)
1412 ubyte2
&delays
= const_cast<ubyte2
&>(hrtf
->delays
[i
]);
1413 for(size_t j
{0};j
< 2;++j
)
1414 delays
[j
] = static_cast<ubyte
>(float2int(new_delays
[i
][j
]*delay_scale
+ 0.5f
));
1417 /* Scale the IR size for the new sample rate and update the stored
1420 const float newIrSize
{std::round(static_cast<float>(hrtf
->irSize
) * rate_scale
)};
1421 hrtf
->irSize
= static_cast<uint
>(minf(HrirLength
, newIrSize
));
1422 hrtf
->sampleRate
= devrate
;
1425 TRACE("Loaded HRTF %s for sample rate %uhz, %u-sample filter\n", name
.c_str(),
1426 hrtf
->sampleRate
, hrtf
->irSize
);
1427 handle
= LoadedHrtfs
.emplace(handle
, LoadedHrtf
{fname
, std::move(hrtf
)});
1429 return HrtfStorePtr
{handle
->mEntry
.get()};
1433 void HrtfStore::add_ref()
1435 auto ref
= IncrementRef(mRef
);
1436 TRACE("HrtfStore %p increasing refcount to %u\n", decltype(std::declval
<void*>()){this}, ref
);
1439 void HrtfStore::release()
1441 auto ref
= DecrementRef(mRef
);
1442 TRACE("HrtfStore %p decreasing refcount to %u\n", decltype(std::declval
<void*>()){this}, ref
);
1445 std::lock_guard
<std::mutex
> _
{LoadedHrtfLock
};
1447 /* Go through and remove all unused HRTFs. */
1448 auto remove_unused
= [](LoadedHrtf
&hrtf
) -> bool
1450 HrtfStore
*entry
{hrtf
.mEntry
.get()};
1451 if(entry
&& ReadRef(entry
->mRef
) == 0)
1453 TRACE("Unloading unused HRTF %s\n", hrtf
.mFilename
.data());
1454 hrtf
.mEntry
= nullptr;
1459 auto iter
= std::remove_if(LoadedHrtfs
.begin(), LoadedHrtfs
.end(), remove_unused
);
1460 LoadedHrtfs
.erase(iter
, LoadedHrtfs
.end());