1 /**
2  * OpenAL cross platform audio library
3  * Copyright (C) 2011 by Chris Robinson
4  * This library is free software; you can redistribute it and/or
5  *  modify it under the terms of the GNU Library General Public
6  *  License as published by the Free Software Foundation; either
7  *  version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  *  Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  *  License along with this library; if not, write to the
16  *  Free Software Foundation, Inc.,
17  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  * Or go to http://www.gnu.org/copyleft/lgpl.html
19  */
20 
21 #include "config.h"
22 
23 #include "hrtf.h"
24 
25 #include <algorithm>
26 #include <array>
27 #include <cassert>
28 #include <cctype>
29 #include <cmath>
30 #include <cstdint>
31 #include <cstdio>
32 #include <cstring>
33 #include <functional>
34 #include <fstream>
35 #include <iterator>
36 #include <memory>
37 #include <mutex>
38 #include <new>
39 #include <numeric>
40 #include <type_traits>
41 #include <utility>
42 
43 #include "albit.h"
44 #include "albyte.h"
45 #include "alcmain.h"
46 #include "alconfig.h"
47 #include "alfstream.h"
48 #include "almalloc.h"
49 #include "alnumeric.h"
50 #include "aloptional.h"
51 #include "alspan.h"
52 #include "core/filters/splitter.h"
53 #include "core/logging.h"
54 #include "math_defs.h"
55 #include "opthelpers.h"
56 #include "polyphase_resampler.h"
57 
58 
59 namespace {
60 
61 using namespace std::placeholders;
62 
63 struct HrtfEntry {
64     std::string mDispName;
65     std::string mFilename;
66 };
67 
68 struct LoadedHrtf {
69     std::string mFilename;
70     std::unique_ptr<HrtfStore> mEntry;
71 };
72 
73 /* Data set limits must be the same as or more flexible than those defined in
74  * the makemhr utility.
75  */
76 constexpr uint MinFdCount{1};
77 constexpr uint MaxFdCount{16};
78 
79 constexpr uint MinFdDistance{50};
80 constexpr uint MaxFdDistance{2500};
81 
82 constexpr uint MinEvCount{5};
83 constexpr uint MaxEvCount{181};
84 
85 constexpr uint MinAzCount{1};
86 constexpr uint MaxAzCount{255};
87 
88 constexpr uint MaxHrirDelay{HrtfHistoryLength - 1};
89 
90 constexpr uint HrirDelayFracBits{2};
91 constexpr uint HrirDelayFracOne{1 << HrirDelayFracBits};
92 constexpr uint HrirDelayFracHalf{HrirDelayFracOne >> 1};
93 
94 static_assert(MaxHrirDelay*HrirDelayFracOne < 256, "MAX_HRIR_DELAY or DELAY_FRAC too large");
95 
96 constexpr char magicMarker00[8]{'M','i','n','P','H','R','0','0'};
97 constexpr char magicMarker01[8]{'M','i','n','P','H','R','0','1'};
98 constexpr char magicMarker02[8]{'M','i','n','P','H','R','0','2'};
99 constexpr char magicMarker03[8]{'M','i','n','P','H','R','0','3'};
100 
101 /* First value for pass-through coefficients (remaining are 0), used for omni-
102  * directional sounds. */
103 constexpr float PassthruCoeff{0.707106781187f/*sqrt(0.5)*/};
104 
105 std::mutex LoadedHrtfLock;
106 al::vector<LoadedHrtf> LoadedHrtfs;
107 
108 std::mutex EnumeratedHrtfLock;
109 al::vector<HrtfEntry> EnumeratedHrtfs;
110 
111 
112 class databuf final : public std::streambuf {
underflow()113     int_type underflow() override
114     { return traits_type::eof(); }
115 
seekoff(off_type offset,std::ios_base::seekdir whence,std::ios_base::openmode mode)116     pos_type seekoff(off_type offset, std::ios_base::seekdir whence, std::ios_base::openmode mode) override
117     {
118         if((mode&std::ios_base::out) || !(mode&std::ios_base::in))
119             return traits_type::eof();
120 
121         char_type *cur;
122         switch(whence)
123         {
124             case std::ios_base::beg:
125                 if(offset < 0 || offset > egptr()-eback())
126                     return traits_type::eof();
127                 cur = eback() + offset;
128                 break;
129 
130             case std::ios_base::cur:
131                 if((offset >= 0 && offset > egptr()-gptr()) ||
132                    (offset < 0 && -offset > gptr()-eback()))
133                     return traits_type::eof();
134                 cur = gptr() + offset;
135                 break;
136 
137             case std::ios_base::end:
138                 if(offset > 0 || -offset > egptr()-eback())
139                     return traits_type::eof();
140                 cur = egptr() + offset;
141                 break;
142 
143             default:
144                 return traits_type::eof();
145         }
146 
147         setg(eback(), cur, egptr());
148         return cur - eback();
149     }
150 
seekpos(pos_type pos,std::ios_base::openmode mode)151     pos_type seekpos(pos_type pos, std::ios_base::openmode mode) override
152     {
153         // Simplified version of seekoff
154         if((mode&std::ios_base::out) || !(mode&std::ios_base::in))
155             return traits_type::eof();
156 
157         if(pos < 0 || pos > egptr()-eback())
158             return traits_type::eof();
159 
160         setg(eback(), eback() + static_cast<size_t>(pos), egptr());
161         return pos;
162     }
163 
164 public:
databuf(const char_type * start_,const char_type * end_)165     databuf(const char_type *start_, const char_type *end_) noexcept
166     {
167         setg(const_cast<char_type*>(start_), const_cast<char_type*>(start_),
168              const_cast<char_type*>(end_));
169     }
170 };
171 
172 class idstream final : public std::istream {
173     databuf mStreamBuf;
174 
175 public:
idstream(const char * start_,const char * end_)176     idstream(const char *start_, const char *end_)
177       : std::istream{nullptr}, mStreamBuf{start_, end_}
178     { init(&mStreamBuf); }
179 };
180 
181 
182 struct IdxBlend { uint idx; float blend; };
183 /* Calculate the elevation index given the polar elevation in radians. This
184  * will return an index between 0 and (evcount - 1).
185  */
CalcEvIndex(uint evcount,float ev)186 IdxBlend CalcEvIndex(uint evcount, float ev)
187 {
188     ev = (al::MathDefs<float>::Pi()*0.5f + ev) * static_cast<float>(evcount-1) /
189         al::MathDefs<float>::Pi();
190     uint idx{float2uint(ev)};
191 
192     return IdxBlend{minu(idx, evcount-1), ev-static_cast<float>(idx)};
193 }
194 
195 /* Calculate the azimuth index given the polar azimuth in radians. This will
196  * return an index between 0 and (azcount - 1).
197  */
CalcAzIndex(uint azcount,float az)198 IdxBlend CalcAzIndex(uint azcount, float az)
199 {
200     az = (al::MathDefs<float>::Tau()+az) * static_cast<float>(azcount) /
201         al::MathDefs<float>::Tau();
202     uint idx{float2uint(az)};
203 
204     return IdxBlend{idx%azcount, az-static_cast<float>(idx)};
205 }
206 
207 } // namespace
208 
209 
210 /* Calculates static HRIR coefficients and delays for the given polar elevation
211  * and azimuth in radians. The coefficients are normalized.
212  */
GetHrtfCoeffs(const HrtfStore * Hrtf,float elevation,float azimuth,float distance,float spread,HrirArray & coeffs,const al::span<uint,2> delays)213 void GetHrtfCoeffs(const HrtfStore *Hrtf, float elevation, float azimuth, float distance,
214     float spread, HrirArray &coeffs, const al::span<uint,2> delays)
215 {
216     const float dirfact{1.0f - (spread / al::MathDefs<float>::Tau())};
217 
218     const auto *field = Hrtf->field;
219     const auto *field_end = field + Hrtf->fdCount-1;
220     size_t ebase{0};
221     while(distance < field->distance && field != field_end)
222     {
223         ebase += field->evCount;
224         ++field;
225     }
226 
227     /* Calculate the elevation indices. */
228     const auto elev0 = CalcEvIndex(field->evCount, elevation);
229     const size_t elev1_idx{minu(elev0.idx+1, field->evCount-1)};
230     const size_t ir0offset{Hrtf->elev[ebase + elev0.idx].irOffset};
231     const size_t ir1offset{Hrtf->elev[ebase + elev1_idx].irOffset};
232 
233     /* Calculate azimuth indices. */
234     const auto az0 = CalcAzIndex(Hrtf->elev[ebase + elev0.idx].azCount, azimuth);
235     const auto az1 = CalcAzIndex(Hrtf->elev[ebase + elev1_idx].azCount, azimuth);
236 
237     /* Calculate the HRIR indices to blend. */
238     const size_t idx[4]{
239         ir0offset + az0.idx,
240         ir0offset + ((az0.idx+1) % Hrtf->elev[ebase + elev0.idx].azCount),
241         ir1offset + az1.idx,
242         ir1offset + ((az1.idx+1) % Hrtf->elev[ebase + elev1_idx].azCount)
243     };
244 
245     /* Calculate bilinear blending weights, attenuated according to the
246      * directional panning factor.
247      */
248     const float blend[4]{
249         (1.0f-elev0.blend) * (1.0f-az0.blend) * dirfact,
250         (1.0f-elev0.blend) * (     az0.blend) * dirfact,
251         (     elev0.blend) * (1.0f-az1.blend) * dirfact,
252         (     elev0.blend) * (     az1.blend) * dirfact
253     };
254 
255     /* Calculate the blended HRIR delays. */
256     float d{Hrtf->delays[idx[0]][0]*blend[0] + Hrtf->delays[idx[1]][0]*blend[1] +
257         Hrtf->delays[idx[2]][0]*blend[2] + Hrtf->delays[idx[3]][0]*blend[3]};
258     delays[0] = fastf2u(d * float{1.0f/HrirDelayFracOne});
259     d = Hrtf->delays[idx[0]][1]*blend[0] + Hrtf->delays[idx[1]][1]*blend[1] +
260         Hrtf->delays[idx[2]][1]*blend[2] + Hrtf->delays[idx[3]][1]*blend[3];
261     delays[1] = fastf2u(d * float{1.0f/HrirDelayFracOne});
262 
263     /* Calculate the blended HRIR coefficients. */
264     float *coeffout{al::assume_aligned<16>(&coeffs[0][0])};
265     coeffout[0] = PassthruCoeff * (1.0f-dirfact);
266     coeffout[1] = PassthruCoeff * (1.0f-dirfact);
267     std::fill_n(coeffout+2, size_t{HrirLength-1}*2, 0.0f);
268     for(size_t c{0};c < 4;c++)
269     {
270         const float *srccoeffs{al::assume_aligned<16>(Hrtf->coeffs[idx[c]][0].data())};
271         const float mult{blend[c]};
272         auto blend_coeffs = [mult](const float src, const float coeff) noexcept -> float
273         { return src*mult + coeff; };
274         std::transform(srccoeffs, srccoeffs + HrirLength*2, coeffout, coeffout, blend_coeffs);
275     }
276 }
277 
278 
Create(size_t num_chans)279 std::unique_ptr<DirectHrtfState> DirectHrtfState::Create(size_t num_chans)
280 { return std::unique_ptr<DirectHrtfState>{new(FamCount(num_chans)) DirectHrtfState{num_chans}}; }
281 
build(const HrtfStore * Hrtf,const uint irSize,const al::span<const AngularPoint> AmbiPoints,const float (* AmbiMatrix)[MaxAmbiChannels],const float XOverFreq,const al::span<const float,MaxAmbiOrder+1> AmbiOrderHFGain)282 void DirectHrtfState::build(const HrtfStore *Hrtf, const uint irSize,
283     const al::span<const AngularPoint> AmbiPoints, const float (*AmbiMatrix)[MaxAmbiChannels],
284     const float XOverFreq, const al::span<const float,MaxAmbiOrder+1> AmbiOrderHFGain)
285 {
286     using double2 = std::array<double,2>;
287     struct ImpulseResponse {
288         const HrirArray &hrir;
289         uint ldelay, rdelay;
290     };
291 
292     const double xover_norm{double{XOverFreq} / Hrtf->sampleRate};
293     for(size_t i{0};i < mChannels.size();++i)
294     {
295         const size_t order{AmbiIndex::OrderFromChannel()[i]};
296         mChannels[i].mSplitter.init(static_cast<float>(xover_norm));
297         mChannels[i].mHfScale = AmbiOrderHFGain[order];
298     }
299 
300     uint min_delay{HrtfHistoryLength*HrirDelayFracOne}, max_delay{0};
301     al::vector<ImpulseResponse> impres; impres.reserve(AmbiPoints.size());
302     auto calc_res = [Hrtf,&max_delay,&min_delay](const AngularPoint &pt) -> ImpulseResponse
303     {
304         auto &field = Hrtf->field[0];
305         const auto elev0 = CalcEvIndex(field.evCount, pt.Elev.value);
306         const size_t elev1_idx{minu(elev0.idx+1, field.evCount-1)};
307         const size_t ir0offset{Hrtf->elev[elev0.idx].irOffset};
308         const size_t ir1offset{Hrtf->elev[elev1_idx].irOffset};
309 
310         const auto az0 = CalcAzIndex(Hrtf->elev[elev0.idx].azCount, pt.Azim.value);
311         const auto az1 = CalcAzIndex(Hrtf->elev[elev1_idx].azCount, pt.Azim.value);
312 
313         const size_t idx[4]{
314             ir0offset + az0.idx,
315             ir0offset + ((az0.idx+1) % Hrtf->elev[elev0.idx].azCount),
316             ir1offset + az1.idx,
317             ir1offset + ((az1.idx+1) % Hrtf->elev[elev1_idx].azCount)
318         };
319 
320         const std::array<double,4> blend{{
321             (1.0-elev0.blend) * (1.0-az0.blend),
322             (1.0-elev0.blend) * (    az0.blend),
323             (    elev0.blend) * (1.0-az1.blend),
324             (    elev0.blend) * (    az1.blend)
325         }};
326 
327         /* The largest blend factor serves as the closest HRIR. */
328         const size_t irOffset{idx[std::max_element(blend.begin(), blend.end()) - blend.begin()]};
329         ImpulseResponse res{Hrtf->coeffs[irOffset],
330             Hrtf->delays[irOffset][0], Hrtf->delays[irOffset][1]};
331 
332         min_delay = minu(min_delay, minu(res.ldelay, res.rdelay));
333         max_delay = maxu(max_delay, maxu(res.ldelay, res.rdelay));
334 
335         return res;
336     };
337     std::transform(AmbiPoints.begin(), AmbiPoints.end(), std::back_inserter(impres), calc_res);
338     auto hrir_delay_round = [](const uint d) noexcept -> uint
339     { return (d+HrirDelayFracHalf) >> HrirDelayFracBits; };
340 
341     auto tmpres = al::vector<std::array<double2,HrirLength>>(mChannels.size());
342     for(size_t c{0u};c < AmbiPoints.size();++c)
343     {
344         const HrirArray &hrir{impres[c].hrir};
345         const uint ldelay{hrir_delay_round(impres[c].ldelay - min_delay)};
346         const uint rdelay{hrir_delay_round(impres[c].rdelay - min_delay)};
347 
348         for(size_t i{0u};i < mChannels.size();++i)
349         {
350             const double mult{AmbiMatrix[c][i]};
351             const size_t numirs{HrirLength - maxz(ldelay, rdelay)};
352             size_t lidx{ldelay}, ridx{rdelay};
353             for(size_t j{0};j < numirs;++j)
354             {
355                 tmpres[i][lidx++][0] += hrir[j][0] * mult;
356                 tmpres[i][ridx++][1] += hrir[j][1] * mult;
357             }
358         }
359     }
360     impres.clear();
361 
362     for(size_t i{0u};i < mChannels.size();++i)
363     {
364         auto copy_arr = [](const double2 &in) noexcept -> float2
365         { return float2{{static_cast<float>(in[0]), static_cast<float>(in[1])}}; };
366         std::transform(tmpres[i].cbegin(), tmpres[i].cend(), mChannels[i].mCoeffs.begin(),
367             copy_arr);
368     }
369     tmpres.clear();
370 
371     max_delay -= min_delay;
372     const uint max_length{minu(hrir_delay_round(max_delay) + irSize, HrirLength)};
373 
374     TRACE("Skipped delay: %.2f, new max delay: %.2f, FIR length: %u\n",
375         min_delay/double{HrirDelayFracOne}, max_delay/double{HrirDelayFracOne},
376         max_length);
377     mIrSize = max_length;
378 }
379 
380 
381 namespace {
382 
CreateHrtfStore(uint rate,ushort irSize,const al::span<const HrtfStore::Field> fields,const al::span<const HrtfStore::Elevation> elevs,const HrirArray * coeffs,const ubyte2 * delays,const char * filename)383 std::unique_ptr<HrtfStore> CreateHrtfStore(uint rate, ushort irSize,
384     const al::span<const HrtfStore::Field> fields,
385     const al::span<const HrtfStore::Elevation> elevs, const HrirArray *coeffs,
386     const ubyte2 *delays, const char *filename)
387 {
388     std::unique_ptr<HrtfStore> Hrtf;
389 
390     const size_t irCount{size_t{elevs.back().azCount} + elevs.back().irOffset};
391     size_t total{sizeof(HrtfStore)};
392     total  = RoundUp(total, alignof(HrtfStore::Field)); /* Align for field infos */
393     total += sizeof(HrtfStore::Field)*fields.size();
394     total  = RoundUp(total, alignof(HrtfStore::Elevation)); /* Align for elevation infos */
395     total += sizeof(Hrtf->elev[0])*elevs.size();
396     total  = RoundUp(total, 16); /* Align for coefficients using SIMD */
397     total += sizeof(Hrtf->coeffs[0])*irCount;
398     total += sizeof(Hrtf->delays[0])*irCount;
399 
400     Hrtf.reset(new (al_calloc(16, total)) HrtfStore{});
401     if(!Hrtf)
402         ERR("Out of memory allocating storage for %s.\n", filename);
403     else
404     {
405         InitRef(Hrtf->mRef, 1u);
406         Hrtf->sampleRate = rate;
407         Hrtf->irSize = irSize;
408         Hrtf->fdCount = static_cast<uint>(fields.size());
409 
410         /* Set up pointers to storage following the main HRTF struct. */
411         char *base = reinterpret_cast<char*>(Hrtf.get());
412         size_t offset{sizeof(HrtfStore)};
413 
414         offset = RoundUp(offset, alignof(HrtfStore::Field)); /* Align for field infos */
415         auto field_ = reinterpret_cast<HrtfStore::Field*>(base + offset);
416         offset += sizeof(field_[0])*fields.size();
417 
418         offset = RoundUp(offset, alignof(HrtfStore::Elevation)); /* Align for elevation infos */
419         auto elev_ = reinterpret_cast<HrtfStore::Elevation*>(base + offset);
420         offset += sizeof(elev_[0])*elevs.size();
421 
422         offset = RoundUp(offset, 16); /* Align for coefficients using SIMD */
423         auto coeffs_ = reinterpret_cast<HrirArray*>(base + offset);
424         offset += sizeof(coeffs_[0])*irCount;
425 
426         auto delays_ = reinterpret_cast<ubyte2*>(base + offset);
427         offset += sizeof(delays_[0])*irCount;
428 
429         assert(offset == total);
430 
431         /* Copy input data to storage. */
432         std::copy(fields.cbegin(), fields.cend(), field_);
433         std::copy(elevs.cbegin(), elevs.cend(), elev_);
434         std::copy_n(coeffs, irCount, coeffs_);
435         std::copy_n(delays, irCount, delays_);
436 
437         /* Finally, assign the storage pointers. */
438         Hrtf->field = field_;
439         Hrtf->elev = elev_;
440         Hrtf->coeffs = coeffs_;
441         Hrtf->delays = delays_;
442     }
443 
444     return Hrtf;
445 }
446 
MirrorLeftHrirs(const al::span<const HrtfStore::Elevation> elevs,HrirArray * coeffs,ubyte2 * delays)447 void MirrorLeftHrirs(const al::span<const HrtfStore::Elevation> elevs, HrirArray *coeffs,
448     ubyte2 *delays)
449 {
450     for(const auto &elev : elevs)
451     {
452         const ushort evoffset{elev.irOffset};
453         const ushort azcount{elev.azCount};
454         for(size_t j{0};j < azcount;j++)
455         {
456             const size_t lidx{evoffset + j};
457             const size_t ridx{evoffset + ((azcount-j) % azcount)};
458 
459             const size_t irSize{coeffs[ridx].size()};
460             for(size_t k{0};k < irSize;k++)
461                 coeffs[ridx][k][1] = coeffs[lidx][k][0];
462             delays[ridx][1] = delays[lidx][0];
463         }
464     }
465 }
466 
467 
468 template<typename T, size_t num_bits=sizeof(T)*8>
readle(std::istream & data)469 inline T readle(std::istream &data)
470 {
471     static_assert((num_bits&7) == 0, "num_bits must be a multiple of 8");
472     static_assert(num_bits <= sizeof(T)*8, "num_bits is too large for the type");
473 
474     T ret{};
475     if_constexpr(al::endian::native == al::endian::little)
476     {
477         if(!data.read(reinterpret_cast<char*>(&ret), num_bits/8))
478             return static_cast<T>(EOF);
479     }
480     else
481     {
482         al::byte b[sizeof(T)]{};
483         if(!data.read(reinterpret_cast<char*>(b), num_bits/8))
484             return static_cast<T>(EOF);
485         std::reverse_copy(std::begin(b), std::end(b), reinterpret_cast<al::byte*>(&ret));
486     }
487 
488     if_constexpr(std::is_signed<T>::value && num_bits < sizeof(T)*8)
489     {
490         constexpr auto signbit = static_cast<T>(1u << (num_bits-1));
491         return static_cast<T>((ret^signbit) - signbit);
492     }
493     return ret;
494 }
495 
496 template<>
readle(std::istream & data)497 inline uint8_t readle<uint8_t,8>(std::istream &data)
498 { return static_cast<uint8_t>(data.get()); }
499 
500 
LoadHrtf00(std::istream & data,const char * filename)501 std::unique_ptr<HrtfStore> LoadHrtf00(std::istream &data, const char *filename)
502 {
503     uint rate{readle<uint32_t>(data)};
504     ushort irCount{readle<uint16_t>(data)};
505     ushort irSize{readle<uint16_t>(data)};
506     ubyte evCount{readle<uint8_t>(data)};
507     if(!data || data.eof())
508     {
509         ERR("Failed reading %s\n", filename);
510         return nullptr;
511     }
512 
513     if(irSize < MinIrLength || irSize > HrirLength)
514     {
515         ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
516         return nullptr;
517     }
518     if(evCount < MinEvCount || evCount > MaxEvCount)
519     {
520         ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
521             evCount, MinEvCount, MaxEvCount);
522         return nullptr;
523     }
524 
525     auto elevs = al::vector<HrtfStore::Elevation>(evCount);
526     for(auto &elev : elevs)
527         elev.irOffset = readle<uint16_t>(data);
528     if(!data || data.eof())
529     {
530         ERR("Failed reading %s\n", filename);
531         return nullptr;
532     }
533     for(size_t i{1};i < evCount;i++)
534     {
535         if(elevs[i].irOffset <= elevs[i-1].irOffset)
536         {
537             ERR("Invalid evOffset: evOffset[%zu]=%d (last=%d)\n", i, elevs[i].irOffset,
538                 elevs[i-1].irOffset);
539             return nullptr;
540         }
541     }
542     if(irCount <= elevs.back().irOffset)
543     {
544         ERR("Invalid evOffset: evOffset[%zu]=%d (irCount=%d)\n",
545             elevs.size()-1, elevs.back().irOffset, irCount);
546         return nullptr;
547     }
548 
549     for(size_t i{1};i < evCount;i++)
550     {
551         elevs[i-1].azCount = static_cast<ushort>(elevs[i].irOffset - elevs[i-1].irOffset);
552         if(elevs[i-1].azCount < MinAzCount || elevs[i-1].azCount > MaxAzCount)
553         {
554             ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n",
555                 i-1, elevs[i-1].azCount, MinAzCount, MaxAzCount);
556             return nullptr;
557         }
558     }
559     elevs.back().azCount = static_cast<ushort>(irCount - elevs.back().irOffset);
560     if(elevs.back().azCount < MinAzCount || elevs.back().azCount > MaxAzCount)
561     {
562         ERR("Unsupported azimuth count: azCount[%zu]=%d (%d to %d)\n",
563             elevs.size()-1, elevs.back().azCount, MinAzCount, MaxAzCount);
564         return nullptr;
565     }
566 
567     auto coeffs = al::vector<HrirArray>(irCount, HrirArray{});
568     auto delays = al::vector<ubyte2>(irCount);
569     for(auto &hrir : coeffs)
570     {
571         for(auto &val : al::span<float2>{hrir.data(), irSize})
572             val[0] = readle<int16_t>(data) / 32768.0f;
573     }
574     for(auto &val : delays)
575         val[0] = readle<uint8_t>(data);
576     if(!data || data.eof())
577     {
578         ERR("Failed reading %s\n", filename);
579         return nullptr;
580     }
581     for(size_t i{0};i < irCount;i++)
582     {
583         if(delays[i][0] > MaxHrirDelay)
584         {
585             ERR("Invalid delays[%zd]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
586             return nullptr;
587         }
588         delays[i][0] <<= HrirDelayFracBits;
589     }
590 
591     /* Mirror the left ear responses to the right ear. */
592     MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
593 
594     const HrtfStore::Field field[1]{{0.0f, evCount}};
595     return CreateHrtfStore(rate, irSize, field, {elevs.data(), elevs.size()}, coeffs.data(),
596         delays.data(), filename);
597 }
598 
LoadHrtf01(std::istream & data,const char * filename)599 std::unique_ptr<HrtfStore> LoadHrtf01(std::istream &data, const char *filename)
600 {
601     uint rate{readle<uint32_t>(data)};
602     ushort irSize{readle<uint8_t>(data)};
603     ubyte evCount{readle<uint8_t>(data)};
604     if(!data || data.eof())
605     {
606         ERR("Failed reading %s\n", filename);
607         return nullptr;
608     }
609 
610     if(irSize < MinIrLength || irSize > HrirLength)
611     {
612         ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
613         return nullptr;
614     }
615     if(evCount < MinEvCount || evCount > MaxEvCount)
616     {
617         ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
618             evCount, MinEvCount, MaxEvCount);
619         return nullptr;
620     }
621 
622     auto elevs = al::vector<HrtfStore::Elevation>(evCount);
623     for(auto &elev : elevs)
624         elev.azCount = readle<uint8_t>(data);
625     if(!data || data.eof())
626     {
627         ERR("Failed reading %s\n", filename);
628         return nullptr;
629     }
630     for(size_t i{0};i < evCount;++i)
631     {
632         if(elevs[i].azCount < MinAzCount || elevs[i].azCount > MaxAzCount)
633         {
634             ERR("Unsupported azimuth count: azCount[%zd]=%d (%d to %d)\n", i, elevs[i].azCount,
635                 MinAzCount, MaxAzCount);
636             return nullptr;
637         }
638     }
639 
640     elevs[0].irOffset = 0;
641     for(size_t i{1};i < evCount;i++)
642         elevs[i].irOffset = static_cast<ushort>(elevs[i-1].irOffset + elevs[i-1].azCount);
643     const ushort irCount{static_cast<ushort>(elevs.back().irOffset + elevs.back().azCount)};
644 
645     auto coeffs = al::vector<HrirArray>(irCount, HrirArray{});
646     auto delays = al::vector<ubyte2>(irCount);
647     for(auto &hrir : coeffs)
648     {
649         for(auto &val : al::span<float2>{hrir.data(), irSize})
650             val[0] = readle<int16_t>(data) / 32768.0f;
651     }
652     for(auto &val : delays)
653         val[0] = readle<uint8_t>(data);
654     if(!data || data.eof())
655     {
656         ERR("Failed reading %s\n", filename);
657         return nullptr;
658     }
659     for(size_t i{0};i < irCount;i++)
660     {
661         if(delays[i][0] > MaxHrirDelay)
662         {
663             ERR("Invalid delays[%zd]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
664             return nullptr;
665         }
666         delays[i][0] <<= HrirDelayFracBits;
667     }
668 
669     /* Mirror the left ear responses to the right ear. */
670     MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
671 
672     const HrtfStore::Field field[1]{{0.0f, evCount}};
673     return CreateHrtfStore(rate, irSize, field, {elevs.data(), elevs.size()}, coeffs.data(),
674         delays.data(), filename);
675 }
676 
LoadHrtf02(std::istream & data,const char * filename)677 std::unique_ptr<HrtfStore> LoadHrtf02(std::istream &data, const char *filename)
678 {
679     constexpr ubyte SampleType_S16{0};
680     constexpr ubyte SampleType_S24{1};
681     constexpr ubyte ChanType_LeftOnly{0};
682     constexpr ubyte ChanType_LeftRight{1};
683 
684     uint rate{readle<uint32_t>(data)};
685     ubyte sampleType{readle<uint8_t>(data)};
686     ubyte channelType{readle<uint8_t>(data)};
687     ushort irSize{readle<uint8_t>(data)};
688     ubyte fdCount{readle<uint8_t>(data)};
689     if(!data || data.eof())
690     {
691         ERR("Failed reading %s\n", filename);
692         return nullptr;
693     }
694 
695     if(sampleType > SampleType_S24)
696     {
697         ERR("Unsupported sample type: %d\n", sampleType);
698         return nullptr;
699     }
700     if(channelType > ChanType_LeftRight)
701     {
702         ERR("Unsupported channel type: %d\n", channelType);
703         return nullptr;
704     }
705 
706     if(irSize < MinIrLength || irSize > HrirLength)
707     {
708         ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
709         return nullptr;
710     }
711     if(fdCount < 1 || fdCount > MaxFdCount)
712     {
713         ERR("Unsupported number of field-depths: fdCount=%d (%d to %d)\n", fdCount, MinFdCount,
714             MaxFdCount);
715         return nullptr;
716     }
717 
718     auto fields = al::vector<HrtfStore::Field>(fdCount);
719     auto elevs = al::vector<HrtfStore::Elevation>{};
720     for(size_t f{0};f < fdCount;f++)
721     {
722         const ushort distance{readle<uint16_t>(data)};
723         const ubyte evCount{readle<uint8_t>(data)};
724         if(!data || data.eof())
725         {
726             ERR("Failed reading %s\n", filename);
727             return nullptr;
728         }
729 
730         if(distance < MinFdDistance || distance > MaxFdDistance)
731         {
732             ERR("Unsupported field distance[%zu]=%d (%d to %d millimeters)\n", f, distance,
733                 MinFdDistance, MaxFdDistance);
734             return nullptr;
735         }
736         if(evCount < MinEvCount || evCount > MaxEvCount)
737         {
738             ERR("Unsupported elevation count: evCount[%zu]=%d (%d to %d)\n", f, evCount,
739                 MinEvCount, MaxEvCount);
740             return nullptr;
741         }
742 
743         fields[f].distance = distance / 1000.0f;
744         fields[f].evCount = evCount;
745         if(f > 0 && fields[f].distance <= fields[f-1].distance)
746         {
747             ERR("Field distance[%zu] is not after previous (%f > %f)\n", f, fields[f].distance,
748                 fields[f-1].distance);
749             return nullptr;
750         }
751 
752         const size_t ebase{elevs.size()};
753         elevs.resize(ebase + evCount);
754         for(auto &elev : al::span<HrtfStore::Elevation>(elevs.data()+ebase, evCount))
755             elev.azCount = readle<uint8_t>(data);
756         if(!data || data.eof())
757         {
758             ERR("Failed reading %s\n", filename);
759             return nullptr;
760         }
761 
762         for(size_t e{0};e < evCount;e++)
763         {
764             if(elevs[ebase+e].azCount < MinAzCount || elevs[ebase+e].azCount > MaxAzCount)
765             {
766                 ERR("Unsupported azimuth count: azCount[%zu][%zu]=%d (%d to %d)\n", f, e,
767                     elevs[ebase+e].azCount, MinAzCount, MaxAzCount);
768                 return nullptr;
769             }
770         }
771     }
772 
773     elevs[0].irOffset = 0;
774     std::partial_sum(elevs.cbegin(), elevs.cend(), elevs.begin(),
775         [](const HrtfStore::Elevation &last, const HrtfStore::Elevation &cur)
776             -> HrtfStore::Elevation
777         {
778             return HrtfStore::Elevation{cur.azCount,
779                 static_cast<ushort>(last.azCount + last.irOffset)};
780         });
781     const auto irTotal = static_cast<ushort>(elevs.back().azCount + elevs.back().irOffset);
782 
783     auto coeffs = al::vector<HrirArray>(irTotal, HrirArray{});
784     auto delays = al::vector<ubyte2>(irTotal);
785     if(channelType == ChanType_LeftOnly)
786     {
787         if(sampleType == SampleType_S16)
788         {
789             for(auto &hrir : coeffs)
790             {
791                 for(auto &val : al::span<float2>{hrir.data(), irSize})
792                     val[0] = readle<int16_t>(data) / 32768.0f;
793             }
794         }
795         else if(sampleType == SampleType_S24)
796         {
797             for(auto &hrir : coeffs)
798             {
799                 for(auto &val : al::span<float2>{hrir.data(), irSize})
800                     val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
801             }
802         }
803         for(auto &val : delays)
804             val[0] = readle<uint8_t>(data);
805         if(!data || data.eof())
806         {
807             ERR("Failed reading %s\n", filename);
808             return nullptr;
809         }
810         for(size_t i{0};i < irTotal;++i)
811         {
812             if(delays[i][0] > MaxHrirDelay)
813             {
814                 ERR("Invalid delays[%zu][0]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
815                 return nullptr;
816             }
817             delays[i][0] <<= HrirDelayFracBits;
818         }
819 
820         /* Mirror the left ear responses to the right ear. */
821         MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
822     }
823     else if(channelType == ChanType_LeftRight)
824     {
825         if(sampleType == SampleType_S16)
826         {
827             for(auto &hrir : coeffs)
828             {
829                 for(auto &val : al::span<float2>{hrir.data(), irSize})
830                 {
831                     val[0] = readle<int16_t>(data) / 32768.0f;
832                     val[1] = readle<int16_t>(data) / 32768.0f;
833                 }
834             }
835         }
836         else if(sampleType == SampleType_S24)
837         {
838             for(auto &hrir : coeffs)
839             {
840                 for(auto &val : al::span<float2>{hrir.data(), irSize})
841                 {
842                     val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
843                     val[1] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
844                 }
845             }
846         }
847         for(auto &val : delays)
848         {
849             val[0] = readle<uint8_t>(data);
850             val[1] = readle<uint8_t>(data);
851         }
852         if(!data || data.eof())
853         {
854             ERR("Failed reading %s\n", filename);
855             return nullptr;
856         }
857 
858         for(size_t i{0};i < irTotal;++i)
859         {
860             if(delays[i][0] > MaxHrirDelay)
861             {
862                 ERR("Invalid delays[%zu][0]: %d (%d)\n", i, delays[i][0], MaxHrirDelay);
863                 return nullptr;
864             }
865             if(delays[i][1] > MaxHrirDelay)
866             {
867                 ERR("Invalid delays[%zu][1]: %d (%d)\n", i, delays[i][1], MaxHrirDelay);
868                 return nullptr;
869             }
870             delays[i][0] <<= HrirDelayFracBits;
871             delays[i][1] <<= HrirDelayFracBits;
872         }
873     }
874 
875     if(fdCount > 1)
876     {
877         auto fields_ = al::vector<HrtfStore::Field>(fields.size());
878         auto elevs_ = al::vector<HrtfStore::Elevation>(elevs.size());
879         auto coeffs_ = al::vector<HrirArray>(coeffs.size());
880         auto delays_ = al::vector<ubyte2>(delays.size());
881 
882         /* Simple reverse for the per-field elements. */
883         std::reverse_copy(fields.cbegin(), fields.cend(), fields_.begin());
884 
885         /* Each field has a group of elevations, which each have an azimuth
886          * count. Reverse the order of the groups, keeping the relative order
887          * of per-group azimuth counts.
888          */
889         auto elevs__end = elevs_.end();
890         auto copy_azs = [&elevs,&elevs__end](const ptrdiff_t ebase, const HrtfStore::Field &field)
891             -> ptrdiff_t
892         {
893             auto elevs_src = elevs.begin()+ebase;
894             elevs__end = std::copy_backward(elevs_src, elevs_src+field.evCount, elevs__end);
895             return ebase + field.evCount;
896         };
897         (void)std::accumulate(fields.cbegin(), fields.cend(), ptrdiff_t{0}, copy_azs);
898         assert(elevs_.begin() == elevs__end);
899 
900         /* Reestablish the IR offset for each elevation index, given the new
901          * ordering of elevations.
902          */
903         elevs_[0].irOffset = 0;
904         std::partial_sum(elevs_.cbegin(), elevs_.cend(), elevs_.begin(),
905             [](const HrtfStore::Elevation &last, const HrtfStore::Elevation &cur)
906                 -> HrtfStore::Elevation
907             {
908                 return HrtfStore::Elevation{cur.azCount,
909                     static_cast<ushort>(last.azCount + last.irOffset)};
910             });
911 
912         /* Reverse the order of each field's group of IRs. */
913         auto coeffs_end = coeffs_.end();
914         auto delays_end = delays_.end();
915         auto copy_irs = [&elevs,&coeffs,&delays,&coeffs_end,&delays_end](
916             const ptrdiff_t ebase, const HrtfStore::Field &field) -> ptrdiff_t
917         {
918             auto accum_az = [](int count, const HrtfStore::Elevation &elev) noexcept -> int
919             { return count + elev.azCount; };
920             const auto elevs_mid = elevs.cbegin() + ebase;
921             const auto elevs_end = elevs_mid + field.evCount;
922             const int abase{std::accumulate(elevs.cbegin(), elevs_mid, 0, accum_az)};
923             const int num_azs{std::accumulate(elevs_mid, elevs_end, 0, accum_az)};
924 
925             coeffs_end = std::copy_backward(coeffs.cbegin() + abase,
926                 coeffs.cbegin() + (abase+num_azs), coeffs_end);
927             delays_end = std::copy_backward(delays.cbegin() + abase,
928                 delays.cbegin() + (abase+num_azs), delays_end);
929 
930             return ebase + field.evCount;
931         };
932         (void)std::accumulate(fields.cbegin(), fields.cend(), ptrdiff_t{0}, copy_irs);
933         assert(coeffs_.begin() == coeffs_end);
934         assert(delays_.begin() == delays_end);
935 
936         fields = std::move(fields_);
937         elevs = std::move(elevs_);
938         coeffs = std::move(coeffs_);
939         delays = std::move(delays_);
940     }
941 
942     return CreateHrtfStore(rate, irSize, {fields.data(), fields.size()},
943         {elevs.data(), elevs.size()}, coeffs.data(), delays.data(), filename);
944 }
945 
LoadHrtf03(std::istream & data,const char * filename)946 std::unique_ptr<HrtfStore> LoadHrtf03(std::istream &data, const char *filename)
947 {
948     constexpr ubyte ChanType_LeftOnly{0};
949     constexpr ubyte ChanType_LeftRight{1};
950 
951     uint rate{readle<uint32_t>(data)};
952     ubyte channelType{readle<uint8_t>(data)};
953     ushort irSize{readle<uint8_t>(data)};
954     ubyte fdCount{readle<uint8_t>(data)};
955     if(!data || data.eof())
956     {
957         ERR("Failed reading %s\n", filename);
958         return nullptr;
959     }
960 
961     if(channelType > ChanType_LeftRight)
962     {
963         ERR("Unsupported channel type: %d\n", channelType);
964         return nullptr;
965     }
966 
967     if(irSize < MinIrLength || irSize > HrirLength)
968     {
969         ERR("Unsupported HRIR size, irSize=%d (%d to %d)\n", irSize, MinIrLength, HrirLength);
970         return nullptr;
971     }
972     if(fdCount < 1 || fdCount > MaxFdCount)
973     {
974         ERR("Unsupported number of field-depths: fdCount=%d (%d to %d)\n", fdCount, MinFdCount,
975             MaxFdCount);
976         return nullptr;
977     }
978 
979     auto fields = al::vector<HrtfStore::Field>(fdCount);
980     auto elevs = al::vector<HrtfStore::Elevation>{};
981     for(size_t f{0};f < fdCount;f++)
982     {
983         const ushort distance{readle<uint16_t>(data)};
984         const ubyte evCount{readle<uint8_t>(data)};
985         if(!data || data.eof())
986         {
987             ERR("Failed reading %s\n", filename);
988             return nullptr;
989         }
990 
991         if(distance < MinFdDistance || distance > MaxFdDistance)
992         {
993             ERR("Unsupported field distance[%zu]=%d (%d to %d millimeters)\n", f, distance,
994                 MinFdDistance, MaxFdDistance);
995             return nullptr;
996         }
997         if(evCount < MinEvCount || evCount > MaxEvCount)
998         {
999             ERR("Unsupported elevation count: evCount[%zu]=%d (%d to %d)\n", f, evCount,
1000                 MinEvCount, MaxEvCount);
1001             return nullptr;
1002         }
1003 
1004         fields[f].distance = distance / 1000.0f;
1005         fields[f].evCount = evCount;
1006         if(f > 0 && fields[f].distance > fields[f-1].distance)
1007         {
1008             ERR("Field distance[%zu] is not before previous (%f <= %f)\n", f, fields[f].distance,
1009                 fields[f-1].distance);
1010             return nullptr;
1011         }
1012 
1013         const size_t ebase{elevs.size()};
1014         elevs.resize(ebase + evCount);
1015         for(auto &elev : al::span<HrtfStore::Elevation>(elevs.data()+ebase, evCount))
1016             elev.azCount = readle<uint8_t>(data);
1017         if(!data || data.eof())
1018         {
1019             ERR("Failed reading %s\n", filename);
1020             return nullptr;
1021         }
1022 
1023         for(size_t e{0};e < evCount;e++)
1024         {
1025             if(elevs[ebase+e].azCount < MinAzCount || elevs[ebase+e].azCount > MaxAzCount)
1026             {
1027                 ERR("Unsupported azimuth count: azCount[%zu][%zu]=%d (%d to %d)\n", f, e,
1028                     elevs[ebase+e].azCount, MinAzCount, MaxAzCount);
1029                 return nullptr;
1030             }
1031         }
1032     }
1033 
1034     elevs[0].irOffset = 0;
1035     std::partial_sum(elevs.cbegin(), elevs.cend(), elevs.begin(),
1036         [](const HrtfStore::Elevation &last, const HrtfStore::Elevation &cur)
1037             -> HrtfStore::Elevation
1038         {
1039             return HrtfStore::Elevation{cur.azCount,
1040                 static_cast<ushort>(last.azCount + last.irOffset)};
1041         });
1042     const auto irTotal = static_cast<ushort>(elevs.back().azCount + elevs.back().irOffset);
1043 
1044     auto coeffs = al::vector<HrirArray>(irTotal, HrirArray{});
1045     auto delays = al::vector<ubyte2>(irTotal);
1046     if(channelType == ChanType_LeftOnly)
1047     {
1048         for(auto &hrir : coeffs)
1049         {
1050             for(auto &val : al::span<float2>{hrir.data(), irSize})
1051                 val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
1052         }
1053         for(auto &val : delays)
1054             val[0] = readle<uint8_t>(data);
1055         if(!data || data.eof())
1056         {
1057             ERR("Failed reading %s\n", filename);
1058             return nullptr;
1059         }
1060         for(size_t i{0};i < irTotal;++i)
1061         {
1062             if(delays[i][0] > MaxHrirDelay<<HrirDelayFracBits)
1063             {
1064                 ERR("Invalid delays[%zu][0]: %f (%d)\n", i,
1065                     delays[i][0] / float{HrirDelayFracOne}, MaxHrirDelay);
1066                 return nullptr;
1067             }
1068         }
1069 
1070         /* Mirror the left ear responses to the right ear. */
1071         MirrorLeftHrirs({elevs.data(), elevs.size()}, coeffs.data(), delays.data());
1072     }
1073     else if(channelType == ChanType_LeftRight)
1074     {
1075         for(auto &hrir : coeffs)
1076         {
1077             for(auto &val : al::span<float2>{hrir.data(), irSize})
1078             {
1079                 val[0] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
1080                 val[1] = static_cast<float>(readle<int,24>(data)) / 8388608.0f;
1081             }
1082         }
1083         for(auto &val : delays)
1084         {
1085             val[0] = readle<uint8_t>(data);
1086             val[1] = readle<uint8_t>(data);
1087         }
1088         if(!data || data.eof())
1089         {
1090             ERR("Failed reading %s\n", filename);
1091             return nullptr;
1092         }
1093 
1094         for(size_t i{0};i < irTotal;++i)
1095         {
1096             if(delays[i][0] > MaxHrirDelay<<HrirDelayFracBits)
1097             {
1098                 ERR("Invalid delays[%zu][0]: %f (%d)\n", i,
1099                     delays[i][0] / float{HrirDelayFracOne}, MaxHrirDelay);
1100                 return nullptr;
1101             }
1102             if(delays[i][1] > MaxHrirDelay<<HrirDelayFracBits)
1103             {
1104                 ERR("Invalid delays[%zu][1]: %f (%d)\n", i,
1105                     delays[i][1] / float{HrirDelayFracOne}, MaxHrirDelay);
1106                 return nullptr;
1107             }
1108         }
1109     }
1110 
1111     return CreateHrtfStore(rate, irSize, {fields.data(), fields.size()},
1112         {elevs.data(), elevs.size()}, coeffs.data(), delays.data(), filename);
1113 }
1114 
1115 
checkName(const std::string & name)1116 bool checkName(const std::string &name)
1117 {
1118     auto match_name = [&name](const HrtfEntry &entry) -> bool { return name == entry.mDispName; };
1119     auto &enum_names = EnumeratedHrtfs;
1120     return std::find_if(enum_names.cbegin(), enum_names.cend(), match_name) != enum_names.cend();
1121 }
1122 
AddFileEntry(const std::string & filename)1123 void AddFileEntry(const std::string &filename)
1124 {
1125     /* Check if this file has already been enumerated. */
1126     auto enum_iter = std::find_if(EnumeratedHrtfs.cbegin(), EnumeratedHrtfs.cend(),
1127         [&filename](const HrtfEntry &entry) -> bool
1128         { return entry.mFilename == filename; });
1129     if(enum_iter != EnumeratedHrtfs.cend())
1130     {
1131         TRACE("Skipping duplicate file entry %s\n", filename.c_str());
1132         return;
1133     }
1134 
1135     /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1136      * format update). */
1137     size_t namepos{filename.find_last_of('/')+1};
1138     if(!namepos) namepos = filename.find_last_of('\\')+1;
1139 
1140     size_t extpos{filename.find_last_of('.')};
1141     if(extpos <= namepos) extpos = std::string::npos;
1142 
1143     const std::string basename{(extpos == std::string::npos) ?
1144         filename.substr(namepos) : filename.substr(namepos, extpos-namepos)};
1145     std::string newname{basename};
1146     int count{1};
1147     while(checkName(newname))
1148     {
1149         newname = basename;
1150         newname += " #";
1151         newname += std::to_string(++count);
1152     }
1153     EnumeratedHrtfs.emplace_back(HrtfEntry{newname, filename});
1154     const HrtfEntry &entry = EnumeratedHrtfs.back();
1155 
1156     TRACE("Adding file entry \"%s\"\n", entry.mFilename.c_str());
1157 }
1158 
1159 /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
1160  * for input instead of opening the given filename.
1161  */
AddBuiltInEntry(const std::string & dispname,uint residx)1162 void AddBuiltInEntry(const std::string &dispname, uint residx)
1163 {
1164     const std::string filename{'!'+std::to_string(residx)+'_'+dispname};
1165 
1166     auto enum_iter = std::find_if(EnumeratedHrtfs.cbegin(), EnumeratedHrtfs.cend(),
1167         [&filename](const HrtfEntry &entry) -> bool
1168         { return entry.mFilename == filename; });
1169     if(enum_iter != EnumeratedHrtfs.cend())
1170     {
1171         TRACE("Skipping duplicate file entry %s\n", filename.c_str());
1172         return;
1173     }
1174 
1175     /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
1176      * format update). */
1177 
1178     std::string newname{dispname};
1179     int count{1};
1180     while(checkName(newname))
1181     {
1182         newname = dispname;
1183         newname += " #";
1184         newname += std::to_string(++count);
1185     }
1186     EnumeratedHrtfs.emplace_back(HrtfEntry{newname, filename});
1187     const HrtfEntry &entry = EnumeratedHrtfs.back();
1188 
1189     TRACE("Adding built-in entry \"%s\"\n", entry.mFilename.c_str());
1190 }
1191 
1192 
1193 #define IDR_DEFAULT_HRTF_MHR 1
1194 
1195 #ifndef ALSOFT_EMBED_HRTF_DATA
1196 
GetResource(int)1197 al::span<const char> GetResource(int /*name*/)
1198 { return {}; }
1199 
1200 #else
1201 
1202 #include "hrtf_default.h"
1203 
GetResource(int name)1204 al::span<const char> GetResource(int name)
1205 {
1206     if(name == IDR_DEFAULT_HRTF_MHR)
1207         return {reinterpret_cast<const char*>(hrtf_default), sizeof(hrtf_default)};
1208     return {};
1209 }
1210 #endif
1211 
1212 } // namespace
1213 
1214 
EnumerateHrtf(const char * devname)1215 al::vector<std::string> EnumerateHrtf(const char *devname)
1216 {
1217     std::lock_guard<std::mutex> _{EnumeratedHrtfLock};
1218     EnumeratedHrtfs.clear();
1219 
1220     bool usedefaults{true};
1221     if(auto pathopt = ConfigValueStr(devname, nullptr, "hrtf-paths"))
1222     {
1223         const char *pathlist{pathopt->c_str()};
1224         while(pathlist && *pathlist)
1225         {
1226             const char *next, *end;
1227 
1228             while(isspace(*pathlist) || *pathlist == ',')
1229                 pathlist++;
1230             if(*pathlist == '\0')
1231                 continue;
1232 
1233             next = strchr(pathlist, ',');
1234             if(next)
1235                 end = next++;
1236             else
1237             {
1238                 end = pathlist + strlen(pathlist);
1239                 usedefaults = false;
1240             }
1241 
1242             while(end != pathlist && isspace(*(end-1)))
1243                 --end;
1244             if(end != pathlist)
1245             {
1246                 const std::string pname{pathlist, end};
1247                 for(const auto &fname : SearchDataFiles(".mhr", pname.c_str()))
1248                     AddFileEntry(fname);
1249             }
1250 
1251             pathlist = next;
1252         }
1253     }
1254 
1255     if(usedefaults)
1256     {
1257         for(const auto &fname : SearchDataFiles(".mhr", "openal/hrtf"))
1258             AddFileEntry(fname);
1259 
1260         if(!GetResource(IDR_DEFAULT_HRTF_MHR).empty())
1261             AddBuiltInEntry("Built-In HRTF", IDR_DEFAULT_HRTF_MHR);
1262     }
1263 
1264     al::vector<std::string> list;
1265     list.reserve(EnumeratedHrtfs.size());
1266     for(auto &entry : EnumeratedHrtfs)
1267         list.emplace_back(entry.mDispName);
1268 
1269     if(auto defhrtfopt = ConfigValueStr(devname, nullptr, "default-hrtf"))
1270     {
1271         auto iter = std::find(list.begin(), list.end(), *defhrtfopt);
1272         if(iter == list.end())
1273             WARN("Failed to find default HRTF \"%s\"\n", defhrtfopt->c_str());
1274         else if(iter != list.begin())
1275             std::rotate(list.begin(), iter, iter+1);
1276     }
1277 
1278     return list;
1279 }
1280 
GetLoadedHrtf(const std::string & name,const uint devrate)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->sampleRate == 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->sampleRate != devrate)
1367     {
1368         TRACE("Resampling HRTF %s (%uhz -> %uhz)\n", name.c_str(), hrtf->sampleRate, devrate);
1369 
1370         /* Calculate the last elevation's index and get the total IR count. */
1371         const size_t lastEv{std::accumulate(hrtf->field, hrtf->field+hrtf->fdCount, 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->elev[lastEv].irOffset} + hrtf->elev[lastEv].azCount};
1376 
1377         /* Resample all the IRs. */
1378         std::array<std::array<double,HrirLength>,2> inout;
1379         PPhaseResampler rs;
1380         rs.init(hrtf->sampleRate, devrate);
1381         for(size_t i{0};i < irCount;++i)
1382         {
1383             HrirArray &coeffs = const_cast<HrirArray&>(hrtf->coeffs[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->sampleRate)};
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->delays[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->delays[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->irSize) * rate_scale)};
1432         hrtf->irSize = static_cast<uint>(minf(HrirLength, newIrSize));
1433         hrtf->sampleRate = devrate;
1434     }
1435 
1436     TRACE("Loaded HRTF %s for sample rate %uhz, %u-sample filter\n", name.c_str(),
1437         hrtf->sampleRate, hrtf->irSize);
1438     handle = LoadedHrtfs.emplace(handle, LoadedHrtf{fname, std::move(hrtf)});
1439 
1440     return HrtfStorePtr{handle->mEntry.get()};
1441 }
1442 
1443 
add_ref()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 
release()1450 void HrtfStore::release()
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 }
1474