🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1394 lines
46 KiB

  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 <stdlib.h>
  22. #include <ctype.h>
  23. #include <mutex>
  24. #include <array>
  25. #include <vector>
  26. #include <memory>
  27. #include <istream>
  28. #include <numeric>
  29. #include <algorithm>
  30. #include <functional>
  31. #include "AL/al.h"
  32. #include "AL/alc.h"
  33. #include "alMain.h"
  34. #include "alSource.h"
  35. #include "alu.h"
  36. #include "hrtf.h"
  37. #include "alconfig.h"
  38. #include "filters/splitter.h"
  39. #include "compat.h"
  40. #include "almalloc.h"
  41. #include "alspan.h"
  42. struct HrtfHandle {
  43. std::unique_ptr<HrtfEntry> entry;
  44. al::FlexArray<char> filename;
  45. HrtfHandle(size_t fname_len) : filename{fname_len} { }
  46. HrtfHandle(const HrtfHandle&) = delete;
  47. HrtfHandle& operator=(const HrtfHandle&) = delete;
  48. static std::unique_ptr<HrtfHandle> Create(size_t fname_len);
  49. static constexpr size_t Sizeof(size_t length) noexcept
  50. {
  51. return maxz(sizeof(HrtfHandle),
  52. al::FlexArray<char>::Sizeof(length, offsetof(HrtfHandle, filename)));
  53. }
  54. DEF_PLACE_NEWDEL()
  55. };
  56. std::unique_ptr<HrtfHandle> HrtfHandle::Create(size_t fname_len)
  57. {
  58. void *ptr{al_calloc(DEF_ALIGN, HrtfHandle::Sizeof(fname_len))};
  59. return std::unique_ptr<HrtfHandle>{new (ptr) HrtfHandle{fname_len}};
  60. }
  61. namespace {
  62. using namespace std::placeholders;
  63. using HrtfHandlePtr = std::unique_ptr<HrtfHandle>;
  64. /* Data set limits must be the same as or more flexible than those defined in
  65. * the makemhr utility.
  66. */
  67. #define MIN_IR_SIZE (8)
  68. #define MAX_IR_SIZE (512)
  69. #define MOD_IR_SIZE (2)
  70. #define MIN_FD_COUNT (1)
  71. #define MAX_FD_COUNT (16)
  72. #define MIN_FD_DISTANCE (0.05f)
  73. #define MAX_FD_DISTANCE (2.5f)
  74. #define MIN_EV_COUNT (5)
  75. #define MAX_EV_COUNT (128)
  76. #define MIN_AZ_COUNT (1)
  77. #define MAX_AZ_COUNT (128)
  78. #define MAX_HRIR_DELAY (HRTF_HISTORY_LENGTH-1)
  79. constexpr ALchar magicMarker00[8]{'M','i','n','P','H','R','0','0'};
  80. constexpr ALchar magicMarker01[8]{'M','i','n','P','H','R','0','1'};
  81. constexpr ALchar magicMarker02[8]{'M','i','n','P','H','R','0','2'};
  82. /* First value for pass-through coefficients (remaining are 0), used for omni-
  83. * directional sounds. */
  84. constexpr ALfloat PassthruCoeff{0.707106781187f/*sqrt(0.5)*/};
  85. std::mutex LoadedHrtfLock;
  86. al::vector<HrtfHandlePtr> LoadedHrtfs;
  87. class databuf final : public std::streambuf {
  88. int_type underflow() override
  89. { return traits_type::eof(); }
  90. pos_type seekoff(off_type offset, std::ios_base::seekdir whence, std::ios_base::openmode mode) override
  91. {
  92. if((mode&std::ios_base::out) || !(mode&std::ios_base::in))
  93. return traits_type::eof();
  94. char_type *cur;
  95. switch(whence)
  96. {
  97. case std::ios_base::beg:
  98. if(offset < 0 || offset > egptr()-eback())
  99. return traits_type::eof();
  100. cur = eback() + offset;
  101. break;
  102. case std::ios_base::cur:
  103. if((offset >= 0 && offset > egptr()-gptr()) ||
  104. (offset < 0 && -offset > gptr()-eback()))
  105. return traits_type::eof();
  106. cur = gptr() + offset;
  107. break;
  108. case std::ios_base::end:
  109. if(offset > 0 || -offset > egptr()-eback())
  110. return traits_type::eof();
  111. cur = egptr() + offset;
  112. break;
  113. default:
  114. return traits_type::eof();
  115. }
  116. setg(eback(), cur, egptr());
  117. return cur - eback();
  118. }
  119. pos_type seekpos(pos_type pos, std::ios_base::openmode mode) override
  120. {
  121. // Simplified version of seekoff
  122. if((mode&std::ios_base::out) || !(mode&std::ios_base::in))
  123. return traits_type::eof();
  124. if(pos < 0 || pos > egptr()-eback())
  125. return traits_type::eof();
  126. setg(eback(), eback() + static_cast<size_t>(pos), egptr());
  127. return pos;
  128. }
  129. public:
  130. databuf(const char_type *start, const char_type *end) noexcept
  131. {
  132. setg(const_cast<char_type*>(start), const_cast<char_type*>(start),
  133. const_cast<char_type*>(end));
  134. }
  135. };
  136. class idstream final : public std::istream {
  137. databuf mStreamBuf;
  138. public:
  139. idstream(const char *start, const char *end)
  140. : std::istream{nullptr}, mStreamBuf{start, end}
  141. { init(&mStreamBuf); }
  142. };
  143. struct IdxBlend { ALsizei idx; ALfloat blend; };
  144. /* Calculate the elevation index given the polar elevation in radians. This
  145. * will return an index between 0 and (evcount - 1).
  146. */
  147. IdxBlend CalcEvIndex(ALsizei evcount, ALfloat ev)
  148. {
  149. ev = (al::MathDefs<float>::Pi()*0.5f + ev) * (evcount-1) / al::MathDefs<float>::Pi();
  150. ALsizei idx{float2int(ev)};
  151. return IdxBlend{mini(idx, evcount-1), ev-idx};
  152. }
  153. /* Calculate the azimuth index given the polar azimuth in radians. This will
  154. * return an index between 0 and (azcount - 1).
  155. */
  156. IdxBlend CalcAzIndex(ALsizei azcount, ALfloat az)
  157. {
  158. az = (al::MathDefs<float>::Tau()+az) * azcount / al::MathDefs<float>::Tau();
  159. ALsizei idx{float2int(az)};
  160. return IdxBlend{idx%azcount, az-idx};
  161. }
  162. } // namespace
  163. /* Calculates static HRIR coefficients and delays for the given polar elevation
  164. * and azimuth in radians. The coefficients are normalized.
  165. */
  166. void GetHrtfCoeffs(const HrtfEntry *Hrtf, ALfloat elevation, ALfloat azimuth, ALfloat distance,
  167. ALfloat spread, HrirArray<ALfloat> &coeffs, ALsizei (&delays)[2])
  168. {
  169. const ALfloat dirfact{1.0f - (spread / al::MathDefs<float>::Tau())};
  170. const auto *field = Hrtf->field;
  171. const auto *field_end = field + Hrtf->fdCount-1;
  172. ALsizei ebase{0};
  173. while(distance < field->distance && field != field_end)
  174. {
  175. ebase += field->evCount;
  176. ++field;
  177. }
  178. /* Claculate the elevation indinces. */
  179. const auto elev0 = CalcEvIndex(field->evCount, elevation);
  180. const ALsizei elev1_idx{mini(elev0.idx+1, field->evCount-1)};
  181. const ALsizei ir0offset{Hrtf->elev[ebase + elev0.idx].irOffset};
  182. const ALsizei ir1offset{Hrtf->elev[ebase + elev1_idx].irOffset};
  183. /* Calculate azimuth indices. */
  184. const auto az0 = CalcAzIndex(Hrtf->elev[ebase + elev0.idx].azCount, azimuth);
  185. const auto az1 = CalcAzIndex(Hrtf->elev[ebase + elev1_idx].azCount, azimuth);
  186. /* Calculate the HRIR indices to blend. */
  187. ALsizei idx[4]{
  188. ir0offset + az0.idx,
  189. ir0offset + ((az0.idx+1) % Hrtf->elev[ebase + elev0.idx].azCount),
  190. ir1offset + az1.idx,
  191. ir1offset + ((az1.idx+1) % Hrtf->elev[ebase + elev1_idx].azCount)
  192. };
  193. /* Calculate bilinear blending weights, attenuated according to the
  194. * directional panning factor.
  195. */
  196. const ALfloat blend[4]{
  197. (1.0f-elev0.blend) * (1.0f-az0.blend) * dirfact,
  198. (1.0f-elev0.blend) * ( az0.blend) * dirfact,
  199. ( elev0.blend) * (1.0f-az1.blend) * dirfact,
  200. ( elev0.blend) * ( az1.blend) * dirfact
  201. };
  202. /* Calculate the blended HRIR delays. */
  203. delays[0] = fastf2i(
  204. Hrtf->delays[idx[0]][0]*blend[0] + Hrtf->delays[idx[1]][0]*blend[1] +
  205. Hrtf->delays[idx[2]][0]*blend[2] + Hrtf->delays[idx[3]][0]*blend[3]
  206. );
  207. delays[1] = fastf2i(
  208. Hrtf->delays[idx[0]][1]*blend[0] + Hrtf->delays[idx[1]][1]*blend[1] +
  209. Hrtf->delays[idx[2]][1]*blend[2] + Hrtf->delays[idx[3]][1]*blend[3]
  210. );
  211. const ALsizei irSize{Hrtf->irSize};
  212. ASSUME(irSize >= MIN_IR_SIZE);
  213. /* Calculate the sample offsets for the HRIR indices. */
  214. idx[0] *= irSize;
  215. idx[1] *= irSize;
  216. idx[2] *= irSize;
  217. idx[3] *= irSize;
  218. /* Calculate the blended HRIR coefficients. */
  219. ALfloat *coeffout{al::assume_aligned<16>(&coeffs[0][0])};
  220. coeffout[0] = PassthruCoeff * (1.0f-dirfact);
  221. coeffout[1] = PassthruCoeff * (1.0f-dirfact);
  222. std::fill(coeffout+2, coeffout + irSize*2, 0.0f);
  223. for(ALsizei c{0};c < 4;c++)
  224. {
  225. const ALfloat *srccoeffs{al::assume_aligned<16>(Hrtf->coeffs[idx[c]])};
  226. const ALfloat mult{blend[c]};
  227. auto blend_coeffs = [mult](const ALfloat src, const ALfloat coeff) noexcept -> ALfloat
  228. { return src*mult + coeff; };
  229. std::transform<const ALfloat*RESTRICT>(srccoeffs, srccoeffs + irSize*2, coeffout,
  230. coeffout, blend_coeffs);
  231. }
  232. }
  233. std::unique_ptr<DirectHrtfState> DirectHrtfState::Create(size_t num_chans)
  234. {
  235. void *ptr{al_calloc(16, DirectHrtfState::Sizeof(num_chans))};
  236. return std::unique_ptr<DirectHrtfState>{new (ptr) DirectHrtfState{num_chans}};
  237. }
  238. void BuildBFormatHrtf(const HrtfEntry *Hrtf, DirectHrtfState *state, const ALsizei NumChannels, const AngularPoint *AmbiPoints, const ALfloat (*RESTRICT AmbiMatrix)[MAX_AMBI_CHANNELS], const size_t AmbiCount, const ALfloat *RESTRICT AmbiOrderHFGain)
  239. {
  240. static constexpr int OrderFromChan[MAX_AMBI_CHANNELS]{
  241. 0, 1,1,1, 2,2,2,2,2, 3,3,3,3,3,3,3,
  242. };
  243. /* Set this to true for dual-band HRTF processing. May require better
  244. * calculation of the new IR length to deal with the head and tail
  245. * generated by the HF scaling.
  246. */
  247. static constexpr bool DualBand{true};
  248. ASSUME(NumChannels > 0);
  249. ASSUME(AmbiCount > 0);
  250. auto &field = Hrtf->field[0];
  251. ALsizei min_delay{HRTF_HISTORY_LENGTH};
  252. ALsizei max_delay{0};
  253. auto idx = al::vector<ALsizei>(AmbiCount);
  254. auto calc_idxs = [Hrtf,&field,&max_delay,&min_delay](const AngularPoint &pt) noexcept -> ALsizei
  255. {
  256. /* Calculate elevation index. */
  257. const auto evidx = clampi(
  258. static_cast<ALsizei>((90.0f+pt.Elev)*(field.evCount-1)/180.0f + 0.5f),
  259. 0, field.evCount-1);
  260. const ALsizei azcount{Hrtf->elev[evidx].azCount};
  261. const ALsizei iroffset{Hrtf->elev[evidx].irOffset};
  262. /* Calculate azimuth index for this elevation. */
  263. const auto azidx = static_cast<ALsizei>((360.0f+pt.Azim)*azcount/360.0f + 0.5f) % azcount;
  264. /* Calculate the index for the impulse response. */
  265. ALsizei idx{iroffset + azidx};
  266. min_delay = mini(min_delay, mini(Hrtf->delays[idx][0], Hrtf->delays[idx][1]));
  267. max_delay = maxi(max_delay, maxi(Hrtf->delays[idx][0], Hrtf->delays[idx][1]));
  268. return idx;
  269. };
  270. std::transform(AmbiPoints, AmbiPoints+AmbiCount, idx.begin(), calc_idxs);
  271. /* For dual-band processing, add a 12-sample delay to compensate for the HF
  272. * scale on the minimum-phase response.
  273. */
  274. static constexpr ALsizei base_delay{DualBand ? 12 : 0};
  275. const ALdouble xover_norm{400.0 / Hrtf->sampleRate};
  276. BandSplitterR<double> splitter{xover_norm};
  277. SplitterAllpassR<double> allpass{xover_norm};
  278. auto tmpres = al::vector<HrirArray<ALdouble>>(NumChannels);
  279. auto tmpfilt = al::vector<std::array<ALdouble,HRIR_LENGTH*4>>(3);
  280. for(size_t c{0u};c < AmbiCount;++c)
  281. {
  282. const ALfloat (*fir)[2]{&Hrtf->coeffs[idx[c] * Hrtf->irSize]};
  283. const ALsizei ldelay{Hrtf->delays[idx[c]][0] - min_delay + base_delay};
  284. const ALsizei rdelay{Hrtf->delays[idx[c]][1] - min_delay + base_delay};
  285. if(!DualBand)
  286. {
  287. /* For single-band decoding, apply the HF scale to the response. */
  288. for(ALsizei i{0};i < NumChannels;++i)
  289. {
  290. const ALdouble mult{ALdouble{AmbiOrderHFGain[OrderFromChan[i]]} *
  291. AmbiMatrix[c][i]};
  292. const ALsizei numirs{mini(Hrtf->irSize, HRIR_LENGTH-maxi(ldelay, rdelay))};
  293. ALsizei lidx{ldelay}, ridx{rdelay};
  294. for(ALsizei j{0};j < numirs;++j)
  295. {
  296. tmpres[i][lidx++][0] += fir[j][0] * mult;
  297. tmpres[i][ridx++][1] += fir[j][1] * mult;
  298. }
  299. }
  300. continue;
  301. }
  302. /* For dual-band processing, the HRIR needs to be split into low and
  303. * high frequency responses. The band-splitter alone creates frequency-
  304. * dependent phase-shifts, which is not ideal. To counteract it,
  305. * combine it with a backwards phase-shift.
  306. */
  307. /* Load the (left) HRIR backwards, into a temp buffer with padding. */
  308. std::fill(tmpfilt[2].begin(), tmpfilt[2].end(), 0.0);
  309. std::transform(fir, fir+Hrtf->irSize, tmpfilt[2].rbegin() + HRIR_LENGTH*3,
  310. [](const ALfloat (&ir)[2]) noexcept -> ALdouble { return ir[0]; });
  311. /* Apply the all-pass on the reversed signal and reverse the resulting
  312. * sample array. This produces the forward response with a backwards
  313. * phase-shift (+n degrees becomes -n degrees).
  314. */
  315. allpass.clear();
  316. allpass.process(tmpfilt[2].data(), static_cast<int>(tmpfilt[2].size()));
  317. std::reverse(tmpfilt[2].begin(), tmpfilt[2].end());
  318. /* Now apply the band-splitter. This applies the normal phase-shift,
  319. * which cancels out with the backwards phase-shift to get the original
  320. * phase on the split signal.
  321. */
  322. splitter.clear();
  323. splitter.process(tmpfilt[0].data(), tmpfilt[1].data(), tmpfilt[2].data(),
  324. static_cast<int>(tmpfilt[2].size()));
  325. /* Apply left ear response with delay and HF scale. */
  326. for(ALsizei i{0};i < NumChannels;++i)
  327. {
  328. const ALdouble mult{AmbiMatrix[c][i]};
  329. const ALdouble hfgain{AmbiOrderHFGain[OrderFromChan[i]]};
  330. ALsizei j{HRIR_LENGTH*3 - ldelay};
  331. for(ALsizei lidx{0};lidx < HRIR_LENGTH;++lidx,++j)
  332. tmpres[i][lidx][0] += (tmpfilt[0][j]*hfgain + tmpfilt[1][j]) * mult;
  333. }
  334. /* Now run the same process on the right HRIR. */
  335. std::fill(tmpfilt[2].begin(), tmpfilt[2].end(), 0.0);
  336. std::transform(fir, fir+Hrtf->irSize, tmpfilt[2].rbegin() + HRIR_LENGTH*3,
  337. [](const ALfloat (&ir)[2]) noexcept -> ALdouble { return ir[1]; });
  338. allpass.clear();
  339. allpass.process(tmpfilt[2].data(), static_cast<int>(tmpfilt[2].size()));
  340. std::reverse(tmpfilt[2].begin(), tmpfilt[2].end());
  341. splitter.clear();
  342. splitter.process(tmpfilt[0].data(), tmpfilt[1].data(), tmpfilt[2].data(),
  343. static_cast<int>(tmpfilt[2].size()));
  344. for(ALsizei i{0};i < NumChannels;++i)
  345. {
  346. const ALdouble mult{AmbiMatrix[c][i]};
  347. const ALdouble hfgain{AmbiOrderHFGain[OrderFromChan[i]]};
  348. ALsizei j{HRIR_LENGTH*3 - rdelay};
  349. for(ALsizei ridx{0};ridx < HRIR_LENGTH;++ridx,++j)
  350. tmpres[i][ridx][1] += (tmpfilt[0][j]*hfgain + tmpfilt[1][j]) * mult;
  351. }
  352. }
  353. tmpfilt.clear();
  354. idx.clear();
  355. for(ALsizei i{0};i < NumChannels;++i)
  356. {
  357. auto copy_arr = [](const std::array<double,2> &in) noexcept -> std::array<float,2>
  358. { return std::array<float,2>{{static_cast<float>(in[0]), static_cast<float>(in[1])}}; };
  359. std::transform(tmpres[i].begin(), tmpres[i].end(), state->Chan[i].Coeffs.begin(),
  360. copy_arr);
  361. }
  362. tmpres.clear();
  363. ALsizei max_length{HRIR_LENGTH};
  364. /* Increase the IR size by 24 samples with dual-band processing to account
  365. * for the head and tail from the HF response scale.
  366. */
  367. const ALsizei irsize{DualBand ? mini(Hrtf->irSize + base_delay*2, max_length) : Hrtf->irSize};
  368. max_length = mini(max_delay-min_delay + irsize, max_length);
  369. /* Round up to the next IR size multiple. */
  370. max_length += MOD_IR_SIZE-1;
  371. max_length -= max_length%MOD_IR_SIZE;
  372. TRACE("Skipped delay: %d, max delay: %d, new FIR length: %d\n",
  373. min_delay, max_delay-min_delay, max_length);
  374. state->IrSize = max_length;
  375. }
  376. namespace {
  377. std::unique_ptr<HrtfEntry> CreateHrtfStore(ALuint rate, ALsizei irSize, const ALsizei fdCount,
  378. const ALubyte *evCount, const ALfloat *distance, const ALushort *azCount,
  379. const ALushort *irOffset, ALsizei irCount, const ALfloat (*coeffs)[2],
  380. const ALubyte (*delays)[2], const char *filename)
  381. {
  382. std::unique_ptr<HrtfEntry> Hrtf;
  383. ALsizei evTotal{std::accumulate(evCount, evCount+fdCount, 0)};
  384. size_t total{sizeof(HrtfEntry)};
  385. total = RoundUp(total, alignof(HrtfEntry::Field)); /* Align for field infos */
  386. total += sizeof(HrtfEntry::Field)*fdCount;
  387. total = RoundUp(total, alignof(HrtfEntry::Elevation)); /* Align for elevation infos */
  388. total += sizeof(Hrtf->elev[0])*evTotal;
  389. total = RoundUp(total, 16); /* Align for coefficients using SIMD */
  390. total += sizeof(Hrtf->coeffs[0])*irSize*irCount;
  391. total += sizeof(Hrtf->delays[0])*irCount;
  392. Hrtf.reset(new (al_calloc(16, total)) HrtfEntry{});
  393. if(!Hrtf)
  394. ERR("Out of memory allocating storage for %s.\n", filename);
  395. else
  396. {
  397. InitRef(&Hrtf->ref, 1u);
  398. Hrtf->sampleRate = rate;
  399. Hrtf->irSize = irSize;
  400. Hrtf->fdCount = fdCount;
  401. /* Set up pointers to storage following the main HRTF struct. */
  402. char *base = reinterpret_cast<char*>(Hrtf.get());
  403. uintptr_t offset = sizeof(HrtfEntry);
  404. offset = RoundUp(offset, alignof(HrtfEntry::Field)); /* Align for field infos */
  405. auto field_ = reinterpret_cast<HrtfEntry::Field*>(base + offset);
  406. offset += sizeof(field_[0])*fdCount;
  407. offset = RoundUp(offset, alignof(HrtfEntry::Elevation)); /* Align for elevation infos */
  408. auto elev_ = reinterpret_cast<HrtfEntry::Elevation*>(base + offset);
  409. offset += sizeof(elev_[0])*evTotal;
  410. offset = RoundUp(offset, 16); /* Align for coefficients using SIMD */
  411. auto coeffs_ = reinterpret_cast<ALfloat(*)[2]>(base + offset);
  412. offset += sizeof(coeffs_[0])*irSize*irCount;
  413. auto delays_ = reinterpret_cast<ALubyte(*)[2]>(base + offset);
  414. offset += sizeof(delays_[0])*irCount;
  415. assert(offset == total);
  416. /* Copy input data to storage. */
  417. for(ALsizei i{0};i < fdCount;i++)
  418. {
  419. field_[i].distance = distance[i];
  420. field_[i].evCount = evCount[i];
  421. }
  422. for(ALsizei i{0};i < evTotal;i++)
  423. {
  424. elev_[i].azCount = azCount[i];
  425. elev_[i].irOffset = irOffset[i];
  426. }
  427. for(ALsizei i{0};i < irSize*irCount;i++)
  428. {
  429. coeffs_[i][0] = coeffs[i][0];
  430. coeffs_[i][1] = coeffs[i][1];
  431. }
  432. for(ALsizei i{0};i < irCount;i++)
  433. {
  434. delays_[i][0] = delays[i][0];
  435. delays_[i][1] = delays[i][1];
  436. }
  437. /* Finally, assign the storage pointers. */
  438. Hrtf->field = field_;
  439. Hrtf->elev = elev_;
  440. Hrtf->coeffs = coeffs_;
  441. Hrtf->delays = delays_;
  442. }
  443. return Hrtf;
  444. }
  445. ALubyte GetLE_ALubyte(std::istream &data)
  446. {
  447. return static_cast<ALubyte>(data.get());
  448. }
  449. ALshort GetLE_ALshort(std::istream &data)
  450. {
  451. int ret = data.get();
  452. ret |= data.get() << 8;
  453. return static_cast<ALshort>((ret^32768) - 32768);
  454. }
  455. ALushort GetLE_ALushort(std::istream &data)
  456. {
  457. int ret = data.get();
  458. ret |= data.get() << 8;
  459. return static_cast<ALushort>(ret);
  460. }
  461. ALint GetLE_ALint24(std::istream &data)
  462. {
  463. int ret = data.get();
  464. ret |= data.get() << 8;
  465. ret |= data.get() << 16;
  466. return (ret^8388608) - 8388608;
  467. }
  468. ALuint GetLE_ALuint(std::istream &data)
  469. {
  470. int ret = data.get();
  471. ret |= data.get() << 8;
  472. ret |= data.get() << 16;
  473. ret |= data.get() << 24;
  474. return ret;
  475. }
  476. std::unique_ptr<HrtfEntry> LoadHrtf00(std::istream &data, const char *filename)
  477. {
  478. ALuint rate{GetLE_ALuint(data)};
  479. ALushort irCount{GetLE_ALushort(data)};
  480. ALushort irSize{GetLE_ALushort(data)};
  481. ALubyte evCount{GetLE_ALubyte(data)};
  482. if(!data || data.eof())
  483. {
  484. ERR("Failed reading %s\n", filename);
  485. return nullptr;
  486. }
  487. ALboolean failed{AL_FALSE};
  488. if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
  489. {
  490. ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
  491. irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
  492. failed = AL_TRUE;
  493. }
  494. if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
  495. {
  496. ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
  497. evCount, MIN_EV_COUNT, MAX_EV_COUNT);
  498. failed = AL_TRUE;
  499. }
  500. if(failed)
  501. return nullptr;
  502. al::vector<ALushort> evOffset(evCount);
  503. for(auto &val : evOffset)
  504. val = GetLE_ALushort(data);
  505. if(!data || data.eof())
  506. {
  507. ERR("Failed reading %s\n", filename);
  508. return nullptr;
  509. }
  510. for(ALsizei i{1};i < evCount;i++)
  511. {
  512. if(evOffset[i] <= evOffset[i-1])
  513. {
  514. ERR("Invalid evOffset: evOffset[%d]=%d (last=%d)\n",
  515. i, evOffset[i], evOffset[i-1]);
  516. failed = AL_TRUE;
  517. }
  518. }
  519. if(irCount <= evOffset.back())
  520. {
  521. ERR("Invalid evOffset: evOffset[%zu]=%d (irCount=%d)\n",
  522. evOffset.size()-1, evOffset.back(), irCount);
  523. failed = AL_TRUE;
  524. }
  525. if(failed)
  526. return nullptr;
  527. al::vector<ALushort> azCount(evCount);
  528. for(ALsizei i{1};i < evCount;i++)
  529. {
  530. azCount[i-1] = evOffset[i] - evOffset[i-1];
  531. if(azCount[i-1] < MIN_AZ_COUNT || azCount[i-1] > MAX_AZ_COUNT)
  532. {
  533. ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
  534. i-1, azCount[i-1], MIN_AZ_COUNT, MAX_AZ_COUNT);
  535. failed = AL_TRUE;
  536. }
  537. }
  538. azCount.back() = irCount - evOffset.back();
  539. if(azCount.back() < MIN_AZ_COUNT || azCount.back() > MAX_AZ_COUNT)
  540. {
  541. ERR("Unsupported azimuth count: azCount[%zu]=%d (%d to %d)\n",
  542. azCount.size()-1, azCount.back(), MIN_AZ_COUNT, MAX_AZ_COUNT);
  543. failed = AL_TRUE;
  544. }
  545. if(failed)
  546. return nullptr;
  547. al::vector<std::array<ALfloat,2>> coeffs(irSize*irCount);
  548. al::vector<std::array<ALubyte,2>> delays(irCount);
  549. for(auto &val : coeffs)
  550. val[0] = GetLE_ALshort(data) / 32768.0f;
  551. for(auto &val : delays)
  552. val[0] = GetLE_ALubyte(data);
  553. if(!data || data.eof())
  554. {
  555. ERR("Failed reading %s\n", filename);
  556. return nullptr;
  557. }
  558. for(ALsizei i{0};i < irCount;i++)
  559. {
  560. if(delays[i][0] > MAX_HRIR_DELAY)
  561. {
  562. ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i][0], MAX_HRIR_DELAY);
  563. failed = AL_TRUE;
  564. }
  565. }
  566. if(failed)
  567. return nullptr;
  568. /* Mirror the left ear responses to the right ear. */
  569. for(ALsizei i{0};i < evCount;i++)
  570. {
  571. ALushort evoffset = evOffset[i];
  572. ALubyte azcount = azCount[i];
  573. for(ALsizei j{0};j < azcount;j++)
  574. {
  575. ALsizei lidx = evoffset + j;
  576. ALsizei ridx = evoffset + ((azcount-j) % azcount);
  577. for(ALsizei k{0};k < irSize;k++)
  578. coeffs[ridx*irSize + k][1] = coeffs[lidx*irSize + k][0];
  579. delays[ridx][1] = delays[lidx][0];
  580. }
  581. }
  582. static constexpr ALfloat distance{0.0f};
  583. return CreateHrtfStore(rate, irSize, 1, &evCount, &distance, azCount.data(), evOffset.data(),
  584. irCount, &reinterpret_cast<ALfloat(&)[2]>(coeffs[0]),
  585. &reinterpret_cast<ALubyte(&)[2]>(delays[0]), filename);
  586. }
  587. std::unique_ptr<HrtfEntry> LoadHrtf01(std::istream &data, const char *filename)
  588. {
  589. ALuint rate{GetLE_ALuint(data)};
  590. ALushort irSize{GetLE_ALubyte(data)};
  591. ALubyte evCount{GetLE_ALubyte(data)};
  592. if(!data || data.eof())
  593. {
  594. ERR("Failed reading %s\n", filename);
  595. return nullptr;
  596. }
  597. ALboolean failed{AL_FALSE};
  598. if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
  599. {
  600. ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
  601. irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
  602. failed = AL_TRUE;
  603. }
  604. if(evCount < MIN_EV_COUNT || evCount > MAX_EV_COUNT)
  605. {
  606. ERR("Unsupported elevation count: evCount=%d (%d to %d)\n",
  607. evCount, MIN_EV_COUNT, MAX_EV_COUNT);
  608. failed = AL_TRUE;
  609. }
  610. if(failed)
  611. return nullptr;
  612. al::vector<ALushort> azCount(evCount);
  613. std::generate(azCount.begin(), azCount.end(), std::bind(GetLE_ALubyte, std::ref(data)));
  614. if(!data || data.eof())
  615. {
  616. ERR("Failed reading %s\n", filename);
  617. return nullptr;
  618. }
  619. for(ALsizei i{0};i < evCount;++i)
  620. {
  621. if(azCount[i] < MIN_AZ_COUNT || azCount[i] > MAX_AZ_COUNT)
  622. {
  623. ERR("Unsupported azimuth count: azCount[%d]=%d (%d to %d)\n",
  624. i, azCount[i], MIN_AZ_COUNT, MAX_AZ_COUNT);
  625. failed = AL_TRUE;
  626. }
  627. }
  628. if(failed)
  629. return nullptr;
  630. al::vector<ALushort> evOffset(evCount);
  631. evOffset[0] = 0;
  632. ALushort irCount{azCount[0]};
  633. for(ALsizei i{1};i < evCount;i++)
  634. {
  635. evOffset[i] = evOffset[i-1] + azCount[i-1];
  636. irCount += azCount[i];
  637. }
  638. al::vector<std::array<ALfloat,2>> coeffs(irSize*irCount);
  639. al::vector<std::array<ALubyte,2>> delays(irCount);
  640. for(auto &val : coeffs)
  641. val[0] = GetLE_ALshort(data) / 32768.0f;
  642. for(auto &val : delays)
  643. val[0] = GetLE_ALubyte(data);
  644. if(!data || data.eof())
  645. {
  646. ERR("Failed reading %s\n", filename);
  647. return nullptr;
  648. }
  649. for(ALsizei i{0};i < irCount;i++)
  650. {
  651. if(delays[i][0] > MAX_HRIR_DELAY)
  652. {
  653. ERR("Invalid delays[%d]: %d (%d)\n", i, delays[i][0], MAX_HRIR_DELAY);
  654. failed = AL_TRUE;
  655. }
  656. }
  657. if(failed)
  658. return nullptr;
  659. /* Mirror the left ear responses to the right ear. */
  660. for(ALsizei i{0};i < evCount;i++)
  661. {
  662. ALushort evoffset = evOffset[i];
  663. ALubyte azcount = azCount[i];
  664. for(ALsizei j{0};j < azcount;j++)
  665. {
  666. ALsizei lidx = evoffset + j;
  667. ALsizei ridx = evoffset + ((azcount-j) % azcount);
  668. for(ALsizei k{0};k < irSize;k++)
  669. coeffs[ridx*irSize + k][1] = coeffs[lidx*irSize + k][0];
  670. delays[ridx][1] = delays[lidx][0];
  671. }
  672. }
  673. static constexpr ALfloat distance{0.0f};
  674. return CreateHrtfStore(rate, irSize, 1, &evCount, &distance, azCount.data(), evOffset.data(),
  675. irCount, &reinterpret_cast<ALfloat(&)[2]>(coeffs[0]),
  676. &reinterpret_cast<ALubyte(&)[2]>(delays[0]), filename);
  677. }
  678. #define SAMPLETYPE_S16 0
  679. #define SAMPLETYPE_S24 1
  680. #define CHANTYPE_LEFTONLY 0
  681. #define CHANTYPE_LEFTRIGHT 1
  682. std::unique_ptr<HrtfEntry> LoadHrtf02(std::istream &data, const char *filename)
  683. {
  684. ALuint rate{GetLE_ALuint(data)};
  685. ALubyte sampleType{GetLE_ALubyte(data)};
  686. ALubyte channelType{GetLE_ALubyte(data)};
  687. ALushort irSize{GetLE_ALubyte(data)};
  688. ALubyte fdCount{GetLE_ALubyte(data)};
  689. if(!data || data.eof())
  690. {
  691. ERR("Failed reading %s\n", filename);
  692. return nullptr;
  693. }
  694. ALboolean failed{AL_FALSE};
  695. if(sampleType > SAMPLETYPE_S24)
  696. {
  697. ERR("Unsupported sample type: %d\n", sampleType);
  698. failed = AL_TRUE;
  699. }
  700. if(channelType > CHANTYPE_LEFTRIGHT)
  701. {
  702. ERR("Unsupported channel type: %d\n", channelType);
  703. failed = AL_TRUE;
  704. }
  705. if(irSize < MIN_IR_SIZE || irSize > MAX_IR_SIZE || (irSize%MOD_IR_SIZE))
  706. {
  707. ERR("Unsupported HRIR size: irSize=%d (%d to %d by %d)\n",
  708. irSize, MIN_IR_SIZE, MAX_IR_SIZE, MOD_IR_SIZE);
  709. failed = AL_TRUE;
  710. }
  711. if(fdCount < 1 || fdCount > MAX_FD_COUNT)
  712. {
  713. ERR("Multiple field-depths not supported: fdCount=%d (%d to %d)\n",
  714. fdCount, MIN_FD_COUNT, MAX_FD_COUNT);
  715. failed = AL_TRUE;
  716. }
  717. if(failed)
  718. return nullptr;
  719. al::vector<ALfloat> distance(fdCount);
  720. al::vector<ALubyte> evCount(fdCount);
  721. al::vector<ALushort> azCount;
  722. for(ALsizei f{0};f < fdCount;f++)
  723. {
  724. distance[f] = GetLE_ALushort(data) / 1000.0f;
  725. evCount[f] = GetLE_ALubyte(data);
  726. if(!data || data.eof())
  727. {
  728. ERR("Failed reading %s\n", filename);
  729. return nullptr;
  730. }
  731. if(distance[f] < MIN_FD_DISTANCE || distance[f] > MAX_FD_DISTANCE)
  732. {
  733. ERR("Unsupported field distance[%d]=%f (%f to %f meters)\n", f,
  734. distance[f], MIN_FD_DISTANCE, MAX_FD_DISTANCE);
  735. failed = AL_TRUE;
  736. }
  737. if(f > 0 && distance[f] <= distance[f-1])
  738. {
  739. ERR("Field distance[%d] is not after previous (%f > %f)\n", f, distance[f],
  740. distance[f-1]);
  741. failed = AL_TRUE;
  742. }
  743. if(evCount[f] < MIN_EV_COUNT || evCount[f] > MAX_EV_COUNT)
  744. {
  745. ERR("Unsupported elevation count: evCount[%d]=%d (%d to %d)\n", f,
  746. evCount[f], MIN_EV_COUNT, MAX_EV_COUNT);
  747. failed = AL_TRUE;
  748. }
  749. if(failed)
  750. return nullptr;
  751. size_t ebase{azCount.size()};
  752. azCount.resize(ebase + evCount[f]);
  753. std::generate(azCount.begin()+ebase, azCount.end(),
  754. std::bind(GetLE_ALubyte, std::ref(data)));
  755. if(!data || data.eof())
  756. {
  757. ERR("Failed reading %s\n", filename);
  758. return nullptr;
  759. }
  760. for(ALsizei e{0};e < evCount[f];e++)
  761. {
  762. if(azCount[ebase+e] < MIN_AZ_COUNT || azCount[ebase+e] > MAX_AZ_COUNT)
  763. {
  764. ERR("Unsupported azimuth count: azCount[%d][%d]=%d (%d to %d)\n", f, e,
  765. azCount[ebase+e], MIN_AZ_COUNT, MAX_AZ_COUNT);
  766. failed = AL_TRUE;
  767. }
  768. }
  769. if(failed)
  770. return nullptr;
  771. }
  772. al::vector<ALushort> evOffset(azCount.size());
  773. evOffset[0] = 0;
  774. std::partial_sum(azCount.cbegin(), azCount.cend()-1, evOffset.begin()+1);
  775. const ALsizei irTotal{evOffset.back() + azCount.back()};
  776. al::vector<std::array<ALfloat,2>> coeffs(irSize*irTotal);
  777. al::vector<std::array<ALubyte,2>> delays(irTotal);
  778. if(channelType == CHANTYPE_LEFTONLY)
  779. {
  780. if(sampleType == SAMPLETYPE_S16)
  781. {
  782. for(auto &val : coeffs)
  783. val[0] = GetLE_ALshort(data) / 32768.0f;
  784. }
  785. else if(sampleType == SAMPLETYPE_S24)
  786. {
  787. for(auto &val : coeffs)
  788. val[0] = GetLE_ALint24(data) / 8388608.0f;
  789. }
  790. for(auto &val : delays)
  791. val[0] = GetLE_ALubyte(data);
  792. if(!data || data.eof())
  793. {
  794. ERR("Failed reading %s\n", filename);
  795. return nullptr;
  796. }
  797. for(ALsizei i{0};i < irTotal;++i)
  798. {
  799. if(delays[i][0] > MAX_HRIR_DELAY)
  800. {
  801. ERR("Invalid delays[%d][0]: %d (%d)\n", i, delays[i][0], MAX_HRIR_DELAY);
  802. failed = AL_TRUE;
  803. }
  804. }
  805. }
  806. else if(channelType == CHANTYPE_LEFTRIGHT)
  807. {
  808. if(sampleType == SAMPLETYPE_S16)
  809. {
  810. for(auto &val : coeffs)
  811. {
  812. val[0] = GetLE_ALshort(data) / 32768.0f;
  813. val[1] = GetLE_ALshort(data) / 32768.0f;
  814. }
  815. }
  816. else if(sampleType == SAMPLETYPE_S24)
  817. {
  818. for(auto &val : coeffs)
  819. {
  820. val[0] = GetLE_ALint24(data) / 8388608.0f;
  821. val[1] = GetLE_ALint24(data) / 8388608.0f;
  822. }
  823. }
  824. for(auto &val : delays)
  825. {
  826. val[0] = GetLE_ALubyte(data);
  827. val[1] = GetLE_ALubyte(data);
  828. }
  829. if(!data || data.eof())
  830. {
  831. ERR("Failed reading %s\n", filename);
  832. return nullptr;
  833. }
  834. for(ALsizei i{0};i < irTotal;++i)
  835. {
  836. if(delays[i][0] > MAX_HRIR_DELAY)
  837. {
  838. ERR("Invalid delays[%d][0]: %d (%d)\n", i, delays[i][0], MAX_HRIR_DELAY);
  839. failed = AL_TRUE;
  840. }
  841. if(delays[i][1] > MAX_HRIR_DELAY)
  842. {
  843. ERR("Invalid delays[%d][1]: %d (%d)\n", i, delays[i][1], MAX_HRIR_DELAY);
  844. failed = AL_TRUE;
  845. }
  846. }
  847. }
  848. if(failed)
  849. return nullptr;
  850. if(channelType == CHANTYPE_LEFTONLY)
  851. {
  852. /* Mirror the left ear responses to the right ear. */
  853. ALsizei ebase{0};
  854. for(ALsizei f{0};f < fdCount;f++)
  855. {
  856. for(ALsizei e{0};e < evCount[f];e++)
  857. {
  858. ALushort evoffset = evOffset[ebase+e];
  859. ALubyte azcount = azCount[ebase+e];
  860. for(ALsizei a{0};a < azcount;a++)
  861. {
  862. ALsizei lidx = evoffset + a;
  863. ALsizei ridx = evoffset + ((azcount-a) % azcount);
  864. for(ALsizei k{0};k < irSize;k++)
  865. coeffs[ridx*irSize + k][1] = coeffs[lidx*irSize + k][0];
  866. delays[ridx][1] = delays[lidx][0];
  867. }
  868. }
  869. ebase += evCount[f];
  870. }
  871. }
  872. if(fdCount > 1)
  873. {
  874. auto distance_ = al::vector<ALfloat>(distance.size());
  875. auto evCount_ = al::vector<ALubyte>(evCount.size());
  876. auto azCount_ = al::vector<ALushort>(azCount.size());
  877. auto evOffset_ = al::vector<ALushort>(evOffset.size());
  878. auto coeffs_ = al::vector<float2>(coeffs.size());
  879. auto delays_ = al::vector<std::array<ALubyte,2>>(delays.size());
  880. /* Simple reverse for the per-field elements. */
  881. std::reverse_copy(distance.cbegin(), distance.cend(), distance_.begin());
  882. std::reverse_copy(evCount.cbegin(), evCount.cend(), evCount_.begin());
  883. /* Each field has a group of elevations, which each have an azimuth
  884. * count. Reverse the order of the groups, keeping the relative order
  885. * of per-group azimuth counts.
  886. */
  887. auto azcnt_end = azCount_.end();
  888. auto copy_azs = [&azCount,&azcnt_end](const size_t ebase, const ALubyte num_evs) -> size_t
  889. {
  890. auto azcnt_src = azCount.begin()+ebase;
  891. azcnt_end = std::copy_backward(azcnt_src, azcnt_src+num_evs, azcnt_end);
  892. return ebase + num_evs;
  893. };
  894. std::accumulate(evCount.cbegin(), evCount.cend(), 0u, copy_azs);
  895. assert(azCount_.begin() == azcnt_end);
  896. /* Reestablish the IR offset for each elevation index, given the new
  897. * ordering of elevations.
  898. */
  899. evOffset_[0] = 0;
  900. std::partial_sum(azCount_.cbegin(), azCount_.cend()-1, evOffset_.begin()+1);
  901. /* Reverse the order of each field's group of IRs. */
  902. auto coeffs_end = coeffs_.end();
  903. auto delays_end = delays_.end();
  904. auto copy_irs = [irSize,&azCount,&coeffs,&delays,&coeffs_end,&delays_end](const size_t ebase, const ALubyte num_evs) -> size_t
  905. {
  906. const ALsizei abase{std::accumulate(azCount.cbegin(), azCount.cbegin()+ebase, 0)};
  907. const ALsizei num_azs{std::accumulate(azCount.cbegin()+ebase,
  908. azCount.cbegin() + (ebase+num_evs), 0)};
  909. coeffs_end = std::copy_backward(coeffs.cbegin() + abase*irSize,
  910. coeffs.cbegin() + (abase+num_azs)*irSize, coeffs_end);
  911. delays_end = std::copy_backward(delays.cbegin() + abase,
  912. delays.cbegin() + (abase+num_azs), delays_end);
  913. return ebase + num_evs;
  914. };
  915. std::accumulate(evCount.cbegin(), evCount.cend(), 0u, copy_irs);
  916. assert(coeffs_.begin() == coeffs_end);
  917. assert(delays_.begin() == delays_end);
  918. distance = std::move(distance_);
  919. evCount = std::move(evCount_);
  920. azCount = std::move(azCount_);
  921. evOffset = std::move(evOffset_);
  922. coeffs = std::move(coeffs_);
  923. delays = std::move(delays_);
  924. }
  925. return CreateHrtfStore(rate, irSize, fdCount, evCount.data(), distance.data(), azCount.data(),
  926. evOffset.data(), irTotal, &reinterpret_cast<ALfloat(&)[2]>(coeffs[0]),
  927. &reinterpret_cast<ALubyte(&)[2]>(delays[0]), filename);
  928. }
  929. bool checkName(al::vector<EnumeratedHrtf> &list, const std::string &name)
  930. {
  931. return std::find_if(list.cbegin(), list.cend(),
  932. [&name](const EnumeratedHrtf &entry)
  933. { return name == entry.name; }
  934. ) != list.cend();
  935. }
  936. void AddFileEntry(al::vector<EnumeratedHrtf> &list, const std::string &filename)
  937. {
  938. /* Check if this file has already been loaded globally. */
  939. auto loaded_entry = LoadedHrtfs.begin();
  940. for(;loaded_entry != LoadedHrtfs.end();++loaded_entry)
  941. {
  942. if(filename != (*loaded_entry)->filename.data())
  943. continue;
  944. /* Check if this entry has already been added to the list. */
  945. auto iter = std::find_if(list.cbegin(), list.cend(),
  946. [loaded_entry](const EnumeratedHrtf &entry) -> bool
  947. { return loaded_entry->get() == entry.hrtf; }
  948. );
  949. if(iter != list.cend())
  950. {
  951. TRACE("Skipping duplicate file entry %s\n", filename.c_str());
  952. return;
  953. }
  954. break;
  955. }
  956. if(loaded_entry == LoadedHrtfs.end())
  957. {
  958. TRACE("Got new file \"%s\"\n", filename.c_str());
  959. LoadedHrtfs.emplace_back(HrtfHandle::Create(filename.length()+1));
  960. loaded_entry = LoadedHrtfs.end()-1;
  961. strcpy((*loaded_entry)->filename.data(), filename.c_str());
  962. }
  963. /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
  964. * format update). */
  965. size_t namepos = filename.find_last_of('/')+1;
  966. if(!namepos) namepos = filename.find_last_of('\\')+1;
  967. size_t extpos{filename.find_last_of('.')};
  968. if(extpos <= namepos) extpos = std::string::npos;
  969. const std::string basename{(extpos == std::string::npos) ?
  970. filename.substr(namepos) : filename.substr(namepos, extpos-namepos)};
  971. std::string newname{basename};
  972. int count{1};
  973. while(checkName(list, newname))
  974. {
  975. newname = basename;
  976. newname += " #";
  977. newname += std::to_string(++count);
  978. }
  979. list.emplace_back(EnumeratedHrtf{newname, loaded_entry->get()});
  980. const EnumeratedHrtf &entry = list.back();
  981. TRACE("Adding file entry \"%s\"\n", entry.name.c_str());
  982. }
  983. /* Unfortunate that we have to duplicate AddFileEntry to take a memory buffer
  984. * for input instead of opening the given filename.
  985. */
  986. void AddBuiltInEntry(al::vector<EnumeratedHrtf> &list, const std::string &filename, ALuint residx)
  987. {
  988. auto loaded_entry = LoadedHrtfs.begin();
  989. for(;loaded_entry != LoadedHrtfs.end();++loaded_entry)
  990. {
  991. if(filename != (*loaded_entry)->filename.data())
  992. continue;
  993. /* Check if this entry has already been added to the list. */
  994. auto iter = std::find_if(list.cbegin(), list.cend(),
  995. [loaded_entry](const EnumeratedHrtf &entry) -> bool
  996. { return loaded_entry->get() == entry.hrtf; }
  997. );
  998. if(iter != list.cend())
  999. {
  1000. TRACE("Skipping duplicate file entry %s\n", filename.c_str());
  1001. return;
  1002. }
  1003. break;
  1004. }
  1005. if(loaded_entry == LoadedHrtfs.end())
  1006. {
  1007. TRACE("Got new file \"%s\"\n", filename.c_str());
  1008. LoadedHrtfs.emplace_back(HrtfHandle::Create(filename.length()+32));
  1009. loaded_entry = LoadedHrtfs.end()-1;
  1010. snprintf((*loaded_entry)->filename.data(), (*loaded_entry)->filename.size(), "!%u_%s",
  1011. residx, filename.c_str());
  1012. }
  1013. /* TODO: Get a human-readable name from the HRTF data (possibly coming in a
  1014. * format update). */
  1015. std::string newname{filename};
  1016. int count{1};
  1017. while(checkName(list, newname))
  1018. {
  1019. newname = filename;
  1020. newname += " #";
  1021. newname += std::to_string(++count);
  1022. }
  1023. list.emplace_back(EnumeratedHrtf{newname, loaded_entry->get()});
  1024. const EnumeratedHrtf &entry = list.back();
  1025. TRACE("Adding built-in entry \"%s\"\n", entry.name.c_str());
  1026. }
  1027. #define IDR_DEFAULT_44100_MHR 1
  1028. #define IDR_DEFAULT_48000_MHR 2
  1029. using ResData = al::span<const char>;
  1030. #ifndef ALSOFT_EMBED_HRTF_DATA
  1031. ResData GetResource(int UNUSED(name))
  1032. { return ResData{}; }
  1033. #else
  1034. #include "default-44100.mhr.h"
  1035. #include "default-48000.mhr.h"
  1036. ResData GetResource(int name)
  1037. {
  1038. if(name == IDR_DEFAULT_44100_MHR)
  1039. return {reinterpret_cast<const char*>(hrtf_default_44100), sizeof(hrtf_default_44100)};
  1040. if(name == IDR_DEFAULT_48000_MHR)
  1041. return {reinterpret_cast<const char*>(hrtf_default_48000), sizeof(hrtf_default_48000)};
  1042. return ResData{};
  1043. }
  1044. #endif
  1045. } // namespace
  1046. al::vector<EnumeratedHrtf> EnumerateHrtf(const char *devname)
  1047. {
  1048. al::vector<EnumeratedHrtf> list;
  1049. bool usedefaults{true};
  1050. const char *pathlist{""};
  1051. if(ConfigValueStr(devname, nullptr, "hrtf-paths", &pathlist))
  1052. {
  1053. while(pathlist && *pathlist)
  1054. {
  1055. const char *next, *end;
  1056. while(isspace(*pathlist) || *pathlist == ',')
  1057. pathlist++;
  1058. if(*pathlist == '\0')
  1059. continue;
  1060. next = strchr(pathlist, ',');
  1061. if(next)
  1062. end = next++;
  1063. else
  1064. {
  1065. end = pathlist + strlen(pathlist);
  1066. usedefaults = false;
  1067. }
  1068. while(end != pathlist && isspace(*(end-1)))
  1069. --end;
  1070. if(end != pathlist)
  1071. {
  1072. const std::string pname{pathlist, end};
  1073. for(const auto &fname : SearchDataFiles(".mhr", pname.c_str()))
  1074. AddFileEntry(list, fname);
  1075. }
  1076. pathlist = next;
  1077. }
  1078. }
  1079. else if(ConfigValueExists(devname, nullptr, "hrtf_tables"))
  1080. ERR("The hrtf_tables option is deprecated, please use hrtf-paths instead.\n");
  1081. if(usedefaults)
  1082. {
  1083. for(const auto &fname : SearchDataFiles(".mhr", "openal/hrtf"))
  1084. AddFileEntry(list, fname);
  1085. if(!GetResource(IDR_DEFAULT_44100_MHR).empty())
  1086. AddBuiltInEntry(list, "Built-In 44100hz", IDR_DEFAULT_44100_MHR);
  1087. if(!GetResource(IDR_DEFAULT_48000_MHR).empty())
  1088. AddBuiltInEntry(list, "Built-In 48000hz", IDR_DEFAULT_48000_MHR);
  1089. }
  1090. const char *defaulthrtf{""};
  1091. if(!list.empty() && ConfigValueStr(devname, nullptr, "default-hrtf", &defaulthrtf))
  1092. {
  1093. auto iter = std::find_if(list.begin(), list.end(),
  1094. [defaulthrtf](const EnumeratedHrtf &entry) -> bool
  1095. { return entry.name == defaulthrtf; }
  1096. );
  1097. if(iter == list.end())
  1098. WARN("Failed to find default HRTF \"%s\"\n", defaulthrtf);
  1099. else if(iter != list.begin())
  1100. {
  1101. EnumeratedHrtf entry{*iter};
  1102. list.erase(iter);
  1103. list.insert(list.begin(), entry);
  1104. }
  1105. }
  1106. return list;
  1107. }
  1108. HrtfEntry *GetLoadedHrtf(HrtfHandle *handle)
  1109. {
  1110. std::lock_guard<std::mutex> _{LoadedHrtfLock};
  1111. if(handle->entry)
  1112. {
  1113. HrtfEntry *hrtf{handle->entry.get()};
  1114. hrtf->IncRef();
  1115. return hrtf;
  1116. }
  1117. std::unique_ptr<std::istream> stream;
  1118. const char *name{""};
  1119. ALuint residx{};
  1120. char ch{};
  1121. if(sscanf(handle->filename.data(), "!%u%c", &residx, &ch) == 2 && ch == '_')
  1122. {
  1123. name = strchr(handle->filename.data(), ch)+1;
  1124. TRACE("Loading %s...\n", name);
  1125. ResData res{GetResource(residx)};
  1126. if(res.empty())
  1127. {
  1128. ERR("Could not get resource %u, %s\n", residx, name);
  1129. return nullptr;
  1130. }
  1131. stream = al::make_unique<idstream>(res.begin(), res.end());
  1132. }
  1133. else
  1134. {
  1135. name = handle->filename.data();
  1136. TRACE("Loading %s...\n", handle->filename.data());
  1137. auto fstr = al::make_unique<al::ifstream>(handle->filename.data(), std::ios::binary);
  1138. if(!fstr->is_open())
  1139. {
  1140. ERR("Could not open %s\n", handle->filename.data());
  1141. return nullptr;
  1142. }
  1143. stream = std::move(fstr);
  1144. }
  1145. std::unique_ptr<HrtfEntry> hrtf;
  1146. char magic[sizeof(magicMarker02)];
  1147. stream->read(magic, sizeof(magic));
  1148. if(stream->gcount() < static_cast<std::streamsize>(sizeof(magicMarker02)))
  1149. ERR("%s data is too short (%zu bytes)\n", name, stream->gcount());
  1150. else if(memcmp(magic, magicMarker02, sizeof(magicMarker02)) == 0)
  1151. {
  1152. TRACE("Detected data set format v2\n");
  1153. hrtf = LoadHrtf02(*stream, name);
  1154. }
  1155. else if(memcmp(magic, magicMarker01, sizeof(magicMarker01)) == 0)
  1156. {
  1157. TRACE("Detected data set format v1\n");
  1158. hrtf = LoadHrtf01(*stream, name);
  1159. }
  1160. else if(memcmp(magic, magicMarker00, sizeof(magicMarker00)) == 0)
  1161. {
  1162. TRACE("Detected data set format v0\n");
  1163. hrtf = LoadHrtf00(*stream, name);
  1164. }
  1165. else
  1166. ERR("Invalid header in %s: \"%.8s\"\n", name, magic);
  1167. stream.reset();
  1168. if(!hrtf)
  1169. {
  1170. ERR("Failed to load %s\n", name);
  1171. return nullptr;
  1172. }
  1173. TRACE("Loaded HRTF support for format: %s %uhz\n",
  1174. DevFmtChannelsString(DevFmtStereo), hrtf->sampleRate);
  1175. handle->entry = std::move(hrtf);
  1176. return handle->entry.get();
  1177. }
  1178. void HrtfEntry::IncRef()
  1179. {
  1180. auto ref = IncrementRef(&this->ref);
  1181. TRACEREF("%p increasing refcount to %u\n", this, ref);
  1182. }
  1183. void HrtfEntry::DecRef()
  1184. {
  1185. auto ref = DecrementRef(&this->ref);
  1186. TRACEREF("%p decreasing refcount to %u\n", this, ref);
  1187. if(ref == 0)
  1188. {
  1189. std::lock_guard<std::mutex> _{LoadedHrtfLock};
  1190. /* Need to double-check that it's still unused, as another device
  1191. * could've reacquired this HRTF after its reference went to 0 and
  1192. * before the lock was taken.
  1193. */
  1194. auto iter = std::find_if(LoadedHrtfs.begin(), LoadedHrtfs.end(),
  1195. [this](const HrtfHandlePtr &entry) noexcept -> bool
  1196. { return this == entry->entry.get(); }
  1197. );
  1198. if(iter != LoadedHrtfs.end() && ReadRef(&this->ref) == 0)
  1199. {
  1200. (*iter)->entry = nullptr;
  1201. TRACE("Unloaded unused HRTF %s\n", (*iter)->filename.data());
  1202. }
  1203. }
  1204. }