]> git.tdb.fi Git - ext/openal.git/blob - core/hrtf.cpp
Tweak some types to work around an MSVC compile error
[ext/openal.git] / core / hrtf.cpp
1
2 #include "config.h"
3
4 #include "hrtf.h"
5
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>
21
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"
38
39
40 namespace {
41
42 struct HrtfEntry {
43     std::string mDispName;
44     std::string mFilename;
45
46     /* GCC warns when it tries to inline this. */
47     ~HrtfEntry();
48 };
49 HrtfEntry::~HrtfEntry() = default;
50
51 struct LoadedHrtf {
52     std::string mFilename;
53     std::unique_ptr<HrtfStore> mEntry;
54
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();
62
63     LoadedHrtf& operator=(LoadedHrtf&&) = default;
64 };
65 LoadedHrtf::~LoadedHrtf() = default;
66
67
68 /* Data set limits must be the same as or more flexible than those defined in
69  * the makemhr utility.
70  */
71 constexpr uint MinFdCount{1};
72 constexpr uint MaxFdCount{16};
73
74 constexpr uint MinFdDistance{50};
75 constexpr uint MaxFdDistance{2500};
76
77 constexpr uint MinEvCount{5};
78 constexpr uint MaxEvCount{181};
79
80 constexpr uint MinAzCount{1};
81 constexpr uint MaxAzCount{255};
82
83 constexpr uint MaxHrirDelay{HrtfHistoryLength - 1};
84
85 constexpr uint HrirDelayFracBits{2};
86 constexpr uint HrirDelayFracOne{1 << HrirDelayFracBits};
87 constexpr uint HrirDelayFracHalf{HrirDelayFracOne >> 1};
88
89 static_assert(MaxHrirDelay*HrirDelayFracOne < 256, "MAX_HRIR_DELAY or DELAY_FRAC too large");
90
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'};
95
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);
99
100 std::mutex LoadedHrtfLock;
101 al::vector<LoadedHrtf> LoadedHrtfs;
102
103 std::mutex EnumeratedHrtfLock;
104 al::vector<HrtfEntry> EnumeratedHrtfs;
105
106
107 class databuf final : public std::streambuf {
108     int_type underflow() override
109     { return traits_type::eof(); }
110
111     pos_type seekoff(off_type offset, std::ios_base::seekdir whence, std::ios_base::openmode mode) override
112     {
113         if((mode&std::ios_base::out) || !(mode&std::ios_base::in))
114             return traits_type::eof();
115
116         char_type *cur;
117         switch(whence)
118         {
119             case std::ios_base::beg:
120                 if(offset < 0 || offset > egptr()-eback())
121                     return traits_type::eof();
122                 cur = eback() + offset;
123                 break;
124
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;
131
132             case std::ios_base::end:
133                 if(offset > 0 || -offset > egptr()-eback())
134                     return traits_type::eof();
135                 cur = egptr() + offset;
136                 break;
137
138             default:
139                 return traits_type::eof();
140         }
141
142         setg(eback(), cur, egptr());
143         return cur - eback();
144     }
145
146     pos_type seekpos(pos_type pos, std::ios_base::openmode mode) override
147     {
148         // Simplified version of seekoff
149         if((mode&std::ios_base::out) || !(mode&std::ios_base::in))
150             return traits_type::eof();
151
152         if(pos < 0 || pos > egptr()-eback())
153             return traits_type::eof();
154
155         setg(eback(), eback() + static_cast<size_t>(pos), egptr());
156         return pos;
157     }
158
159 public:
160     databuf(const char_type *start_, const char_type *end_) noexcept
161     {
162         setg(const_cast<char_type*>(start_), const_cast<char_type*>(start_),
163              const_cast<char_type*>(end_));
164     }
165 };
166
167 class idstream final : public std::istream {
168     databuf mStreamBuf;
169
170 public:
171     idstream(const char *start_, const char *end_)
172       : std::istream{nullptr}, mStreamBuf{start_, end_}
173     { init(&mStreamBuf); }
174 };
175
176
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).
180  */
181 IdxBlend CalcEvIndex(uint evcount, float ev)
182 {
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)};
186
187     return IdxBlend{minu(idx, evcount-1), ev-static_cast<float>(idx)};
188 }
189
190 /* Calculate the azimuth index given the polar azimuth in radians. This will
191  * return an index between 0 and (azcount - 1).
192  */
193 IdxBlend CalcAzIndex(uint azcount, float az)
194 {
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)};
198
199     return IdxBlend{idx%azcount, az-static_cast<float>(idx)};
200 }
201
202 } // namespace
203
204
205 /* Calculates static HRIR coefficients and delays for the given polar elevation
206  * and azimuth in radians. The coefficients are normalized.
207  */
208 void HrtfStore::getCoeffs(float elevation, float azimuth, float distance, float spread,
209     HrirArray &coeffs, const al::span<uint,2> delays)
210 {
211     const float dirfact{1.0f - (al::numbers::inv_pi_v<float>/2.0f * spread)};
212
213     size_t ebase{0};
214     auto match_field = [&ebase,distance](const Field &field) noexcept -> bool
215     {
216         if(distance >= field.distance)
217             return true;
218         ebase += field.evCount;
219         return false;
220     };
221     auto field = std::find_if(mFields.begin(), mFields.end()-1, match_field);
222
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};
228
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);
232
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)
239     };
240
241     /* Calculate bilinear blending weights, attenuated according to the
242      * directional panning factor.
243      */
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
249     };
250
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});
258
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++)
265     {
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);
271     }
272 }
273
274
275 std::unique_ptr<DirectHrtfState> DirectHrtfState::Create(size_t num_chans)
276 { return std::unique_ptr<DirectHrtfState>{new(FamCount(num_chans)) DirectHrtfState{num_chans}}; }
277
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)
281 {
282     using double2 = std::array<double,2>;
283     struct ImpulseResponse {
284         const ConstHrirSpan hrir;
285         uint ldelay, rdelay;
286     };
287
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)
291     {
292         const size_t order{AmbiIndex::OrderFromChannel()[i]};
293         mChannels[i].mSplitter = mChannels[0].mSplitter;
294         mChannels[i].mHfScale = AmbiOrderHFGain[order];
295     }
296
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
300     {
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};
306
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);
309
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)
315         };
316
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]};
321
322         min_delay = minu(min_delay, minu(res.ldelay, res.rdelay));
323         max_delay = maxu(max_delay, maxu(res.ldelay, res.rdelay));
324
325         return res;
326     };
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; };
330
331     TRACE("Min delay: %.2f, max delay: %.2f, FIR length: %u\n",
332         min_delay/double{HrirDelayFracOne}, max_delay/double{HrirDelayFracOne}, irSize);
333
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)
337     {
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);
343
344         for(size_t i{0u};i < mChannels.size();++i)
345         {
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)
350             {
351                 tmpres[i][lidx++][0] += hrir[j][0] * mult;
352                 tmpres[i][ridx++][1] += hrir[j][1] * mult;
353             }
354         }
355     }
356     impres.clear();
357
358     for(size_t i{0u};i < mChannels.size();++i)
359     {
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);
364     }
365     tmpres.clear();
366
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;
371 }
372
373
374 namespace {
375
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)
380 {
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;
390
391     std::unique_ptr<HrtfStore> Hrtf{};
392     if(void *ptr{al_calloc(16, total)})
393     {
394         Hrtf.reset(al::construct_at(static_cast<HrtfStore*>(ptr)));
395         InitRef(Hrtf->mRef, 1u);
396         Hrtf->mSampleRate = rate;
397         Hrtf->mIrSize = irSize;
398
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)};
402
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();
406
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();
410
411         offset = RoundUp(offset, 16); /* Align for coefficients using SIMD */
412         auto coeffs_ = reinterpret_cast<HrirArray*>(base + offset);
413         offset += sizeof(coeffs_[0])*irCount;
414
415         auto delays_ = reinterpret_cast<ubyte2*>(base + offset);
416         offset += sizeof(delays_[0])*irCount;
417
418         if(offset != total)
419             throw std::runtime_error{"HrtfStore allocation size mismatch"};
420
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_);
426
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_;
432     }
433     else
434         ERR("Out of memory allocating storage for %s.\n", filename);
435
436     return Hrtf;
437 }
438
439 void MirrorLeftHrirs(const al::span<const HrtfStore::Elevation> elevs, HrirArray *coeffs,
440     ubyte2 *delays)
441 {
442     for(const auto &elev : elevs)
443     {
444         const ushort evoffset{elev.irOffset};
445         const ushort azcount{elev.azCount};
446         for(size_t j{0};j < azcount;j++)
447         {
448             const size_t lidx{evoffset + j};
449             const size_t ridx{evoffset + ((azcount-j) % azcount)};
450
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];
455         }
456     }
457 }
458
459
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
463 {
464     constexpr auto signbit = static_cast<T>(1u << (num_bits-1));
465     return static_cast<T>((value^signbit) - signbit);
466 }
467
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; }
472
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)
476 {
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");
479
480     T ret{};
481     if(!data.read(reinterpret_cast<char*>(&ret), num_bits/8))
482         return static_cast<T>(EOF);
483
484     return fixsign<num_bits>(ret);
485 }
486
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)
490 {
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");
493
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));
499
500     return fixsign<num_bits>(ret);
501 }
502
503 template<>
504 inline uint8_t readle<uint8_t,8>(std::istream &data)
505 { return static_cast<uint8_t>(data.get()); }
506
507
508 std::unique_ptr<HrtfStore> LoadHrtf00(std::istream &data, const char *filename)
509 {
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())
515     {
516         ERR("Failed reading %s\n", filename);
517         return nullptr;
518     }
519
520     if(irSize < MinIrLength || irSize > HrirLength)
521     {
522         ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
523         return nullptr;
524     }
525     if(evCount < MinEvCount || evCount > MaxEvCount)
526     {
527         ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
528             evCount, MinEvCount, MaxEvCount);
529         return nullptr;
530     }
531
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())
536     {
537         ERR("Failed reading %s\n", filename);
538         return nullptr;
539     }
540     for(size_t i{1};i < evCount;i++)
541     {
542         if(elevs[i].irOffset <= elevs[i-1].irOffset)
543         {
544             ERR("Invalid evOffset: evOffset[%zu]=%d (last=%d)\n", i, elevs[i].irOffset,
545                 elevs[i-1].irOffset);
546             return nullptr;
547         }
548     }
549     if(irCount <= elevs.back().irOffset)
550     {
551         ERR("Invalid evOffset: evOffset[%zu]=%d (irCount=%d)\n",
552             elevs.size()-1, elevs.back().irOffset, irCount);
553         return nullptr;
554     }
555
556     for(size_t i{1};i < evCount;i++)
557     {
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)
560         {
561             ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n",
562                 i-1, elevs[i-1].azCount, MinAzCount, MaxAzCount);
563             return nullptr;
564         }
565     }
566     elevs.back().azCount = static_cast<ushort>(irCount - elevs.back().irOffset);
567     if(elevs.back().azCount < MinAzCount || elevs.back().azCount > MaxAzCount)
568     {
569         ERR("Unsupported azimuth count: azCount[%zu]=%d (%d to %d)\n",
570             elevs.size()-1, elevs.back().azCount, MinAzCount, MaxAzCount);
571         return nullptr;
572     }
573
574     auto coeffs = al::vector<HrirArray>(irCount, HrirArray{});
575     auto delays = al::vector<ubyte2>(irCount);
576     for(auto &hrir : coeffs)
577     {
578         for(auto &val : al::span<float2>{hrir.data(), irSize})
579             val[0] = readle<int16_t>(data) / 32768.0f;
580     }
581     for(auto &val : delays)
582         val[0] = readle<uint8_t>(data);
583     if(!data || data.eof())
584     {
585         ERR("Failed reading %s\n", filename);
586         return nullptr;
587     }
588     for(size_t i{0};i < irCount;i++)
589     {
590         if(delays[i][0] > MaxHrirDelay)
591         {
592             ERR("Invalid delays[%zd]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
593             return nullptr;
594         }
595         delays[i][0] <<= HrirDelayFracBits;
596     }
597
598     /* Mirror the left ear responses to the right ear. */
599     MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
600
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);
604 }
605
606 std::unique_ptr<HrtfStore> LoadHrtf01(std::istream &data, const char *filename)
607 {
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())
612     {
613         ERR("Failed reading %s\n", filename);
614         return nullptr;
615     }
616
617     if(irSize < MinIrLength || irSize > HrirLength)
618     {
619         ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
620         return nullptr;
621     }
622     if(evCount < MinEvCount || evCount > MaxEvCount)
623     {
624         ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
625             evCount, MinEvCount, MaxEvCount);
626         return nullptr;
627     }
628
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())
633     {
634         ERR("Failed reading %s\n", filename);
635         return nullptr;
636     }
637     for(size_t i{0};i < evCount;++i)
638     {
639         if(elevs[i].azCount < MinAzCount || elevs[i].azCount > MaxAzCount)
640         {
641             ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n", i, elevs[i].azCount,
642                 MinAzCount, MaxAzCount);
643             return nullptr;
644         }
645     }
646
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)};
651
652     auto coeffs = al::vector<HrirArray>(irCount, HrirArray{});
653     auto delays = al::vector<ubyte2>(irCount);
654     for(auto &hrir : coeffs)
655     {
656         for(auto &val : al::span<float2>{hrir.data(), irSize})
657             val[0] = readle<int16_t>(data) / 32768.0f;
658     }
659     for(auto &val : delays)
660         val[0] = readle<uint8_t>(data);
661     if(!data || data.eof())
662     {
663         ERR("Failed reading %s\n", filename);
664         return nullptr;
665     }
666     for(size_t i{0};i < irCount;i++)
667     {
668         if(delays[i][0] > MaxHrirDelay)
669         {
670             ERR("Invalid delays[%zd]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
671             return nullptr;
672         }
673         delays[i][0] <<= HrirDelayFracBits;
674     }
675
676     /* Mirror the left ear responses to the right ear. */
677     MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
678
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);
682 }
683
684 std::unique_ptr<HrtfStore> LoadHrtf02(std::istream &data, const char *filename)
685 {
686     constexpr ubyte SampleType_S16{0};
687     constexpr ubyte SampleType_S24{1};
688     constexpr ubyte ChanType_LeftOnly{0};
689     constexpr ubyte ChanType_LeftRight{1};
690
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())
697     {
698         ERR("Failed reading %s\n", filename);
699         return nullptr;
700     }
701
702     if(sampleType > SampleType_S24)
703     {
704         ERR("Unsupported sample type: %d\n", sampleType);
705         return nullptr;
706     }
707     if(channelType > ChanType_LeftRight)
708     {
709         ERR("Unsupported channel type: %d\n", channelType);
710         return nullptr;
711     }
712
713     if(irSize < MinIrLength || irSize > HrirLength)
714     {
715         ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
716         return nullptr;
717     }
718     if(fdCount < 1 || fdCount > MaxFdCount)
719     {
720         ERR("Unsupported number of field-depths: fdCount=%d (%d to %d)\n", fdCount, MinFdCount,
721             MaxFdCount);
722         return nullptr;
723     }
724
725     auto fields = al::vector<HrtfStore::Field>(fdCount);
726     auto elevs = al::vector<HrtfStore::Elevation>{};
727     for(size_t f{0};f < fdCount;f++)
728     {
729         const ushort distance{readle<uint16_t>(data)};
730         const ubyte evCount{readle<uint8_t>(data)};
731         if(!data || data.eof())
732         {
733             ERR("Failed reading %s\n", filename);
734             return nullptr;
735         }
736
737         if(distance < MinFdDistance || distance > MaxFdDistance)
738         {
739             ERR("Unsupported field distance[%zu]=%d (%d to %d millimeters)\n", f, distance,
740                 MinFdDistance, MaxFdDistance);
741             return nullptr;
742         }
743         if(evCount < MinEvCount || evCount > MaxEvCount)
744         {
745             ERR("Unsupported elevation count: evCount[%zu]=%d (%d to %d)\n", f, evCount,
746                 MinEvCount, MaxEvCount);
747             return nullptr;
748         }
749
750         fields[f].distance = distance / 1000.0f;
751         fields[f].evCount = evCount;
752         if(f > 0 && fields[f].distance <= fields[f-1].distance)
753         {
754             ERR("Field distance[%zu] is not after previous (%f > %f)\n", f, fields[f].distance,
755                 fields[f-1].distance);
756             return nullptr;
757         }
758
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())
764         {
765             ERR("Failed reading %s\n", filename);
766             return nullptr;
767         }
768
769         for(size_t e{0};e < evCount;e++)
770         {
771             if(elevs[ebase+e].azCount < MinAzCount || elevs[ebase+e].azCount > MaxAzCount)
772             {
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;
776             }
777         }
778     }
779
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
784         {
785             return HrtfStore::Elevation{cur.azCount,
786                 static_cast<ushort>(last.azCount + last.irOffset)};
787         });
788     const auto irTotal = static_cast<ushort>(elevs.back().azCount + elevs.back().irOffset);
789
790     auto coeffs = al::vector<HrirArray>(irTotal, HrirArray{});
791     auto delays = al::vector<ubyte2>(irTotal);
792     if(channelType == ChanType_LeftOnly)
793     {
794         if(sampleType == SampleType_S16)
795         {
796             for(auto &hrir : coeffs)
797             {
798                 for(auto &val : al::span<float2>{hrir.data(), irSize})
799                     val[0] = readle<int16_t>(data) / 32768.0f;
800             }
801         }
802         else if(sampleType == SampleType_S24)
803         {
804             for(auto &hrir : coeffs)
805             {
806                 for(auto &val : al::span<float2>{hrir.data(), irSize})
807                     val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
808             }
809         }
810         for(auto &val : delays)
811             val[0] = readle<uint8_t>(data);
812         if(!data || data.eof())
813         {
814             ERR("Failed reading %s\n", filename);
815             return nullptr;
816         }
817         for(size_t i{0};i < irTotal;++i)
818         {
819             if(delays[i][0] > MaxHrirDelay)
820             {
821                 ERR("Invalid delays[%zu][0]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
822                 return nullptr;
823             }
824             delays[i][0] <<= HrirDelayFracBits;
825         }
826
827         /* Mirror the left ear responses to the right ear. */
828         MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
829     }
830     else if(channelType == ChanType_LeftRight)
831     {
832         if(sampleType == SampleType_S16)
833         {
834             for(auto &hrir : coeffs)
835             {
836                 for(auto &val : al::span<float2>{hrir.data(), irSize})
837                 {
838                     val[0] = readle<int16_t>(data) / 32768.0f;
839                     val[1] = readle<int16_t>(data) / 32768.0f;
840                 }
841             }
842         }
843         else if(sampleType == SampleType_S24)
844         {
845             for(auto &hrir : coeffs)
846             {
847                 for(auto &val : al::span<float2>{hrir.data(), irSize})
848                 {
849                     val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
850                     val[1] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
851                 }
852             }
853         }
854         for(auto &val : delays)
855         {
856             val[0] = readle<uint8_t>(data);
857             val[1] = readle<uint8_t>(data);
858         }
859         if(!data || data.eof())
860         {
861             ERR("Failed reading %s\n", filename);
862             return nullptr;
863         }
864
865         for(size_t i{0};i < irTotal;++i)
866         {
867             if(delays[i][0] > MaxHrirDelay)
868             {
869                 ERR("Invalid delays[%zu][0]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
870                 return nullptr;
871             }
872             if(delays[i][1] > MaxHrirDelay)
873             {
874                 ERR("Invalid delays[%zu][1]: %d (%d)\n", i, delays[i][1], MaxHrirDelay);
875                 return nullptr;
876             }
877             delays[i][0] <<= HrirDelayFracBits;
878             delays[i][1] <<= HrirDelayFracBits;
879         }
880     }
881
882     if(fdCount > 1)
883     {
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());
888
889         /* Simple reverse for the per-field elements. */
890         std::reverse_copy(fields.cbegin(), fields.cend(), fields_.begin());
891
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.
895          */
896         auto elevs__end = elevs_.end();
897         auto copy_azs = [&elevs,&elevs__end](const ptrdiff_t ebase, const HrtfStore::Field &field)
898             -> ptrdiff_t
899         {
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;
903         };
904         (void)std::accumulate(fields.cbegin(), fields.cend(), ptrdiff_t{0}, copy_azs);
905         assert(elevs_.begin() == elevs__end);
906
907         /* Reestablish the IR offset for each elevation index, given the new
908          * ordering of elevations.
909          */
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
914             {
915                 return HrtfStore::Elevation{cur.azCount,
916                     static_cast<ushort>(last.azCount + last.irOffset)};
917             });
918
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
924         {
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)};
931
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);
936
937             return ebase + field.evCount;
938         };
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);
942
943         fields = std::move(fields_);
944         elevs = std::move(elevs_);
945         coeffs = std::move(coeffs_);
946         delays = std::move(delays_);
947     }
948
949     return CreateHrtfStore(rate, irSize, {fields.data(), fields.size()},
950         {elevs.data(), elevs.size()}, coeffs.data(), delays.data(), filename);
951 }
952
953 std::unique_ptr<HrtfStore> LoadHrtf03(std::istream &data, const char *filename)
954 {
955     constexpr ubyte ChanType_LeftOnly{0};
956     constexpr ubyte ChanType_LeftRight{1};
957
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())
963     {
964         ERR("Failed reading %s\n", filename);
965         return nullptr;
966     }
967
968     if(channelType > ChanType_LeftRight)
969     {
970         ERR("Unsupported channel type: %d\n", channelType);
971         return nullptr;
972     }
973
974     if(irSize < MinIrLength || irSize > HrirLength)
975     {
976         ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
977         return nullptr;
978     }
979     if(fdCount < 1 || fdCount > MaxFdCount)
980     {
981         ERR("Unsupported number of field-depths: fdCount=%d (%d to %d)\n", fdCount, MinFdCount,
982             MaxFdCount);
983         return nullptr;
984     }
985
986     auto fields = al::vector<HrtfStore::Field>(fdCount);
987     auto elevs = al::vector<HrtfStore::Elevation>{};
988     for(size_t f{0};f < fdCount;f++)
989     {
990         const ushort distance{readle<uint16_t>(data)};
991         const ubyte evCount{readle<uint8_t>(data)};
992         if(!data || data.eof())
993         {
994             ERR("Failed reading %s\n", filename);
995             return nullptr;
996         }
997
998         if(distance < MinFdDistance || distance > MaxFdDistance)
999         {
1000             ERR("Unsupported field distance[%zu]=%d (%d to %d millimeters)\n", f, distance,
1001                 MinFdDistance, MaxFdDistance);
1002             return nullptr;
1003         }
1004         if(evCount < MinEvCount || evCount > MaxEvCount)
1005         {
1006             ERR("Unsupported elevation count: evCount[%zu]=%d (%d to %d)\n", f, evCount,
1007                 MinEvCount, MaxEvCount);
1008             return nullptr;
1009         }
1010
1011         fields[f].distance = distance / 1000.0f;
1012         fields[f].evCount = evCount;
1013         if(f > 0 && fields[f].distance > fields[f-1].distance)
1014         {
1015             ERR("Field distance[%zu] is not before previous (%f <= %f)\n", f, fields[f].distance,
1016                 fields[f-1].distance);
1017             return nullptr;
1018         }
1019
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())
1025         {
1026             ERR("Failed reading %s\n", filename);
1027             return nullptr;
1028         }
1029
1030         for(size_t e{0};e < evCount;e++)
1031         {
1032             if(elevs[ebase+e].azCount < MinAzCount || elevs[ebase+e].azCount > MaxAzCount)
1033             {
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;
1037             }
1038         }
1039     }
1040
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
1045         {
1046             return HrtfStore::Elevation{cur.azCount,
1047                 static_cast<ushort>(last.azCount + last.irOffset)};
1048         });
1049     const auto irTotal = static_cast<ushort>(elevs.back().azCount + elevs.back().irOffset);
1050
1051     auto coeffs = al::vector<HrirArray>(irTotal, HrirArray{});
1052     auto delays = al::vector<ubyte2>(irTotal);
1053     if(channelType == ChanType_LeftOnly)
1054     {
1055         for(auto &hrir : coeffs)
1056         {
1057             for(auto &val : al::span<float2>{hrir.data(), irSize})
1058                 val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
1059         }
1060         for(auto &val : delays)
1061             val[0] = readle<uint8_t>(data);
1062         if(!data || data.eof())
1063         {
1064             ERR("Failed reading %s\n", filename);
1065             return nullptr;
1066         }
1067         for(size_t i{0};i < irTotal;++i)
1068         {
1069             if(delays[i][0] > MaxHrirDelay<<HrirDelayFracBits)
1070             {
1071                 ERR("Invalid delays[%zu][0]: %f (%d)\n", i,
1072                     delays[i][0] / float{HrirDelayFracOne}, MaxHrirDelay);
1073                 return nullptr;
1074             }
1075         }
1076
1077         /* Mirror the left ear responses to the right ear. */
1078         MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
1079     }
1080     else if(channelType == ChanType_LeftRight)
1081     {
1082         for(auto &hrir : coeffs)
1083         {
1084             for(auto &val : al::span<float2>{hrir.data(), irSize})
1085             {
1086                 val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
1087                 val[1] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
1088             }
1089         }
1090         for(auto &val : delays)
1091         {
1092             val[0] = readle<uint8_t>(data);
1093             val[1] = readle<uint8_t>(data);
1094         }
1095         if(!data || data.eof())
1096         {
1097             ERR("Failed reading %s\n", filename);
1098             return nullptr;
1099         }
1100
1101         for(size_t i{0};i < irTotal;++i)
1102         {
1103             if(delays[i][0] > MaxHrirDelay<<HrirDelayFracBits)
1104             {
1105                 ERR("Invalid delays[%zu][0]: %f (%d)\n", i,
1106                     delays[i][0] / float{HrirDelayFracOne}, MaxHrirDelay);
1107                 return nullptr;
1108             }
1109             if(delays[i][1] > MaxHrirDelay<<HrirDelayFracBits)
1110             {
1111                 ERR("Invalid delays[%zu][1]: %f (%d)\n", i,
1112                     delays[i][1] / float{HrirDelayFracOne}, MaxHrirDelay);
1113                 return nullptr;
1114             }
1115         }
1116     }
1117
1118     return CreateHrtfStore(rate, irSize, {fields.data(), fields.size()},
1119         {elevs.data(), elevs.size()}, coeffs.data(), delays.data(), filename);
1120 }
1121
1122
1123 bool checkName(const std::string &name)
1124 {
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();
1128 }
1129
1130 void AddFileEntry(const std::string &filename)
1131 {
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())
1137     {
1138         TRACE("Skipping duplicate file entry %s\n", filename.c_str());
1139         return;
1140     }
1141
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;
1146
1147     size_t extpos{filename.find_last_of('.')};
1148     if(extpos <= namepos) extpos = std::string::npos;
1149
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))
1155     {
1156         newname = basename;
1157         newname += " #";
1158         newname += std::to_string(++count);
1159     }
1160     EnumeratedHrtfs.emplace_back(HrtfEntry{newname, filename});
1161     const HrtfEntry &entry = EnumeratedHrtfs.back();
1162
1163     TRACE("Adding file entry \"%s\"\n", entry.mFilename.c_str());
1164 }
1165
1166 /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
1167  * for input instead of opening the given filename.
1168  */
1169 void AddBuiltInEntry(const std::string &dispname, uint residx)
1170 {
1171     const std::string filename{'!'+std::to_string(residx)+'_'+dispname};
1172
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())
1177     {
1178         TRACE("Skipping duplicate file entry %s\n", filename.c_str());
1179         return;
1180     }
1181
1182     /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1183      * format update). */
1184
1185     std::string newname{dispname};
1186     int count{1};
1187     while(checkName(newname))
1188     {
1189         newname = dispname;
1190         newname += " #";
1191         newname += std::to_string(++count);
1192     }
1193     EnumeratedHrtfs.emplace_back(HrtfEntry{newname, filename});
1194     const HrtfEntry &entry = EnumeratedHrtfs.back();
1195
1196     TRACE("Adding built-in entry \"%s\"\n", entry.mFilename.c_str());
1197 }
1198
1199
1200 #define IDR_DEFAULT_HRTF_MHR 1
1201
1202 #ifndef ALSOFT_EMBED_HRTF_DATA
1203
1204 al::span<const char> GetResource(int /*name*/)
1205 { return {}; }
1206
1207 #else
1208
1209 constexpr unsigned char hrtf_default[]{
1210 #include "default_hrtf.txt"
1211 };
1212
1213 al::span<const char> GetResource(int name)
1214 {
1215     if(name == IDR_DEFAULT_HRTF_MHR)
1216         return {reinterpret_cast<const char*>(hrtf_default), sizeof(hrtf_default)};
1217     return {};
1218 }
1219 #endif
1220
1221 } // namespace
1222
1223
1224 al::vector<std::string> EnumerateHrtf(al::optional<std::string> pathopt)
1225 {
1226     std::lock_guard<std::mutex> _{EnumeratedHrtfLock};
1227     EnumeratedHrtfs.clear();
1228
1229     bool usedefaults{true};
1230     if(pathopt)
1231     {
1232         const char *pathlist{pathopt->c_str()};
1233         while(pathlist && *pathlist)
1234         {
1235             const char *next, *end;
1236
1237             while(isspace(*pathlist) || *pathlist == ',')
1238                 pathlist++;
1239             if(*pathlist == '\0')
1240                 continue;
1241
1242             next = strchr(pathlist, ',');
1243             if(next)
1244                 end = next++;
1245             else
1246             {
1247                 end = pathlist + strlen(pathlist);
1248                 usedefaults = false;
1249             }
1250
1251             while(end != pathlist && isspace(*(end-1)))
1252                 --end;
1253             if(end != pathlist)
1254             {
1255                 const std::string pname{pathlist, end};
1256                 for(const auto &fname : SearchDataFiles(".mhr", pname.c_str()))
1257                     AddFileEntry(fname);
1258             }
1259
1260             pathlist = next;
1261         }
1262     }
1263
1264     if(usedefaults)
1265     {
1266         for(const auto &fname : SearchDataFiles(".mhr", "openal/hrtf"))
1267             AddFileEntry(fname);
1268
1269         if(!GetResource(IDR_DEFAULT_HRTF_MHR).empty())
1270             AddBuiltInEntry("Built-In HRTF", IDR_DEFAULT_HRTF_MHR);
1271     }
1272
1273     al::vector<std::string> list;
1274     list.reserve(EnumeratedHrtfs.size());
1275     for(auto &entry : EnumeratedHrtfs)
1276         list.emplace_back(entry.mDispName);
1277
1278     return list;
1279 }
1280
1281 HrtfStorePtr GetLoadedHrtf(const std::string &name, const uint devrate)
1282 {
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;
1289
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)
1295     {
1296         HrtfStore *hrtf{handle->mEntry.get()};
1297         if(hrtf && hrtf->mSampleRate == devrate)
1298         {
1299             hrtf->add_ref();
1300             return HrtfStorePtr{hrtf};
1301         }
1302         ++handle;
1303     }
1304
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 == '_')
1309     {
1310         TRACE("Loading %s...\n", fname.c_str());
1311         al::span<const char> res{GetResource(residx)};
1312         if(res.empty())
1313         {
1314             ERR("Could not get resource %u, %s\n", residx, name.c_str());
1315             return nullptr;
1316         }
1317         stream = std::make_unique<idstream>(res.begin(), res.end());
1318     }
1319     else
1320     {
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())
1324         {
1325             ERR("Could not open %s\n", fname.c_str());
1326             return nullptr;
1327         }
1328         stream = std::move(fstr);
1329     }
1330
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)
1337     {
1338         TRACE("Detected data set format v3\n");
1339         hrtf = LoadHrtf03(*stream, name.c_str());
1340     }
1341     else if(memcmp(magic, magicMarker02, sizeof(magicMarker02)) == 0)
1342     {
1343         TRACE("Detected data set format v2\n");
1344         hrtf = LoadHrtf02(*stream, name.c_str());
1345     }
1346     else if(memcmp(magic, magicMarker01, sizeof(magicMarker01)) == 0)
1347     {
1348         TRACE("Detected data set format v1\n");
1349         hrtf = LoadHrtf01(*stream, name.c_str());
1350     }
1351     else if(memcmp(magic, magicMarker00, sizeof(magicMarker00)) == 0)
1352     {
1353         TRACE("Detected data set format v0\n");
1354         hrtf = LoadHrtf00(*stream, name.c_str());
1355     }
1356     else
1357         ERR("Invalid header in %s: \"%.8s\"\n", name.c_str(), magic);
1358     stream.reset();
1359
1360     if(!hrtf)
1361     {
1362         ERR("Failed to load %s\n", name.c_str());
1363         return nullptr;
1364     }
1365
1366     if(hrtf->mSampleRate != devrate)
1367     {
1368         TRACE("Resampling HRTF %s (%uhz -> %uhz)\n", name.c_str(), hrtf->mSampleRate, devrate);
1369
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};
1376
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)
1382         {
1383             HrirArray &coeffs = const_cast<HrirArray&>(hrtf->mCoeffs[i]);
1384             for(size_t j{0};j < 2;++j)
1385             {
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]);
1391             }
1392         }
1393         rs = {};
1394
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)
1400         {
1401             for(size_t j{0};j < 2;++j)
1402             {
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;
1407             }
1408         }
1409
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).
1413          */
1414         float delay_scale{HrirDelayFracOne};
1415         if(max_delay > MaxHrirDelay)
1416         {
1417             WARN("Resampled delay exceeds max (%.2f > %d)\n", max_delay, MaxHrirDelay);
1418             delay_scale *= float{MaxHrirDelay} / max_delay;
1419         }
1420
1421         for(size_t i{0};i < irCount;++i)
1422         {
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));
1426         }
1427
1428         /* Scale the IR size for the new sample rate and update the stored
1429          * sample rate.
1430          */
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;
1434     }
1435
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));
1439
1440     return HrtfStorePtr{handle->mEntry.get()};
1441 }
1442
1443
1444 void HrtfStore::add_ref()
1445 {
1446     auto ref = IncrementRef(mRef);
1447     TRACE("HrtfStore %p increasing refcount to %u\n", decltype(std::declval<void*>()){this}, ref);
1448 }
1449
1450 void HrtfStore::dec_ref()
1451 {
1452     auto ref = DecrementRef(mRef);
1453     TRACE("HrtfStore %p decreasing refcount to %u\n", decltype(std::declval<void*>()){this}, ref);
1454     if(ref == 0)
1455     {
1456         std::lock_guard<std::mutex> _{LoadedHrtfLock};
1457
1458         /* Go through and remove all unused HRTFs. */
1459         auto remove_unused = [](LoadedHrtf &hrtf) -> bool
1460         {
1461             HrtfStore *entry{hrtf.mEntry.get()};
1462             if(entry && ReadRef(entry->mRef) == 0)
1463             {
1464                 TRACE("Unloading unused HRTF %s\n", hrtf.mFilename.data());
1465                 hrtf.mEntry = nullptr;
1466                 return true;
1467             }
1468             return false;
1469         };
1470         auto iter = std::remove_if(LoadedHrtfs.begin(), LoadedHrtfs.end(), remove_unused);
1471         LoadedHrtfs.erase(iter, LoadedHrtfs.end());
1472     }
1473 }