aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--CMakeLists.txt17
-rw-r--r--utils/makemhr/loadsofa.cpp260
-rw-r--r--utils/sofa-info.cpp270
-rw-r--r--utils/sofa-support.cpp292
-rw-r--r--utils/sofa-support.h30
5 files changed, 355 insertions, 514 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4bc0aeeb..1d847fe9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1393,6 +1393,15 @@ IF(ALSOFT_UTILS)
find_package(MySOFA)
if(MYSOFA_FOUND)
+ set(SOFA_SUPPORT_SRCS
+ utils/sofa-support.cpp
+ utils/sofa-support.h)
+ add_library(sofa-support STATIC EXCLUDE_FROM_ALL ${SOFA_SUPPORT_SRCS})
+ target_compile_definitions(sofa-support PRIVATE ${CPP_DEFS})
+ target_include_directories(sofa-support PUBLIC ${OpenAL_SOURCE_DIR}/common)
+ target_compile_options(sofa-support PRIVATE ${C_FLAGS})
+ target_link_libraries(sofa-support PUBLIC common MySOFA::MySOFA PRIVATE ${LINKER_FLAGS})
+
set(MAKEMHR_SRCS
utils/makemhr/loaddef.cpp
utils/makemhr/loaddef.h
@@ -1406,17 +1415,17 @@ IF(ALSOFT_UTILS)
add_executable(makemhr ${MAKEMHR_SRCS})
target_compile_definitions(makemhr PRIVATE ${CPP_DEFS})
target_include_directories(makemhr
- PRIVATE ${OpenAL_SOURCE_DIR}/common ${OpenAL_BINARY_DIR})
+ PRIVATE ${OpenAL_BINARY_DIR} ${OpenAL_SOURCE_DIR}/utils)
target_compile_options(makemhr PRIVATE ${C_FLAGS})
- target_link_libraries(makemhr PRIVATE common ${LINKER_FLAGS} MySOFA::MySOFA)
+ target_link_libraries(makemhr PRIVATE ${LINKER_FLAGS} sofa-support)
set(UTIL_TARGETS ${UTIL_TARGETS} makemhr)
set(SOFAINFO_SRCS utils/sofa-info.cpp)
add_executable(sofa-info ${SOFAINFO_SRCS})
target_compile_definitions(sofa-info PRIVATE ${CPP_DEFS})
- target_include_directories(sofa-info PRIVATE ${OpenAL_SOURCE_DIR}/common)
+ target_include_directories(sofa-info PRIVATE ${OpenAL_SOURCE_DIR}/utils)
target_compile_options(sofa-info PRIVATE ${C_FLAGS})
- target_link_libraries(sofa-info PRIVATE ${LINKER_FLAGS} MySOFA::MySOFA)
+ target_link_libraries(sofa-info PRIVATE ${LINKER_FLAGS} sofa-support)
endif()
IF(ALSOFT_INSTALL)
diff --git a/utils/makemhr/loadsofa.cpp b/utils/makemhr/loadsofa.cpp
index 886bd6ff..81df8aa4 100644
--- a/utils/makemhr/loadsofa.cpp
+++ b/utils/makemhr/loadsofa.cpp
@@ -24,11 +24,10 @@
#include "loadsofa.h"
#include <algorithm>
-#include <array>
#include <atomic>
+#include <chrono>
#include <cmath>
#include <cstdio>
-#include <functional>
#include <future>
#include <iterator>
#include <memory>
@@ -37,148 +36,13 @@
#include <vector>
#include "makemhr.h"
+#include "polyphase_resampler.h"
+#include "sofa-support.h"
#include "mysofa.h"
-using namespace std::placeholders;
-
-using double3 = std::array<double,3>;
-
-static const char *SofaErrorStr(int err)
-{
- switch(err)
- {
- case MYSOFA_OK: return "OK";
- case MYSOFA_INVALID_FORMAT: return "Invalid format";
- case MYSOFA_UNSUPPORTED_FORMAT: return "Unsupported format";
- case MYSOFA_INTERNAL_ERROR: return "Internal error";
- case MYSOFA_NO_MEMORY: return "Out of memory";
- case MYSOFA_READ_ERROR: return "Read error";
- }
- return "Unknown";
-}
-
-
-/* Produces a sorted array of unique elements from a particular axis of the
- * triplets array. The filters are used to focus on particular coordinates
- * of other axes as necessary. The epsilons are used to constrain the
- * equality of unique elements.
- */
-static std::vector<double> GetUniquelySortedElems(const std::vector<double3> &aers,
- const uint axis, const double *const (&filters)[3], const double (&epsilons)[3])
-{
- std::vector<double> elems;
- for(const double3 &aer : aers)
- {
- const double elem{aer[axis]};
-
- uint j;
- for(j = 0;j < 3;j++)
- {
- if(filters[j] && std::abs(aer[j] - *filters[j]) > epsilons[j])
- break;
- }
- if(j < 3)
- continue;
-
- auto iter = elems.begin();
- for(;iter != elems.end();++iter)
- {
- const double delta{elem - *iter};
- if(delta > epsilons[axis]) continue;
- if(delta >= -epsilons[axis]) break;
-
- iter = elems.emplace(iter, elem);
- break;
- }
- if(iter == elems.end())
- elems.emplace_back(elem);
- }
- return elems;
-}
-
-/* Given a list of azimuths, this will produce the smallest step size that can
- * uniformly cover the list. Ideally this will be over half, but in degenerate
- * cases this can fall to a minimum of 5 (the lower limit).
- */
-static double GetUniformAzimStep(const double epsilon, const std::vector<double> &elems)
-{
- if(elems.size() < 5) return 0.0;
-
- /* Get the maximum count possible, given the first two elements. It would
- * be impossible to have more than this since the first element must be
- * included.
- */
- uint count{static_cast<uint>(std::ceil(360.0 / (elems[1]-elems[0])))};
- count = std::min(count, uint{MAX_AZ_COUNT});
-
- for(;count >= 5;--count)
- {
- /* Given the stepping value for this number of elements, check each
- * multiple to ensure there's a matching element.
- */
- const double step{360.0 / count};
- bool good{true};
- size_t idx{1u};
- for(uint mult{1u};mult < count && good;++mult)
- {
- const double target{step*mult + elems[0]};
- while(idx < elems.size() && target-elems[idx] > epsilon)
- ++idx;
- good &= (idx < elems.size()) && !(std::abs(target-elems[idx++]) > epsilon);
- }
- if(good)
- return step;
- }
- return 0.0;
-}
-
-/* Given a list of elevations, this will produce the smallest step size that
- * can uniformly cover the list. Ideally this will be over half, but in
- * degenerate cases this can fall to a minimum of 5 (the lower limit).
- */
-static double GetUniformElevStep(const double epsilon, std::vector<double> &elems)
-{
- if(elems.size() < 5) return 0.0;
-
- /* Reverse the elevations so it increments starting with -90 (flipped from
- * +90). This makes it easier to work out a proper stepping value.
- */
- std::reverse(elems.begin(), elems.end());
- for(auto &v : elems) v *= -1.0;
-
- uint count{static_cast<uint>(std::ceil(180.0 / (elems[1]-elems[0])))};
- count = std::min(count, uint{MAX_EV_COUNT-1u});
-
- double ret{0.0};
- for(;count >= 5;--count)
- {
- const double step{180.0 / count};
- bool good{true};
- size_t idx{1u};
- /* Elevations don't need to match all multiples if there's not enough
- * elements to check. Missing elevations can be synthesized.
- */
- for(uint mult{1u};mult <= count && idx < elems.size() && good;++mult)
- {
- const double target{step*mult + elems[0]};
- while(idx < elems.size() && target-elems[idx] > epsilon)
- ++idx;
- good &= !(idx < elems.size()) || !(std::abs(target-elems[idx++]) > epsilon);
- }
- if(good)
- {
- ret = step;
- break;
- }
- }
- /* Re-reverse the elevations to restore the correct order. */
- for(auto &v : elems) v *= -1.0;
- std::reverse(elems.begin(), elems.end());
-
- return ret;
-}
+using uint = unsigned int;
/* Attempts to produce a compatible layout. Most data sets tend to be
* uniform and have the same major axis as used by OpenAL Soft's HRTF model.
@@ -190,16 +54,8 @@ static bool PrepareLayout(const uint m, const float *xyzs, HrirDataT *hData)
{
fprintf(stdout, "Detecting compatible layout...\n");
- auto aers = std::vector<double3>(m, double3{});
- for(uint i{0u};i < m;++i)
- {
- float vals[3]{xyzs[i*3], xyzs[i*3 + 1], xyzs[i*3 + 2]};
- mysofa_c2s(&vals[0]);
- aers[i] = {vals[0], vals[1], vals[2]};
- }
-
- auto radii = GetUniquelySortedElems(aers, 2, {}, {0.1, 0.1, 0.001});
- if(radii.size() > MAX_FD_COUNT)
+ auto fds = GetCompatibleLayout(m, xyzs);
+ if(fds.size() > MAX_FD_COUNT)
{
fprintf(stdout, "Incompatible layout (inumerable radii).\n");
return false;
@@ -209,104 +65,24 @@ static bool PrepareLayout(const uint m, const float *xyzs, HrirDataT *hData)
uint evCounts[MAX_FD_COUNT]{};
auto azCounts = std::vector<uint>(MAX_FD_COUNT*MAX_EV_COUNT, 0u);
- auto dist_end = std::copy_if(radii.cbegin(), radii.cend(), std::begin(distances),
- std::bind(std::greater_equal<double>{}, _1, hData->mRadius));
- auto fdCount = static_cast<uint>(std::distance(std::begin(distances), dist_end));
-
- uint ir_total{0u};
- for(uint fi{0u};fi < fdCount;)
+ uint fi{0u}, ir_total{0u};
+ for(const auto &field : fds)
{
- const double dist{distances[fi]};
- auto elevs = GetUniquelySortedElems(aers, 1, {nullptr, nullptr, &dist},
- {0.1, 0.1, 0.001});
-
- /* Remove elevations that don't have a valid set of azimuths. */
- auto invalid_elev = [&dist,&aers](const double ev) -> bool
- {
- auto azims = GetUniquelySortedElems(aers, 0, {nullptr, &ev, &dist}, {0.1, 0.1, 0.001});
-
- if(std::abs(ev) > 89.999)
- return azims.size() != 1;
- if(azims.empty() || !(std::abs(azims[0]) < 0.1))
- return true;
- return GetUniformAzimStep(0.1, azims) <= 0.0;
- };
- elevs.erase(std::remove_if(elevs.begin(), elevs.end(), invalid_elev), elevs.end());
-
- double step{GetUniformElevStep(0.1, elevs)};
- if(step <= 0.0)
- {
- fprintf(stdout, "Non-uniform elevations on field distance %f.\n", dist);
- std::copy(&distances[fi+1], &distances[fdCount], &distances[fi]);
- --fdCount;
- continue;
- }
-
- uint evStart{0u};
- for(uint ei{0u};ei < elevs.size();ei++)
- {
- if(!(elevs[ei] < 0.0))
- {
- fprintf(stdout, "Too many missing elevations on field distance %f.\n", dist);
- return false;
- }
-
- double eif{(90.0+elevs[ei]) / step};
- const double ev_start{std::round(eif)};
+ distances[fi] = field.mDistance;
+ evCounts[fi] = field.mEvCount;
- if(std::abs(eif - ev_start) < (0.1/step))
- {
- evStart = static_cast<uint>(ev_start);
- break;
- }
- }
-
- const auto evCount = static_cast<uint>(std::round(180.0 / step)) + 1;
- if(evCount < 5)
+ for(uint ei{0u};ei < field.mEvStart;ei++)
+ azCounts[fi*MAX_EV_COUNT + ei] = field.mAzCounts[field.mEvCount-ei-1];
+ for(uint ei{field.mEvStart};ei < field.mEvCount;ei++)
{
- fprintf(stdout, "Too few uniform elevations on field distance %f.\n", dist);
- std::copy(&distances[fi+1], &distances[fdCount], &distances[fi]);
- --fdCount;
- continue;
- }
- evCounts[fi] = evCount;
-
- for(uint ei{evStart};ei < evCount;ei++)
- {
- const double ev{-90.0 + ei*180.0/(evCount - 1)};
- auto azims = GetUniquelySortedElems(aers, 0, {nullptr, &ev, &dist}, {0.1, 0.1, 0.001});
-
- uint azCount;
- if(ei == 0 || ei == (evCount-1))
- {
- if(azims.size() != 1)
- {
- fprintf(stdout, "Non-singular poles on field distance %f.\n", dist);
- return false;
- }
- azCount = 1u;
- }
- else
- {
- step = GetUniformAzimStep(0.1, azims);
- if(step <= 0.0)
- {
- fprintf(stdout, "Non-uniform azimuths on elevation %f, field distance %f.\n",
- ev, dist);
- return false;
- }
- azCount = static_cast<uint>(std::round(360.0 / step));
- }
- azCounts[fi*MAX_EV_COUNT + ei] = azCount;
- ir_total += azCount;
+ azCounts[fi*MAX_EV_COUNT + ei] = field.mAzCounts[ei];
+ ir_total += field.mAzCounts[ei];
}
- for(uint ei{0u};ei < evStart;ei++)
- azCounts[fi*MAX_EV_COUNT + ei] = azCounts[fi*MAX_EV_COUNT + evCount - ei - 1];
++fi;
}
fprintf(stdout, "Using %u of %u IRs.\n", ir_total, m);
- return PrepareHrirData(fdCount, distances, evCounts, azCounts.data(), hData) != 0;
+ return PrepareHrirData(fi, distances, evCounts, azCounts.data(), hData) != 0;
}
@@ -575,10 +351,6 @@ static bool LoadResponses(MYSOFA_HRTF *sofaHrtf, HrirDataT *hData)
return load_future.get();
}
-struct MySofaHrtfDeleter {
- void operator()(MYSOFA_HRTF *ptr) { mysofa_free(ptr); }
-};
-using MySofaHrtfPtr = std::unique_ptr<MYSOFA_HRTF,MySofaHrtfDeleter>;
bool LoadSofaFile(const char *filename, const uint fftSize, const uint truncSize,
const ChannelModeT chanMode, HrirDataT *hData)
diff --git a/utils/sofa-info.cpp b/utils/sofa-info.cpp
index 81136334..6ab71306 100644
--- a/utils/sofa-info.cpp
+++ b/utils/sofa-info.cpp
@@ -23,46 +23,16 @@
#include <stdio.h>
-#include <algorithm>
-#include <array>
-#include <cmath>
#include <memory>
#include <vector>
-#include <mysofa.h>
-
+#include "sofa-support.h"
#include "win_main_utf8.h"
+#include "mysofa.h"
-using uint = unsigned int;
-using double3 = std::array<double,3>;
-
-struct MySofaDeleter {
- void operator()(MYSOFA_HRTF *sofa) { mysofa_free(sofa); }
-};
-using MySofaHrtfPtr = std::unique_ptr<MYSOFA_HRTF,MySofaDeleter>;
-
-// Per-field measurement info.
-struct HrirFdT {
- double mDistance{0.0};
- uint mEvCount{0u};
- uint mEvStart{0u};
- std::vector<uint> mAzCounts;
-};
-static const char *SofaErrorStr(int err)
-{
- switch(err)
- {
- case MYSOFA_OK: return "OK";
- case MYSOFA_INVALID_FORMAT: return "Invalid format";
- case MYSOFA_UNSUPPORTED_FORMAT: return "Unsupported format";
- case MYSOFA_INTERNAL_ERROR: return "Internal error";
- case MYSOFA_NO_MEMORY: return "Out of memory";
- case MYSOFA_READ_ERROR: return "Read error";
- }
- return "Unknown";
-}
+using uint = unsigned int;
static void PrintSofaAttributes(const char *prefix, struct MYSOFA_ATTRIBUTE *attribute)
{
@@ -76,131 +46,10 @@ static void PrintSofaAttributes(const char *prefix, struct MYSOFA_ATTRIBUTE *att
static void PrintSofaArray(const char *prefix, struct MYSOFA_ARRAY *array)
{
PrintSofaAttributes(prefix, array->attributes);
-
for(uint i{0u};i < array->elements;i++)
fprintf(stdout, "%s[%u]: %.6f\n", prefix, i, array->values[i]);
}
-/* Produces a sorted array of unique elements from a particular axis of the
- * triplets array. The filters are used to focus on particular coordinates
- * of other axes as necessary. The epsilons are used to constrain the
- * equality of unique elements.
- */
-static std::vector<double> GetUniquelySortedElems(const std::vector<double3> &aers,
- const uint axis, const double *const (&filters)[3], const double (&epsilons)[3])
-{
- std::vector<double> elems;
- for(const double3 &aer : aers)
- {
- const double elem{aer[axis]};
-
- uint j;
- for(j = 0;j < 3;j++)
- {
- if(filters[j] && std::abs(aer[j] - *filters[j]) > epsilons[j])
- break;
- }
- if(j < 3)
- continue;
-
- auto iter = elems.begin();
- for(;iter != elems.end();++iter)
- {
- const double delta{elem - *iter};
- if(delta > epsilons[axis]) continue;
- if(delta >= -epsilons[axis]) break;
-
- iter = elems.emplace(iter, elem);
- break;
- }
- if(iter == elems.end())
- elems.emplace_back(elem);
- }
- return elems;
-}
-
-/* Given a list of azimuths, this will produce the smallest step size that can
- * uniformly cover the list. Ideally this will be over half, but in degenerate
- * cases this can fall to a minimum of 5 (the lower limit).
- */
-static double GetUniformAzimStep(const double epsilon, const std::vector<double> &elems)
-{
- if(elems.size() < 5) return 0.0;
-
- /* Get the maximum count possible, given the first two elements. It would
- * be impossible to have more than this since the first element must be
- * included.
- */
- uint count{static_cast<uint>(std::ceil(360.0 / (elems[1]-elems[0])))};
- count = std::min(count, 255u);
-
- for(;count >= 5;--count)
- {
- /* Given the stepping value for this number of elements, check each
- * multiple to ensure there's a matching element.
- */
- const double step{360.0 / count};
- bool good{true};
- size_t idx{1u};
- for(uint mult{1u};mult < count && good;++mult)
- {
- const double target{step*mult + elems[0]};
- while(idx < elems.size() && target-elems[idx] > epsilon)
- ++idx;
- good &= (idx < elems.size()) && !(std::abs(target-elems[idx++]) > epsilon);
- }
- if(good)
- return step;
- }
- return 0.0;
-}
-
-/* Given a list of elevations, this will produce the smallest step size that
- * can uniformly cover the list. Ideally this will be over half, but in
- * degenerate cases this can fall to a minimum of 5 (the lower limit).
- */
-static double GetUniformElevStep(const double epsilon, std::vector<double> &elems)
-{
- if(elems.size() < 5) return 0.0;
-
- /* Reverse the elevations so it increments starting with -90 (flipped from
- * +90). This makes it easier to work out a proper stepping value.
- */
- std::reverse(elems.begin(), elems.end());
- for(auto &v : elems) v *= -1.0;
-
- uint count{static_cast<uint>(std::ceil(180.0 / (elems[1]-elems[0])))};
- count = std::min(count, 255u);
-
- double ret{0.0};
- for(;count >= 5;--count)
- {
- const double step{180.0 / count};
- bool good{true};
- size_t idx{1u};
- /* Elevations don't need to match all multiples if there's not enough
- * elements to check. Missing elevations can be synthesized.
- */
- for(uint mult{1u};mult <= count && idx < elems.size() && good;++mult)
- {
- const double target{step*mult + elems[0]};
- while(idx < elems.size() && target-elems[idx] > epsilon)
- ++idx;
- good &= !(idx < elems.size()) || !(std::abs(target-elems[idx++]) > epsilon);
- }
- if(good)
- {
- ret = step;
- break;
- }
- }
- /* Re-reverse the elevations to restore the correct order. */
- for(auto &v : elems) v *= -1.0;
- std::reverse(elems.begin(), elems.end());
-
- return ret;
-}
-
/* Attempts to produce a compatible layout. Most data sets tend to be
* uniform and have the same major axis as used by OpenAL Soft's HRTF model.
* This will remove outliers and produce a maximally dense layout when
@@ -211,118 +60,7 @@ static void PrintCompatibleLayout(const uint m, const float *xyzs)
{
fputc('\n', stdout);
- auto aers = std::vector<double3>(m, double3{});
- for(uint i{0u};i < m;++i)
- {
- float vals[3]{xyzs[i*3], xyzs[i*3 + 1], xyzs[i*3 + 2]};
- mysofa_c2s(&vals[0]);
- aers[i] = {vals[0], vals[1], vals[2]};
- }
-
- auto radii = GetUniquelySortedElems(aers, 2, {}, {0.1, 0.1, 0.001});
-
- auto fds = std::vector<HrirFdT>(radii.size());
- for(size_t fi{0u};fi < radii.size();fi++)
- fds[fi].mDistance = radii[fi];
-
- for(uint fi{0u};fi < fds.size();)
- {
- const double dist{fds[fi].mDistance};
- auto elevs = GetUniquelySortedElems(aers, 1, {nullptr, nullptr, &dist}, {0.1, 0.1, 0.001});
-
- /* Remove elevations that don't have a valid set of azimuths. */
- auto invalid_elev = [&dist,&aers](const double ev) -> bool
- {
- auto azims = GetUniquelySortedElems(aers, 0, {nullptr, &ev, &dist}, {0.1, 0.1, 0.001});
-
- if(std::abs(ev) > 89.999)
- return azims.size() != 1;
- if(azims.empty() || !(std::abs(azims[0]) < 0.1))
- return true;
- return GetUniformAzimStep(0.1, azims) <= 0.0;
- };
- elevs.erase(std::remove_if(elevs.begin(), elevs.end(), invalid_elev), elevs.end());
-
- double step{GetUniformElevStep(0.1, elevs)};
- if(step <= 0.0)
- {
- if(elevs.empty())
- fprintf(stdout, "No usable elevations on field distance %f.\n", dist);
- else
- {
- fprintf(stdout, "Non-uniform elevations on field distance %.3f.\nGot: %+.2f", dist,
- elevs[0]);
- for(size_t ei{1u};ei < elevs.size();++ei)
- fprintf(stdout, ", %+.2f", elevs[ei]);
- fputc('\n', stdout);
- }
- fds.erase(fds.begin() + static_cast<ptrdiff_t>(fi));
- continue;
- }
-
- uint evStart{0u};
- for(uint ei{0u};ei < elevs.size();ei++)
- {
- if(!(elevs[ei] < 0.0))
- {
- fprintf(stdout, "Too many missing elevations on field distance %f.\n", dist);
- return;
- }
-
- double eif{(90.0+elevs[ei]) / step};
- const double ev_start{std::round(eif)};
-
- if(std::abs(eif - ev_start) < (0.1/step))
- {
- evStart = static_cast<uint>(ev_start);
- break;
- }
- }
-
- const auto evCount = static_cast<uint>(std::round(180.0 / step)) + 1;
- if(evCount < 5)
- {
- fprintf(stdout, "Too few uniform elevations on field distance %f.\n", dist);
- fds.erase(fds.begin() + static_cast<ptrdiff_t>(fi));
- continue;
- }
-
- fds[fi].mEvCount = evCount;
- fds[fi].mEvStart = evStart;
- fds[fi].mAzCounts.resize(evCount);
- auto &azCounts = fds[fi].mAzCounts;
-
- for(uint ei{evStart};ei < evCount;ei++)
- {
- double ev{-90.0 + ei*180.0/(evCount - 1)};
- auto azims = GetUniquelySortedElems(aers, 0, {nullptr, &ev, &dist}, {0.1, 0.1, 0.001});
-
- if(ei == 0 || ei == (evCount-1))
- {
- if(azims.size() != 1)
- {
- fprintf(stdout, "Non-singular poles on field distance %f.\n", dist);
- return;
- }
- azCounts[ei] = 1;
- }
- else
- {
- step = GetUniformAzimStep(0.1, azims);
- if(step <= 0.0)
- {
- fprintf(stdout, "Non-uniform azimuths on elevation %f, field distance %f.\n",
- ev, dist);
- return;
- }
- azCounts[ei] = static_cast<uint>(std::round(360.0f / step));
- }
- }
-
- for(uint ei{0u};ei < evStart;ei++)
- azCounts[ei] = azCounts[evCount - ei - 1];
- ++fi;
- }
+ auto fds = GetCompatibleLayout(m, xyzs);
if(fds.empty())
{
fprintf(stdout, "No compatible field layouts in SOFA file.\n");
diff --git a/utils/sofa-support.cpp b/utils/sofa-support.cpp
new file mode 100644
index 00000000..e37789d5
--- /dev/null
+++ b/utils/sofa-support.cpp
@@ -0,0 +1,292 @@
+/*
+ * SOFA utility methods for inspecting SOFA file metrics and determining HRTF
+ * utility compatible layouts.
+ *
+ * Copyright (C) 2018-2019 Christopher Fitzgerald
+ * Copyright (C) 2019 Christopher Robinson
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Or visit: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
+ */
+
+#include "sofa-support.h"
+
+#include <stdio.h>
+
+#include <algorithm>
+#include <array>
+#include <cmath>
+#include <utility>
+#include <vector>
+
+#include "mysofa.h"
+
+
+namespace {
+
+using uint = unsigned int;
+using double3 = std::array<double,3>;
+
+
+/* Produces a sorted array of unique elements from a particular axis of the
+ * triplets array. The filters are used to focus on particular coordinates
+ * of other axes as necessary. The epsilons are used to constrain the
+ * equality of unique elements.
+ */
+std::vector<double> GetUniquelySortedElems(const std::vector<double3> &aers, const uint axis,
+ const double *const (&filters)[3], const double (&epsilons)[3])
+{
+ std::vector<double> elems;
+ for(const double3 &aer : aers)
+ {
+ const double elem{aer[axis]};
+
+ uint j;
+ for(j = 0;j < 3;j++)
+ {
+ if(filters[j] && std::abs(aer[j] - *filters[j]) > epsilons[j])
+ break;
+ }
+ if(j < 3)
+ continue;
+
+ auto iter = elems.begin();
+ for(;iter != elems.end();++iter)
+ {
+ const double delta{elem - *iter};
+ if(delta > epsilons[axis]) continue;
+ if(delta >= -epsilons[axis]) break;
+
+ iter = elems.emplace(iter, elem);
+ break;
+ }
+ if(iter == elems.end())
+ elems.emplace_back(elem);
+ }
+ return elems;
+}
+
+/* Given a list of azimuths, this will produce the smallest step size that can
+ * uniformly cover the list. Ideally this will be over half, but in degenerate
+ * cases this can fall to a minimum of 5 (the lower limit).
+ */
+double GetUniformAzimStep(const double epsilon, const std::vector<double> &elems)
+{
+ if(elems.size() < 5) return 0.0;
+
+ /* Get the maximum count possible, given the first two elements. It would
+ * be impossible to have more than this since the first element must be
+ * included.
+ */
+ uint count{static_cast<uint>(std::ceil(360.0 / (elems[1]-elems[0])))};
+ count = std::min(count, 255u);
+
+ for(;count >= 5;--count)
+ {
+ /* Given the stepping value for this number of elements, check each
+ * multiple to ensure there's a matching element.
+ */
+ const double step{360.0 / count};
+ bool good{true};
+ size_t idx{1u};
+ for(uint mult{1u};mult < count && good;++mult)
+ {
+ const double target{step*mult + elems[0]};
+ while(idx < elems.size() && target-elems[idx] > epsilon)
+ ++idx;
+ good &= (idx < elems.size()) && !(std::abs(target-elems[idx++]) > epsilon);
+ }
+ if(good)
+ return step;
+ }
+ return 0.0;
+}
+
+/* Given a list of elevations, this will produce the smallest step size that
+ * can uniformly cover the list. Ideally this will be over half, but in
+ * degenerate cases this can fall to a minimum of 5 (the lower limit).
+ */
+double GetUniformElevStep(const double epsilon, std::vector<double> &elems)
+{
+ if(elems.size() < 5) return 0.0;
+
+ /* Reverse the elevations so it increments starting with -90 (flipped from
+ * +90). This makes it easier to work out a proper stepping value.
+ */
+ std::reverse(elems.begin(), elems.end());
+ for(auto &v : elems) v *= -1.0;
+
+ uint count{static_cast<uint>(std::ceil(180.0 / (elems[1]-elems[0])))};
+ count = std::min(count, 255u);
+
+ double ret{0.0};
+ for(;count >= 5;--count)
+ {
+ const double step{180.0 / count};
+ bool good{true};
+ size_t idx{1u};
+ /* Elevations don't need to match all multiples if there's not enough
+ * elements to check. Missing elevations can be synthesized.
+ */
+ for(uint mult{1u};mult <= count && idx < elems.size() && good;++mult)
+ {
+ const double target{step*mult + elems[0]};
+ while(idx < elems.size() && target-elems[idx] > epsilon)
+ ++idx;
+ good &= !(idx < elems.size()) || !(std::abs(target-elems[idx++]) > epsilon);
+ }
+ if(good)
+ {
+ ret = step;
+ break;
+ }
+ }
+ /* Re-reverse the elevations to restore the correct order. */
+ for(auto &v : elems) v *= -1.0;
+ std::reverse(elems.begin(), elems.end());
+
+ return ret;
+}
+
+} // namespace
+
+
+const char *SofaErrorStr(int err)
+{
+ switch(err)
+ {
+ case MYSOFA_OK: return "OK";
+ case MYSOFA_INVALID_FORMAT: return "Invalid format";
+ case MYSOFA_UNSUPPORTED_FORMAT: return "Unsupported format";
+ case MYSOFA_INTERNAL_ERROR: return "Internal error";
+ case MYSOFA_NO_MEMORY: return "Out of memory";
+ case MYSOFA_READ_ERROR: return "Read error";
+ }
+ return "Unknown";
+}
+
+std::vector<SofaField> GetCompatibleLayout(const size_t m, const float *xyzs)
+{
+ auto aers = std::vector<double3>(m, double3{});
+ for(size_t i{0u};i < m;++i)
+ {
+ float vals[3]{xyzs[i*3], xyzs[i*3 + 1], xyzs[i*3 + 2]};
+ mysofa_c2s(&vals[0]);
+ aers[i] = {vals[0], vals[1], vals[2]};
+ }
+
+ auto radii = GetUniquelySortedElems(aers, 2, {}, {0.1, 0.1, 0.001});
+ std::vector<SofaField> fds;
+ fds.reserve(radii.size());
+
+ for(const double dist : radii)
+ {
+ auto elevs = GetUniquelySortedElems(aers, 1, {nullptr, nullptr, &dist}, {0.1, 0.1, 0.001});
+
+ /* Remove elevations that don't have a valid set of azimuths. */
+ auto invalid_elev = [&dist,&aers](const double ev) -> bool
+ {
+ auto azims = GetUniquelySortedElems(aers, 0, {nullptr, &ev, &dist}, {0.1, 0.1, 0.001});
+
+ if(std::abs(ev) > 89.999)
+ return azims.size() != 1;
+ if(azims.empty() || !(std::abs(azims[0]) < 0.1))
+ return true;
+ return GetUniformAzimStep(0.1, azims) <= 0.0;
+ };
+ elevs.erase(std::remove_if(elevs.begin(), elevs.end(), invalid_elev), elevs.end());
+
+ double step{GetUniformElevStep(0.1, elevs)};
+ if(step <= 0.0)
+ {
+ if(elevs.empty())
+ fprintf(stdout, "No usable elevations on field distance %f.\n", dist);
+ else
+ {
+ fprintf(stdout, "Non-uniform elevations on field distance %.3f.\nGot: %+.2f", dist,
+ elevs[0]);
+ for(size_t ei{1u};ei < elevs.size();++ei)
+ fprintf(stdout, ", %+.2f", elevs[ei]);
+ fputc('\n', stdout);
+ }
+ continue;
+ }
+
+ uint evStart{0u};
+ for(uint ei{0u};ei < elevs.size();ei++)
+ {
+ if(!(elevs[ei] < 0.0))
+ {
+ fprintf(stdout, "Too many missing elevations on field distance %f.\n", dist);
+ return fds;
+ }
+
+ double eif{(90.0+elevs[ei]) / step};
+ const double ev_start{std::round(eif)};
+
+ if(std::abs(eif - ev_start) < (0.1/step))
+ {
+ evStart = static_cast<uint>(ev_start);
+ break;
+ }
+ }
+
+ const auto evCount = static_cast<uint>(std::round(180.0 / step)) + 1;
+ if(evCount < 5)
+ {
+ fprintf(stdout, "Too few uniform elevations on field distance %f.\n", dist);
+ continue;
+ }
+
+ SofaField field{};
+ field.mDistance = dist;
+ field.mEvCount = evCount;
+ field.mEvStart = evStart;
+ field.mAzCounts.resize(evCount, 0u);
+ auto &azCounts = field.mAzCounts;
+
+ for(uint ei{evStart};ei < evCount;ei++)
+ {
+ double ev{-90.0 + ei*180.0/(evCount - 1)};
+ auto azims = GetUniquelySortedElems(aers, 0, {nullptr, &ev, &dist}, {0.1, 0.1, 0.001});
+
+ if(ei == 0 || ei == (evCount-1))
+ {
+ if(azims.size() != 1)
+ {
+ fprintf(stdout, "Non-singular poles on field distance %f.\n", dist);
+ return fds;
+ }
+ azCounts[ei] = 1;
+ }
+ else
+ {
+ step = GetUniformAzimStep(0.1, azims);
+ if(step <= 0.0)
+ {
+ fprintf(stdout, "Non-uniform azimuths on elevation %f, field distance %f.\n",
+ ev, dist);
+ return fds;
+ }
+ azCounts[ei] = static_cast<uint>(std::round(360.0f / step));
+ }
+ }
+
+ fds.emplace_back(std::move(field));
+ }
+
+ return fds;
+}
diff --git a/utils/sofa-support.h b/utils/sofa-support.h
new file mode 100644
index 00000000..1229f49d
--- /dev/null
+++ b/utils/sofa-support.h
@@ -0,0 +1,30 @@
+#ifndef UTILS_SOFA_SUPPORT_H
+#define UTILS_SOFA_SUPPORT_H
+
+#include <cstddef>
+#include <memory>
+#include <vector>
+
+#include "mysofa.h"
+
+
+struct MySofaDeleter {
+ void operator()(MYSOFA_HRTF *sofa) { mysofa_free(sofa); }
+};
+using MySofaHrtfPtr = std::unique_ptr<MYSOFA_HRTF,MySofaDeleter>;
+
+// Per-field measurement info.
+struct SofaField {
+ using uint = unsigned int;
+
+ double mDistance{0.0};
+ uint mEvCount{0u};
+ uint mEvStart{0u};
+ std::vector<uint> mAzCounts;
+};
+
+const char *SofaErrorStr(int err);
+
+std::vector<SofaField> GetCompatibleLayout(const size_t m, const float *xyzs);
+
+#endif /* UTILS_SOFA_SUPPORT_H */