Make a couple more operator bools explicit
[openal-soft.git] / core / hrtf.cpp
blobe8d3310a94d39800e3d414172d1fdb3a97b63a8c
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;
47 struct LoadedHrtf {
48 std::string mFilename;
49 std::unique_ptr<HrtfStore> mEntry;
52 /* Data set limits must be the same as or more flexible than those defined in
53 * the makemhr utility.
55 constexpr uint MinFdCount{1};
56 constexpr uint MaxFdCount{16};
58 constexpr uint MinFdDistance{50};
59 constexpr uint MaxFdDistance{2500};
61 constexpr uint MinEvCount{5};
62 constexpr uint MaxEvCount{181};
64 constexpr uint MinAzCount{1};
65 constexpr uint MaxAzCount{255};
67 constexpr uint MaxHrirDelay{HrtfHistoryLength - 1};
69 constexpr uint HrirDelayFracBits{2};
70 constexpr uint HrirDelayFracOne{1 << HrirDelayFracBits};
71 constexpr uint HrirDelayFracHalf{HrirDelayFracOne >> 1};
73 static_assert(MaxHrirDelay*HrirDelayFracOne < 256, "MAX_HRIR_DELAY or DELAY_FRAC too large");
75 constexpr char magicMarker00[8]{'M','i','n','P','H','R','0','0'};
76 constexpr char magicMarker01[8]{'M','i','n','P','H','R','0','1'};
77 constexpr char magicMarker02[8]{'M','i','n','P','H','R','0','2'};
78 constexpr char magicMarker03[8]{'M','i','n','P','H','R','0','3'};
80 /* First value for pass-through coefficients (remaining are 0), used for omni-
81 * directional sounds. */
82 constexpr auto PassthruCoeff = static_cast<float>(1.0/al::numbers::sqrt2);
84 std::mutex LoadedHrtfLock;
85 al::vector<LoadedHrtf> LoadedHrtfs;
87 std::mutex EnumeratedHrtfLock;
88 al::vector<HrtfEntry> EnumeratedHrtfs;
91 class databuf final : public std::streambuf {
92 int_type underflow() override
93 { return traits_type::eof(); }
95 pos_type seekoff(off_type offset, std::ios_base::seekdir whence, std::ios_base::openmode mode) override
97 if((mode&std::ios_base::out) || !(mode&std::ios_base::in))
98 return traits_type::eof();
100 char_type *cur;
101 switch(whence)
103 case std::ios_base::beg:
104 if(offset < 0 || offset > egptr()-eback())
105 return traits_type::eof();
106 cur = eback() + offset;
107 break;
109 case std::ios_base::cur:
110 if((offset >= 0 && offset > egptr()-gptr()) ||
111 (offset < 0 && -offset > gptr()-eback()))
112 return traits_type::eof();
113 cur = gptr() + offset;
114 break;
116 case std::ios_base::end:
117 if(offset > 0 || -offset > egptr()-eback())
118 return traits_type::eof();
119 cur = egptr() + offset;
120 break;
122 default:
123 return traits_type::eof();
126 setg(eback(), cur, egptr());
127 return cur - eback();
130 pos_type seekpos(pos_type pos, std::ios_base::openmode mode) override
132 // Simplified version of seekoff
133 if((mode&std::ios_base::out) || !(mode&std::ios_base::in))
134 return traits_type::eof();
136 if(pos < 0 || pos > egptr()-eback())
137 return traits_type::eof();
139 setg(eback(), eback() + static_cast<size_t>(pos), egptr());
140 return pos;
143 public:
144 databuf(const char_type *start_, const char_type *end_) noexcept
146 setg(const_cast<char_type*>(start_), const_cast<char_type*>(start_),
147 const_cast<char_type*>(end_));
151 class idstream final : public std::istream {
152 databuf mStreamBuf;
154 public:
155 idstream(const char *start_, const char *end_)
156 : std::istream{nullptr}, mStreamBuf{start_, end_}
157 { init(&mStreamBuf); }
161 struct IdxBlend { uint idx; float blend; };
162 /* Calculate the elevation index given the polar elevation in radians. This
163 * will return an index between 0 and (evcount - 1).
165 IdxBlend CalcEvIndex(uint evcount, float ev)
167 ev = (al::numbers::pi_v<float>*0.5f + ev) * static_cast<float>(evcount-1) /
168 al::numbers::pi_v<float>;
169 uint idx{float2uint(ev)};
171 return IdxBlend{minu(idx, evcount-1), ev-static_cast<float>(idx)};
174 /* Calculate the azimuth index given the polar azimuth in radians. This will
175 * return an index between 0 and (azcount - 1).
177 IdxBlend CalcAzIndex(uint azcount, float az)
179 az = (al::numbers::pi_v<float>*2.0f + az) * static_cast<float>(azcount) /
180 (al::numbers::pi_v<float>*2.0f);
181 uint idx{float2uint(az)};
183 return IdxBlend{idx%azcount, az-static_cast<float>(idx)};
186 } // namespace
189 /* Calculates static HRIR coefficients and delays for the given polar elevation
190 * and azimuth in radians. The coefficients are normalized.
192 void GetHrtfCoeffs(const HrtfStore *Hrtf, float elevation, float azimuth, float distance,
193 float spread, HrirArray &coeffs, const al::span<uint,2> delays)
195 const float dirfact{1.0f - (al::numbers::inv_pi_v<float>/2.0f * spread)};
197 const auto *field = Hrtf->field;
198 const auto *field_end = field + Hrtf->fdCount-1;
199 size_t ebase{0};
200 while(distance < field->distance && field != field_end)
202 ebase += field->evCount;
203 ++field;
206 /* Calculate the elevation indices. */
207 const auto elev0 = CalcEvIndex(field->evCount, elevation);
208 const size_t elev1_idx{minu(elev0.idx+1, field->evCount-1)};
209 const size_t ir0offset{Hrtf->elev[ebase + elev0.idx].irOffset};
210 const size_t ir1offset{Hrtf->elev[ebase + elev1_idx].irOffset};
212 /* Calculate azimuth indices. */
213 const auto az0 = CalcAzIndex(Hrtf->elev[ebase + elev0.idx].azCount, azimuth);
214 const auto az1 = CalcAzIndex(Hrtf->elev[ebase + elev1_idx].azCount, azimuth);
216 /* Calculate the HRIR indices to blend. */
217 const size_t idx[4]{
218 ir0offset + az0.idx,
219 ir0offset + ((az0.idx+1) % Hrtf->elev[ebase + elev0.idx].azCount),
220 ir1offset + az1.idx,
221 ir1offset + ((az1.idx+1) % Hrtf->elev[ebase + elev1_idx].azCount)
224 /* Calculate bilinear blending weights, attenuated according to the
225 * directional panning factor.
227 const float blend[4]{
228 (1.0f-elev0.blend) * (1.0f-az0.blend) * dirfact,
229 (1.0f-elev0.blend) * ( az0.blend) * dirfact,
230 ( elev0.blend) * (1.0f-az1.blend) * dirfact,
231 ( elev0.blend) * ( az1.blend) * dirfact
234 /* Calculate the blended HRIR delays. */
235 float d{Hrtf->delays[idx[0]][0]*blend[0] + Hrtf->delays[idx[1]][0]*blend[1] +
236 Hrtf->delays[idx[2]][0]*blend[2] + Hrtf->delays[idx[3]][0]*blend[3]};
237 delays[0] = fastf2u(d * float{1.0f/HrirDelayFracOne});
238 d = Hrtf->delays[idx[0]][1]*blend[0] + Hrtf->delays[idx[1]][1]*blend[1] +
239 Hrtf->delays[idx[2]][1]*blend[2] + Hrtf->delays[idx[3]][1]*blend[3];
240 delays[1] = fastf2u(d * float{1.0f/HrirDelayFracOne});
242 /* Calculate the blended HRIR coefficients. */
243 float *coeffout{al::assume_aligned<16>(&coeffs[0][0])};
244 coeffout[0] = PassthruCoeff * (1.0f-dirfact);
245 coeffout[1] = PassthruCoeff * (1.0f-dirfact);
246 std::fill_n(coeffout+2, size_t{HrirLength-1}*2, 0.0f);
247 for(size_t c{0};c < 4;c++)
249 const float *srccoeffs{al::assume_aligned<16>(Hrtf->coeffs[idx[c]][0].data())};
250 const float mult{blend[c]};
251 auto blend_coeffs = [mult](const float src, const float coeff) noexcept -> float
252 { return src*mult + coeff; };
253 std::transform(srccoeffs, srccoeffs + HrirLength*2, coeffout, coeffout, blend_coeffs);
258 std::unique_ptr<DirectHrtfState> DirectHrtfState::Create(size_t num_chans)
259 { return std::unique_ptr<DirectHrtfState>{new(FamCount(num_chans)) DirectHrtfState{num_chans}}; }
261 void DirectHrtfState::build(const HrtfStore *Hrtf, const uint irSize,
262 const al::span<const AngularPoint> AmbiPoints, const float (*AmbiMatrix)[MaxAmbiChannels],
263 const float XOverFreq, const al::span<const float,MaxAmbiOrder+1> AmbiOrderHFGain)
265 using double2 = std::array<double,2>;
266 struct ImpulseResponse {
267 const ConstHrirSpan hrir;
268 uint ldelay, rdelay;
271 const double xover_norm{double{XOverFreq} / Hrtf->sampleRate};
272 for(size_t i{0};i < mChannels.size();++i)
274 const size_t order{AmbiIndex::OrderFromChannel()[i]};
275 mChannels[i].mSplitter.init(static_cast<float>(xover_norm));
276 mChannels[i].mHfScale = AmbiOrderHFGain[order];
279 uint min_delay{HrtfHistoryLength*HrirDelayFracOne}, max_delay{0};
280 al::vector<ImpulseResponse> impres; impres.reserve(AmbiPoints.size());
281 auto calc_res = [Hrtf,&max_delay,&min_delay](const AngularPoint &pt) -> ImpulseResponse
283 auto &field = Hrtf->field[0];
284 const auto elev0 = CalcEvIndex(field.evCount, pt.Elev.value);
285 const size_t elev1_idx{minu(elev0.idx+1, field.evCount-1)};
286 const size_t ir0offset{Hrtf->elev[elev0.idx].irOffset};
287 const size_t ir1offset{Hrtf->elev[elev1_idx].irOffset};
289 const auto az0 = CalcAzIndex(Hrtf->elev[elev0.idx].azCount, pt.Azim.value);
290 const auto az1 = CalcAzIndex(Hrtf->elev[elev1_idx].azCount, pt.Azim.value);
292 const size_t idx[4]{
293 ir0offset + az0.idx,
294 ir0offset + ((az0.idx+1) % Hrtf->elev[elev0.idx].azCount),
295 ir1offset + az1.idx,
296 ir1offset + ((az1.idx+1) % Hrtf->elev[elev1_idx].azCount)
299 const std::array<double,4> blend{{
300 (1.0-elev0.blend) * (1.0-az0.blend),
301 (1.0-elev0.blend) * ( az0.blend),
302 ( elev0.blend) * (1.0-az1.blend),
303 ( elev0.blend) * ( az1.blend)
306 /* The largest blend factor serves as the closest HRIR. */
307 const size_t irOffset{idx[std::max_element(blend.begin(), blend.end()) - blend.begin()]};
308 ImpulseResponse res{Hrtf->coeffs[irOffset],
309 Hrtf->delays[irOffset][0], Hrtf->delays[irOffset][1]};
311 min_delay = minu(min_delay, minu(res.ldelay, res.rdelay));
312 max_delay = maxu(max_delay, maxu(res.ldelay, res.rdelay));
314 return res;
316 std::transform(AmbiPoints.begin(), AmbiPoints.end(), std::back_inserter(impres), calc_res);
317 auto hrir_delay_round = [](const uint d) noexcept -> uint
318 { return (d+HrirDelayFracHalf) >> HrirDelayFracBits; };
320 TRACE("Min delay: %.2f, max delay: %.2f, FIR length: %u\n",
321 min_delay/double{HrirDelayFracOne}, max_delay/double{HrirDelayFracOne}, irSize);
323 const bool per_hrir_min{mChannels.size() > AmbiChannelsFromOrder(1)};
324 auto tmpres = al::vector<std::array<double2,HrirLength>>(mChannels.size());
325 max_delay = 0;
326 for(size_t c{0u};c < AmbiPoints.size();++c)
328 const ConstHrirSpan hrir{impres[c].hrir};
329 const uint base_delay{per_hrir_min ? minu(impres[c].ldelay, impres[c].rdelay) : min_delay};
330 const uint ldelay{hrir_delay_round(impres[c].ldelay - base_delay)};
331 const uint rdelay{hrir_delay_round(impres[c].rdelay - base_delay)};
332 max_delay = maxu(max_delay, maxu(impres[c].ldelay, impres[c].rdelay) - base_delay);
334 for(size_t i{0u};i < mChannels.size();++i)
336 const double mult{AmbiMatrix[c][i]};
337 const size_t numirs{HrirLength - maxz(ldelay, rdelay)};
338 size_t lidx{ldelay}, ridx{rdelay};
339 for(size_t j{0};j < numirs;++j)
341 tmpres[i][lidx++][0] += hrir[j][0] * mult;
342 tmpres[i][ridx++][1] += hrir[j][1] * mult;
346 impres.clear();
348 for(size_t i{0u};i < mChannels.size();++i)
350 auto copy_arr = [](const double2 &in) noexcept -> float2
351 { return float2{{static_cast<float>(in[0]), static_cast<float>(in[1])}}; };
352 std::transform(tmpres[i].cbegin(), tmpres[i].cend(), mChannels[i].mCoeffs.begin(),
353 copy_arr);
355 tmpres.clear();
357 const uint max_length{minu(hrir_delay_round(max_delay) + irSize, HrirLength)};
358 TRACE("New max delay: %.2f, FIR length: %u\n", max_delay/double{HrirDelayFracOne},
359 max_length);
360 mIrSize = max_length;
364 namespace {
366 std::unique_ptr<HrtfStore> CreateHrtfStore(uint rate, ushort irSize,
367 const al::span<const HrtfStore::Field> fields,
368 const al::span<const HrtfStore::Elevation> elevs, const HrirArray *coeffs,
369 const ubyte2 *delays, const char *filename)
371 const size_t irCount{size_t{elevs.back().azCount} + elevs.back().irOffset};
372 size_t total{sizeof(HrtfStore)};
373 total = RoundUp(total, alignof(HrtfStore::Field)); /* Align for field infos */
374 total += sizeof(std::declval<HrtfStore&>().field[0])*fields.size();
375 total = RoundUp(total, alignof(HrtfStore::Elevation)); /* Align for elevation infos */
376 total += sizeof(std::declval<HrtfStore&>().elev[0])*elevs.size();
377 total = RoundUp(total, 16); /* Align for coefficients using SIMD */
378 total += sizeof(std::declval<HrtfStore&>().coeffs[0])*irCount;
379 total += sizeof(std::declval<HrtfStore&>().delays[0])*irCount;
381 void *ptr{al_calloc(16, total)};
382 std::unique_ptr<HrtfStore> Hrtf{al::construct_at(static_cast<HrtfStore*>(ptr))};
383 if(!Hrtf)
384 ERR("Out of memory allocating storage for %s.\n", filename);
385 else
387 InitRef(Hrtf->mRef, 1u);
388 Hrtf->sampleRate = rate;
389 Hrtf->irSize = irSize;
390 Hrtf->fdCount = static_cast<uint>(fields.size());
392 /* Set up pointers to storage following the main HRTF struct. */
393 char *base = reinterpret_cast<char*>(Hrtf.get());
394 size_t offset{sizeof(HrtfStore)};
396 offset = RoundUp(offset, alignof(HrtfStore::Field)); /* Align for field infos */
397 auto field_ = reinterpret_cast<HrtfStore::Field*>(base + offset);
398 offset += sizeof(field_[0])*fields.size();
400 offset = RoundUp(offset, alignof(HrtfStore::Elevation)); /* Align for elevation infos */
401 auto elev_ = reinterpret_cast<HrtfStore::Elevation*>(base + offset);
402 offset += sizeof(elev_[0])*elevs.size();
404 offset = RoundUp(offset, 16); /* Align for coefficients using SIMD */
405 auto coeffs_ = reinterpret_cast<HrirArray*>(base + offset);
406 offset += sizeof(coeffs_[0])*irCount;
408 auto delays_ = reinterpret_cast<ubyte2*>(base + offset);
409 offset += sizeof(delays_[0])*irCount;
411 assert(offset == total);
413 /* Copy input data to storage. */
414 std::uninitialized_copy(fields.cbegin(), fields.cend(), field_);
415 std::uninitialized_copy(elevs.cbegin(), elevs.cend(), elev_);
416 std::uninitialized_copy_n(coeffs, irCount, coeffs_);
417 std::uninitialized_copy_n(delays, irCount, delays_);
419 /* Finally, assign the storage pointers. */
420 Hrtf->field = field_;
421 Hrtf->elev = elev_;
422 Hrtf->coeffs = coeffs_;
423 Hrtf->delays = delays_;
426 return Hrtf;
429 void MirrorLeftHrirs(const al::span<const HrtfStore::Elevation> elevs, HrirArray *coeffs,
430 ubyte2 *delays)
432 for(const auto &elev : elevs)
434 const ushort evoffset{elev.irOffset};
435 const ushort azcount{elev.azCount};
436 for(size_t j{0};j < azcount;j++)
438 const size_t lidx{evoffset + j};
439 const size_t ridx{evoffset + ((azcount-j) % azcount)};
441 const size_t irSize{coeffs[ridx].size()};
442 for(size_t k{0};k < irSize;k++)
443 coeffs[ridx][k][1] = coeffs[lidx][k][0];
444 delays[ridx][1] = delays[lidx][0];
450 template<typename T, size_t num_bits=sizeof(T)*8>
451 inline T readle(std::istream &data)
453 static_assert((num_bits&7) == 0, "num_bits must be a multiple of 8");
454 static_assert(num_bits <= sizeof(T)*8, "num_bits is too large for the type");
456 T ret{};
457 if_constexpr(al::endian::native == al::endian::little)
459 if(!data.read(reinterpret_cast<char*>(&ret), num_bits/8))
460 return static_cast<T>(EOF);
462 else
464 al::byte b[sizeof(T)]{};
465 if(!data.read(reinterpret_cast<char*>(b), num_bits/8))
466 return static_cast<T>(EOF);
467 std::reverse_copy(std::begin(b), std::end(b), reinterpret_cast<al::byte*>(&ret));
470 if_constexpr(std::is_signed<T>::value && num_bits < sizeof(T)*8)
472 constexpr auto signbit = static_cast<T>(1u << (num_bits-1));
473 return static_cast<T>((ret^signbit) - signbit);
475 return ret;
478 template<>
479 inline uint8_t readle<uint8_t,8>(std::istream &data)
480 { return static_cast<uint8_t>(data.get()); }
483 std::unique_ptr<HrtfStore> LoadHrtf00(std::istream &data, const char *filename)
485 uint rate{readle<uint32_t>(data)};
486 ushort irCount{readle<uint16_t>(data)};
487 ushort irSize{readle<uint16_t>(data)};
488 ubyte evCount{readle<uint8_t>(data)};
489 if(!data || data.eof())
491 ERR("Failed reading %s\n", filename);
492 return nullptr;
495 if(irSize < MinIrLength || irSize > HrirLength)
497 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
498 return nullptr;
500 if(evCount < MinEvCount || evCount > MaxEvCount)
502 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
503 evCount, MinEvCount, MaxEvCount);
504 return nullptr;
507 auto elevs = al::vector<HrtfStore::Elevation>(evCount);
508 for(auto &elev : elevs)
509 elev.irOffset = readle<uint16_t>(data);
510 if(!data || data.eof())
512 ERR("Failed reading %s\n", filename);
513 return nullptr;
515 for(size_t i{1};i < evCount;i++)
517 if(elevs[i].irOffset <= elevs[i-1].irOffset)
519 ERR("Invalid evOffset: evOffset[%zu]=%d (last=%d)\n", i, elevs[i].irOffset,
520 elevs[i-1].irOffset);
521 return nullptr;
524 if(irCount <= elevs.back().irOffset)
526 ERR("Invalid evOffset: evOffset[%zu]=%d (irCount=%d)\n",
527 elevs.size()-1, elevs.back().irOffset, irCount);
528 return nullptr;
531 for(size_t i{1};i < evCount;i++)
533 elevs[i-1].azCount = static_cast<ushort>(elevs[i].irOffset - elevs[i-1].irOffset);
534 if(elevs[i-1].azCount < MinAzCount || elevs[i-1].azCount > MaxAzCount)
536 ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n",
537 i-1, elevs[i-1].azCount, MinAzCount, MaxAzCount);
538 return nullptr;
541 elevs.back().azCount = static_cast<ushort>(irCount - elevs.back().irOffset);
542 if(elevs.back().azCount < MinAzCount || elevs.back().azCount > MaxAzCount)
544 ERR("Unsupported azimuth count: azCount[%zu]=%d (%d to %d)\n",
545 elevs.size()-1, elevs.back().azCount, MinAzCount, MaxAzCount);
546 return nullptr;
549 auto coeffs = al::vector<HrirArray>(irCount, HrirArray{});
550 auto delays = al::vector<ubyte2>(irCount);
551 for(auto &hrir : coeffs)
553 for(auto &val : al::span<float2>{hrir.data(), irSize})
554 val[0] = readle<int16_t>(data) / 32768.0f;
556 for(auto &val : delays)
557 val[0] = readle<uint8_t>(data);
558 if(!data || data.eof())
560 ERR("Failed reading %s\n", filename);
561 return nullptr;
563 for(size_t i{0};i < irCount;i++)
565 if(delays[i][0] > MaxHrirDelay)
567 ERR("Invalid delays[%zd]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
568 return nullptr;
570 delays[i][0] <<= HrirDelayFracBits;
573 /* Mirror the left ear responses to the right ear. */
574 MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
576 const HrtfStore::Field field[1]{{0.0f, evCount}};
577 return CreateHrtfStore(rate, irSize, field, {elevs.data(), elevs.size()}, coeffs.data(),
578 delays.data(), filename);
581 std::unique_ptr<HrtfStore> LoadHrtf01(std::istream &data, const char *filename)
583 uint rate{readle<uint32_t>(data)};
584 ushort irSize{readle<uint8_t>(data)};
585 ubyte evCount{readle<uint8_t>(data)};
586 if(!data || data.eof())
588 ERR("Failed reading %s\n", filename);
589 return nullptr;
592 if(irSize < MinIrLength || irSize > HrirLength)
594 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
595 return nullptr;
597 if(evCount < MinEvCount || evCount > MaxEvCount)
599 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
600 evCount, MinEvCount, MaxEvCount);
601 return nullptr;
604 auto elevs = al::vector<HrtfStore::Elevation>(evCount);
605 for(auto &elev : elevs)
606 elev.azCount = readle<uint8_t>(data);
607 if(!data || data.eof())
609 ERR("Failed reading %s\n", filename);
610 return nullptr;
612 for(size_t i{0};i < evCount;++i)
614 if(elevs[i].azCount < MinAzCount || elevs[i].azCount > MaxAzCount)
616 ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n", i, elevs[i].azCount,
617 MinAzCount, MaxAzCount);
618 return nullptr;
622 elevs[0].irOffset = 0;
623 for(size_t i{1};i < evCount;i++)
624 elevs[i].irOffset = static_cast<ushort>(elevs[i-1].irOffset + elevs[i-1].azCount);
625 const ushort irCount{static_cast<ushort>(elevs.back().irOffset + elevs.back().azCount)};
627 auto coeffs = al::vector<HrirArray>(irCount, HrirArray{});
628 auto delays = al::vector<ubyte2>(irCount);
629 for(auto &hrir : coeffs)
631 for(auto &val : al::span<float2>{hrir.data(), irSize})
632 val[0] = readle<int16_t>(data) / 32768.0f;
634 for(auto &val : delays)
635 val[0] = readle<uint8_t>(data);
636 if(!data || data.eof())
638 ERR("Failed reading %s\n", filename);
639 return nullptr;
641 for(size_t i{0};i < irCount;i++)
643 if(delays[i][0] > MaxHrirDelay)
645 ERR("Invalid delays[%zd]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
646 return nullptr;
648 delays[i][0] <<= HrirDelayFracBits;
651 /* Mirror the left ear responses to the right ear. */
652 MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
654 const HrtfStore::Field field[1]{{0.0f, evCount}};
655 return CreateHrtfStore(rate, irSize, field, {elevs.data(), elevs.size()}, coeffs.data(),
656 delays.data(), filename);
659 std::unique_ptr<HrtfStore> LoadHrtf02(std::istream &data, const char *filename)
661 constexpr ubyte SampleType_S16{0};
662 constexpr ubyte SampleType_S24{1};
663 constexpr ubyte ChanType_LeftOnly{0};
664 constexpr ubyte ChanType_LeftRight{1};
666 uint rate{readle<uint32_t>(data)};
667 ubyte sampleType{readle<uint8_t>(data)};
668 ubyte channelType{readle<uint8_t>(data)};
669 ushort irSize{readle<uint8_t>(data)};
670 ubyte fdCount{readle<uint8_t>(data)};
671 if(!data || data.eof())
673 ERR("Failed reading %s\n", filename);
674 return nullptr;
677 if(sampleType > SampleType_S24)
679 ERR("Unsupported sample type: %d\n", sampleType);
680 return nullptr;
682 if(channelType > ChanType_LeftRight)
684 ERR("Unsupported channel type: %d\n", channelType);
685 return nullptr;
688 if(irSize < MinIrLength || irSize > HrirLength)
690 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
691 return nullptr;
693 if(fdCount < 1 || fdCount > MaxFdCount)
695 ERR("Unsupported number of field-depths: fdCount=%d (%d to %d)\n", fdCount, MinFdCount,
696 MaxFdCount);
697 return nullptr;
700 auto fields = al::vector<HrtfStore::Field>(fdCount);
701 auto elevs = al::vector<HrtfStore::Elevation>{};
702 for(size_t f{0};f < fdCount;f++)
704 const ushort distance{readle<uint16_t>(data)};
705 const ubyte evCount{readle<uint8_t>(data)};
706 if(!data || data.eof())
708 ERR("Failed reading %s\n", filename);
709 return nullptr;
712 if(distance < MinFdDistance || distance > MaxFdDistance)
714 ERR("Unsupported field distance[%zu]=%d (%d to %d millimeters)\n", f, distance,
715 MinFdDistance, MaxFdDistance);
716 return nullptr;
718 if(evCount < MinEvCount || evCount > MaxEvCount)
720 ERR("Unsupported elevation count: evCount[%zu]=%d (%d to %d)\n", f, evCount,
721 MinEvCount, MaxEvCount);
722 return nullptr;
725 fields[f].distance = distance / 1000.0f;
726 fields[f].evCount = evCount;
727 if(f > 0 && fields[f].distance <= fields[f-1].distance)
729 ERR("Field distance[%zu] is not after previous (%f > %f)\n", f, fields[f].distance,
730 fields[f-1].distance);
731 return nullptr;
734 const size_t ebase{elevs.size()};
735 elevs.resize(ebase + evCount);
736 for(auto &elev : al::span<HrtfStore::Elevation>(elevs.data()+ebase, evCount))
737 elev.azCount = readle<uint8_t>(data);
738 if(!data || data.eof())
740 ERR("Failed reading %s\n", filename);
741 return nullptr;
744 for(size_t e{0};e < evCount;e++)
746 if(elevs[ebase+e].azCount < MinAzCount || elevs[ebase+e].azCount > MaxAzCount)
748 ERR("Unsupported azimuth count: azCount[%zu][%zu]=%d (%d to %d)\n", f, e,
749 elevs[ebase+e].azCount, MinAzCount, MaxAzCount);
750 return nullptr;
755 elevs[0].irOffset = 0;
756 std::partial_sum(elevs.cbegin(), elevs.cend(), elevs.begin(),
757 [](const HrtfStore::Elevation &last, const HrtfStore::Elevation &cur)
758 -> HrtfStore::Elevation
760 return HrtfStore::Elevation{cur.azCount,
761 static_cast<ushort>(last.azCount + last.irOffset)};
763 const auto irTotal = static_cast<ushort>(elevs.back().azCount + elevs.back().irOffset);
765 auto coeffs = al::vector<HrirArray>(irTotal, HrirArray{});
766 auto delays = al::vector<ubyte2>(irTotal);
767 if(channelType == ChanType_LeftOnly)
769 if(sampleType == SampleType_S16)
771 for(auto &hrir : coeffs)
773 for(auto &val : al::span<float2>{hrir.data(), irSize})
774 val[0] = readle<int16_t>(data) / 32768.0f;
777 else if(sampleType == SampleType_S24)
779 for(auto &hrir : coeffs)
781 for(auto &val : al::span<float2>{hrir.data(), irSize})
782 val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
785 for(auto &val : delays)
786 val[0] = readle<uint8_t>(data);
787 if(!data || data.eof())
789 ERR("Failed reading %s\n", filename);
790 return nullptr;
792 for(size_t i{0};i < irTotal;++i)
794 if(delays[i][0] > MaxHrirDelay)
796 ERR("Invalid delays[%zu][0]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
797 return nullptr;
799 delays[i][0] <<= HrirDelayFracBits;
802 /* Mirror the left ear responses to the right ear. */
803 MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
805 else if(channelType == ChanType_LeftRight)
807 if(sampleType == SampleType_S16)
809 for(auto &hrir : coeffs)
811 for(auto &val : al::span<float2>{hrir.data(), irSize})
813 val[0] = readle<int16_t>(data) / 32768.0f;
814 val[1] = readle<int16_t>(data) / 32768.0f;
818 else if(sampleType == SampleType_S24)
820 for(auto &hrir : coeffs)
822 for(auto &val : al::span<float2>{hrir.data(), irSize})
824 val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
825 val[1] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
829 for(auto &val : delays)
831 val[0] = readle<uint8_t>(data);
832 val[1] = readle<uint8_t>(data);
834 if(!data || data.eof())
836 ERR("Failed reading %s\n", filename);
837 return nullptr;
840 for(size_t i{0};i < irTotal;++i)
842 if(delays[i][0] > MaxHrirDelay)
844 ERR("Invalid delays[%zu][0]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
845 return nullptr;
847 if(delays[i][1] > MaxHrirDelay)
849 ERR("Invalid delays[%zu][1]: %d (%d)\n", i, delays[i][1], MaxHrirDelay);
850 return nullptr;
852 delays[i][0] <<= HrirDelayFracBits;
853 delays[i][1] <<= HrirDelayFracBits;
857 if(fdCount > 1)
859 auto fields_ = al::vector<HrtfStore::Field>(fields.size());
860 auto elevs_ = al::vector<HrtfStore::Elevation>(elevs.size());
861 auto coeffs_ = al::vector<HrirArray>(coeffs.size());
862 auto delays_ = al::vector<ubyte2>(delays.size());
864 /* Simple reverse for the per-field elements. */
865 std::reverse_copy(fields.cbegin(), fields.cend(), fields_.begin());
867 /* Each field has a group of elevations, which each have an azimuth
868 * count. Reverse the order of the groups, keeping the relative order
869 * of per-group azimuth counts.
871 auto elevs__end = elevs_.end();
872 auto copy_azs = [&elevs,&elevs__end](const ptrdiff_t ebase, const HrtfStore::Field &field)
873 -> ptrdiff_t
875 auto elevs_src = elevs.begin()+ebase;
876 elevs__end = std::copy_backward(elevs_src, elevs_src+field.evCount, elevs__end);
877 return ebase + field.evCount;
879 (void)std::accumulate(fields.cbegin(), fields.cend(), ptrdiff_t{0}, copy_azs);
880 assert(elevs_.begin() == elevs__end);
882 /* Reestablish the IR offset for each elevation index, given the new
883 * ordering of elevations.
885 elevs_[0].irOffset = 0;
886 std::partial_sum(elevs_.cbegin(), elevs_.cend(), elevs_.begin(),
887 [](const HrtfStore::Elevation &last, const HrtfStore::Elevation &cur)
888 -> HrtfStore::Elevation
890 return HrtfStore::Elevation{cur.azCount,
891 static_cast<ushort>(last.azCount + last.irOffset)};
894 /* Reverse the order of each field's group of IRs. */
895 auto coeffs_end = coeffs_.end();
896 auto delays_end = delays_.end();
897 auto copy_irs = [&elevs,&coeffs,&delays,&coeffs_end,&delays_end](
898 const ptrdiff_t ebase, const HrtfStore::Field &field) -> ptrdiff_t
900 auto accum_az = [](int count, const HrtfStore::Elevation &elev) noexcept -> int
901 { return count + elev.azCount; };
902 const auto elevs_mid = elevs.cbegin() + ebase;
903 const auto elevs_end = elevs_mid + field.evCount;
904 const int abase{std::accumulate(elevs.cbegin(), elevs_mid, 0, accum_az)};
905 const int num_azs{std::accumulate(elevs_mid, elevs_end, 0, accum_az)};
907 coeffs_end = std::copy_backward(coeffs.cbegin() + abase,
908 coeffs.cbegin() + (abase+num_azs), coeffs_end);
909 delays_end = std::copy_backward(delays.cbegin() + abase,
910 delays.cbegin() + (abase+num_azs), delays_end);
912 return ebase + field.evCount;
914 (void)std::accumulate(fields.cbegin(), fields.cend(), ptrdiff_t{0}, copy_irs);
915 assert(coeffs_.begin() == coeffs_end);
916 assert(delays_.begin() == delays_end);
918 fields = std::move(fields_);
919 elevs = std::move(elevs_);
920 coeffs = std::move(coeffs_);
921 delays = std::move(delays_);
924 return CreateHrtfStore(rate, irSize, {fields.data(), fields.size()},
925 {elevs.data(), elevs.size()}, coeffs.data(), delays.data(), filename);
928 std::unique_ptr<HrtfStore> LoadHrtf03(std::istream &data, const char *filename)
930 constexpr ubyte ChanType_LeftOnly{0};
931 constexpr ubyte ChanType_LeftRight{1};
933 uint rate{readle<uint32_t>(data)};
934 ubyte channelType{readle<uint8_t>(data)};
935 ushort irSize{readle<uint8_t>(data)};
936 ubyte fdCount{readle<uint8_t>(data)};
937 if(!data || data.eof())
939 ERR("Failed reading %s\n", filename);
940 return nullptr;
943 if(channelType > ChanType_LeftRight)
945 ERR("Unsupported channel type: %d\n", channelType);
946 return nullptr;
949 if(irSize < MinIrLength || irSize > HrirLength)
951 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
952 return nullptr;
954 if(fdCount < 1 || fdCount > MaxFdCount)
956 ERR("Unsupported number of field-depths: fdCount=%d (%d to %d)\n", fdCount, MinFdCount,
957 MaxFdCount);
958 return nullptr;
961 auto fields = al::vector<HrtfStore::Field>(fdCount);
962 auto elevs = al::vector<HrtfStore::Elevation>{};
963 for(size_t f{0};f < fdCount;f++)
965 const ushort distance{readle<uint16_t>(data)};
966 const ubyte evCount{readle<uint8_t>(data)};
967 if(!data || data.eof())
969 ERR("Failed reading %s\n", filename);
970 return nullptr;
973 if(distance < MinFdDistance || distance > MaxFdDistance)
975 ERR("Unsupported field distance[%zu]=%d (%d to %d millimeters)\n", f, distance,
976 MinFdDistance, MaxFdDistance);
977 return nullptr;
979 if(evCount < MinEvCount || evCount > MaxEvCount)
981 ERR("Unsupported elevation count: evCount[%zu]=%d (%d to %d)\n", f, evCount,
982 MinEvCount, MaxEvCount);
983 return nullptr;
986 fields[f].distance = distance / 1000.0f;
987 fields[f].evCount = evCount;
988 if(f > 0 && fields[f].distance > fields[f-1].distance)
990 ERR("Field distance[%zu] is not before previous (%f <= %f)\n", f, fields[f].distance,
991 fields[f-1].distance);
992 return nullptr;
995 const size_t ebase{elevs.size()};
996 elevs.resize(ebase + evCount);
997 for(auto &elev : al::span<HrtfStore::Elevation>(elevs.data()+ebase, evCount))
998 elev.azCount = readle<uint8_t>(data);
999 if(!data || data.eof())
1001 ERR("Failed reading %s\n", filename);
1002 return nullptr;
1005 for(size_t e{0};e < evCount;e++)
1007 if(elevs[ebase+e].azCount < MinAzCount || elevs[ebase+e].azCount > MaxAzCount)
1009 ERR("Unsupported azimuth count: azCount[%zu][%zu]=%d (%d to %d)\n", f, e,
1010 elevs[ebase+e].azCount, MinAzCount, MaxAzCount);
1011 return nullptr;
1016 elevs[0].irOffset = 0;
1017 std::partial_sum(elevs.cbegin(), elevs.cend(), elevs.begin(),
1018 [](const HrtfStore::Elevation &last, const HrtfStore::Elevation &cur)
1019 -> HrtfStore::Elevation
1021 return HrtfStore::Elevation{cur.azCount,
1022 static_cast<ushort>(last.azCount + last.irOffset)};
1024 const auto irTotal = static_cast<ushort>(elevs.back().azCount + elevs.back().irOffset);
1026 auto coeffs = al::vector<HrirArray>(irTotal, HrirArray{});
1027 auto delays = al::vector<ubyte2>(irTotal);
1028 if(channelType == ChanType_LeftOnly)
1030 for(auto &hrir : coeffs)
1032 for(auto &val : al::span<float2>{hrir.data(), irSize})
1033 val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
1035 for(auto &val : delays)
1036 val[0] = readle<uint8_t>(data);
1037 if(!data || data.eof())
1039 ERR("Failed reading %s\n", filename);
1040 return nullptr;
1042 for(size_t i{0};i < irTotal;++i)
1044 if(delays[i][0] > MaxHrirDelay<<HrirDelayFracBits)
1046 ERR("Invalid delays[%zu][0]: %f (%d)\n", i,
1047 delays[i][0] / float{HrirDelayFracOne}, MaxHrirDelay);
1048 return nullptr;
1052 /* Mirror the left ear responses to the right ear. */
1053 MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
1055 else if(channelType == ChanType_LeftRight)
1057 for(auto &hrir : coeffs)
1059 for(auto &val : al::span<float2>{hrir.data(), irSize})
1061 val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
1062 val[1] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
1065 for(auto &val : delays)
1067 val[0] = readle<uint8_t>(data);
1068 val[1] = readle<uint8_t>(data);
1070 if(!data || data.eof())
1072 ERR("Failed reading %s\n", filename);
1073 return nullptr;
1076 for(size_t i{0};i < irTotal;++i)
1078 if(delays[i][0] > MaxHrirDelay<<HrirDelayFracBits)
1080 ERR("Invalid delays[%zu][0]: %f (%d)\n", i,
1081 delays[i][0] / float{HrirDelayFracOne}, MaxHrirDelay);
1082 return nullptr;
1084 if(delays[i][1] > MaxHrirDelay<<HrirDelayFracBits)
1086 ERR("Invalid delays[%zu][1]: %f (%d)\n", i,
1087 delays[i][1] / float{HrirDelayFracOne}, MaxHrirDelay);
1088 return nullptr;
1093 return CreateHrtfStore(rate, irSize, {fields.data(), fields.size()},
1094 {elevs.data(), elevs.size()}, coeffs.data(), delays.data(), filename);
1098 bool checkName(const std::string &name)
1100 auto match_name = [&name](const HrtfEntry &entry) -> bool { return name == entry.mDispName; };
1101 auto &enum_names = EnumeratedHrtfs;
1102 return std::find_if(enum_names.cbegin(), enum_names.cend(), match_name) != enum_names.cend();
1105 void AddFileEntry(const std::string &filename)
1107 /* Check if this file has already been enumerated. */
1108 auto enum_iter = std::find_if(EnumeratedHrtfs.cbegin(), EnumeratedHrtfs.cend(),
1109 [&filename](const HrtfEntry &entry) -> bool
1110 { return entry.mFilename == filename; });
1111 if(enum_iter != EnumeratedHrtfs.cend())
1113 TRACE("Skipping duplicate file entry %s\n", filename.c_str());
1114 return;
1117 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1118 * format update). */
1119 size_t namepos{filename.find_last_of('/')+1};
1120 if(!namepos) namepos = filename.find_last_of('\\')+1;
1122 size_t extpos{filename.find_last_of('.')};
1123 if(extpos <= namepos) extpos = std::string::npos;
1125 const std::string basename{(extpos == std::string::npos) ?
1126 filename.substr(namepos) : filename.substr(namepos, extpos-namepos)};
1127 std::string newname{basename};
1128 int count{1};
1129 while(checkName(newname))
1131 newname = basename;
1132 newname += " #";
1133 newname += std::to_string(++count);
1135 EnumeratedHrtfs.emplace_back(HrtfEntry{newname, filename});
1136 const HrtfEntry &entry = EnumeratedHrtfs.back();
1138 TRACE("Adding file entry \"%s\"\n", entry.mFilename.c_str());
1141 /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
1142 * for input instead of opening the given filename.
1144 void AddBuiltInEntry(const std::string &dispname, uint residx)
1146 const std::string filename{'!'+std::to_string(residx)+'_'+dispname};
1148 auto enum_iter = std::find_if(EnumeratedHrtfs.cbegin(), EnumeratedHrtfs.cend(),
1149 [&filename](const HrtfEntry &entry) -> bool
1150 { return entry.mFilename == filename; });
1151 if(enum_iter != EnumeratedHrtfs.cend())
1153 TRACE("Skipping duplicate file entry %s\n", filename.c_str());
1154 return;
1157 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1158 * format update). */
1160 std::string newname{dispname};
1161 int count{1};
1162 while(checkName(newname))
1164 newname = dispname;
1165 newname += " #";
1166 newname += std::to_string(++count);
1168 EnumeratedHrtfs.emplace_back(HrtfEntry{newname, filename});
1169 const HrtfEntry &entry = EnumeratedHrtfs.back();
1171 TRACE("Adding built-in entry \"%s\"\n", entry.mFilename.c_str());
1175 #define IDR_DEFAULT_HRTF_MHR 1
1177 #ifndef ALSOFT_EMBED_HRTF_DATA
1179 al::span<const char> GetResource(int /*name*/)
1180 { return {}; }
1182 #else
1184 #include "hrtf_default.h"
1186 al::span<const char> GetResource(int name)
1188 if(name == IDR_DEFAULT_HRTF_MHR)
1189 return {reinterpret_cast<const char*>(hrtf_default), sizeof(hrtf_default)};
1190 return {};
1192 #endif
1194 } // namespace
1197 al::vector<std::string> EnumerateHrtf(al::optional<std::string> pathopt)
1199 std::lock_guard<std::mutex> _{EnumeratedHrtfLock};
1200 EnumeratedHrtfs.clear();
1202 bool usedefaults{true};
1203 if(pathopt)
1205 const char *pathlist{pathopt->c_str()};
1206 while(pathlist && *pathlist)
1208 const char *next, *end;
1210 while(isspace(*pathlist) || *pathlist == ',')
1211 pathlist++;
1212 if(*pathlist == '\0')
1213 continue;
1215 next = strchr(pathlist, ',');
1216 if(next)
1217 end = next++;
1218 else
1220 end = pathlist + strlen(pathlist);
1221 usedefaults = false;
1224 while(end != pathlist && isspace(*(end-1)))
1225 --end;
1226 if(end != pathlist)
1228 const std::string pname{pathlist, end};
1229 for(const auto &fname : SearchDataFiles(".mhr", pname.c_str()))
1230 AddFileEntry(fname);
1233 pathlist = next;
1237 if(usedefaults)
1239 for(const auto &fname : SearchDataFiles(".mhr", "openal/hrtf"))
1240 AddFileEntry(fname);
1242 if(!GetResource(IDR_DEFAULT_HRTF_MHR).empty())
1243 AddBuiltInEntry("Built-In HRTF", IDR_DEFAULT_HRTF_MHR);
1246 al::vector<std::string> list;
1247 list.reserve(EnumeratedHrtfs.size());
1248 for(auto &entry : EnumeratedHrtfs)
1249 list.emplace_back(entry.mDispName);
1251 return list;
1254 HrtfStorePtr GetLoadedHrtf(const std::string &name, const uint devrate)
1256 std::lock_guard<std::mutex> _{EnumeratedHrtfLock};
1257 auto entry_iter = std::find_if(EnumeratedHrtfs.cbegin(), EnumeratedHrtfs.cend(),
1258 [&name](const HrtfEntry &entry) -> bool { return entry.mDispName == name; });
1259 if(entry_iter == EnumeratedHrtfs.cend())
1260 return nullptr;
1261 const std::string &fname = entry_iter->mFilename;
1263 std::lock_guard<std::mutex> __{LoadedHrtfLock};
1264 auto hrtf_lt_fname = [](LoadedHrtf &hrtf, const std::string &filename) -> bool
1265 { return hrtf.mFilename < filename; };
1266 auto handle = std::lower_bound(LoadedHrtfs.begin(), LoadedHrtfs.end(), fname, hrtf_lt_fname);
1267 while(handle != LoadedHrtfs.end() && handle->mFilename == fname)
1269 HrtfStore *hrtf{handle->mEntry.get()};
1270 if(hrtf && hrtf->sampleRate == devrate)
1272 hrtf->add_ref();
1273 return HrtfStorePtr{hrtf};
1275 ++handle;
1278 std::unique_ptr<std::istream> stream;
1279 int residx{};
1280 char ch{};
1281 if(sscanf(fname.c_str(), "!%d%c", &residx, &ch) == 2 && ch == '_')
1283 TRACE("Loading %s...\n", fname.c_str());
1284 al::span<const char> res{GetResource(residx)};
1285 if(res.empty())
1287 ERR("Could not get resource %u, %s\n", residx, name.c_str());
1288 return nullptr;
1290 stream = std::make_unique<idstream>(res.begin(), res.end());
1292 else
1294 TRACE("Loading %s...\n", fname.c_str());
1295 auto fstr = std::make_unique<al::ifstream>(fname.c_str(), std::ios::binary);
1296 if(!fstr->is_open())
1298 ERR("Could not open %s\n", fname.c_str());
1299 return nullptr;
1301 stream = std::move(fstr);
1304 std::unique_ptr<HrtfStore> hrtf;
1305 char magic[sizeof(magicMarker03)];
1306 stream->read(magic, sizeof(magic));
1307 if(stream->gcount() < static_cast<std::streamsize>(sizeof(magicMarker03)))
1308 ERR("%s data is too short (%zu bytes)\n", name.c_str(), stream->gcount());
1309 else if(memcmp(magic, magicMarker03, sizeof(magicMarker03)) == 0)
1311 TRACE("Detected data set format v3\n");
1312 hrtf = LoadHrtf03(*stream, name.c_str());
1314 else if(memcmp(magic, magicMarker02, sizeof(magicMarker02)) == 0)
1316 TRACE("Detected data set format v2\n");
1317 hrtf = LoadHrtf02(*stream, name.c_str());
1319 else if(memcmp(magic, magicMarker01, sizeof(magicMarker01)) == 0)
1321 TRACE("Detected data set format v1\n");
1322 hrtf = LoadHrtf01(*stream, name.c_str());
1324 else if(memcmp(magic, magicMarker00, sizeof(magicMarker00)) == 0)
1326 TRACE("Detected data set format v0\n");
1327 hrtf = LoadHrtf00(*stream, name.c_str());
1329 else
1330 ERR("Invalid header in %s: \"%.8s\"\n", name.c_str(), magic);
1331 stream.reset();
1333 if(!hrtf)
1335 ERR("Failed to load %s\n", name.c_str());
1336 return nullptr;
1339 if(hrtf->sampleRate != devrate)
1341 TRACE("Resampling HRTF %s (%uhz -> %uhz)\n", name.c_str(), hrtf->sampleRate, devrate);
1343 /* Calculate the last elevation's index and get the total IR count. */
1344 const size_t lastEv{std::accumulate(hrtf->field, hrtf->field+hrtf->fdCount, size_t{0},
1345 [](const size_t curval, const HrtfStore::Field &field) noexcept -> size_t
1346 { return curval + field.evCount; }
1347 ) - 1};
1348 const size_t irCount{size_t{hrtf->elev[lastEv].irOffset} + hrtf->elev[lastEv].azCount};
1350 /* Resample all the IRs. */
1351 std::array<std::array<double,HrirLength>,2> inout;
1352 PPhaseResampler rs;
1353 rs.init(hrtf->sampleRate, devrate);
1354 for(size_t i{0};i < irCount;++i)
1356 HrirArray &coeffs = const_cast<HrirArray&>(hrtf->coeffs[i]);
1357 for(size_t j{0};j < 2;++j)
1359 std::transform(coeffs.cbegin(), coeffs.cend(), inout[0].begin(),
1360 [j](const float2 &in) noexcept -> double { return in[j]; });
1361 rs.process(HrirLength, inout[0].data(), HrirLength, inout[1].data());
1362 for(size_t k{0};k < HrirLength;++k)
1363 coeffs[k][j] = static_cast<float>(inout[1][k]);
1366 rs = {};
1368 /* Scale the delays for the new sample rate. */
1369 float max_delay{0.0f};
1370 auto new_delays = al::vector<float2>(irCount);
1371 const float rate_scale{static_cast<float>(devrate)/static_cast<float>(hrtf->sampleRate)};
1372 for(size_t i{0};i < irCount;++i)
1374 for(size_t j{0};j < 2;++j)
1376 const float new_delay{std::round(hrtf->delays[i][j] * rate_scale) /
1377 float{HrirDelayFracOne}};
1378 max_delay = maxf(max_delay, new_delay);
1379 new_delays[i][j] = new_delay;
1383 /* If the new delays exceed the max, scale it down to fit (essentially
1384 * shrinking the head radius; not ideal but better than a per-delay
1385 * clamp).
1387 float delay_scale{HrirDelayFracOne};
1388 if(max_delay > MaxHrirDelay)
1390 WARN("Resampled delay exceeds max (%.2f > %d)\n", max_delay, MaxHrirDelay);
1391 delay_scale *= float{MaxHrirDelay} / max_delay;
1394 for(size_t i{0};i < irCount;++i)
1396 ubyte2 &delays = const_cast<ubyte2&>(hrtf->delays[i]);
1397 for(size_t j{0};j < 2;++j)
1398 delays[j] = static_cast<ubyte>(float2int(new_delays[i][j]*delay_scale + 0.5f));
1401 /* Scale the IR size for the new sample rate and update the stored
1402 * sample rate.
1404 const float newIrSize{std::round(static_cast<float>(hrtf->irSize) * rate_scale)};
1405 hrtf->irSize = static_cast<uint>(minf(HrirLength, newIrSize));
1406 hrtf->sampleRate = devrate;
1409 TRACE("Loaded HRTF %s for sample rate %uhz, %u-sample filter\n", name.c_str(),
1410 hrtf->sampleRate, hrtf->irSize);
1411 handle = LoadedHrtfs.emplace(handle, LoadedHrtf{fname, std::move(hrtf)});
1413 return HrtfStorePtr{handle->mEntry.get()};
1417 void HrtfStore::add_ref()
1419 auto ref = IncrementRef(mRef);
1420 TRACE("HrtfStore %p increasing refcount to %u\n", decltype(std::declval<void*>()){this}, ref);
1423 void HrtfStore::release()
1425 auto ref = DecrementRef(mRef);
1426 TRACE("HrtfStore %p decreasing refcount to %u\n", decltype(std::declval<void*>()){this}, ref);
1427 if(ref == 0)
1429 std::lock_guard<std::mutex> _{LoadedHrtfLock};
1431 /* Go through and remove all unused HRTFs. */
1432 auto remove_unused = [](LoadedHrtf &hrtf) -> bool
1434 HrtfStore *entry{hrtf.mEntry.get()};
1435 if(entry && ReadRef(entry->mRef) == 0)
1437 TRACE("Unloading unused HRTF %s\n", hrtf.mFilename.data());
1438 hrtf.mEntry = nullptr;
1439 return true;
1441 return false;
1443 auto iter = std::remove_if(LoadedHrtfs.begin(), LoadedHrtfs.end(), remove_unused);
1444 LoadedHrtfs.erase(iter, LoadedHrtfs.end());