hrtf.cpp 51 KB

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