sofa-support.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. /*
  2. * SOFA utility methods for inspecting SOFA file metrics and determining HRTF
  3. * utility compatible layouts.
  4. *
  5. * Copyright (C) 2018-2019 Christopher Fitzgerald
  6. * Copyright (C) 2019 Christopher Robinson
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. *
  22. * Or visit: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  23. */
  24. #include "sofa-support.h"
  25. #include <algorithm>
  26. #include <array>
  27. #include <cmath>
  28. #include <cstdio>
  29. #include <utility>
  30. #include <vector>
  31. #include "fmt/core.h"
  32. #include "mysofa.h"
  33. namespace {
  34. using uint = unsigned int;
  35. using double3 = std::array<double,3>;
  36. /* Produces a sorted array of unique elements from a particular axis of the
  37. * triplets array. The filters are used to focus on particular coordinates
  38. * of other axes as necessary. The epsilons are used to constrain the
  39. * equality of unique elements.
  40. */
  41. std::vector<double> GetUniquelySortedElems(const std::vector<double3> &aers, const uint axis,
  42. const std::array<const double*,3> &filters, const std::array<double,3> &epsilons)
  43. {
  44. std::vector<double> elems;
  45. for(const double3 &aer : aers)
  46. {
  47. const double elem{aer[axis]};
  48. uint j;
  49. for(j = 0;j < 3;j++)
  50. {
  51. if(filters[j] && std::abs(aer[j] - *filters[j]) > epsilons[j])
  52. break;
  53. }
  54. if(j < 3)
  55. continue;
  56. auto iter = elems.begin();
  57. for(;iter != elems.end();++iter)
  58. {
  59. const double delta{elem - *iter};
  60. if(delta > epsilons[axis]) continue;
  61. if(delta >= -epsilons[axis]) break;
  62. iter = elems.emplace(iter, elem);
  63. break;
  64. }
  65. if(iter == elems.end())
  66. elems.emplace_back(elem);
  67. }
  68. return elems;
  69. }
  70. /* Given a list of azimuths, this will produce the smallest step size that can
  71. * uniformly cover the list. Ideally this will be over half, but in degenerate
  72. * cases this can fall to a minimum of 5 (the lower limit).
  73. */
  74. double GetUniformAzimStep(const double epsilon, const std::vector<double> &elems)
  75. {
  76. if(elems.size() < 5) return 0.0;
  77. /* Get the maximum count possible, given the first two elements. It would
  78. * be impossible to have more than this since the first element must be
  79. * included.
  80. */
  81. uint count{static_cast<uint>(std::ceil(360.0 / (elems[1]-elems[0])))};
  82. count = std::min(count, 255u);
  83. for(;count >= 5;--count)
  84. {
  85. /* Given the stepping value for this number of elements, check each
  86. * multiple to ensure there's a matching element.
  87. */
  88. const double step{360.0 / count};
  89. bool good{true};
  90. size_t idx{1u};
  91. for(uint mult{1u};mult < count && good;++mult)
  92. {
  93. const double target{step*mult + elems[0]};
  94. while(idx < elems.size() && target-elems[idx] > epsilon)
  95. ++idx;
  96. good &= (idx < elems.size()) && !(std::abs(target-elems[idx++]) > epsilon);
  97. }
  98. if(good)
  99. return step;
  100. }
  101. return 0.0;
  102. }
  103. /* Given a list of elevations, this will produce the smallest step size that
  104. * can uniformly cover the list. Ideally this will be over half, but in
  105. * degenerate cases this can fall to a minimum of 5 (the lower limit).
  106. */
  107. double GetUniformElevStep(const double epsilon, std::vector<double> &elems)
  108. {
  109. if(elems.size() < 5) return 0.0;
  110. /* Reverse the elevations so it increments starting with -90 (flipped from
  111. * +90). This makes it easier to work out a proper stepping value.
  112. */
  113. std::reverse(elems.begin(), elems.end());
  114. for(auto &v : elems) v *= -1.0;
  115. uint count{static_cast<uint>(std::ceil(180.0 / (elems[1]-elems[0])))};
  116. count = std::min(count, 255u);
  117. double ret{0.0};
  118. for(;count >= 5;--count)
  119. {
  120. const double step{180.0 / count};
  121. bool good{true};
  122. size_t idx{1u};
  123. /* Elevations don't need to match all multiples if there's not enough
  124. * elements to check. Missing elevations can be synthesized.
  125. */
  126. for(uint mult{1u};mult <= count && idx < elems.size() && good;++mult)
  127. {
  128. const double target{step*mult + elems[0]};
  129. while(idx < elems.size() && target-elems[idx] > epsilon)
  130. ++idx;
  131. good &= !(idx < elems.size()) || !(std::abs(target-elems[idx++]) > epsilon);
  132. }
  133. if(good)
  134. {
  135. ret = step;
  136. break;
  137. }
  138. }
  139. /* Re-reverse the elevations to restore the correct order. */
  140. for(auto &v : elems) v *= -1.0;
  141. std::reverse(elems.begin(), elems.end());
  142. return ret;
  143. }
  144. } // namespace
  145. const char *SofaErrorStr(int err)
  146. {
  147. switch(err)
  148. {
  149. case MYSOFA_OK: return "OK";
  150. case MYSOFA_INVALID_FORMAT: return "Invalid format";
  151. case MYSOFA_UNSUPPORTED_FORMAT: return "Unsupported format";
  152. case MYSOFA_INTERNAL_ERROR: return "Internal error";
  153. case MYSOFA_NO_MEMORY: return "Out of memory";
  154. case MYSOFA_READ_ERROR: return "Read error";
  155. }
  156. return "Unknown";
  157. }
  158. auto GetCompatibleLayout(const al::span<const float> xyzs) -> std::vector<SofaField>
  159. {
  160. auto aers = std::vector<double3>(xyzs.size()/3, double3{});
  161. for(size_t i{0u};i < aers.size();++i)
  162. {
  163. std::array vals{xyzs[i*3], xyzs[i*3 + 1], xyzs[i*3 + 2]};
  164. mysofa_c2s(vals.data());
  165. aers[i] = {vals[0], vals[1], vals[2]};
  166. }
  167. auto radii = GetUniquelySortedElems(aers, 2, {}, {0.1, 0.1, 0.001});
  168. std::vector<SofaField> fds;
  169. fds.reserve(radii.size());
  170. for(const double dist : radii)
  171. {
  172. auto elevs = GetUniquelySortedElems(aers, 1, {nullptr, nullptr, &dist}, {0.1, 0.1, 0.001});
  173. /* Remove elevations that don't have a valid set of azimuths. */
  174. auto invalid_elev = [&dist,&aers](const double ev) -> bool
  175. {
  176. auto azims = GetUniquelySortedElems(aers, 0, {nullptr, &ev, &dist}, {0.1, 0.1, 0.001});
  177. if(std::abs(ev) > 89.999)
  178. return azims.size() != 1;
  179. if(azims.empty() || !(std::abs(azims[0]) < 0.1))
  180. return true;
  181. return GetUniformAzimStep(0.1, azims) <= 0.0;
  182. };
  183. elevs.erase(std::remove_if(elevs.begin(), elevs.end(), invalid_elev), elevs.end());
  184. double step{GetUniformElevStep(0.1, elevs)};
  185. if(step <= 0.0)
  186. {
  187. if(elevs.empty())
  188. fmt::println("No usable elevations on field distance {:f}.", dist);
  189. else
  190. {
  191. fmt::print("Non-uniform elevations on field distance {:.3f}.\nGot: {:+.2f}", dist,
  192. elevs[0]);
  193. for(size_t ei{1u};ei < elevs.size();++ei)
  194. fmt::print(", {:+.2f}", elevs[ei]);
  195. fmt::println("");
  196. }
  197. continue;
  198. }
  199. uint evStart{0u};
  200. for(uint ei{0u};ei < elevs.size();ei++)
  201. {
  202. if(!(elevs[ei] < 0.0))
  203. {
  204. fmt::println("Too many missing elevations on field distance {:f}.", dist);
  205. return fds;
  206. }
  207. double eif{(90.0+elevs[ei]) / step};
  208. const double ev_start{std::round(eif)};
  209. if(std::abs(eif - ev_start) < (0.1/step))
  210. {
  211. evStart = static_cast<uint>(ev_start);
  212. break;
  213. }
  214. }
  215. const auto evCount = static_cast<uint>(std::round(180.0 / step)) + 1;
  216. if(evCount < 5)
  217. {
  218. fmt::println("Too few uniform elevations on field distance {:f}.", dist);
  219. continue;
  220. }
  221. SofaField field{};
  222. field.mDistance = dist;
  223. field.mEvCount = evCount;
  224. field.mEvStart = evStart;
  225. field.mAzCounts.resize(evCount, 0u);
  226. auto &azCounts = field.mAzCounts;
  227. for(uint ei{evStart};ei < evCount;ei++)
  228. {
  229. double ev{-90.0 + ei*180.0/(evCount - 1)};
  230. auto azims = GetUniquelySortedElems(aers, 0, {nullptr, &ev, &dist}, {0.1, 0.1, 0.001});
  231. if(ei == 0 || ei == (evCount-1))
  232. {
  233. if(azims.size() != 1)
  234. {
  235. fmt::println("Non-singular poles on field distance {:f}.", dist);
  236. return fds;
  237. }
  238. azCounts[ei] = 1;
  239. }
  240. else
  241. {
  242. step = GetUniformAzimStep(0.1, azims);
  243. if(step <= 0.0)
  244. {
  245. fmt::println("Non-uniform azimuths on elevation {:f}, field distance {:f}.",
  246. ev, dist);
  247. return fds;
  248. }
  249. azCounts[ei] = static_cast<uint>(std::round(360.0f / step));
  250. }
  251. }
  252. fds.emplace_back(std::move(field));
  253. }
  254. return fds;
  255. }