hrtf.cpp 47 KB

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