Hrtf.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. #include "Hrtf.h"
  2. #include "WallpaperEngine/Audio/DefaultHrtf.generated.h"
  3. #include "WallpaperEngine/Logging/Log.h"
  4. #include "WallpaperEngine/Data/Utils/FloatCompare.h"
  5. #include <algorithm>
  6. #include <cmath>
  7. #include <cstring>
  8. #include <numeric>
  9. using namespace WallpaperEngine::Audio::Hrtf;
  10. namespace {
  11. constexpr float Pi = 3.14159265358979323846f;
  12. constexpr float Tau = 6.28318530717958647692f;
  13. constexpr unsigned MinIrLength = 8;
  14. constexpr unsigned MaxHrirDelay = HistoryLength - 1;
  15. constexpr unsigned HrirDelayFracOne = 4;
  16. constexpr float PassthruCoeff = 0.707106781187f;
  17. unsigned float2uint (float value) { return static_cast<unsigned> (static_cast<int> (value)); }
  18. /** polyphase_resampler.cpp: Kaiser windowed sinc, only used to bring the HRIRs to the device rate */
  19. class PolyphaseResampler {
  20. public:
  21. PolyphaseResampler (unsigned srcRate, unsigned dstRate) {
  22. const unsigned gcd = std::gcd (srcRate, dstRate);
  23. this->m_p = dstRate / gcd;
  24. this->m_q = srcRate / gcd;
  25. const double cutoff = 0.475 / std::max (this->m_p, this->m_q);
  26. const double width = 0.05 / std::max (this->m_p, this->m_q);
  27. // -180 dB stop band, the left offset rounded up so the transition doesn't widen
  28. const unsigned l = (kaiserOrder (180.0, width) + 1) / 2;
  29. const double beta = kaiserBeta (180.0);
  30. this->m_m = l * 2 + 1;
  31. this->m_l = l;
  32. this->m_filter.resize (this->m_m);
  33. for (unsigned i = 0; i < this->m_m; i++) {
  34. this->m_filter[i] = sincFilter (l, beta, this->m_p, cutoff, i);
  35. }
  36. }
  37. void process (unsigned inN, const double* in, unsigned outN, double* out) const {
  38. const unsigned p = this->m_p, q = this->m_q, m = this->m_m, l = this->m_l;
  39. const double* f = this->m_filter.data ();
  40. for (unsigned i = 0; i < outN; i++) {
  41. size_t jf = (l + q * i) % p;
  42. size_t js = (l + q * i) / p;
  43. double r = 0.0;
  44. if (jf < m) {
  45. size_t length = (m - jf + p - 1) / p;
  46. if (js + 1 > inN) {
  47. const size_t skip = std::min<size_t> (js + 1 - inN, length);
  48. jf += p * skip;
  49. js -= skip;
  50. length -= skip;
  51. }
  52. for (size_t todo = std::min<size_t> (js + 1, length); todo > 0; todo--) {
  53. r += f[jf] * in[js];
  54. jf += p;
  55. --js;
  56. }
  57. }
  58. out[i] = r;
  59. }
  60. }
  61. private:
  62. static double sinc (double x) {
  63. if (std::abs (x) < 1e-9) {
  64. return 1.0;
  65. }
  66. return std::sin (M_PI * x) / (M_PI * x);
  67. }
  68. static double besselI0 (double x) {
  69. const double x2 = x / 2.0;
  70. double term = 1.0;
  71. double sum = 1.0;
  72. double last;
  73. int k = 1;
  74. do {
  75. const double y = x2 / k;
  76. ++k;
  77. last = sum;
  78. term *= y * y;
  79. sum += term;
  80. } while (!WallpaperEngine::Data::Utils::sameFloat (sum, last));
  81. return sum;
  82. }
  83. static double kaiser (double b, double k) {
  84. if (!(k >= -1.0 && k <= 1.0)) {
  85. return 0.0;
  86. }
  87. return besselI0 (b * std::sqrt (1.0 - k * k)) / besselI0 (b);
  88. }
  89. static unsigned kaiserOrder (double rejection, double transition) {
  90. const double wt = 2.0 * M_PI * transition;
  91. if (rejection > 21.0) {
  92. return static_cast<unsigned> (std::ceil ((rejection - 7.95) / (2.285 * wt)));
  93. }
  94. return static_cast<unsigned> (std::ceil (5.79 / wt));
  95. }
  96. static double kaiserBeta (double rejection) {
  97. if (rejection > 50.0) {
  98. return 0.1102 * (rejection - 8.7);
  99. }
  100. if (rejection >= 21.0) {
  101. return 0.5842 * std::pow (rejection - 21.0, 0.4) + 0.07886 * (rejection - 21.0);
  102. }
  103. return 0.0;
  104. }
  105. static double sincFilter (unsigned l, double b, double gain, double cutoff, unsigned i) {
  106. const double x = static_cast<double> (i) - l;
  107. return kaiser (b, x / l) * 2.0 * gain * cutoff * sinc (2.0 * cutoff * x);
  108. }
  109. unsigned m_p, m_q, m_m, m_l;
  110. std::vector<double> m_filter;
  111. };
  112. class Reader {
  113. public:
  114. Reader (const unsigned char* data, size_t size) : m_data (data), m_size (size) { }
  115. [[nodiscard]] bool good () const { return this->m_good; }
  116. unsigned read (unsigned bytes) {
  117. if (this->m_offset + bytes > this->m_size) {
  118. this->m_good = false;
  119. return 0;
  120. }
  121. unsigned value = 0;
  122. for (unsigned i = 0; i < bytes; i++) {
  123. value |= static_cast<unsigned> (this->m_data[this->m_offset++]) << (i * 8);
  124. }
  125. return value;
  126. }
  127. int read24 () {
  128. constexpr int signbit = 1 << 23;
  129. return (static_cast<int> (this->read (3)) ^ signbit) - signbit;
  130. }
  131. private:
  132. const unsigned char* m_data;
  133. size_t m_size;
  134. size_t m_offset = 0;
  135. bool m_good = true;
  136. };
  137. std::unique_ptr<Store> loadHrtf03 (Reader& data) {
  138. auto store = std::make_unique<Store> ();
  139. store->sampleRate = data.read (4);
  140. const unsigned channelType = data.read (1);
  141. store->irSize = data.read (1);
  142. const unsigned fdCount = data.read (1);
  143. if (!data.good () || channelType > 1 || store->irSize < MinIrLength || store->irSize > HrirLength || fdCount < 1
  144. || fdCount > 16) {
  145. return nullptr;
  146. }
  147. for (unsigned f = 0; f < fdCount; f++) {
  148. const unsigned distance = data.read (2);
  149. const unsigned evCount = data.read (1);
  150. if (!data.good () || distance < 50 || distance > 2500 || evCount < 5 || evCount > 181) {
  151. return nullptr;
  152. }
  153. store->fields.push_back ({ static_cast<float> (distance) / 1000.0f, static_cast<uint8_t> (evCount) });
  154. if (f > 0 && store->fields[f].distance > store->fields[f - 1].distance) {
  155. return nullptr;
  156. }
  157. for (unsigned e = 0; e < evCount; e++) {
  158. const auto azCount = static_cast<uint16_t> (data.read (1));
  159. if (azCount < 1) {
  160. return nullptr;
  161. }
  162. store->elevations.push_back ({ azCount, 0 });
  163. }
  164. }
  165. if (!data.good ()) {
  166. return nullptr;
  167. }
  168. for (size_t e = 1; e < store->elevations.size (); e++) {
  169. const auto& last = store->elevations[e - 1];
  170. store->elevations[e].irOffset = static_cast<uint16_t> (last.azCount + last.irOffset);
  171. }
  172. const auto irTotal = static_cast<size_t> (store->elevations.back ().azCount + store->elevations.back ().irOffset);
  173. store->coeffs.assign (irTotal, HrirArray {});
  174. store->delays.assign (irTotal, {});
  175. for (auto& hrir : store->coeffs) {
  176. for (unsigned k = 0; k < store->irSize; k++) {
  177. hrir[k][0] = static_cast<float> (data.read24 ()) / 8388608.0f;
  178. if (channelType == 1) {
  179. hrir[k][1] = static_cast<float> (data.read24 ()) / 8388608.0f;
  180. }
  181. }
  182. }
  183. for (auto& delay : store->delays) {
  184. delay[0] = static_cast<uint8_t> (data.read (1));
  185. if (channelType == 1) {
  186. delay[1] = static_cast<uint8_t> (data.read (1));
  187. }
  188. }
  189. if (!data.good ()) {
  190. return nullptr;
  191. }
  192. for (const auto& delay : store->delays) {
  193. if (delay[0] > MaxHrirDelay * HrirDelayFracOne || delay[1] > MaxHrirDelay * HrirDelayFracOne) {
  194. return nullptr;
  195. }
  196. }
  197. // left ear only: the right ear's response is the left one mirrored around the median plane
  198. if (channelType == 0) {
  199. for (const auto& elevation : store->elevations) {
  200. for (size_t j = 0; j < elevation.azCount; j++) {
  201. const size_t left = elevation.irOffset + j;
  202. const size_t right = elevation.irOffset + (elevation.azCount - j) % elevation.azCount;
  203. for (size_t k = 0; k < HrirLength; k++) {
  204. store->coeffs[right][k][1] = store->coeffs[left][k][0];
  205. }
  206. store->delays[right][1] = store->delays[left][0];
  207. }
  208. }
  209. }
  210. return store;
  211. }
  212. void resample (Store& store, unsigned deviceRate) {
  213. std::array<std::array<double, HrirLength>, 2> inout {};
  214. const PolyphaseResampler resampler (store.sampleRate, deviceRate);
  215. for (auto& coeffs : store.coeffs) {
  216. for (size_t j = 0; j < 2; j++) {
  217. for (size_t k = 0; k < HrirLength; k++) {
  218. inout[0][k] = coeffs[k][j];
  219. }
  220. resampler.process (HrirLength, inout[0].data (), HrirLength, inout[1].data ());
  221. for (size_t k = 0; k < HrirLength; k++) {
  222. coeffs[k][j] = static_cast<float> (inout[1][k]);
  223. }
  224. }
  225. }
  226. // delays scaled for the new rate, shrunk together (a smaller head) if one passes the history length
  227. const float rateScale = static_cast<float> (deviceRate) / static_cast<float> (store.sampleRate);
  228. std::vector<std::array<float, 2>> delays (store.delays.size ());
  229. float maxDelay = 0.0f;
  230. for (size_t i = 0; i < store.delays.size (); i++) {
  231. for (size_t j = 0; j < 2; j++) {
  232. const float delay = std::round (static_cast<float> (store.delays[i][j]) * rateScale)
  233. / static_cast<float> (HrirDelayFracOne);
  234. maxDelay = std::max (maxDelay, delay);
  235. delays[i][j] = delay;
  236. }
  237. }
  238. float delayScale = HrirDelayFracOne;
  239. if (maxDelay > MaxHrirDelay) {
  240. sLog.debug ("HRTF: resampled delay exceeds the maximum (", maxDelay, " > ", MaxHrirDelay, ")");
  241. delayScale *= static_cast<float> (MaxHrirDelay) / maxDelay;
  242. }
  243. for (size_t i = 0; i < store.delays.size (); i++) {
  244. for (size_t j = 0; j < 2; j++) {
  245. store.delays[i][j] = static_cast<uint8_t> (static_cast<int> (delays[i][j] * delayScale + 0.5f));
  246. }
  247. }
  248. const float irSize = std::round (static_cast<float> (store.irSize) * rateScale);
  249. store.irSize = static_cast<unsigned> (std::min (static_cast<float> (HrirLength), irSize));
  250. store.sampleRate = deviceRate;
  251. }
  252. struct IdxBlend {
  253. unsigned idx;
  254. float blend;
  255. };
  256. IdxBlend evIndex (unsigned evCount, float elevation) {
  257. elevation = (Pi * 0.5f + elevation) * static_cast<float> (evCount - 1) / Pi;
  258. const unsigned idx = float2uint (elevation);
  259. return { std::min (idx, evCount - 1), elevation - static_cast<float> (idx) };
  260. }
  261. IdxBlend azIndex (unsigned azCount, float azimuth) {
  262. azimuth = (Tau + azimuth) * static_cast<float> (azCount) / Tau;
  263. const unsigned idx = float2uint (azimuth);
  264. return { idx % azCount, azimuth - static_cast<float> (idx) };
  265. }
  266. /**
  267. * ApplyCoeffs. The DLL mixes with the SSE variant (sub_1801A5EA0/sub_1801A6010), which goes through the taps in
  268. * pairs: an odd IR size also gets the next tap of the (resampled, so not zero) response
  269. */
  270. void applyCoeffs (std::array<float, 2>* values, unsigned irSize, const HrirArray& coeffs, float left, float right) {
  271. const unsigned taps = (irSize + 1) & ~1u;
  272. for (unsigned c = 0; c < taps; c++) {
  273. values[c][0] += coeffs[c][0] * left;
  274. values[c][1] += coeffs[c][1] * right;
  275. }
  276. }
  277. }
  278. std::unique_ptr<Store> WallpaperEngine::Audio::Hrtf::loadDefault (unsigned deviceRate) {
  279. if (sizeof (DEFAULT_HRTF) < 8 || std::memcmp (DEFAULT_HRTF, "MinPHR03", 8) != 0) {
  280. sLog.error ("HRTF: the built-in data set has an unknown header");
  281. return nullptr;
  282. }
  283. Reader reader (DEFAULT_HRTF + 8, sizeof (DEFAULT_HRTF) - 8);
  284. auto store = loadHrtf03 (reader);
  285. if (store == nullptr) {
  286. sLog.error ("HRTF: failed to read the built-in data set");
  287. return nullptr;
  288. }
  289. if (store->sampleRate != deviceRate) {
  290. resample (*store, deviceRate);
  291. }
  292. sLog.debug ("HRTF: loaded the built-in data set for ", store->sampleRate, "hz, ", store->irSize, "-sample filter");
  293. return store;
  294. }
  295. void WallpaperEngine::Audio::Hrtf::getCoeffs (
  296. const Store& store, float elevation, float azimuth, float distance, float spread, Filter& out
  297. ) {
  298. const float dirfact = 1.0f - spread / Tau;
  299. size_t field = 0;
  300. size_t ebase = 0;
  301. while (distance < store.fields[field].distance && field != store.fields.size () - 1) {
  302. ebase += store.fields[field].evCount;
  303. ++field;
  304. }
  305. const unsigned evCount = store.fields[field].evCount;
  306. const auto elev0 = evIndex (evCount, elevation);
  307. const size_t elev1 = std::min (elev0.idx + 1, evCount - 1);
  308. const auto& e0 = store.elevations[ebase + elev0.idx];
  309. const auto& e1 = store.elevations[ebase + elev1];
  310. const auto az0 = azIndex (e0.azCount, azimuth);
  311. const auto az1 = azIndex (e1.azCount, azimuth);
  312. const size_t idx[4] = { e0.irOffset + az0.idx, e0.irOffset + (az0.idx + 1) % e0.azCount, e1.irOffset + az1.idx,
  313. e1.irOffset + (az1.idx + 1) % e1.azCount };
  314. const float blend[4]
  315. = { (1.0f - elev0.blend) * (1.0f - az0.blend) * dirfact, (1.0f - elev0.blend) * az0.blend * dirfact,
  316. elev0.blend * (1.0f - az1.blend) * dirfact, elev0.blend * az1.blend * dirfact };
  317. for (size_t ear = 0; ear < 2; ear++) {
  318. float d = static_cast<float> (store.delays[idx[0]][ear]) * blend[0];
  319. d += static_cast<float> (store.delays[idx[1]][ear]) * blend[1];
  320. d += static_cast<float> (store.delays[idx[2]][ear]) * blend[2];
  321. d += static_cast<float> (store.delays[idx[3]][ear]) * blend[3];
  322. // fastf2u: cvtss2si, rounded to nearest (0x18018AE8D), not truncated like the indices
  323. out.delay[ear] = static_cast<unsigned> (std::lrint (d * (1.0f / HrirDelayFracOne)));
  324. }
  325. out.coeffs = {};
  326. out.coeffs[0][0] = PassthruCoeff * (1.0f - dirfact);
  327. out.coeffs[0][1] = PassthruCoeff * (1.0f - dirfact);
  328. for (size_t c = 0; c < 4; c++) {
  329. const HrirArray& source = store.coeffs[idx[c]];
  330. for (size_t k = 0; k < HrirLength; k++) {
  331. out.coeffs[k][0] = source[k][0] * blend[c] + out.coeffs[k][0];
  332. out.coeffs[k][1] = source[k][1] * blend[c] + out.coeffs[k][1];
  333. }
  334. }
  335. }
  336. Mixer::Mixer (unsigned irSize) :
  337. m_irSize (irSize), m_accum (BufferLineSize + HrirLength + DirectDelay), m_samples (HistoryLength + BufferLineSize) {
  338. }
  339. void Mixer::mix (
  340. Channel& channel, const Filter& target, const float* samples, unsigned count, unsigned counter, unsigned outPos
  341. ) {
  342. // voice mixing lands after the direct delay, aligned with the device's own HRTF filtering of the dry buffer
  343. auto* accum = this->m_accum.data () + DirectDelay + outPos;
  344. float* input = this->m_samples.data ();
  345. std::copy (channel.history.begin (), channel.history.end (), input);
  346. std::copy_n (samples, count, input + HistoryLength);
  347. std::copy_n (input + count, HistoryLength, channel.history.begin ());
  348. if (counter == 0) {
  349. channel.old = target;
  350. }
  351. unsigned pos = 0;
  352. unsigned fademix = 0;
  353. // fading: the new response fades in while the old one fades out, in the update's first pass only
  354. if (counter > 0 && outPos == 0) {
  355. fademix = std::min (count, counter);
  356. float gain = target.gain;
  357. if (counter > fademix) {
  358. const float a = static_cast<float> (fademix) / static_cast<float> (counter);
  359. gain = channel.old.gain + (target.gain - channel.old.gain) * a;
  360. }
  361. const float newGainStep = gain / static_cast<float> (fademix);
  362. if (channel.old.gain > 0.00001f) {
  363. const float oldGainStep = channel.old.gain / static_cast<float> (fademix);
  364. size_t left = HistoryLength - channel.old.delay[0];
  365. size_t right = HistoryLength - channel.old.delay[1];
  366. auto stepcount = static_cast<float> (fademix);
  367. for (unsigned i = 0; i < fademix; i++) {
  368. const float g = oldGainStep * stepcount;
  369. applyCoeffs (accum + i, this->m_irSize, channel.old.coeffs, input[left++] * g, input[right++] * g);
  370. stepcount -= 1.0f;
  371. }
  372. }
  373. if (newGainStep * static_cast<float> (fademix) > 0.00001f) {
  374. size_t left = HistoryLength + 1 - target.delay[0];
  375. size_t right = HistoryLength + 1 - target.delay[1];
  376. float stepcount = 1.0f;
  377. for (unsigned i = 1; i < fademix; i++) {
  378. const float g = newGainStep * stepcount;
  379. applyCoeffs (accum + i, this->m_irSize, target.coeffs, input[left++] * g, input[right++] * g);
  380. stepcount += 1.0f;
  381. }
  382. }
  383. channel.old = target;
  384. channel.old.gain = gain;
  385. pos = fademix;
  386. }
  387. if (fademix < count) {
  388. const unsigned todo = count - fademix;
  389. float gain = target.gain;
  390. if (counter > count) {
  391. const float a = static_cast<float> (todo) / static_cast<float> (counter - fademix);
  392. gain = channel.old.gain + (target.gain - channel.old.gain) * a;
  393. }
  394. const float gainStep = (gain - channel.old.gain) / static_cast<float> (todo);
  395. const float* source = input + fademix;
  396. size_t left = HistoryLength - target.delay[0];
  397. size_t right = HistoryLength - target.delay[1];
  398. float stepcount = 0.0f;
  399. for (unsigned i = 0; i < todo; i++) {
  400. const float g = channel.old.gain + gainStep * stepcount;
  401. applyCoeffs (accum + pos + i, this->m_irSize, target.coeffs, source[left++] * g, source[right++] * g);
  402. stepcount += 1.0f;
  403. }
  404. channel.old.gain = gain;
  405. }
  406. }
  407. void Mixer::finish (float* left, float* right, unsigned count) {
  408. for (unsigned i = 0; i < count; i++) {
  409. left[i] = this->m_accum[i][0];
  410. right[i] = this->m_accum[i][1];
  411. }
  412. const auto end = std::copy_n (this->m_accum.begin () + count, HrirLength + DirectDelay, this->m_accum.begin ());
  413. std::fill_n (end, count, std::array<float, 2> {});
  414. }
  415. void Mixer::clear () { std::ranges::fill (this->m_accum, std::array<float, 2> {}); }