Avoid a stateful unique_ptr deleter
[openal-soft.git] / core / hrtf.cpp
blobd94c0569821ecb6a5f8d408841e800dd60ac1598
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<size_t num_bits, typename T>
451 constexpr std::enable_if_t<std::is_signed<T>::value && num_bits < sizeof(T)*8,
452 T> fixsign(T value) noexcept
454 constexpr auto signbit = static_cast<T>(1u << (num_bits-1));
455 return static_cast<T>((value^signbit) - signbit);
458 template<size_t num_bits, typename T>
459 constexpr std::enable_if_t<!std::is_signed<T>::value || num_bits == sizeof(T)*8,
460 T> fixsign(T value) noexcept
461 { return value; }
463 template<typename T, size_t num_bits=sizeof(T)*8>
464 inline std::enable_if_t<al::endian::native == al::endian::little,
465 T> readle(std::istream &data)
467 static_assert((num_bits&7) == 0, "num_bits must be a multiple of 8");
468 static_assert(num_bits <= sizeof(T)*8, "num_bits is too large for the type");
470 T ret{};
471 if(!data.read(reinterpret_cast<char*>(&ret), num_bits/8))
472 return static_cast<T>(EOF);
474 return fixsign<num_bits>(ret);
477 template<typename T, size_t num_bits=sizeof(T)*8>
478 inline std::enable_if_t<al::endian::native == al::endian::big,
479 T> readle(std::istream &data)
481 static_assert((num_bits&7) == 0, "num_bits must be a multiple of 8");
482 static_assert(num_bits <= sizeof(T)*8, "num_bits is too large for the type");
484 T ret{};
485 al::byte b[sizeof(T)]{};
486 if(!data.read(reinterpret_cast<char*>(b), num_bits/8))
487 return static_cast<T>(EOF);
488 std::reverse_copy(std::begin(b), std::end(b), reinterpret_cast<al::byte*>(&ret));
490 return fixsign<num_bits>(ret);
493 template<>
494 inline uint8_t readle<uint8_t,8>(std::istream &data)
495 { return static_cast<uint8_t>(data.get()); }
498 std::unique_ptr<HrtfStore> LoadHrtf00(std::istream &data, const char *filename)
500 uint rate{readle<uint32_t>(data)};
501 ushort irCount{readle<uint16_t>(data)};
502 ushort irSize{readle<uint16_t>(data)};
503 ubyte evCount{readle<uint8_t>(data)};
504 if(!data || data.eof())
506 ERR("Failed reading %s\n", filename);
507 return nullptr;
510 if(irSize < MinIrLength || irSize > HrirLength)
512 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
513 return nullptr;
515 if(evCount < MinEvCount || evCount > MaxEvCount)
517 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
518 evCount, MinEvCount, MaxEvCount);
519 return nullptr;
522 auto elevs = al::vector<HrtfStore::Elevation>(evCount);
523 for(auto &elev : elevs)
524 elev.irOffset = readle<uint16_t>(data);
525 if(!data || data.eof())
527 ERR("Failed reading %s\n", filename);
528 return nullptr;
530 for(size_t i{1};i < evCount;i++)
532 if(elevs[i].irOffset <= elevs[i-1].irOffset)
534 ERR("Invalid evOffset: evOffset[%zu]=%d (last=%d)\n", i, elevs[i].irOffset,
535 elevs[i-1].irOffset);
536 return nullptr;
539 if(irCount <= elevs.back().irOffset)
541 ERR("Invalid evOffset: evOffset[%zu]=%d (irCount=%d)\n",
542 elevs.size()-1, elevs.back().irOffset, irCount);
543 return nullptr;
546 for(size_t i{1};i < evCount;i++)
548 elevs[i-1].azCount = static_cast<ushort>(elevs[i].irOffset - elevs[i-1].irOffset);
549 if(elevs[i-1].azCount < MinAzCount || elevs[i-1].azCount > MaxAzCount)
551 ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n",
552 i-1, elevs[i-1].azCount, MinAzCount, MaxAzCount);
553 return nullptr;
556 elevs.back().azCount = static_cast<ushort>(irCount - elevs.back().irOffset);
557 if(elevs.back().azCount < MinAzCount || elevs.back().azCount > MaxAzCount)
559 ERR("Unsupported azimuth count: azCount[%zu]=%d (%d to %d)\n",
560 elevs.size()-1, elevs.back().azCount, MinAzCount, MaxAzCount);
561 return nullptr;
564 auto coeffs = al::vector<HrirArray>(irCount, HrirArray{});
565 auto delays = al::vector<ubyte2>(irCount);
566 for(auto &hrir : coeffs)
568 for(auto &val : al::span<float2>{hrir.data(), irSize})
569 val[0] = readle<int16_t>(data) / 32768.0f;
571 for(auto &val : delays)
572 val[0] = readle<uint8_t>(data);
573 if(!data || data.eof())
575 ERR("Failed reading %s\n", filename);
576 return nullptr;
578 for(size_t i{0};i < irCount;i++)
580 if(delays[i][0] > MaxHrirDelay)
582 ERR("Invalid delays[%zd]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
583 return nullptr;
585 delays[i][0] <<= HrirDelayFracBits;
588 /* Mirror the left ear responses to the right ear. */
589 MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
591 const HrtfStore::Field field[1]{{0.0f, evCount}};
592 return CreateHrtfStore(rate, irSize, field, {elevs.data(), elevs.size()}, coeffs.data(),
593 delays.data(), filename);
596 std::unique_ptr<HrtfStore> LoadHrtf01(std::istream &data, const char *filename)
598 uint rate{readle<uint32_t>(data)};
599 ushort irSize{readle<uint8_t>(data)};
600 ubyte evCount{readle<uint8_t>(data)};
601 if(!data || data.eof())
603 ERR("Failed reading %s\n", filename);
604 return nullptr;
607 if(irSize < MinIrLength || irSize > HrirLength)
609 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
610 return nullptr;
612 if(evCount < MinEvCount || evCount > MaxEvCount)
614 ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
615 evCount, MinEvCount, MaxEvCount);
616 return nullptr;
619 auto elevs = al::vector<HrtfStore::Elevation>(evCount);
620 for(auto &elev : elevs)
621 elev.azCount = readle<uint8_t>(data);
622 if(!data || data.eof())
624 ERR("Failed reading %s\n", filename);
625 return nullptr;
627 for(size_t i{0};i < evCount;++i)
629 if(elevs[i].azCount < MinAzCount || elevs[i].azCount > MaxAzCount)
631 ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n", i, elevs[i].azCount,
632 MinAzCount, MaxAzCount);
633 return nullptr;
637 elevs[0].irOffset = 0;
638 for(size_t i{1};i < evCount;i++)
639 elevs[i].irOffset = static_cast<ushort>(elevs[i-1].irOffset + elevs[i-1].azCount);
640 const ushort irCount{static_cast<ushort>(elevs.back().irOffset + elevs.back().azCount)};
642 auto coeffs = al::vector<HrirArray>(irCount, HrirArray{});
643 auto delays = al::vector<ubyte2>(irCount);
644 for(auto &hrir : coeffs)
646 for(auto &val : al::span<float2>{hrir.data(), irSize})
647 val[0] = readle<int16_t>(data) / 32768.0f;
649 for(auto &val : delays)
650 val[0] = readle<uint8_t>(data);
651 if(!data || data.eof())
653 ERR("Failed reading %s\n", filename);
654 return nullptr;
656 for(size_t i{0};i < irCount;i++)
658 if(delays[i][0] > MaxHrirDelay)
660 ERR("Invalid delays[%zd]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
661 return nullptr;
663 delays[i][0] <<= HrirDelayFracBits;
666 /* Mirror the left ear responses to the right ear. */
667 MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
669 const HrtfStore::Field field[1]{{0.0f, evCount}};
670 return CreateHrtfStore(rate, irSize, field, {elevs.data(), elevs.size()}, coeffs.data(),
671 delays.data(), filename);
674 std::unique_ptr<HrtfStore> LoadHrtf02(std::istream &data, const char *filename)
676 constexpr ubyte SampleType_S16{0};
677 constexpr ubyte SampleType_S24{1};
678 constexpr ubyte ChanType_LeftOnly{0};
679 constexpr ubyte ChanType_LeftRight{1};
681 uint rate{readle<uint32_t>(data)};
682 ubyte sampleType{readle<uint8_t>(data)};
683 ubyte channelType{readle<uint8_t>(data)};
684 ushort irSize{readle<uint8_t>(data)};
685 ubyte fdCount{readle<uint8_t>(data)};
686 if(!data || data.eof())
688 ERR("Failed reading %s\n", filename);
689 return nullptr;
692 if(sampleType > SampleType_S24)
694 ERR("Unsupported sample type: %d\n", sampleType);
695 return nullptr;
697 if(channelType > ChanType_LeftRight)
699 ERR("Unsupported channel type: %d\n", channelType);
700 return nullptr;
703 if(irSize < MinIrLength || irSize > HrirLength)
705 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
706 return nullptr;
708 if(fdCount < 1 || fdCount > MaxFdCount)
710 ERR("Unsupported number of field-depths: fdCount=%d (%d to %d)\n", fdCount, MinFdCount,
711 MaxFdCount);
712 return nullptr;
715 auto fields = al::vector<HrtfStore::Field>(fdCount);
716 auto elevs = al::vector<HrtfStore::Elevation>{};
717 for(size_t f{0};f < fdCount;f++)
719 const ushort distance{readle<uint16_t>(data)};
720 const ubyte evCount{readle<uint8_t>(data)};
721 if(!data || data.eof())
723 ERR("Failed reading %s\n", filename);
724 return nullptr;
727 if(distance < MinFdDistance || distance > MaxFdDistance)
729 ERR("Unsupported field distance[%zu]=%d (%d to %d millimeters)\n", f, distance,
730 MinFdDistance, MaxFdDistance);
731 return nullptr;
733 if(evCount < MinEvCount || evCount > MaxEvCount)
735 ERR("Unsupported elevation count: evCount[%zu]=%d (%d to %d)\n", f, evCount,
736 MinEvCount, MaxEvCount);
737 return nullptr;
740 fields[f].distance = distance / 1000.0f;
741 fields[f].evCount = evCount;
742 if(f > 0 && fields[f].distance <= fields[f-1].distance)
744 ERR("Field distance[%zu] is not after previous (%f > %f)\n", f, fields[f].distance,
745 fields[f-1].distance);
746 return nullptr;
749 const size_t ebase{elevs.size()};
750 elevs.resize(ebase + evCount);
751 for(auto &elev : al::span<HrtfStore::Elevation>(elevs.data()+ebase, evCount))
752 elev.azCount = readle<uint8_t>(data);
753 if(!data || data.eof())
755 ERR("Failed reading %s\n", filename);
756 return nullptr;
759 for(size_t e{0};e < evCount;e++)
761 if(elevs[ebase+e].azCount < MinAzCount || elevs[ebase+e].azCount > MaxAzCount)
763 ERR("Unsupported azimuth count: azCount[%zu][%zu]=%d (%d to %d)\n", f, e,
764 elevs[ebase+e].azCount, MinAzCount, MaxAzCount);
765 return nullptr;
770 elevs[0].irOffset = 0;
771 std::partial_sum(elevs.cbegin(), elevs.cend(), elevs.begin(),
772 [](const HrtfStore::Elevation &last, const HrtfStore::Elevation &cur)
773 -> HrtfStore::Elevation
775 return HrtfStore::Elevation{cur.azCount,
776 static_cast<ushort>(last.azCount + last.irOffset)};
778 const auto irTotal = static_cast<ushort>(elevs.back().azCount + elevs.back().irOffset);
780 auto coeffs = al::vector<HrirArray>(irTotal, HrirArray{});
781 auto delays = al::vector<ubyte2>(irTotal);
782 if(channelType == ChanType_LeftOnly)
784 if(sampleType == SampleType_S16)
786 for(auto &hrir : coeffs)
788 for(auto &val : al::span<float2>{hrir.data(), irSize})
789 val[0] = readle<int16_t>(data) / 32768.0f;
792 else if(sampleType == SampleType_S24)
794 for(auto &hrir : coeffs)
796 for(auto &val : al::span<float2>{hrir.data(), irSize})
797 val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
800 for(auto &val : delays)
801 val[0] = readle<uint8_t>(data);
802 if(!data || data.eof())
804 ERR("Failed reading %s\n", filename);
805 return nullptr;
807 for(size_t i{0};i < irTotal;++i)
809 if(delays[i][0] > MaxHrirDelay)
811 ERR("Invalid delays[%zu][0]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
812 return nullptr;
814 delays[i][0] <<= HrirDelayFracBits;
817 /* Mirror the left ear responses to the right ear. */
818 MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
820 else if(channelType == ChanType_LeftRight)
822 if(sampleType == SampleType_S16)
824 for(auto &hrir : coeffs)
826 for(auto &val : al::span<float2>{hrir.data(), irSize})
828 val[0] = readle<int16_t>(data) / 32768.0f;
829 val[1] = readle<int16_t>(data) / 32768.0f;
833 else if(sampleType == SampleType_S24)
835 for(auto &hrir : coeffs)
837 for(auto &val : al::span<float2>{hrir.data(), irSize})
839 val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
840 val[1] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
844 for(auto &val : delays)
846 val[0] = readle<uint8_t>(data);
847 val[1] = readle<uint8_t>(data);
849 if(!data || data.eof())
851 ERR("Failed reading %s\n", filename);
852 return nullptr;
855 for(size_t i{0};i < irTotal;++i)
857 if(delays[i][0] > MaxHrirDelay)
859 ERR("Invalid delays[%zu][0]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
860 return nullptr;
862 if(delays[i][1] > MaxHrirDelay)
864 ERR("Invalid delays[%zu][1]: %d (%d)\n", i, delays[i][1], MaxHrirDelay);
865 return nullptr;
867 delays[i][0] <<= HrirDelayFracBits;
868 delays[i][1] <<= HrirDelayFracBits;
872 if(fdCount > 1)
874 auto fields_ = al::vector<HrtfStore::Field>(fields.size());
875 auto elevs_ = al::vector<HrtfStore::Elevation>(elevs.size());
876 auto coeffs_ = al::vector<HrirArray>(coeffs.size());
877 auto delays_ = al::vector<ubyte2>(delays.size());
879 /* Simple reverse for the per-field elements. */
880 std::reverse_copy(fields.cbegin(), fields.cend(), fields_.begin());
882 /* Each field has a group of elevations, which each have an azimuth
883 * count. Reverse the order of the groups, keeping the relative order
884 * of per-group azimuth counts.
886 auto elevs__end = elevs_.end();
887 auto copy_azs = [&elevs,&elevs__end](const ptrdiff_t ebase, const HrtfStore::Field &field)
888 -> ptrdiff_t
890 auto elevs_src = elevs.begin()+ebase;
891 elevs__end = std::copy_backward(elevs_src, elevs_src+field.evCount, elevs__end);
892 return ebase + field.evCount;
894 (void)std::accumulate(fields.cbegin(), fields.cend(), ptrdiff_t{0}, copy_azs);
895 assert(elevs_.begin() == elevs__end);
897 /* Reestablish the IR offset for each elevation index, given the new
898 * ordering of elevations.
900 elevs_[0].irOffset = 0;
901 std::partial_sum(elevs_.cbegin(), elevs_.cend(), elevs_.begin(),
902 [](const HrtfStore::Elevation &last, const HrtfStore::Elevation &cur)
903 -> HrtfStore::Elevation
905 return HrtfStore::Elevation{cur.azCount,
906 static_cast<ushort>(last.azCount + last.irOffset)};
909 /* Reverse the order of each field's group of IRs. */
910 auto coeffs_end = coeffs_.end();
911 auto delays_end = delays_.end();
912 auto copy_irs = [&elevs,&coeffs,&delays,&coeffs_end,&delays_end](
913 const ptrdiff_t ebase, const HrtfStore::Field &field) -> ptrdiff_t
915 auto accum_az = [](int count, const HrtfStore::Elevation &elev) noexcept -> int
916 { return count + elev.azCount; };
917 const auto elevs_mid = elevs.cbegin() + ebase;
918 const auto elevs_end = elevs_mid + field.evCount;
919 const int abase{std::accumulate(elevs.cbegin(), elevs_mid, 0, accum_az)};
920 const int num_azs{std::accumulate(elevs_mid, elevs_end, 0, accum_az)};
922 coeffs_end = std::copy_backward(coeffs.cbegin() + abase,
923 coeffs.cbegin() + (abase+num_azs), coeffs_end);
924 delays_end = std::copy_backward(delays.cbegin() + abase,
925 delays.cbegin() + (abase+num_azs), delays_end);
927 return ebase + field.evCount;
929 (void)std::accumulate(fields.cbegin(), fields.cend(), ptrdiff_t{0}, copy_irs);
930 assert(coeffs_.begin() == coeffs_end);
931 assert(delays_.begin() == delays_end);
933 fields = std::move(fields_);
934 elevs = std::move(elevs_);
935 coeffs = std::move(coeffs_);
936 delays = std::move(delays_);
939 return CreateHrtfStore(rate, irSize, {fields.data(), fields.size()},
940 {elevs.data(), elevs.size()}, coeffs.data(), delays.data(), filename);
943 std::unique_ptr<HrtfStore> LoadHrtf03(std::istream &data, const char *filename)
945 constexpr ubyte ChanType_LeftOnly{0};
946 constexpr ubyte ChanType_LeftRight{1};
948 uint rate{readle<uint32_t>(data)};
949 ubyte channelType{readle<uint8_t>(data)};
950 ushort irSize{readle<uint8_t>(data)};
951 ubyte fdCount{readle<uint8_t>(data)};
952 if(!data || data.eof())
954 ERR("Failed reading %s\n", filename);
955 return nullptr;
958 if(channelType > ChanType_LeftRight)
960 ERR("Unsupported channel type: %d\n", channelType);
961 return nullptr;
964 if(irSize < MinIrLength || irSize > HrirLength)
966 ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
967 return nullptr;
969 if(fdCount < 1 || fdCount > MaxFdCount)
971 ERR("Unsupported number of field-depths: fdCount=%d (%d to %d)\n", fdCount, MinFdCount,
972 MaxFdCount);
973 return nullptr;
976 auto fields = al::vector<HrtfStore::Field>(fdCount);
977 auto elevs = al::vector<HrtfStore::Elevation>{};
978 for(size_t f{0};f < fdCount;f++)
980 const ushort distance{readle<uint16_t>(data)};
981 const ubyte evCount{readle<uint8_t>(data)};
982 if(!data || data.eof())
984 ERR("Failed reading %s\n", filename);
985 return nullptr;
988 if(distance < MinFdDistance || distance > MaxFdDistance)
990 ERR("Unsupported field distance[%zu]=%d (%d to %d millimeters)\n", f, distance,
991 MinFdDistance, MaxFdDistance);
992 return nullptr;
994 if(evCount < MinEvCount || evCount > MaxEvCount)
996 ERR("Unsupported elevation count: evCount[%zu]=%d (%d to %d)\n", f, evCount,
997 MinEvCount, MaxEvCount);
998 return nullptr;
1001 fields[f].distance = distance / 1000.0f;
1002 fields[f].evCount = evCount;
1003 if(f > 0 && fields[f].distance > fields[f-1].distance)
1005 ERR("Field distance[%zu] is not before previous (%f <= %f)\n", f, fields[f].distance,
1006 fields[f-1].distance);
1007 return nullptr;
1010 const size_t ebase{elevs.size()};
1011 elevs.resize(ebase + evCount);
1012 for(auto &elev : al::span<HrtfStore::Elevation>(elevs.data()+ebase, evCount))
1013 elev.azCount = readle<uint8_t>(data);
1014 if(!data || data.eof())
1016 ERR("Failed reading %s\n", filename);
1017 return nullptr;
1020 for(size_t e{0};e < evCount;e++)
1022 if(elevs[ebase+e].azCount < MinAzCount || elevs[ebase+e].azCount > MaxAzCount)
1024 ERR("Unsupported azimuth count: azCount[%zu][%zu]=%d (%d to %d)\n", f, e,
1025 elevs[ebase+e].azCount, MinAzCount, MaxAzCount);
1026 return nullptr;
1031 elevs[0].irOffset = 0;
1032 std::partial_sum(elevs.cbegin(), elevs.cend(), elevs.begin(),
1033 [](const HrtfStore::Elevation &last, const HrtfStore::Elevation &cur)
1034 -> HrtfStore::Elevation
1036 return HrtfStore::Elevation{cur.azCount,
1037 static_cast<ushort>(last.azCount + last.irOffset)};
1039 const auto irTotal = static_cast<ushort>(elevs.back().azCount + elevs.back().irOffset);
1041 auto coeffs = al::vector<HrirArray>(irTotal, HrirArray{});
1042 auto delays = al::vector<ubyte2>(irTotal);
1043 if(channelType == ChanType_LeftOnly)
1045 for(auto &hrir : coeffs)
1047 for(auto &val : al::span<float2>{hrir.data(), irSize})
1048 val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
1050 for(auto &val : delays)
1051 val[0] = readle<uint8_t>(data);
1052 if(!data || data.eof())
1054 ERR("Failed reading %s\n", filename);
1055 return nullptr;
1057 for(size_t i{0};i < irTotal;++i)
1059 if(delays[i][0] > MaxHrirDelay<<HrirDelayFracBits)
1061 ERR("Invalid delays[%zu][0]: %f (%d)\n", i,
1062 delays[i][0] / float{HrirDelayFracOne}, MaxHrirDelay);
1063 return nullptr;
1067 /* Mirror the left ear responses to the right ear. */
1068 MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
1070 else if(channelType == ChanType_LeftRight)
1072 for(auto &hrir : coeffs)
1074 for(auto &val : al::span<float2>{hrir.data(), irSize})
1076 val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
1077 val[1] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
1080 for(auto &val : delays)
1082 val[0] = readle<uint8_t>(data);
1083 val[1] = readle<uint8_t>(data);
1085 if(!data || data.eof())
1087 ERR("Failed reading %s\n", filename);
1088 return nullptr;
1091 for(size_t i{0};i < irTotal;++i)
1093 if(delays[i][0] > MaxHrirDelay<<HrirDelayFracBits)
1095 ERR("Invalid delays[%zu][0]: %f (%d)\n", i,
1096 delays[i][0] / float{HrirDelayFracOne}, MaxHrirDelay);
1097 return nullptr;
1099 if(delays[i][1] > MaxHrirDelay<<HrirDelayFracBits)
1101 ERR("Invalid delays[%zu][1]: %f (%d)\n", i,
1102 delays[i][1] / float{HrirDelayFracOne}, MaxHrirDelay);
1103 return nullptr;
1108 return CreateHrtfStore(rate, irSize, {fields.data(), fields.size()},
1109 {elevs.data(), elevs.size()}, coeffs.data(), delays.data(), filename);
1113 bool checkName(const std::string &name)
1115 auto match_name = [&name](const HrtfEntry &entry) -> bool { return name == entry.mDispName; };
1116 auto &enum_names = EnumeratedHrtfs;
1117 return std::find_if(enum_names.cbegin(), enum_names.cend(), match_name) != enum_names.cend();
1120 void AddFileEntry(const std::string &filename)
1122 /* Check if this file has already been enumerated. */
1123 auto enum_iter = std::find_if(EnumeratedHrtfs.cbegin(), EnumeratedHrtfs.cend(),
1124 [&filename](const HrtfEntry &entry) -> bool
1125 { return entry.mFilename == filename; });
1126 if(enum_iter != EnumeratedHrtfs.cend())
1128 TRACE("Skipping duplicate file entry %s\n", filename.c_str());
1129 return;
1132 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1133 * format update). */
1134 size_t namepos{filename.find_last_of('/')+1};
1135 if(!namepos) namepos = filename.find_last_of('\\')+1;
1137 size_t extpos{filename.find_last_of('.')};
1138 if(extpos <= namepos) extpos = std::string::npos;
1140 const std::string basename{(extpos == std::string::npos) ?
1141 filename.substr(namepos) : filename.substr(namepos, extpos-namepos)};
1142 std::string newname{basename};
1143 int count{1};
1144 while(checkName(newname))
1146 newname = basename;
1147 newname += " #";
1148 newname += std::to_string(++count);
1150 EnumeratedHrtfs.emplace_back(HrtfEntry{newname, filename});
1151 const HrtfEntry &entry = EnumeratedHrtfs.back();
1153 TRACE("Adding file entry \"%s\"\n", entry.mFilename.c_str());
1156 /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
1157 * for input instead of opening the given filename.
1159 void AddBuiltInEntry(const std::string &dispname, uint residx)
1161 const std::string filename{'!'+std::to_string(residx)+'_'+dispname};
1163 auto enum_iter = std::find_if(EnumeratedHrtfs.cbegin(), EnumeratedHrtfs.cend(),
1164 [&filename](const HrtfEntry &entry) -> bool
1165 { return entry.mFilename == filename; });
1166 if(enum_iter != EnumeratedHrtfs.cend())
1168 TRACE("Skipping duplicate file entry %s\n", filename.c_str());
1169 return;
1172 /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1173 * format update). */
1175 std::string newname{dispname};
1176 int count{1};
1177 while(checkName(newname))
1179 newname = dispname;
1180 newname += " #";
1181 newname += std::to_string(++count);
1183 EnumeratedHrtfs.emplace_back(HrtfEntry{newname, filename});
1184 const HrtfEntry &entry = EnumeratedHrtfs.back();
1186 TRACE("Adding built-in entry \"%s\"\n", entry.mFilename.c_str());
1190 #define IDR_DEFAULT_HRTF_MHR 1
1192 #ifndef ALSOFT_EMBED_HRTF_DATA
1194 al::span<const char> GetResource(int /*name*/)
1195 { return {}; }
1197 #else
1199 #include "hrtf_default.h"
1201 al::span<const char> GetResource(int name)
1203 if(name == IDR_DEFAULT_HRTF_MHR)
1204 return {reinterpret_cast<const char*>(hrtf_default), sizeof(hrtf_default)};
1205 return {};
1207 #endif
1209 } // namespace
1212 al::vector<std::string> EnumerateHrtf(al::optional<std::string> pathopt)
1214 std::lock_guard<std::mutex> _{EnumeratedHrtfLock};
1215 EnumeratedHrtfs.clear();
1217 bool usedefaults{true};
1218 if(pathopt)
1220 const char *pathlist{pathopt->c_str()};
1221 while(pathlist && *pathlist)
1223 const char *next, *end;
1225 while(isspace(*pathlist) || *pathlist == ',')
1226 pathlist++;
1227 if(*pathlist == '\0')
1228 continue;
1230 next = strchr(pathlist, ',');
1231 if(next)
1232 end = next++;
1233 else
1235 end = pathlist + strlen(pathlist);
1236 usedefaults = false;
1239 while(end != pathlist && isspace(*(end-1)))
1240 --end;
1241 if(end != pathlist)
1243 const std::string pname{pathlist, end};
1244 for(const auto &fname : SearchDataFiles(".mhr", pname.c_str()))
1245 AddFileEntry(fname);
1248 pathlist = next;
1252 if(usedefaults)
1254 for(const auto &fname : SearchDataFiles(".mhr", "openal/hrtf"))
1255 AddFileEntry(fname);
1257 if(!GetResource(IDR_DEFAULT_HRTF_MHR).empty())
1258 AddBuiltInEntry("Built-In HRTF", IDR_DEFAULT_HRTF_MHR);
1261 al::vector<std::string> list;
1262 list.reserve(EnumeratedHrtfs.size());
1263 for(auto &entry : EnumeratedHrtfs)
1264 list.emplace_back(entry.mDispName);
1266 return list;
1269 HrtfStorePtr GetLoadedHrtf(const std::string &name, const uint devrate)
1271 std::lock_guard<std::mutex> _{EnumeratedHrtfLock};
1272 auto entry_iter = std::find_if(EnumeratedHrtfs.cbegin(), EnumeratedHrtfs.cend(),
1273 [&name](const HrtfEntry &entry) -> bool { return entry.mDispName == name; });
1274 if(entry_iter == EnumeratedHrtfs.cend())
1275 return nullptr;
1276 const std::string &fname = entry_iter->mFilename;
1278 std::lock_guard<std::mutex> __{LoadedHrtfLock};
1279 auto hrtf_lt_fname = [](LoadedHrtf &hrtf, const std::string &filename) -> bool
1280 { return hrtf.mFilename < filename; };
1281 auto handle = std::lower_bound(LoadedHrtfs.begin(), LoadedHrtfs.end(), fname, hrtf_lt_fname);
1282 while(handle != LoadedHrtfs.end() && handle->mFilename == fname)
1284 HrtfStore *hrtf{handle->mEntry.get()};
1285 if(hrtf && hrtf->sampleRate == devrate)
1287 hrtf->add_ref();
1288 return HrtfStorePtr{hrtf};
1290 ++handle;
1293 std::unique_ptr<std::istream> stream;
1294 int residx{};
1295 char ch{};
1296 if(sscanf(fname.c_str(), "!%d%c", &residx, &ch) == 2 && ch == '_')
1298 TRACE("Loading %s...\n", fname.c_str());
1299 al::span<const char> res{GetResource(residx)};
1300 if(res.empty())
1302 ERR("Could not get resource %u, %s\n", residx, name.c_str());
1303 return nullptr;
1305 stream = std::make_unique<idstream>(res.begin(), res.end());
1307 else
1309 TRACE("Loading %s...\n", fname.c_str());
1310 auto fstr = std::make_unique<al::ifstream>(fname.c_str(), std::ios::binary);
1311 if(!fstr->is_open())
1313 ERR("Could not open %s\n", fname.c_str());
1314 return nullptr;
1316 stream = std::move(fstr);
1319 std::unique_ptr<HrtfStore> hrtf;
1320 char magic[sizeof(magicMarker03)];
1321 stream->read(magic, sizeof(magic));
1322 if(stream->gcount() < static_cast<std::streamsize>(sizeof(magicMarker03)))
1323 ERR("%s data is too short (%zu bytes)\n", name.c_str(), stream->gcount());
1324 else if(memcmp(magic, magicMarker03, sizeof(magicMarker03)) == 0)
1326 TRACE("Detected data set format v3\n");
1327 hrtf = LoadHrtf03(*stream, name.c_str());
1329 else if(memcmp(magic, magicMarker02, sizeof(magicMarker02)) == 0)
1331 TRACE("Detected data set format v2\n");
1332 hrtf = LoadHrtf02(*stream, name.c_str());
1334 else if(memcmp(magic, magicMarker01, sizeof(magicMarker01)) == 0)
1336 TRACE("Detected data set format v1\n");
1337 hrtf = LoadHrtf01(*stream, name.c_str());
1339 else if(memcmp(magic, magicMarker00, sizeof(magicMarker00)) == 0)
1341 TRACE("Detected data set format v0\n");
1342 hrtf = LoadHrtf00(*stream, name.c_str());
1344 else
1345 ERR("Invalid header in %s: \"%.8s\"\n", name.c_str(), magic);
1346 stream.reset();
1348 if(!hrtf)
1350 ERR("Failed to load %s\n", name.c_str());
1351 return nullptr;
1354 if(hrtf->sampleRate != devrate)
1356 TRACE("Resampling HRTF %s (%uhz -> %uhz)\n", name.c_str(), hrtf->sampleRate, devrate);
1358 /* Calculate the last elevation's index and get the total IR count. */
1359 const size_t lastEv{std::accumulate(hrtf->field, hrtf->field+hrtf->fdCount, size_t{0},
1360 [](const size_t curval, const HrtfStore::Field &field) noexcept -> size_t
1361 { return curval + field.evCount; }
1362 ) - 1};
1363 const size_t irCount{size_t{hrtf->elev[lastEv].irOffset} + hrtf->elev[lastEv].azCount};
1365 /* Resample all the IRs. */
1366 std::array<std::array<double,HrirLength>,2> inout;
1367 PPhaseResampler rs;
1368 rs.init(hrtf->sampleRate, devrate);
1369 for(size_t i{0};i < irCount;++i)
1371 HrirArray &coeffs = const_cast<HrirArray&>(hrtf->coeffs[i]);
1372 for(size_t j{0};j < 2;++j)
1374 std::transform(coeffs.cbegin(), coeffs.cend(), inout[0].begin(),
1375 [j](const float2 &in) noexcept -> double { return in[j]; });
1376 rs.process(HrirLength, inout[0].data(), HrirLength, inout[1].data());
1377 for(size_t k{0};k < HrirLength;++k)
1378 coeffs[k][j] = static_cast<float>(inout[1][k]);
1381 rs = {};
1383 /* Scale the delays for the new sample rate. */
1384 float max_delay{0.0f};
1385 auto new_delays = al::vector<float2>(irCount);
1386 const float rate_scale{static_cast<float>(devrate)/static_cast<float>(hrtf->sampleRate)};
1387 for(size_t i{0};i < irCount;++i)
1389 for(size_t j{0};j < 2;++j)
1391 const float new_delay{std::round(hrtf->delays[i][j] * rate_scale) /
1392 float{HrirDelayFracOne}};
1393 max_delay = maxf(max_delay, new_delay);
1394 new_delays[i][j] = new_delay;
1398 /* If the new delays exceed the max, scale it down to fit (essentially
1399 * shrinking the head radius; not ideal but better than a per-delay
1400 * clamp).
1402 float delay_scale{HrirDelayFracOne};
1403 if(max_delay > MaxHrirDelay)
1405 WARN("Resampled delay exceeds max (%.2f > %d)\n", max_delay, MaxHrirDelay);
1406 delay_scale *= float{MaxHrirDelay} / max_delay;
1409 for(size_t i{0};i < irCount;++i)
1411 ubyte2 &delays = const_cast<ubyte2&>(hrtf->delays[i]);
1412 for(size_t j{0};j < 2;++j)
1413 delays[j] = static_cast<ubyte>(float2int(new_delays[i][j]*delay_scale + 0.5f));
1416 /* Scale the IR size for the new sample rate and update the stored
1417 * sample rate.
1419 const float newIrSize{std::round(static_cast<float>(hrtf->irSize) * rate_scale)};
1420 hrtf->irSize = static_cast<uint>(minf(HrirLength, newIrSize));
1421 hrtf->sampleRate = devrate;
1424 TRACE("Loaded HRTF %s for sample rate %uhz, %u-sample filter\n", name.c_str(),
1425 hrtf->sampleRate, hrtf->irSize);
1426 handle = LoadedHrtfs.emplace(handle, LoadedHrtf{fname, std::move(hrtf)});
1428 return HrtfStorePtr{handle->mEntry.get()};
1432 void HrtfStore::add_ref()
1434 auto ref = IncrementRef(mRef);
1435 TRACE("HrtfStore %p increasing refcount to %u\n", decltype(std::declval<void*>()){this}, ref);
1438 void HrtfStore::release()
1440 auto ref = DecrementRef(mRef);
1441 TRACE("HrtfStore %p decreasing refcount to %u\n", decltype(std::declval<void*>()){this}, ref);
1442 if(ref == 0)
1444 std::lock_guard<std::mutex> _{LoadedHrtfLock};
1446 /* Go through and remove all unused HRTFs. */
1447 auto remove_unused = [](LoadedHrtf &hrtf) -> bool
1449 HrtfStore *entry{hrtf.mEntry.get()};
1450 if(entry && ReadRef(entry->mRef) == 0)
1452 TRACE("Unloading unused HRTF %s\n", hrtf.mFilename.data());
1453 hrtf.mEntry = nullptr;
1454 return true;
1456 return false;
1458 auto iter = std::remove_if(LoadedHrtfs.begin(), LoadedHrtfs.end(), remove_unused);
1459 LoadedHrtfs.erase(iter, LoadedHrtfs.end());