Scale B-Format panning coefficients only when needed
[openal-soft.git] / core / hrtf.cpp
blobd5c7573a187c8b9e6be608e35020d7f13bcb77f3
2 #include "config.h"
4 #include "hrtf.h"
6 #include <algorithm>
7 #include <array>
8 #include <cassert>
9 #include <cctype>
10 #include <cmath>
11 #include <cstdint>
12 #include <cstdio>
13 #include <cstring>
14 #include <fstream>
15 #include <iterator>
16 #include <memory>
17 #include <mutex>
18 #include <numeric>
19 #include <type_traits>
20 #include <utility>
22 #include "albit.h"
23 #include "albyte.h"
24 #include "alfstream.h"
25 #include "almalloc.h"
26 #include "alnumbers.h"
27 #include "alnumeric.h"
28 #include "aloptional.h"
29 #include "alspan.h"
30 #include "ambidefs.h"
31 #include "filters/splitter.h"
32 #include "helpers.h"
33 #include "logging.h"
34 #include "mixer/hrtfdefs.h"
35 #include "opthelpers.h"
36 #include "polyphase_resampler.h"
37 #include "vector.h"
40 namespace {
42 struct HrtfEntry {
43 std::string mDispName;
44 std::string mFilename;
46 /* GCC warns when it tries to inline this. */
47 ~HrtfEntry();
49 HrtfEntry::~HrtfEntry() = default;
51 struct LoadedHrtf {
52 std::string mFilename;
53 std::unique_ptr<HrtfStore> mEntry;
55 template<typename T, typename U>
56 LoadedHrtf(T&& name, U&& entry)
57 : mFilename{std::forward<T>(name)}, mEntry{std::forward<U>(entry)}
58 { }
59 LoadedHrtf(LoadedHrtf&&) = default;
60 /* GCC warns when it tries to inline this. */
61 ~LoadedHrtf();
63 LoadedHrtf& operator=(LoadedHrtf&&) = default;
65 LoadedHrtf::~LoadedHrtf() = default;
68 /* Data set limits must be the same as or more flexible than those defined in
69 * the makemhr utility.
71 constexpr uint MinFdCount{1};
72 constexpr uint MaxFdCount{16};
74 constexpr uint MinFdDistance{50};
75 constexpr uint MaxFdDistance{2500};
77 constexpr uint MinEvCount{5};
78 constexpr uint MaxEvCount{181};
80 constexpr uint MinAzCount{1};
81 constexpr uint MaxAzCount{255};
83 constexpr uint MaxHrirDelay{HrtfHistoryLength - 1};
85 constexpr uint HrirDelayFracBits{2};
86 constexpr uint HrirDelayFracOne{1 << HrirDelayFracBits};
87 constexpr uint HrirDelayFracHalf{HrirDelayFracOne >> 1};
89 static_assert(MaxHrirDelay*HrirDelayFracOne < 256, "MAX_HRIR_DELAY or DELAY_FRAC too large");
91 constexpr char magicMarker00[8]{'M','i','n','P','H','R','0','0'};
92 constexpr char magicMarker01[8]{'M','i','n','P','H','R','0','1'};
93 constexpr char magicMarker02[8]{'M','i','n','P','H','R','0','2'};
94 constexpr char magicMarker03[8]{'M','i','n','P','H','R','0','3'};
96 /* First value for pass-through coefficients (remaining are 0), used for omni-
97 * directional sounds. */
98 constexpr auto PassthruCoeff = static_cast<float>(1.0/al::numbers::sqrt2);
100 std::mutex LoadedHrtfLock;
101 al::vector<LoadedHrtf> LoadedHrtfs;
103 std::mutex EnumeratedHrtfLock;
104 al::vector<HrtfEntry> EnumeratedHrtfs;
107 class databuf final : public std::streambuf {
108 int_type underflow() override
109 { return traits_type::eof(); }
111 pos_type seekoff(off_type offset, std::ios_base::seekdir whence, std::ios_base::openmode mode) override
113 if((mode&std::ios_base::out) || !(mode&std::ios_base::in))
114 return traits_type::eof();
116 char_type *cur;
117 switch(whence)
119 case std::ios_base::beg:
120 if(offset < 0 || offset > egptr()-eback())
121 return traits_type::eof();
122 cur = eback() + offset;
123 break;
125 case std::ios_base::cur:
126 if((offset >= 0 && offset > egptr()-gptr()) ||
127 (offset < 0 && -offset > gptr()-eback()))
128 return traits_type::eof();
129 cur = gptr() + offset;
130 break;
132 case std::ios_base::end:
133 if(offset > 0 || -offset > egptr()-eback())
134 return traits_type::eof();
135 cur = egptr() + offset;
136 break;
138 default:
139 return traits_type::eof();
142 setg(eback(), cur, egptr());
143 return cur - eback();
146 pos_type seekpos(pos_type pos, std::ios_base::openmode mode) override
148 // Simplified version of seekoff
149 if((mode&std::ios_base::out) || !(mode&std::ios_base::in))
150 return traits_type::eof();
152 if(pos < 0 || pos > egptr()-eback())
153 return traits_type::eof();
155 setg(eback(), eback() + static_cast<size_t>(pos), egptr());
156 return pos;
159 public:
160 databuf(const char_type *start_, const char_type *end_) noexcept
162 setg(const_cast<char_type*>(start_), const_cast<char_type*>(start_),
163 const_cast<char_type*>(end_));
167 class idstream final : public std::istream {
168 databuf mStreamBuf;
170 public:
171 idstream(const char *start_, const char *end_)
172 : std::istream{nullptr}, mStreamBuf{start_, end_}
173 { init(&mStreamBuf); }
177 struct IdxBlend { uint idx; float blend; };
178 /* Calculate the elevation index given the polar elevation in radians. This
179 * will return an index between 0 and (evcount - 1).
181 IdxBlend CalcEvIndex(uint evcount, float ev)
183 ev = (al::numbers::pi_v<float>*0.5f + ev) * static_cast<float>(evcount-1) *
184 al::numbers::inv_pi_v<float>;
185 uint idx{float2uint(ev)};
187 return IdxBlend{minu(idx, evcount-1), ev-static_cast<float>(idx)};
190 /* Calculate the azimuth index given the polar azimuth in radians. This will
191 * return an index between 0 and (azcount - 1).
193 IdxBlend CalcAzIndex(uint azcount, float az)
195 az = (al::numbers::pi_v<float>*2.0f + az) * static_cast<float>(azcount) *
196 (al::numbers::inv_pi_v<float>*0.5f);
197 uint idx{float2uint(az)};
199 return IdxBlend{idx%azcount, az-static_cast<float>(idx)};
202 } // namespace
205 /* Calculates static HRIR coefficients and delays for the given polar elevation
206 * and azimuth in radians. The coefficients are normalized.
208 void HrtfStore::getCoeffs(float elevation, float azimuth, float distance, float spread,
209 HrirArray &coeffs, const al::span<uint,2> delays)
211 const float dirfact{1.0f - (al::numbers::inv_pi_v<float>/2.0f * spread)};
213 size_t ebase{0};
214 auto match_field = [&ebase,distance](const Field &field) noexcept -> bool
216 if(distance >= field.distance)
217 return true;
218 ebase += field.evCount;
219 return false;
221 auto field = std::find_if(mFields.begin(), mFields.end()-1, match_field);
223 /* Calculate the elevation indices. */
224 const auto elev0 = CalcEvIndex(field->evCount, elevation);
225 const size_t elev1_idx{minu(elev0.idx+1, field->evCount-1)};
226 const size_t ir0offset{mElev[ebase + elev0.idx].irOffset};
227 const size_t ir1offset{mElev[ebase + elev1_idx].irOffset};
229 /* Calculate azimuth indices. */
230 const auto az0 = CalcAzIndex(mElev[ebase + elev0.idx].azCount, azimuth);
231 const auto az1 = CalcAzIndex(mElev[ebase + elev1_idx].azCount, azimuth);
233 /* Calculate the HRIR indices to blend. */
234 const size_t idx[4]{
235 ir0offset + az0.idx,
236 ir0offset + ((az0.idx+1) % mElev[ebase + elev0.idx].azCount),
237 ir1offset + az1.idx,
238 ir1offset + ((az1.idx+1) % mElev[ebase + elev1_idx].azCount)
241 /* Calculate bilinear blending weights, attenuated according to the
242 * directional panning factor.
244 const float blend[4]{
245 (1.0f-elev0.blend) * (1.0f-az0.blend) * dirfact,
246 (1.0f-elev0.blend) * ( az0.blend) * dirfact,
247 ( elev0.blend) * (1.0f-az1.blend) * dirfact,
248 ( elev0.blend) * ( az1.blend) * dirfact
251 /* Calculate the blended HRIR delays. */
252 float d{mDelays[idx[0]][0]*blend[0] + mDelays[idx[1]][0]*blend[1] + mDelays[idx[2]][0]*blend[2]
253 + mDelays[idx[3]][0]*blend[3]};
254 delays[0] = fastf2u(d * float{1.0f/HrirDelayFracOne});
255 d = mDelays[idx[0]][1]*blend[0] + mDelays[idx[1]][1]*blend[1] + mDelays[idx[2]][1]*blend[2]
256 + mDelays[idx[3]][1]*blend[3];
257 delays[1] = fastf2u(d * float{1.0f/HrirDelayFracOne});
259 /* Calculate the blended HRIR coefficients. */
260 float *coeffout{al::assume_aligned<16>(coeffs[0].data())};
261 coeffout[0] = PassthruCoeff * (1.0f-dirfact);
262 coeffout[1] = PassthruCoeff * (1.0f-dirfact);
263 std::fill_n(coeffout+2, size_t{HrirLength-1}*2, 0.0f);
264 for(size_t c{0};c < 4;c++)
266 const float *srccoeffs{al::assume_aligned<16>(mCoeffs[idx[c]][0].data())};
267 const float mult{blend[c]};
268 auto blend_coeffs = [mult](const float src, const float coeff) noexcept -> float
269 { return src*mult + coeff; };
270 std::transform(srccoeffs, srccoeffs + HrirLength*2, coeffout, coeffout, blend_coeffs);
275 std::unique_ptr<DirectHrtfState> DirectHrtfState::Create(size_t num_chans)
276 { return std::unique_ptr<DirectHrtfState>{new(FamCount(num_chans)) DirectHrtfState{num_chans}}; }
278 void DirectHrtfState::build(const HrtfStore *Hrtf, const uint irSize, const bool perHrirMin,
279 const al::span<const AngularPoint> AmbiPoints, const float (*AmbiMatrix)[MaxAmbiChannels],
280 const float XOverFreq, const al::span<const float,MaxAmbiOrder+1> AmbiOrderHFGain)
282 using double2 = std::array<double,2>;
283 struct ImpulseResponse {
284 const ConstHrirSpan hrir;
285 uint ldelay, rdelay;
288 const double xover_norm{double{XOverFreq} / Hrtf->mSampleRate};
289 mChannels[0].mSplitter.init(static_cast<float>(xover_norm));
290 for(size_t i{0};i < mChannels.size();++i)
292 const size_t order{AmbiIndex::OrderFromChannel()[i]};
293 mChannels[i].mSplitter = mChannels[0].mSplitter;
294 mChannels[i].mHfScale = AmbiOrderHFGain[order];
297 uint min_delay{HrtfHistoryLength*HrirDelayFracOne}, max_delay{0};
298 al::vector<ImpulseResponse> impres; impres.reserve(AmbiPoints.size());
299 auto calc_res = [Hrtf,&max_delay,&min_delay](const AngularPoint &pt) -> ImpulseResponse
301 auto &field = Hrtf->mFields[0];
302 const auto elev0 = CalcEvIndex(field.evCount, pt.Elev.value);
303 const size_t elev1_idx{minu(elev0.idx+1, field.evCount-1)};
304 const size_t ir0offset{Hrtf->mElev[elev0.idx].irOffset};
305 const size_t ir1offset{Hrtf->mElev[elev1_idx].irOffset};
307 const auto az0 = CalcAzIndex(Hrtf->mElev[elev0.idx].azCount, pt.Azim.value);
308 const auto az1 = CalcAzIndex(Hrtf->mElev[elev1_idx].azCount, pt.Azim.value);
310 const size_t idx[4]{
311 ir0offset + az0.idx,
312 ir0offset + ((az0.idx+1) % Hrtf->mElev[elev0.idx].azCount),
313 ir1offset + az1.idx,
314 ir1offset + ((az1.idx+1) % Hrtf->mElev[elev1_idx].azCount)
317 /* The largest blend factor serves as the closest HRIR. */
318 const size_t irOffset{idx[(elev0.blend >= 0.5f)*2 + (az1.blend >= 0.5f)]};
319 ImpulseResponse res{Hrtf->mCoeffs[irOffset],
320 Hrtf->mDelays[irOffset][0], Hrtf->mDelays[irOffset][1]};
322 min_delay = minu(min_delay, minu(res.ldelay, res.rdelay));
323 max_delay = maxu(max_delay, maxu(res.ldelay, res.rdelay));
325 return res;
327 std::transform(AmbiPoints.begin(), AmbiPoints.end(), std::back_inserter(impres), calc_res);
328 auto hrir_delay_round = [](const uint d) noexcept -> uint
329 { return (d+HrirDelayFracHalf) >> HrirDelayFracBits; };
331 TRACE("Min delay: %.2f, max delay: %.2f, FIR length: %u\n",
332 min_delay/double{HrirDelayFracOne}, max_delay/double{HrirDelayFracOne}, irSize);
334 auto tmpres = al::vector<std::array<double2,HrirLength>>(mChannels.size());
335 max_delay = 0;
336 for(size_t c{0u};c < AmbiPoints.size();++c)
338 const ConstHrirSpan hrir{impres[c].hrir};
339 const uint base_delay{perHrirMin ? minu(impres[c].ldelay, impres[c].rdelay) : min_delay};
340 const uint ldelay{hrir_delay_round(impres[c].ldelay - base_delay)};
341 const uint rdelay{hrir_delay_round(impres[c].rdelay - base_delay)};
342 max_delay = maxu(max_delay, maxu(impres[c].ldelay, impres[c].rdelay) - base_delay);
344 for(size_t i{0u};i < mChannels.size();++i)
346 const double mult{AmbiMatrix[c][i]};
347 const size_t numirs{HrirLength - maxz(ldelay, rdelay)};
348 size_t lidx{ldelay}, ridx{rdelay};
349 for(size_t j{0};j < numirs;++j)
351 tmpres[i][lidx++][0] += hrir[j][0] * mult;
352 tmpres[i][ridx++][1] += hrir[j][1] * mult;
356 impres.clear();
358 for(size_t i{0u};i < mChannels.size();++i)
360 auto copy_arr = [](const double2 &in) noexcept -> float2
361 { return float2{{static_cast<float>(in[0]), static_cast<float>(in[1])}}; };
362 std::transform(tmpres[i].cbegin(), tmpres[i].cend(), mChannels[i].mCoeffs.begin(),
363 copy_arr);
365 tmpres.clear();
367 const uint max_length{minu(hrir_delay_round(max_delay) + irSize, HrirLength)};
368 TRACE("New max delay: %.2f, FIR length: %u\n", max_delay/double{HrirDelayFracOne},
369 max_length);
370 mIrSize = max_length;
374 namespace {
376 std::unique_ptr<HrtfStore> CreateHrtfStore(uint rate, uint8_t irSize,
377 const al::span<const HrtfStore::Field> fields,
378 const al::span<const HrtfStore::Elevation> elevs, const HrirArray *coeffs,
379 const ubyte2 *delays, const char *filename)
381 const size_t irCount{size_t{elevs.back().azCount} + elevs.back().irOffset};
382 size_t total{sizeof(HrtfStore)};
383 total = RoundUp(total, alignof(HrtfStore::Field)); /* Align for field infos */
384 total += sizeof(std::declval<HrtfStore&>().mFields[0])*fields.size();
385 total = RoundUp(total, alignof(HrtfStore::Elevation)); /* Align for elevation infos */
386 total += sizeof(std::declval<HrtfStore&>().mElev[0])*elevs.size();
387 total = RoundUp(total, 16); /* Align for coefficients using SIMD */
388 total += sizeof(std::declval<HrtfStore&>().mCoeffs[0])*irCount;
389 total += sizeof(std::declval<HrtfStore&>().mDelays[0])*irCount;
391 std::unique_ptr<HrtfStore> Hrtf{};
392 if(void *ptr{al_calloc(16, total)})
394 Hrtf.reset(al::construct_at(static_cast<HrtfStore*>(ptr)));
395 InitRef(Hrtf->mRef, 1u);
396 Hrtf->mSampleRate = rate;
397 Hrtf->mIrSize = irSize;
399 /* Set up pointers to storage following the main HRTF struct. */
400 char *base = reinterpret_cast<char*>(Hrtf.get());
401 size_t offset{sizeof(HrtfStore)};
403 offset = RoundUp(offset, alignof(HrtfStore::Field)); /* Align for field infos */
404 auto field_ = reinterpret_cast<HrtfStore::Field*>(base + offset);
405 offset += sizeof(field_[0])*fields.size();
407 offset = RoundUp(offset, alignof(HrtfStore::Elevation)); /* Align for elevation infos */
408 auto elev_ = reinterpret_cast<HrtfStore::Elevation*>(base + offset);
409 offset += sizeof(elev_[0])*elevs.size();
411 offset = RoundUp(offset, 16); /* Align for coefficients using SIMD */
412 auto coeffs_ = reinterpret_cast<HrirArray*>(base + offset);
413 offset += sizeof(coeffs_[0])*irCount;
415 auto delays_ = reinterpret_cast<ubyte2*>(base + offset);
416 offset += sizeof(delays_[0])*irCount;
418 if(offset != total)
419 throw std::runtime_error{"HrtfStore allocation size mismatch"};
421 /* Copy input data to storage. */
422 std::uninitialized_copy(fields.cbegin(), fields.cend(), field_);
423 std::uninitialized_copy(elevs.cbegin(), elevs.cend(), elev_);
424 std::uninitialized_copy_n(coeffs, irCount, coeffs_);
425 std::uninitialized_copy_n(delays, irCount, delays_);
427 /* Finally, assign the storage pointers. */
428 Hrtf->mFields = al::as_span(field_, fields.size());
429 Hrtf->mElev = elev_;
430 Hrtf->mCoeffs = coeffs_;
431 Hrtf->mDelays = delays_;
433 else
434 ERR("Out of memory allocating storage for %s.\n", filename);
436 return Hrtf;
439 void MirrorLeftHrirs(const al::span<const HrtfStore::Elevation> elevs, HrirArray *coeffs,
440 ubyte2 *delays)
442 for(const auto &elev : elevs)
444 const ushort evoffset{elev.irOffset};
445 const ushort azcount{elev.azCount};
446 for(size_t j{0};j < azcount;j++)
448 const size_t lidx{evoffset + j};
449 const size_t ridx{evoffset + ((azcount-j) % azcount)};
451 const size_t irSize{coeffs[ridx].size()};
452 for(size_t k{0};k < irSize;k++)
453 coeffs[ridx][k][1] = coeffs[lidx][k][0];
454 delays[ridx][1] = delays[lidx][0];
460 template<size_t num_bits, typename T>
461 constexpr std::enable_if_t<std::is_signed<T>::value && num_bits < sizeof(T)*8,
462 T> fixsign(T value) noexcept
464 constexpr auto signbit = static_cast<T>(1u << (num_bits-1));
465 return static_cast<T>((value^signbit) - signbit);
468 template<size_t num_bits, typename T>
469 constexpr std::enable_if_t<!std::is_signed<T>::value || num_bits == sizeof(T)*8,
470 T> fixsign(T value) noexcept
471 { return value; }
473 template<typename T, size_t num_bits=sizeof(T)*8>
474 inline std::enable_if_t<al::endian::native == al::endian::little,
475 T> readle(std::istream &data)
477 static_assert((num_bits&7) == 0, "num_bits must be a multiple of 8");
478 static_assert(num_bits <= sizeof(T)*8, "num_bits is too large for the type");
480 T ret{};
481 if(!data.read(reinterpret_cast<char*>(&ret), num_bits/8))
482 return static_cast<T>(EOF);
484 return fixsign<num_bits>(ret);
487 template<typename T, size_t num_bits=sizeof(T)*8>
488 inline std::enable_if_t<al::endian::native == al::endian::big,
489 T> readle(std::istream &data)
491 static_assert((num_bits&7) == 0, "num_bits must be a multiple of 8");
492 static_assert(num_bits <= sizeof(T)*8, "num_bits is too large for the type");
494 T ret{};
495 al::byte b[sizeof(T)]{};
496 if(!data.read(reinterpret_cast<char*>(b), num_bits/8))
497 return static_cast<T>(EOF);
498 std::reverse_copy(std::begin(b), std::end(b), reinterpret_cast<al::byte*>(&ret));
500 return fixsign<num_bits>(ret);
503 template<>
504 inline uint8_t readle<uint8_t,8>(std::istream &data)
505 { return static_cast<uint8_t>(data.get()); }
508 std::unique_ptr<HrtfStore> LoadHrtf00(std::istream &data, const char *filename)
510 uint rate{readle<uint32_t>(data)};
511 ushort irCount{readle<uint16_t>(data)};
512 ushort irSize{readle<uint16_t>(data)};
513 ubyte evCount{readle<uint8_t>(data)};
514 if(!data || data.eof())
516 ERR("Failed reading %s\n", filename);
517 return nullptr;
520 if(irSize < MinIrLength || irSize > HrirLength)
522 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
523 return nullptr;
525 if(evCount < MinEvCount || evCount > MaxEvCount)
527 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
528 evCount, MinEvCount, MaxEvCount);
529 return nullptr;
532 auto elevs = al::vector<HrtfStore::Elevation>(evCount);
533 for(auto &elev : elevs)
534 elev.irOffset = readle<uint16_t>(data);
535 if(!data || data.eof())
537 ERR("Failed reading %s\n", filename);
538 return nullptr;
540 for(size_t i{1};i < evCount;i++)
542 if(elevs[i].irOffset <= elevs[i-1].irOffset)
544 ERR("Invalid evOffset: evOffset[%zu]=%d (last=%d)\n", i, elevs[i].irOffset,
545 elevs[i-1].irOffset);
546 return nullptr;
549 if(irCount <= elevs.back().irOffset)
551 ERR("Invalid evOffset: evOffset[%zu]=%d (irCount=%d)\n",
552 elevs.size()-1, elevs.back().irOffset, irCount);
553 return nullptr;
556 for(size_t i{1};i < evCount;i++)
558 elevs[i-1].azCount = static_cast<ushort>(elevs[i].irOffset - elevs[i-1].irOffset);
559 if(elevs[i-1].azCount < MinAzCount || elevs[i-1].azCount > MaxAzCount)
561 ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n",
562 i-1, elevs[i-1].azCount, MinAzCount, MaxAzCount);
563 return nullptr;
566 elevs.back().azCount = static_cast<ushort>(irCount - elevs.back().irOffset);
567 if(elevs.back().azCount < MinAzCount || elevs.back().azCount > MaxAzCount)
569 ERR("Unsupported azimuth count: azCount[%zu]=%d (%d to %d)\n",
570 elevs.size()-1, elevs.back().azCount, MinAzCount, MaxAzCount);
571 return nullptr;
574 auto coeffs = al::vector<HrirArray>(irCount, HrirArray{});
575 auto delays = al::vector<ubyte2>(irCount);
576 for(auto &hrir : coeffs)
578 for(auto &val : al::span<float2>{hrir.data(), irSize})
579 val[0] = readle<int16_t>(data) / 32768.0f;
581 for(auto &val : delays)
582 val[0] = readle<uint8_t>(data);
583 if(!data || data.eof())
585 ERR("Failed reading %s\n", filename);
586 return nullptr;
588 for(size_t i{0};i < irCount;i++)
590 if(delays[i][0] > MaxHrirDelay)
592 ERR("Invalid delays[%zd]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
593 return nullptr;
595 delays[i][0] <<= HrirDelayFracBits;
598 /* Mirror the left ear responses to the right ear. */
599 MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
601 const HrtfStore::Field field[1]{{0.0f, evCount}};
602 return CreateHrtfStore(rate, static_cast<uint8_t>(irSize), field, {elevs.data(), elevs.size()},
603 coeffs.data(), delays.data(), filename);
606 std::unique_ptr<HrtfStore> LoadHrtf01(std::istream &data, const char *filename)
608 uint rate{readle<uint32_t>(data)};
609 uint8_t irSize{readle<uint8_t>(data)};
610 ubyte evCount{readle<uint8_t>(data)};
611 if(!data || data.eof())
613 ERR("Failed reading %s\n", filename);
614 return nullptr;
617 if(irSize < MinIrLength || irSize > HrirLength)
619 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
620 return nullptr;
622 if(evCount < MinEvCount || evCount > MaxEvCount)
624 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
625 evCount, MinEvCount, MaxEvCount);
626 return nullptr;
629 auto elevs = al::vector<HrtfStore::Elevation>(evCount);
630 for(auto &elev : elevs)
631 elev.azCount = readle<uint8_t>(data);
632 if(!data || data.eof())
634 ERR("Failed reading %s\n", filename);
635 return nullptr;
637 for(size_t i{0};i < evCount;++i)
639 if(elevs[i].azCount < MinAzCount || elevs[i].azCount > MaxAzCount)
641 ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n", i, elevs[i].azCount,
642 MinAzCount, MaxAzCount);
643 return nullptr;
647 elevs[0].irOffset = 0;
648 for(size_t i{1};i < evCount;i++)
649 elevs[i].irOffset = static_cast<ushort>(elevs[i-1].irOffset + elevs[i-1].azCount);
650 const ushort irCount{static_cast<ushort>(elevs.back().irOffset + elevs.back().azCount)};
652 auto coeffs = al::vector<HrirArray>(irCount, HrirArray{});
653 auto delays = al::vector<ubyte2>(irCount);
654 for(auto &hrir : coeffs)
656 for(auto &val : al::span<float2>{hrir.data(), irSize})
657 val[0] = readle<int16_t>(data) / 32768.0f;
659 for(auto &val : delays)
660 val[0] = readle<uint8_t>(data);
661 if(!data || data.eof())
663 ERR("Failed reading %s\n", filename);
664 return nullptr;
666 for(size_t i{0};i < irCount;i++)
668 if(delays[i][0] > MaxHrirDelay)
670 ERR("Invalid delays[%zd]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
671 return nullptr;
673 delays[i][0] <<= HrirDelayFracBits;
676 /* Mirror the left ear responses to the right ear. */
677 MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
679 const HrtfStore::Field field[1]{{0.0f, evCount}};
680 return CreateHrtfStore(rate, irSize, field, {elevs.data(), elevs.size()}, coeffs.data(),
681 delays.data(), filename);
684 std::unique_ptr<HrtfStore> LoadHrtf02(std::istream &data, const char *filename)
686 constexpr ubyte SampleType_S16{0};
687 constexpr ubyte SampleType_S24{1};
688 constexpr ubyte ChanType_LeftOnly{0};
689 constexpr ubyte ChanType_LeftRight{1};
691 uint rate{readle<uint32_t>(data)};
692 ubyte sampleType{readle<uint8_t>(data)};
693 ubyte channelType{readle<uint8_t>(data)};
694 uint8_t irSize{readle<uint8_t>(data)};
695 ubyte fdCount{readle<uint8_t>(data)};
696 if(!data || data.eof())
698 ERR("Failed reading %s\n", filename);
699 return nullptr;
702 if(sampleType > SampleType_S24)
704 ERR("Unsupported sample type: %d\n", sampleType);
705 return nullptr;
707 if(channelType > ChanType_LeftRight)
709 ERR("Unsupported channel type: %d\n", channelType);
710 return nullptr;
713 if(irSize < MinIrLength || irSize > HrirLength)
715 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
716 return nullptr;
718 if(fdCount < 1 || fdCount > MaxFdCount)
720 ERR("Unsupported number of field-depths: fdCount=%d (%d to %d)\n", fdCount, MinFdCount,
721 MaxFdCount);
722 return nullptr;
725 auto fields = al::vector<HrtfStore::Field>(fdCount);
726 auto elevs = al::vector<HrtfStore::Elevation>{};
727 for(size_t f{0};f < fdCount;f++)
729 const ushort distance{readle<uint16_t>(data)};
730 const ubyte evCount{readle<uint8_t>(data)};
731 if(!data || data.eof())
733 ERR("Failed reading %s\n", filename);
734 return nullptr;
737 if(distance < MinFdDistance || distance > MaxFdDistance)
739 ERR("Unsupported field distance[%zu]=%d (%d to %d millimeters)\n", f, distance,
740 MinFdDistance, MaxFdDistance);
741 return nullptr;
743 if(evCount < MinEvCount || evCount > MaxEvCount)
745 ERR("Unsupported elevation count: evCount[%zu]=%d (%d to %d)\n", f, evCount,
746 MinEvCount, MaxEvCount);
747 return nullptr;
750 fields[f].distance = distance / 1000.0f;
751 fields[f].evCount = evCount;
752 if(f > 0 && fields[f].distance <= fields[f-1].distance)
754 ERR("Field distance[%zu] is not after previous (%f > %f)\n", f, fields[f].distance,
755 fields[f-1].distance);
756 return nullptr;
759 const size_t ebase{elevs.size()};
760 elevs.resize(ebase + evCount);
761 for(auto &elev : al::span<HrtfStore::Elevation>(elevs.data()+ebase, evCount))
762 elev.azCount = readle<uint8_t>(data);
763 if(!data || data.eof())
765 ERR("Failed reading %s\n", filename);
766 return nullptr;
769 for(size_t e{0};e < evCount;e++)
771 if(elevs[ebase+e].azCount < MinAzCount || elevs[ebase+e].azCount > MaxAzCount)
773 ERR("Unsupported azimuth count: azCount[%zu][%zu]=%d (%d to %d)\n", f, e,
774 elevs[ebase+e].azCount, MinAzCount, MaxAzCount);
775 return nullptr;
780 elevs[0].irOffset = 0;
781 std::partial_sum(elevs.cbegin(), elevs.cend(), elevs.begin(),
782 [](const HrtfStore::Elevation &last, const HrtfStore::Elevation &cur)
783 -> HrtfStore::Elevation
785 return HrtfStore::Elevation{cur.azCount,
786 static_cast<ushort>(last.azCount + last.irOffset)};
788 const auto irTotal = static_cast<ushort>(elevs.back().azCount + elevs.back().irOffset);
790 auto coeffs = al::vector<HrirArray>(irTotal, HrirArray{});
791 auto delays = al::vector<ubyte2>(irTotal);
792 if(channelType == ChanType_LeftOnly)
794 if(sampleType == SampleType_S16)
796 for(auto &hrir : coeffs)
798 for(auto &val : al::span<float2>{hrir.data(), irSize})
799 val[0] = readle<int16_t>(data) / 32768.0f;
802 else if(sampleType == SampleType_S24)
804 for(auto &hrir : coeffs)
806 for(auto &val : al::span<float2>{hrir.data(), irSize})
807 val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
810 for(auto &val : delays)
811 val[0] = readle<uint8_t>(data);
812 if(!data || data.eof())
814 ERR("Failed reading %s\n", filename);
815 return nullptr;
817 for(size_t i{0};i < irTotal;++i)
819 if(delays[i][0] > MaxHrirDelay)
821 ERR("Invalid delays[%zu][0]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
822 return nullptr;
824 delays[i][0] <<= HrirDelayFracBits;
827 /* Mirror the left ear responses to the right ear. */
828 MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
830 else if(channelType == ChanType_LeftRight)
832 if(sampleType == SampleType_S16)
834 for(auto &hrir : coeffs)
836 for(auto &val : al::span<float2>{hrir.data(), irSize})
838 val[0] = readle<int16_t>(data) / 32768.0f;
839 val[1] = readle<int16_t>(data) / 32768.0f;
843 else if(sampleType == SampleType_S24)
845 for(auto &hrir : coeffs)
847 for(auto &val : al::span<float2>{hrir.data(), irSize})
849 val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
850 val[1] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
854 for(auto &val : delays)
856 val[0] = readle<uint8_t>(data);
857 val[1] = readle<uint8_t>(data);
859 if(!data || data.eof())
861 ERR("Failed reading %s\n", filename);
862 return nullptr;
865 for(size_t i{0};i < irTotal;++i)
867 if(delays[i][0] > MaxHrirDelay)
869 ERR("Invalid delays[%zu][0]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
870 return nullptr;
872 if(delays[i][1] > MaxHrirDelay)
874 ERR("Invalid delays[%zu][1]: %d (%d)\n", i, delays[i][1], MaxHrirDelay);
875 return nullptr;
877 delays[i][0] <<= HrirDelayFracBits;
878 delays[i][1] <<= HrirDelayFracBits;
882 if(fdCount > 1)
884 auto fields_ = al::vector<HrtfStore::Field>(fields.size());
885 auto elevs_ = al::vector<HrtfStore::Elevation>(elevs.size());
886 auto coeffs_ = al::vector<HrirArray>(coeffs.size());
887 auto delays_ = al::vector<ubyte2>(delays.size());
889 /* Simple reverse for the per-field elements. */
890 std::reverse_copy(fields.cbegin(), fields.cend(), fields_.begin());
892 /* Each field has a group of elevations, which each have an azimuth
893 * count. Reverse the order of the groups, keeping the relative order
894 * of per-group azimuth counts.
896 auto elevs__end = elevs_.end();
897 auto copy_azs = [&elevs,&elevs__end](const ptrdiff_t ebase, const HrtfStore::Field &field)
898 -> ptrdiff_t
900 auto elevs_src = elevs.begin()+ebase;
901 elevs__end = std::copy_backward(elevs_src, elevs_src+field.evCount, elevs__end);
902 return ebase + field.evCount;
904 (void)std::accumulate(fields.cbegin(), fields.cend(), ptrdiff_t{0}, copy_azs);
905 assert(elevs_.begin() == elevs__end);
907 /* Reestablish the IR offset for each elevation index, given the new
908 * ordering of elevations.
910 elevs_[0].irOffset = 0;
911 std::partial_sum(elevs_.cbegin(), elevs_.cend(), elevs_.begin(),
912 [](const HrtfStore::Elevation &last, const HrtfStore::Elevation &cur)
913 -> HrtfStore::Elevation
915 return HrtfStore::Elevation{cur.azCount,
916 static_cast<ushort>(last.azCount + last.irOffset)};
919 /* Reverse the order of each field's group of IRs. */
920 auto coeffs_end = coeffs_.end();
921 auto delays_end = delays_.end();
922 auto copy_irs = [&elevs,&coeffs,&delays,&coeffs_end,&delays_end](
923 const ptrdiff_t ebase, const HrtfStore::Field &field) -> ptrdiff_t
925 auto accum_az = [](int count, const HrtfStore::Elevation &elev) noexcept -> int
926 { return count + elev.azCount; };
927 const auto elevs_mid = elevs.cbegin() + ebase;
928 const auto elevs_end = elevs_mid + field.evCount;
929 const int abase{std::accumulate(elevs.cbegin(), elevs_mid, 0, accum_az)};
930 const int num_azs{std::accumulate(elevs_mid, elevs_end, 0, accum_az)};
932 coeffs_end = std::copy_backward(coeffs.cbegin() + abase,
933 coeffs.cbegin() + (abase+num_azs), coeffs_end);
934 delays_end = std::copy_backward(delays.cbegin() + abase,
935 delays.cbegin() + (abase+num_azs), delays_end);
937 return ebase + field.evCount;
939 (void)std::accumulate(fields.cbegin(), fields.cend(), ptrdiff_t{0}, copy_irs);
940 assert(coeffs_.begin() == coeffs_end);
941 assert(delays_.begin() == delays_end);
943 fields = std::move(fields_);
944 elevs = std::move(elevs_);
945 coeffs = std::move(coeffs_);
946 delays = std::move(delays_);
949 return CreateHrtfStore(rate, irSize, {fields.data(), fields.size()},
950 {elevs.data(), elevs.size()}, coeffs.data(), delays.data(), filename);
953 std::unique_ptr<HrtfStore> LoadHrtf03(std::istream &data, const char *filename)
955 constexpr ubyte ChanType_LeftOnly{0};
956 constexpr ubyte ChanType_LeftRight{1};
958 uint rate{readle<uint32_t>(data)};
959 ubyte channelType{readle<uint8_t>(data)};
960 uint8_t irSize{readle<uint8_t>(data)};
961 ubyte fdCount{readle<uint8_t>(data)};
962 if(!data || data.eof())
964 ERR("Failed reading %s\n", filename);
965 return nullptr;
968 if(channelType > ChanType_LeftRight)
970 ERR("Unsupported channel type: %d\n", channelType);
971 return nullptr;
974 if(irSize < MinIrLength || irSize > HrirLength)
976 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
977 return nullptr;
979 if(fdCount < 1 || fdCount > MaxFdCount)
981 ERR("Unsupported number of field-depths: fdCount=%d (%d to %d)\n", fdCount, MinFdCount,
982 MaxFdCount);
983 return nullptr;
986 auto fields = al::vector<HrtfStore::Field>(fdCount);
987 auto elevs = al::vector<HrtfStore::Elevation>{};
988 for(size_t f{0};f < fdCount;f++)
990 const ushort distance{readle<uint16_t>(data)};
991 const ubyte evCount{readle<uint8_t>(data)};
992 if(!data || data.eof())
994 ERR("Failed reading %s\n", filename);
995 return nullptr;
998 if(distance < MinFdDistance || distance > MaxFdDistance)
1000 ERR("Unsupported field distance[%zu]=%d (%d to %d millimeters)\n", f, distance,
1001 MinFdDistance, MaxFdDistance);
1002 return nullptr;
1004 if(evCount < MinEvCount || evCount > MaxEvCount)
1006 ERR("Unsupported elevation count: evCount[%zu]=%d (%d to %d)\n", f, evCount,
1007 MinEvCount, MaxEvCount);
1008 return nullptr;
1011 fields[f].distance = distance / 1000.0f;
1012 fields[f].evCount = evCount;
1013 if(f > 0 && fields[f].distance > fields[f-1].distance)
1015 ERR("Field distance[%zu] is not before previous (%f <= %f)\n", f, fields[f].distance,
1016 fields[f-1].distance);
1017 return nullptr;
1020 const size_t ebase{elevs.size()};
1021 elevs.resize(ebase + evCount);
1022 for(auto &elev : al::span<HrtfStore::Elevation>(elevs.data()+ebase, evCount))
1023 elev.azCount = readle<uint8_t>(data);
1024 if(!data || data.eof())
1026 ERR("Failed reading %s\n", filename);
1027 return nullptr;
1030 for(size_t e{0};e < evCount;e++)
1032 if(elevs[ebase+e].azCount < MinAzCount || elevs[ebase+e].azCount > MaxAzCount)
1034 ERR("Unsupported azimuth count: azCount[%zu][%zu]=%d (%d to %d)\n", f, e,
1035 elevs[ebase+e].azCount, MinAzCount, MaxAzCount);
1036 return nullptr;
1041 elevs[0].irOffset = 0;
1042 std::partial_sum(elevs.cbegin(), elevs.cend(), elevs.begin(),
1043 [](const HrtfStore::Elevation &last, const HrtfStore::Elevation &cur)
1044 -> HrtfStore::Elevation
1046 return HrtfStore::Elevation{cur.azCount,
1047 static_cast<ushort>(last.azCount + last.irOffset)};
1049 const auto irTotal = static_cast<ushort>(elevs.back().azCount + elevs.back().irOffset);
1051 auto coeffs = al::vector<HrirArray>(irTotal, HrirArray{});
1052 auto delays = al::vector<ubyte2>(irTotal);
1053 if(channelType == ChanType_LeftOnly)
1055 for(auto &hrir : coeffs)
1057 for(auto &val : al::span<float2>{hrir.data(), irSize})
1058 val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
1060 for(auto &val : delays)
1061 val[0] = readle<uint8_t>(data);
1062 if(!data || data.eof())
1064 ERR("Failed reading %s\n", filename);
1065 return nullptr;
1067 for(size_t i{0};i < irTotal;++i)
1069 if(delays[i][0] > MaxHrirDelay<<HrirDelayFracBits)
1071 ERR("Invalid delays[%zu][0]: %f (%d)\n", i,
1072 delays[i][0] / float{HrirDelayFracOne}, MaxHrirDelay);
1073 return nullptr;
1077 /* Mirror the left ear responses to the right ear. */
1078 MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
1080 else if(channelType == ChanType_LeftRight)
1082 for(auto &hrir : coeffs)
1084 for(auto &val : al::span<float2>{hrir.data(), irSize})
1086 val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
1087 val[1] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
1090 for(auto &val : delays)
1092 val[0] = readle<uint8_t>(data);
1093 val[1] = readle<uint8_t>(data);
1095 if(!data || data.eof())
1097 ERR("Failed reading %s\n", filename);
1098 return nullptr;
1101 for(size_t i{0};i < irTotal;++i)
1103 if(delays[i][0] > MaxHrirDelay<<HrirDelayFracBits)
1105 ERR("Invalid delays[%zu][0]: %f (%d)\n", i,
1106 delays[i][0] / float{HrirDelayFracOne}, MaxHrirDelay);
1107 return nullptr;
1109 if(delays[i][1] > MaxHrirDelay<<HrirDelayFracBits)
1111 ERR("Invalid delays[%zu][1]: %f (%d)\n", i,
1112 delays[i][1] / float{HrirDelayFracOne}, MaxHrirDelay);
1113 return nullptr;
1118 return CreateHrtfStore(rate, irSize, {fields.data(), fields.size()},
1119 {elevs.data(), elevs.size()}, coeffs.data(), delays.data(), filename);
1123 bool checkName(const std::string &name)
1125 auto match_name = [&name](const HrtfEntry &entry) -> bool { return name == entry.mDispName; };
1126 auto &enum_names = EnumeratedHrtfs;
1127 return std::find_if(enum_names.cbegin(), enum_names.cend(), match_name) != enum_names.cend();
1130 void AddFileEntry(const std::string &filename)
1132 /* Check if this file has already been enumerated. */
1133 auto enum_iter = std::find_if(EnumeratedHrtfs.cbegin(), EnumeratedHrtfs.cend(),
1134 [&filename](const HrtfEntry &entry) -> bool
1135 { return entry.mFilename == filename; });
1136 if(enum_iter != EnumeratedHrtfs.cend())
1138 TRACE("Skipping duplicate file entry %s\n", filename.c_str());
1139 return;
1142 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1143 * format update). */
1144 size_t namepos{filename.find_last_of('/')+1};
1145 if(!namepos) namepos = filename.find_last_of('\\')+1;
1147 size_t extpos{filename.find_last_of('.')};
1148 if(extpos <= namepos) extpos = std::string::npos;
1150 const std::string basename{(extpos == std::string::npos) ?
1151 filename.substr(namepos) : filename.substr(namepos, extpos-namepos)};
1152 std::string newname{basename};
1153 int count{1};
1154 while(checkName(newname))
1156 newname = basename;
1157 newname += " #";
1158 newname += std::to_string(++count);
1160 EnumeratedHrtfs.emplace_back(HrtfEntry{newname, filename});
1161 const HrtfEntry &entry = EnumeratedHrtfs.back();
1163 TRACE("Adding file entry \"%s\"\n", entry.mFilename.c_str());
1166 /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
1167 * for input instead of opening the given filename.
1169 void AddBuiltInEntry(const std::string &dispname, uint residx)
1171 const std::string filename{'!'+std::to_string(residx)+'_'+dispname};
1173 auto enum_iter = std::find_if(EnumeratedHrtfs.cbegin(), EnumeratedHrtfs.cend(),
1174 [&filename](const HrtfEntry &entry) -> bool
1175 { return entry.mFilename == filename; });
1176 if(enum_iter != EnumeratedHrtfs.cend())
1178 TRACE("Skipping duplicate file entry %s\n", filename.c_str());
1179 return;
1182 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1183 * format update). */
1185 std::string newname{dispname};
1186 int count{1};
1187 while(checkName(newname))
1189 newname = dispname;
1190 newname += " #";
1191 newname += std::to_string(++count);
1193 EnumeratedHrtfs.emplace_back(HrtfEntry{newname, filename});
1194 const HrtfEntry &entry = EnumeratedHrtfs.back();
1196 TRACE("Adding built-in entry \"%s\"\n", entry.mFilename.c_str());
1200 #define IDR_DEFAULT_HRTF_MHR 1
1202 #ifndef ALSOFT_EMBED_HRTF_DATA
1204 al::span<const char> GetResource(int /*name*/)
1205 { return {}; }
1207 #else
1209 constexpr unsigned char hrtf_default[]{
1210 #include "default_hrtf.txt"
1213 al::span<const char> GetResource(int name)
1215 if(name == IDR_DEFAULT_HRTF_MHR)
1216 return {reinterpret_cast<const char*>(hrtf_default), sizeof(hrtf_default)};
1217 return {};
1219 #endif
1221 } // namespace
1224 al::vector<std::string> EnumerateHrtf(al::optional<std::string> pathopt)
1226 std::lock_guard<std::mutex> _{EnumeratedHrtfLock};
1227 EnumeratedHrtfs.clear();
1229 bool usedefaults{true};
1230 if(pathopt)
1232 const char *pathlist{pathopt->c_str()};
1233 while(pathlist && *pathlist)
1235 const char *next, *end;
1237 while(isspace(*pathlist) || *pathlist == ',')
1238 pathlist++;
1239 if(*pathlist == '\0')
1240 continue;
1242 next = strchr(pathlist, ',');
1243 if(next)
1244 end = next++;
1245 else
1247 end = pathlist + strlen(pathlist);
1248 usedefaults = false;
1251 while(end != pathlist && isspace(*(end-1)))
1252 --end;
1253 if(end != pathlist)
1255 const std::string pname{pathlist, end};
1256 for(const auto &fname : SearchDataFiles(".mhr", pname.c_str()))
1257 AddFileEntry(fname);
1260 pathlist = next;
1264 if(usedefaults)
1266 for(const auto &fname : SearchDataFiles(".mhr", "openal/hrtf"))
1267 AddFileEntry(fname);
1269 if(!GetResource(IDR_DEFAULT_HRTF_MHR).empty())
1270 AddBuiltInEntry("Built-In HRTF", IDR_DEFAULT_HRTF_MHR);
1273 al::vector<std::string> list;
1274 list.reserve(EnumeratedHrtfs.size());
1275 for(auto &entry : EnumeratedHrtfs)
1276 list.emplace_back(entry.mDispName);
1278 return list;
1281 HrtfStorePtr GetLoadedHrtf(const std::string &name, const uint devrate)
1283 std::lock_guard<std::mutex> _{EnumeratedHrtfLock};
1284 auto entry_iter = std::find_if(EnumeratedHrtfs.cbegin(), EnumeratedHrtfs.cend(),
1285 [&name](const HrtfEntry &entry) -> bool { return entry.mDispName == name; });
1286 if(entry_iter == EnumeratedHrtfs.cend())
1287 return nullptr;
1288 const std::string &fname = entry_iter->mFilename;
1290 std::lock_guard<std::mutex> __{LoadedHrtfLock};
1291 auto hrtf_lt_fname = [](LoadedHrtf &hrtf, const std::string &filename) -> bool
1292 { return hrtf.mFilename < filename; };
1293 auto handle = std::lower_bound(LoadedHrtfs.begin(), LoadedHrtfs.end(), fname, hrtf_lt_fname);
1294 while(handle != LoadedHrtfs.end() && handle->mFilename == fname)
1296 HrtfStore *hrtf{handle->mEntry.get()};
1297 if(hrtf && hrtf->mSampleRate == devrate)
1299 hrtf->add_ref();
1300 return HrtfStorePtr{hrtf};
1302 ++handle;
1305 std::unique_ptr<std::istream> stream;
1306 int residx{};
1307 char ch{};
1308 if(sscanf(fname.c_str(), "!%d%c", &residx, &ch) == 2 && ch == '_')
1310 TRACE("Loading %s...\n", fname.c_str());
1311 al::span<const char> res{GetResource(residx)};
1312 if(res.empty())
1314 ERR("Could not get resource %u, %s\n", residx, name.c_str());
1315 return nullptr;
1317 stream = std::make_unique<idstream>(res.begin(), res.end());
1319 else
1321 TRACE("Loading %s...\n", fname.c_str());
1322 auto fstr = std::make_unique<al::ifstream>(fname.c_str(), std::ios::binary);
1323 if(!fstr->is_open())
1325 ERR("Could not open %s\n", fname.c_str());
1326 return nullptr;
1328 stream = std::move(fstr);
1331 std::unique_ptr<HrtfStore> hrtf;
1332 char magic[sizeof(magicMarker03)];
1333 stream->read(magic, sizeof(magic));
1334 if(stream->gcount() < static_cast<std::streamsize>(sizeof(magicMarker03)))
1335 ERR("%s data is too short (%zu bytes)\n", name.c_str(), stream->gcount());
1336 else if(memcmp(magic, magicMarker03, sizeof(magicMarker03)) == 0)
1338 TRACE("Detected data set format v3\n");
1339 hrtf = LoadHrtf03(*stream, name.c_str());
1341 else if(memcmp(magic, magicMarker02, sizeof(magicMarker02)) == 0)
1343 TRACE("Detected data set format v2\n");
1344 hrtf = LoadHrtf02(*stream, name.c_str());
1346 else if(memcmp(magic, magicMarker01, sizeof(magicMarker01)) == 0)
1348 TRACE("Detected data set format v1\n");
1349 hrtf = LoadHrtf01(*stream, name.c_str());
1351 else if(memcmp(magic, magicMarker00, sizeof(magicMarker00)) == 0)
1353 TRACE("Detected data set format v0\n");
1354 hrtf = LoadHrtf00(*stream, name.c_str());
1356 else
1357 ERR("Invalid header in %s: \"%.8s\"\n", name.c_str(), magic);
1358 stream.reset();
1360 if(!hrtf)
1362 ERR("Failed to load %s\n", name.c_str());
1363 return nullptr;
1366 if(hrtf->mSampleRate != devrate)
1368 TRACE("Resampling HRTF %s (%uhz -> %uhz)\n", name.c_str(), hrtf->mSampleRate, devrate);
1370 /* Calculate the last elevation's index and get the total IR count. */
1371 const size_t lastEv{std::accumulate(hrtf->mFields.begin(), hrtf->mFields.end(), size_t{0},
1372 [](const size_t curval, const HrtfStore::Field &field) noexcept -> size_t
1373 { return curval + field.evCount; }
1374 ) - 1};
1375 const size_t irCount{size_t{hrtf->mElev[lastEv].irOffset} + hrtf->mElev[lastEv].azCount};
1377 /* Resample all the IRs. */
1378 std::array<std::array<double,HrirLength>,2> inout;
1379 PPhaseResampler rs;
1380 rs.init(hrtf->mSampleRate, devrate);
1381 for(size_t i{0};i < irCount;++i)
1383 HrirArray &coeffs = const_cast<HrirArray&>(hrtf->mCoeffs[i]);
1384 for(size_t j{0};j < 2;++j)
1386 std::transform(coeffs.cbegin(), coeffs.cend(), inout[0].begin(),
1387 [j](const float2 &in) noexcept -> double { return in[j]; });
1388 rs.process(HrirLength, inout[0].data(), HrirLength, inout[1].data());
1389 for(size_t k{0};k < HrirLength;++k)
1390 coeffs[k][j] = static_cast<float>(inout[1][k]);
1393 rs = {};
1395 /* Scale the delays for the new sample rate. */
1396 float max_delay{0.0f};
1397 auto new_delays = al::vector<float2>(irCount);
1398 const float rate_scale{static_cast<float>(devrate)/static_cast<float>(hrtf->mSampleRate)};
1399 for(size_t i{0};i < irCount;++i)
1401 for(size_t j{0};j < 2;++j)
1403 const float new_delay{std::round(hrtf->mDelays[i][j] * rate_scale) /
1404 float{HrirDelayFracOne}};
1405 max_delay = maxf(max_delay, new_delay);
1406 new_delays[i][j] = new_delay;
1410 /* If the new delays exceed the max, scale it down to fit (essentially
1411 * shrinking the head radius; not ideal but better than a per-delay
1412 * clamp).
1414 float delay_scale{HrirDelayFracOne};
1415 if(max_delay > MaxHrirDelay)
1417 WARN("Resampled delay exceeds max (%.2f > %d)\n", max_delay, MaxHrirDelay);
1418 delay_scale *= float{MaxHrirDelay} / max_delay;
1421 for(size_t i{0};i < irCount;++i)
1423 ubyte2 &delays = const_cast<ubyte2&>(hrtf->mDelays[i]);
1424 for(size_t j{0};j < 2;++j)
1425 delays[j] = static_cast<ubyte>(float2int(new_delays[i][j]*delay_scale + 0.5f));
1428 /* Scale the IR size for the new sample rate and update the stored
1429 * sample rate.
1431 const float newIrSize{std::round(static_cast<float>(hrtf->mIrSize) * rate_scale)};
1432 hrtf->mIrSize = static_cast<uint8_t>(minf(HrirLength, newIrSize));
1433 hrtf->mSampleRate = devrate;
1436 TRACE("Loaded HRTF %s for sample rate %uhz, %u-sample filter\n", name.c_str(),
1437 hrtf->mSampleRate, hrtf->mIrSize);
1438 handle = LoadedHrtfs.emplace(handle, fname, std::move(hrtf));
1440 return HrtfStorePtr{handle->mEntry.get()};
1444 void HrtfStore::add_ref()
1446 auto ref = IncrementRef(mRef);
1447 TRACE("HrtfStore %p increasing refcount to %u\n", decltype(std::declval<void*>()){this}, ref);
1450 void HrtfStore::dec_ref()
1452 auto ref = DecrementRef(mRef);
1453 TRACE("HrtfStore %p decreasing refcount to %u\n", decltype(std::declval<void*>()){this}, ref);
1454 if(ref == 0)
1456 std::lock_guard<std::mutex> _{LoadedHrtfLock};
1458 /* Go through and remove all unused HRTFs. */
1459 auto remove_unused = [](LoadedHrtf &hrtf) -> bool
1461 HrtfStore *entry{hrtf.mEntry.get()};
1462 if(entry && ReadRef(entry->mRef) == 0)
1464 TRACE("Unloading unused HRTF %s\n", hrtf.mFilename.data());
1465 hrtf.mEntry = nullptr;
1466 return true;
1468 return false;
1470 auto iter = std::remove_if(LoadedHrtfs.begin(), LoadedHrtfs.end(), remove_unused);
1471 LoadedHrtfs.erase(iter, LoadedHrtfs.end());