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

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