Hrtf.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #pragma once
  2. #include <array>
  3. #include <cstdint>
  4. #include <memory>
  5. #include <vector>
  6. // OpenAL Soft 1.21.1's HRTF renderer as linked into WE's mediaextensions64.dll (alc/hrtf.cpp, hrtfbase.h, voice.cpp
  7. // DoHrtfMix, polyphase_resampler.cpp; LGPL, Chris Robinson) OpenAL turns it on by itself for stereo headphones/headset
  8. // endpoints (sub_1801990F0, sub_180186400): full mode, built-in KEMAR set resampled to the device rate
  9. namespace WallpaperEngine::Audio::Hrtf {
  10. constexpr unsigned HistoryLength = 64;
  11. constexpr unsigned HrirLength = 128;
  12. constexpr unsigned DirectDelay = 256;
  13. constexpr unsigned BufferLineSize = 1024;
  14. using HrirArray = std::array<std::array<float, 2>, HrirLength>;
  15. struct Store {
  16. unsigned sampleRate = 0;
  17. unsigned irSize = 0;
  18. struct Field {
  19. float distance;
  20. uint8_t evCount;
  21. };
  22. struct Elevation {
  23. uint16_t azCount;
  24. uint16_t irOffset;
  25. };
  26. /** stored backwards like OpenAL: the farthest field first */
  27. std::vector<Field> fields;
  28. std::vector<Elevation> elevations;
  29. std::vector<HrirArray> coeffs;
  30. std::vector<std::array<uint8_t, 2>> delays;
  31. };
  32. std::unique_ptr<Store> loadDefault (unsigned deviceRate);
  33. struct Filter {
  34. alignas (16) HrirArray coeffs {};
  35. std::array<unsigned, 2> delay {};
  36. float gain = 0.0f;
  37. };
  38. void getCoeffs (const Store& store, float elevation, float azimuth, float distance, float spread, Filter& out);
  39. struct Channel {
  40. std::array<float, HistoryLength> history {};
  41. Filter old {};
  42. };
  43. class Mixer {
  44. public:
  45. explicit Mixer (unsigned irSize);
  46. // DoHrtfMix for one channel over a pass of count samples; counter is OpenAL's fade counter (0 on a voice's first
  47. // update), the IR crossfade only happens at outPos 0
  48. void mix (
  49. Channel& channel, const Filter& target, const float* samples, unsigned count, unsigned counter,
  50. unsigned outPos = 0
  51. );
  52. void finish (float* left, float* right, unsigned count);
  53. void clear ();
  54. [[nodiscard]] unsigned irSize () const { return this->m_irSize; }
  55. private:
  56. unsigned m_irSize;
  57. std::vector<std::array<float, 2>> m_accum;
  58. std::vector<float> m_samples;
  59. };
  60. }