hrtf.cpp 50 KB

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