🛠️🐜 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.

593 lines
20 KiB

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