loadsofa.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. /*
  2. * HRTF utility for producing and demonstrating the process of creating an
  3. * OpenAL Soft compatible HRIR data set.
  4. *
  5. * Copyright (C) 2018-2019 Christopher Fitzgerald
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License along
  18. * with this program; if not, write to the Free Software Foundation, Inc.,
  19. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. *
  21. * Or visit: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  22. */
  23. #include "loadsofa.h"
  24. #include <algorithm>
  25. #include <atomic>
  26. #include <chrono>
  27. #include <cmath>
  28. #include <cstdio>
  29. #include <functional>
  30. #include <future>
  31. #include <iterator>
  32. #include <memory>
  33. #include <optional>
  34. #include <string>
  35. #include <string_view>
  36. #include <thread>
  37. #include <vector>
  38. #include "alspan.h"
  39. #include "alnumeric.h"
  40. #include "fmt/core.h"
  41. #include "makemhr.h"
  42. #include "polyphase_resampler.h"
  43. #include "sofa-support.h"
  44. #include "mysofa.h"
  45. namespace {
  46. using namespace std::string_view_literals;
  47. using uint = unsigned int;
  48. /* Attempts to produce a compatible layout. Most data sets tend to be
  49. * uniform and have the same major axis as used by OpenAL Soft's HRTF model.
  50. * This will remove outliers and produce a maximally dense layout when
  51. * possible. Those sets that contain purely random measurements or use
  52. * different major axes will fail.
  53. */
  54. auto PrepareLayout(const al::span<const float> xyzs, HrirDataT *hData) -> bool
  55. {
  56. fmt::println("Detecting compatible layout...");
  57. auto fds = GetCompatibleLayout(xyzs);
  58. if(fds.size() > MAX_FD_COUNT)
  59. {
  60. fmt::println("Incompatible layout (inumerable radii).");
  61. return false;
  62. }
  63. std::array<double,MAX_FD_COUNT> distances{};
  64. std::array<uint,MAX_FD_COUNT> evCounts{};
  65. auto azCounts = std::vector<std::array<uint,MAX_EV_COUNT>>(MAX_FD_COUNT);
  66. for(auto &azs : azCounts) azs.fill(0u);
  67. uint fi{0u}, ir_total{0u};
  68. for(const auto &field : fds)
  69. {
  70. distances[fi] = field.mDistance;
  71. evCounts[fi] = field.mEvCount;
  72. for(uint ei{0u};ei < field.mEvStart;ei++)
  73. azCounts[fi][ei] = field.mAzCounts[field.mEvCount-ei-1];
  74. for(uint ei{field.mEvStart};ei < field.mEvCount;ei++)
  75. {
  76. azCounts[fi][ei] = field.mAzCounts[ei];
  77. ir_total += field.mAzCounts[ei];
  78. }
  79. ++fi;
  80. }
  81. fmt::println("Using {} of {} IRs.", ir_total, xyzs.size()/3);
  82. const auto azs = al::span{azCounts}.first<MAX_FD_COUNT>();
  83. return PrepareHrirData(al::span{distances}.first(fi), evCounts, azs, hData);
  84. }
  85. float GetSampleRate(MYSOFA_HRTF *sofaHrtf)
  86. {
  87. const char *srate_dim{nullptr};
  88. const char *srate_units{nullptr};
  89. MYSOFA_ARRAY *srate_array{&sofaHrtf->DataSamplingRate};
  90. MYSOFA_ATTRIBUTE *srate_attrs{srate_array->attributes};
  91. while(srate_attrs)
  92. {
  93. if("DIMENSION_LIST"sv == srate_attrs->name)
  94. {
  95. if(srate_dim)
  96. {
  97. fmt::println(stderr, "Duplicate SampleRate.DIMENSION_LIST");
  98. return 0.0f;
  99. }
  100. srate_dim = srate_attrs->value;
  101. }
  102. else if("Units"sv == srate_attrs->name)
  103. {
  104. if(srate_units)
  105. {
  106. fmt::println(stderr, "Duplicate SampleRate.Units");
  107. return 0.0f;
  108. }
  109. srate_units = srate_attrs->value;
  110. }
  111. else
  112. fmt::println(stderr, "Unexpected sample rate attribute: {} = {}", srate_attrs->name,
  113. srate_attrs->value);
  114. srate_attrs = srate_attrs->next;
  115. }
  116. if(!srate_dim)
  117. {
  118. fmt::println(stderr, "Missing sample rate dimensions");
  119. return 0.0f;
  120. }
  121. if(srate_dim != "I"sv)
  122. {
  123. fmt::println(stderr, "Unsupported sample rate dimensions: {}", srate_dim);
  124. return 0.0f;
  125. }
  126. if(!srate_units)
  127. {
  128. fmt::println(stderr, "Missing sample rate unit type");
  129. return 0.0f;
  130. }
  131. if(srate_units != "hertz"sv)
  132. {
  133. fmt::println(stderr, "Unsupported sample rate unit type: {}", srate_units);
  134. return 0.0f;
  135. }
  136. /* I dimensions guarantees 1 element, so just extract it. */
  137. const auto values = al::span{srate_array->values, sofaHrtf->I};
  138. if(values[0] < float{MIN_RATE} || values[0] > float{MAX_RATE})
  139. {
  140. fmt::println(stderr, "Sample rate out of range: {:f} (expected {} to {})", values[0],
  141. MIN_RATE, MAX_RATE);
  142. return 0.0f;
  143. }
  144. return values[0];
  145. }
  146. enum class DelayType : uint8_t {
  147. None,
  148. I_R, /* [1][Channels] */
  149. M_R, /* [HRIRs][Channels] */
  150. };
  151. auto PrepareDelay(MYSOFA_HRTF *sofaHrtf) -> std::optional<DelayType>
  152. {
  153. const char *delay_dim{nullptr};
  154. MYSOFA_ARRAY *delay_array{&sofaHrtf->DataDelay};
  155. MYSOFA_ATTRIBUTE *delay_attrs{delay_array->attributes};
  156. while(delay_attrs)
  157. {
  158. if("DIMENSION_LIST"sv == delay_attrs->name)
  159. {
  160. if(delay_dim)
  161. {
  162. fmt::println(stderr, "Duplicate Delay.DIMENSION_LIST");
  163. return std::nullopt;
  164. }
  165. delay_dim = delay_attrs->value;
  166. }
  167. else
  168. fmt::println(stderr, "Unexpected delay attribute: {} = {}", delay_attrs->name,
  169. delay_attrs->value ? delay_attrs->value : "<null>");
  170. delay_attrs = delay_attrs->next;
  171. }
  172. if(!delay_dim)
  173. {
  174. fmt::println(stderr, "Missing delay dimensions");
  175. return DelayType::None;
  176. }
  177. if(delay_dim == "I,R"sv)
  178. return DelayType::I_R;
  179. if(delay_dim == "M,R"sv)
  180. return DelayType::M_R;
  181. fmt::println(stderr, "Unsupported delay dimensions: {}", delay_dim);
  182. return std::nullopt;
  183. }
  184. bool CheckIrData(MYSOFA_HRTF *sofaHrtf)
  185. {
  186. const char *ir_dim{nullptr};
  187. MYSOFA_ARRAY *ir_array{&sofaHrtf->DataIR};
  188. MYSOFA_ATTRIBUTE *ir_attrs{ir_array->attributes};
  189. while(ir_attrs)
  190. {
  191. if("DIMENSION_LIST"sv == ir_attrs->name)
  192. {
  193. if(ir_dim)
  194. {
  195. fmt::println(stderr, "Duplicate IR.DIMENSION_LIST");
  196. return false;
  197. }
  198. ir_dim = ir_attrs->value;
  199. }
  200. else
  201. fmt::println(stderr, "Unexpected IR attribute: {} = {}", ir_attrs->name,
  202. ir_attrs->value ? ir_attrs->value : "<null>");
  203. ir_attrs = ir_attrs->next;
  204. }
  205. if(!ir_dim)
  206. {
  207. fmt::println(stderr, "Missing IR dimensions");
  208. return false;
  209. }
  210. if(ir_dim != "M,R,N"sv)
  211. {
  212. fmt::println(stderr, "Unsupported IR dimensions: {}", ir_dim);
  213. return false;
  214. }
  215. return true;
  216. }
  217. /* Calculate the onset time of a HRIR. */
  218. constexpr int OnsetRateMultiple{10};
  219. auto CalcHrirOnset(PPhaseResampler &rs, const uint rate, al::span<double> upsampled,
  220. const al::span<const double> hrir) -> double
  221. {
  222. rs.process(hrir, upsampled);
  223. auto abs_lt = [](const double lhs, const double rhs) -> bool
  224. { return std::abs(lhs) < std::abs(rhs); };
  225. auto iter = std::max_element(upsampled.cbegin(), upsampled.cend(), abs_lt);
  226. return static_cast<double>(std::distance(upsampled.cbegin(), iter)) /
  227. (double{OnsetRateMultiple}*rate);
  228. }
  229. /* Calculate the magnitude response of a HRIR. */
  230. void CalcHrirMagnitude(const uint points, al::span<complex_d> h, const al::span<double> hrir)
  231. {
  232. auto iter = std::copy_n(hrir.cbegin(), points, h.begin());
  233. std::fill(iter, h.end(), complex_d{0.0, 0.0});
  234. forward_fft(h);
  235. MagnitudeResponse(h, hrir.first((h.size()/2) + 1));
  236. }
  237. bool LoadResponses(MYSOFA_HRTF *sofaHrtf, HrirDataT *hData, const DelayType delayType,
  238. const uint outRate)
  239. {
  240. std::atomic<uint> loaded_count{0u};
  241. auto load_proc = [sofaHrtf,hData,delayType,outRate,&loaded_count]() -> bool
  242. {
  243. const uint channels{(hData->mChannelType == CT_STEREO) ? 2u : 1u};
  244. hData->mHrirsBase.resize(channels * size_t{hData->mIrCount} * hData->mIrSize, 0.0);
  245. const auto hrirs = al::span{hData->mHrirsBase};
  246. std::vector<double> restmp;
  247. std::optional<PPhaseResampler> resampler;
  248. if(outRate && outRate != hData->mIrRate)
  249. {
  250. resampler.emplace().init(hData->mIrRate, outRate);
  251. restmp.resize(sofaHrtf->N);
  252. }
  253. const auto srcPosValues = al::span{sofaHrtf->SourcePosition.values, sofaHrtf->M*3_uz};
  254. const auto irValues = al::span{sofaHrtf->DataIR.values,
  255. size_t{sofaHrtf->M}*sofaHrtf->R*sofaHrtf->N};
  256. for(uint si{0u};si < sofaHrtf->M;++si)
  257. {
  258. loaded_count.fetch_add(1u);
  259. std::array aer{srcPosValues[3_uz*si], srcPosValues[3_uz*si + 1],
  260. srcPosValues[3_uz*si + 2]};
  261. mysofa_c2s(aer.data());
  262. if(std::abs(aer[1]) >= 89.999f)
  263. aer[0] = 0.0f;
  264. else
  265. aer[0] = std::fmod(360.0f - aer[0], 360.0f);
  266. auto field = std::find_if(hData->mFds.cbegin(), hData->mFds.cend(),
  267. [&aer](const HrirFdT &fld) -> bool
  268. { return (std::abs(aer[2] - fld.mDistance) < 0.001); });
  269. if(field == hData->mFds.cend())
  270. continue;
  271. const double evscale{180.0 / static_cast<double>(field->mEvs.size()-1)};
  272. double ef{(90.0 + aer[1]) / evscale};
  273. auto ei = static_cast<uint>(std::round(ef));
  274. ef = (ef - ei) * evscale;
  275. if(std::abs(ef) >= 0.1) continue;
  276. const double azscale{360.0 / static_cast<double>(field->mEvs[ei].mAzs.size())};
  277. double af{aer[0] / azscale};
  278. auto ai = static_cast<uint>(std::round(af));
  279. af = (af-ai) * azscale;
  280. ai %= static_cast<uint>(field->mEvs[ei].mAzs.size());
  281. if(std::abs(af) >= 0.1) continue;
  282. HrirAzT &azd = field->mEvs[ei].mAzs[ai];
  283. if(!azd.mIrs[0].empty())
  284. {
  285. fmt::println(stderr, "\nMultiple measurements near [ a={:f}, e={:f}, r={:f} ].",
  286. aer[0], aer[1], aer[2]);
  287. return false;
  288. }
  289. for(uint ti{0u};ti < channels;++ti)
  290. {
  291. azd.mIrs[ti] = hrirs.subspan(
  292. (size_t{hData->mIrCount}*ti + azd.mIndex) * hData->mIrSize, hData->mIrSize);
  293. const auto ir = irValues.subspan((size_t{si}*sofaHrtf->R + ti)*sofaHrtf->N,
  294. sofaHrtf->N);
  295. if(!resampler)
  296. std::copy_n(ir.cbegin(), ir.size(), azd.mIrs[ti].begin());
  297. else
  298. {
  299. std::copy_n(ir.cbegin(), ir.size(), restmp.begin());
  300. resampler->process(restmp, azd.mIrs[ti]);
  301. }
  302. }
  303. /* Include any per-channel or per-HRIR delays. */
  304. if(delayType == DelayType::I_R)
  305. {
  306. const auto delayValues = al::span{sofaHrtf->DataDelay.values,
  307. size_t{sofaHrtf->I}*sofaHrtf->R};
  308. for(uint ti{0u};ti < channels;++ti)
  309. azd.mDelays[ti] = delayValues[ti] / static_cast<float>(hData->mIrRate);
  310. }
  311. else if(delayType == DelayType::M_R)
  312. {
  313. const auto delayValues = al::span{sofaHrtf->DataDelay.values,
  314. size_t{sofaHrtf->M}*sofaHrtf->R};
  315. for(uint ti{0u};ti < channels;++ti)
  316. azd.mDelays[ti] = delayValues[si*sofaHrtf->R + ti] /
  317. static_cast<float>(hData->mIrRate);
  318. }
  319. }
  320. if(outRate && outRate != hData->mIrRate)
  321. {
  322. const double scale{static_cast<double>(outRate) / hData->mIrRate};
  323. hData->mIrRate = outRate;
  324. hData->mIrPoints = std::min(static_cast<uint>(std::ceil(hData->mIrPoints*scale)),
  325. hData->mIrSize);
  326. }
  327. return true;
  328. };
  329. std::future_status load_status{};
  330. auto load_future = std::async(std::launch::async, load_proc);
  331. do {
  332. load_status = load_future.wait_for(std::chrono::milliseconds{50});
  333. fmt::print("\rLoading HRIRs... {} of {}", loaded_count.load(), sofaHrtf->M);
  334. fflush(stdout);
  335. } while(load_status != std::future_status::ready);
  336. fmt::println("");
  337. return load_future.get();
  338. }
  339. /* Calculates the frequency magnitudes of the HRIR set. Work is delegated to
  340. * this struct, which runs asynchronously on one or more threads (sharing the
  341. * same calculator object).
  342. */
  343. struct MagCalculator {
  344. const uint mFftSize{};
  345. const uint mIrPoints{};
  346. std::vector<al::span<double>> mIrs;
  347. std::atomic<size_t> mCurrent{};
  348. std::atomic<size_t> mDone{};
  349. MagCalculator(const uint fftsize, const uint irpoints) : mFftSize{fftsize}, mIrPoints{irpoints}
  350. { }
  351. void Worker()
  352. {
  353. auto htemp = std::vector<complex_d>(mFftSize);
  354. while(true)
  355. {
  356. /* Load the current index to process. */
  357. size_t idx{mCurrent.load()};
  358. do {
  359. /* If the index is at the end, we're done. */
  360. if(idx >= mIrs.size())
  361. return;
  362. /* Otherwise, increment the current index atomically so other
  363. * threads know to go to the next one. If this call fails, the
  364. * current index was just changed by another thread and the new
  365. * value is loaded into idx, which we'll recheck.
  366. */
  367. } while(!mCurrent.compare_exchange_weak(idx, idx+1, std::memory_order_relaxed));
  368. CalcHrirMagnitude(mIrPoints, htemp, mIrs[idx]);
  369. /* Increment the number of IRs done. */
  370. mDone.fetch_add(1);
  371. }
  372. }
  373. };
  374. } // namespace
  375. bool LoadSofaFile(const std::string_view filename, const uint numThreads, const uint fftSize,
  376. const uint truncSize, const uint outRate, const ChannelModeT chanMode, HrirDataT *hData)
  377. {
  378. int err;
  379. MySofaHrtfPtr sofaHrtf{mysofa_load(std::string{filename}.c_str(), &err)};
  380. if(!sofaHrtf)
  381. {
  382. fmt::println("Error: Could not load {}: {} ({})", filename, SofaErrorStr(err), err);
  383. return false;
  384. }
  385. /* NOTE: Some valid SOFA files are failing this check. */
  386. err = mysofa_check(sofaHrtf.get());
  387. if(err != MYSOFA_OK)
  388. fmt::println(stderr, "Warning: Supposedly malformed source file '{}': {} ({})", filename,
  389. SofaErrorStr(err), err);
  390. mysofa_tocartesian(sofaHrtf.get());
  391. /* Make sure emitter and receiver counts are sane. */
  392. if(sofaHrtf->E != 1)
  393. {
  394. fmt::println(stderr, "{} emitters not supported", sofaHrtf->E);
  395. return false;
  396. }
  397. if(sofaHrtf->R > 2 || sofaHrtf->R < 1)
  398. {
  399. fmt::println(stderr, "{} receivers not supported", sofaHrtf->R);
  400. return false;
  401. }
  402. /* Assume R=2 is a stereo measurement, and R=1 is mono left-ear-only. */
  403. if(sofaHrtf->R == 2 && chanMode == CM_AllowStereo)
  404. hData->mChannelType = CT_STEREO;
  405. else
  406. hData->mChannelType = CT_MONO;
  407. /* Check and set the FFT and IR size. */
  408. if(sofaHrtf->N > fftSize)
  409. {
  410. fmt::println(stderr, "Sample points exceeds the FFT size ({} > {}).", sofaHrtf->N,
  411. fftSize);
  412. return false;
  413. }
  414. if(sofaHrtf->N < truncSize)
  415. {
  416. fmt::println(stderr, "Sample points is below the truncation size ({} < {}).", sofaHrtf->N,
  417. truncSize);
  418. return false;
  419. }
  420. hData->mIrPoints = sofaHrtf->N;
  421. hData->mFftSize = fftSize;
  422. hData->mIrSize = std::max(1u + (fftSize/2u), sofaHrtf->N);
  423. /* Assume a default head radius of 9cm. */
  424. hData->mRadius = 0.09;
  425. hData->mIrRate = static_cast<uint>(std::lround(GetSampleRate(sofaHrtf.get())));
  426. if(!hData->mIrRate)
  427. return false;
  428. const auto delayType = PrepareDelay(sofaHrtf.get());
  429. if(!delayType)
  430. return false;
  431. if(!CheckIrData(sofaHrtf.get()))
  432. return false;
  433. if(!PrepareLayout(al::span{sofaHrtf->SourcePosition.values, sofaHrtf->M*3_uz}, hData))
  434. return false;
  435. if(!LoadResponses(sofaHrtf.get(), hData, *delayType, outRate))
  436. return false;
  437. sofaHrtf = nullptr;
  438. for(uint fi{0u};fi < hData->mFds.size();fi++)
  439. {
  440. uint ei{0u};
  441. for(;ei < hData->mFds[fi].mEvs.size();ei++)
  442. {
  443. uint ai{0u};
  444. for(;ai < hData->mFds[fi].mEvs[ei].mAzs.size();ai++)
  445. {
  446. HrirAzT &azd = hData->mFds[fi].mEvs[ei].mAzs[ai];
  447. if(!azd.mIrs[0].empty()) break;
  448. }
  449. if(ai < hData->mFds[fi].mEvs[ei].mAzs.size())
  450. break;
  451. }
  452. if(ei >= hData->mFds[fi].mEvs.size())
  453. {
  454. fmt::println(stderr, "Missing source references [ {}, *, * ].", fi);
  455. return false;
  456. }
  457. hData->mFds[fi].mEvStart = ei;
  458. for(;ei < hData->mFds[fi].mEvs.size();ei++)
  459. {
  460. for(uint ai{0u};ai < hData->mFds[fi].mEvs[ei].mAzs.size();ai++)
  461. {
  462. HrirAzT &azd = hData->mFds[fi].mEvs[ei].mAzs[ai];
  463. if(azd.mIrs[0].empty())
  464. {
  465. fmt::println(stderr, "Missing source reference [ {}, {}, {} ].", fi, ei, ai);
  466. return false;
  467. }
  468. }
  469. }
  470. }
  471. size_t hrir_total{0};
  472. const uint channels{(hData->mChannelType == CT_STEREO) ? 2u : 1u};
  473. const auto hrirs = al::span{hData->mHrirsBase};
  474. for(uint fi{0u};fi < hData->mFds.size();fi++)
  475. {
  476. for(uint ei{0u};ei < hData->mFds[fi].mEvStart;ei++)
  477. {
  478. for(uint ai{0u};ai < hData->mFds[fi].mEvs[ei].mAzs.size();ai++)
  479. {
  480. HrirAzT &azd = hData->mFds[fi].mEvs[ei].mAzs[ai];
  481. for(size_t ti{0u};ti < channels;ti++)
  482. azd.mIrs[ti] = hrirs.subspan((hData->mIrCount*ti + azd.mIndex)*hData->mIrSize,
  483. hData->mIrSize);
  484. }
  485. }
  486. for(uint ei{hData->mFds[fi].mEvStart};ei < hData->mFds[fi].mEvs.size();ei++)
  487. hrir_total += hData->mFds[fi].mEvs[ei].mAzs.size() * channels;
  488. }
  489. std::atomic<size_t> hrir_done{0};
  490. auto onset_proc = [hData,channels,&hrir_done]() -> bool
  491. {
  492. /* Temporary buffer used to calculate the IR's onset. */
  493. auto upsampled = std::vector<double>(size_t{OnsetRateMultiple} * hData->mIrPoints);
  494. /* This resampler is used to help detect the response onset. */
  495. PPhaseResampler rs;
  496. rs.init(hData->mIrRate, OnsetRateMultiple*hData->mIrRate);
  497. for(auto &field : hData->mFds)
  498. {
  499. for(auto &elev : field.mEvs.subspan(field.mEvStart))
  500. {
  501. for(auto &azd : elev.mAzs)
  502. {
  503. for(uint ti{0};ti < channels;ti++)
  504. {
  505. hrir_done.fetch_add(1u, std::memory_order_acq_rel);
  506. azd.mDelays[ti] += CalcHrirOnset(rs, hData->mIrRate, upsampled,
  507. azd.mIrs[ti].first(hData->mIrPoints));
  508. }
  509. }
  510. }
  511. }
  512. return true;
  513. };
  514. std::future_status load_status{};
  515. auto load_future = std::async(std::launch::async, onset_proc);
  516. do {
  517. load_status = load_future.wait_for(std::chrono::milliseconds{50});
  518. fmt::print("\rCalculating HRIR onsets... {} of {}", hrir_done.load(), hrir_total);
  519. fflush(stdout);
  520. } while(load_status != std::future_status::ready);
  521. fmt::println("");
  522. if(!load_future.get())
  523. return false;
  524. MagCalculator calculator{hData->mFftSize, hData->mIrPoints};
  525. for(auto &field : hData->mFds)
  526. {
  527. for(auto &elev : field.mEvs.subspan(field.mEvStart))
  528. {
  529. for(auto &azd : elev.mAzs)
  530. {
  531. for(uint ti{0};ti < channels;ti++)
  532. calculator.mIrs.push_back(azd.mIrs[ti]);
  533. }
  534. }
  535. }
  536. std::vector<std::thread> thrds;
  537. thrds.reserve(numThreads);
  538. for(size_t i{0};i < numThreads;++i)
  539. thrds.emplace_back(&MagCalculator::Worker, &calculator);
  540. size_t count;
  541. do {
  542. std::this_thread::sleep_for(std::chrono::milliseconds{50});
  543. count = calculator.mDone.load();
  544. fmt::print("\rCalculating HRIR magnitudes... {} of {}", count, calculator.mIrs.size());
  545. fflush(stdout);
  546. } while(count != calculator.mIrs.size());
  547. fmt::println("");
  548. for(auto &thrd : thrds)
  549. {
  550. if(thrd.joinable())
  551. thrd.join();
  552. }
  553. return true;
  554. }