alcmain.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. #ifndef ALC_MAIN_H
  2. #define ALC_MAIN_H
  3. #include <algorithm>
  4. #include <array>
  5. #include <atomic>
  6. #include <bitset>
  7. #include <chrono>
  8. #include <cstdint>
  9. #include <cstddef>
  10. #include <memory>
  11. #include <mutex>
  12. #include <string>
  13. #include <thread>
  14. #include <utility>
  15. #include "AL/al.h"
  16. #include "AL/alc.h"
  17. #include "AL/alext.h"
  18. #include "almalloc.h"
  19. #include "alnumeric.h"
  20. #include "alspan.h"
  21. #include "atomic.h"
  22. #include "core/ambidefs.h"
  23. #include "core/bufferline.h"
  24. #include "core/devformat.h"
  25. #include "core/filters/splitter.h"
  26. #include "core/mixer/defs.h"
  27. #include "hrtf.h"
  28. #include "inprogext.h"
  29. #include "intrusive_ptr.h"
  30. #include "vector.h"
  31. class BFormatDec;
  32. struct ALbuffer;
  33. struct ALeffect;
  34. struct ALfilter;
  35. struct BackendBase;
  36. struct Compressor;
  37. struct EffectState;
  38. struct Uhj2Encoder;
  39. struct bs2b;
  40. using uint = unsigned int;
  41. #define MIN_OUTPUT_RATE 8000
  42. #define MAX_OUTPUT_RATE 192000
  43. #define DEFAULT_OUTPUT_RATE 44100
  44. #define DEFAULT_UPDATE_SIZE 882 /* 20ms */
  45. #define DEFAULT_NUM_UPDATES 3
  46. enum class DeviceType : unsigned char {
  47. Playback,
  48. Capture,
  49. Loopback
  50. };
  51. enum class RenderMode : unsigned char {
  52. Normal,
  53. Pairwise,
  54. Hrtf
  55. };
  56. struct InputRemixMap {
  57. struct TargetMix { Channel channel; float mix; };
  58. Channel channel;
  59. std::array<TargetMix,2> targets;
  60. };
  61. struct BufferSubList {
  62. uint64_t FreeMask{~0_u64};
  63. ALbuffer *Buffers{nullptr}; /* 64 */
  64. BufferSubList() noexcept = default;
  65. BufferSubList(const BufferSubList&) = delete;
  66. BufferSubList(BufferSubList&& rhs) noexcept : FreeMask{rhs.FreeMask}, Buffers{rhs.Buffers}
  67. { rhs.FreeMask = ~0_u64; rhs.Buffers = nullptr; }
  68. ~BufferSubList();
  69. BufferSubList& operator=(const BufferSubList&) = delete;
  70. BufferSubList& operator=(BufferSubList&& rhs) noexcept
  71. { std::swap(FreeMask, rhs.FreeMask); std::swap(Buffers, rhs.Buffers); return *this; }
  72. };
  73. struct EffectSubList {
  74. uint64_t FreeMask{~0_u64};
  75. ALeffect *Effects{nullptr}; /* 64 */
  76. EffectSubList() noexcept = default;
  77. EffectSubList(const EffectSubList&) = delete;
  78. EffectSubList(EffectSubList&& rhs) noexcept : FreeMask{rhs.FreeMask}, Effects{rhs.Effects}
  79. { rhs.FreeMask = ~0_u64; rhs.Effects = nullptr; }
  80. ~EffectSubList();
  81. EffectSubList& operator=(const EffectSubList&) = delete;
  82. EffectSubList& operator=(EffectSubList&& rhs) noexcept
  83. { std::swap(FreeMask, rhs.FreeMask); std::swap(Effects, rhs.Effects); return *this; }
  84. };
  85. struct FilterSubList {
  86. uint64_t FreeMask{~0_u64};
  87. ALfilter *Filters{nullptr}; /* 64 */
  88. FilterSubList() noexcept = default;
  89. FilterSubList(const FilterSubList&) = delete;
  90. FilterSubList(FilterSubList&& rhs) noexcept : FreeMask{rhs.FreeMask}, Filters{rhs.Filters}
  91. { rhs.FreeMask = ~0_u64; rhs.Filters = nullptr; }
  92. ~FilterSubList();
  93. FilterSubList& operator=(const FilterSubList&) = delete;
  94. FilterSubList& operator=(FilterSubList&& rhs) noexcept
  95. { std::swap(FreeMask, rhs.FreeMask); std::swap(Filters, rhs.Filters); return *this; }
  96. };
  97. /* Maximum delay in samples for speaker distance compensation. */
  98. #define MAX_DELAY_LENGTH 1024
  99. struct DistanceComp {
  100. struct ChanData {
  101. float Gain{1.0f};
  102. uint Length{0u}; /* Valid range is [0...MAX_DELAY_LENGTH). */
  103. float *Buffer{nullptr};
  104. };
  105. std::array<ChanData,MAX_OUTPUT_CHANNELS> mChannels;
  106. al::FlexArray<float,16> mSamples;
  107. DistanceComp(size_t count) : mSamples{count} { }
  108. static std::unique_ptr<DistanceComp> Create(size_t numsamples)
  109. { return std::unique_ptr<DistanceComp>{new(FamCount(numsamples)) DistanceComp{numsamples}}; }
  110. DEF_FAM_NEWDEL(DistanceComp, mSamples)
  111. };
  112. struct BFChannelConfig {
  113. float Scale;
  114. uint Index;
  115. };
  116. struct MixParams {
  117. /* Coefficient channel mapping for mixing to the buffer. */
  118. std::array<BFChannelConfig,MAX_OUTPUT_CHANNELS> AmbiMap{};
  119. al::span<FloatBufferLine> Buffer;
  120. };
  121. struct RealMixParams {
  122. al::span<const InputRemixMap> RemixMap;
  123. std::array<uint,MaxChannels> ChannelIndex{};
  124. al::span<FloatBufferLine> Buffer;
  125. };
  126. enum {
  127. // Frequency was requested by the app or config file
  128. FrequencyRequest,
  129. // Channel configuration was requested by the config file
  130. ChannelsRequest,
  131. // Sample type was requested by the config file
  132. SampleTypeRequest,
  133. // Specifies if the DSP is paused at user request
  134. DevicePaused,
  135. // Specifies if the device is currently running
  136. DeviceRunning,
  137. DeviceFlagsCount
  138. };
  139. struct ALCdevice : public al::intrusive_ref<ALCdevice> {
  140. std::atomic<bool> Connected{true};
  141. const DeviceType Type{};
  142. uint Frequency{};
  143. uint UpdateSize{};
  144. uint BufferSize{};
  145. DevFmtChannels FmtChans{};
  146. DevFmtType FmtType{};
  147. bool IsHeadphones{false};
  148. uint mAmbiOrder{0};
  149. float mXOverFreq{400.0f};
  150. /* For DevFmtAmbi* output only, specifies the channel order and
  151. * normalization.
  152. */
  153. DevAmbiLayout mAmbiLayout{DevAmbiLayout::Default};
  154. DevAmbiScaling mAmbiScale{DevAmbiScaling::Default};
  155. std::string DeviceName;
  156. // Device flags
  157. std::bitset<DeviceFlagsCount> Flags{};
  158. // Maximum number of sources that can be created
  159. uint SourcesMax{};
  160. // Maximum number of slots that can be created
  161. uint AuxiliaryEffectSlotMax{};
  162. /* Rendering mode. */
  163. RenderMode mRenderMode{RenderMode::Normal};
  164. /* The average speaker distance as determined by the ambdec configuration,
  165. * HRTF data set, or the NFC-HOA reference delay. Only used for NFC.
  166. */
  167. float AvgSpeakerDist{0.0f};
  168. uint SamplesDone{0u};
  169. std::chrono::nanoseconds ClockBase{0};
  170. std::chrono::nanoseconds FixedLatency{0};
  171. /* Temp storage used for mixer processing. */
  172. alignas(16) float SourceData[BufferLineSize + MaxResamplerPadding];
  173. alignas(16) float ResampledData[BufferLineSize];
  174. alignas(16) float FilteredData[BufferLineSize];
  175. union {
  176. alignas(16) float HrtfSourceData[BufferLineSize + HrtfHistoryLength];
  177. alignas(16) float NfcSampleData[BufferLineSize];
  178. };
  179. /* Persistent storage for HRTF mixing. */
  180. alignas(16) float2 HrtfAccumData[BufferLineSize + HrirLength + HrtfDirectDelay];
  181. /* Mixing buffer used by the Dry mix and Real output. */
  182. al::vector<FloatBufferLine, 16> MixBuffer;
  183. /* The "dry" path corresponds to the main output. */
  184. MixParams Dry;
  185. uint NumChannelsPerOrder[MaxAmbiOrder+1]{};
  186. /* "Real" output, which will be written to the device buffer. May alias the
  187. * dry buffer.
  188. */
  189. RealMixParams RealOut;
  190. /* HRTF state and info */
  191. std::unique_ptr<DirectHrtfState> mHrtfState;
  192. al::intrusive_ptr<HrtfStore> mHrtf;
  193. uint mIrSize{0};
  194. /* Ambisonic-to-UHJ encoder */
  195. std::unique_ptr<Uhj2Encoder> Uhj_Encoder;
  196. /* Ambisonic decoder for speakers */
  197. std::unique_ptr<BFormatDec> AmbiDecoder;
  198. /* Stereo-to-binaural filter */
  199. std::unique_ptr<bs2b> Bs2b;
  200. using PostProc = void(ALCdevice::*)(const size_t SamplesToDo);
  201. PostProc PostProcess{nullptr};
  202. std::unique_ptr<Compressor> Limiter;
  203. /* Delay buffers used to compensate for speaker distances. */
  204. std::unique_ptr<DistanceComp> ChannelDelays;
  205. /* Dithering control. */
  206. float DitherDepth{0.0f};
  207. uint DitherSeed{0u};
  208. /* Running count of the mixer invocations, in 31.1 fixed point. This
  209. * actually increments *twice* when mixing, first at the start and then at
  210. * the end, so the bottom bit indicates if the device is currently mixing
  211. * and the upper bits indicates how many mixes have been done.
  212. */
  213. RefCount MixCount{0u};
  214. // Contexts created on this device
  215. std::atomic<al::FlexArray<ALCcontext*>*> mContexts{nullptr};
  216. /* This lock protects the device state (format, update size, etc) from
  217. * being from being changed in multiple threads, or being accessed while
  218. * being changed. It's also used to serialize calls to the backend.
  219. */
  220. std::mutex StateLock;
  221. std::unique_ptr<BackendBase> Backend;
  222. ALCuint NumMonoSources{};
  223. ALCuint NumStereoSources{};
  224. ALCuint NumAuxSends{};
  225. std::string HrtfName;
  226. al::vector<std::string> HrtfList;
  227. ALCenum HrtfStatus{ALC_FALSE};
  228. ALCenum LimiterState{ALC_DONT_CARE_SOFT};
  229. std::atomic<ALCenum> LastError{ALC_NO_ERROR};
  230. // Map of Buffers for this device
  231. std::mutex BufferLock;
  232. al::vector<BufferSubList> BufferList;
  233. // Map of Effects for this device
  234. std::mutex EffectLock;
  235. al::vector<EffectSubList> EffectList;
  236. // Map of Filters for this device
  237. std::mutex FilterLock;
  238. al::vector<FilterSubList> FilterList;
  239. ALCdevice(DeviceType type);
  240. ALCdevice(const ALCdevice&) = delete;
  241. ALCdevice& operator=(const ALCdevice&) = delete;
  242. ~ALCdevice();
  243. uint bytesFromFmt() const noexcept { return BytesFromDevFmt(FmtType); }
  244. uint channelsFromFmt() const noexcept { return ChannelsFromDevFmt(FmtChans, mAmbiOrder); }
  245. uint frameSizeFromFmt() const noexcept { return bytesFromFmt() * channelsFromFmt(); }
  246. uint waitForMix() const noexcept
  247. {
  248. uint refcount;
  249. while((refcount=MixCount.load(std::memory_order_acquire))&1) {
  250. }
  251. return refcount;
  252. }
  253. void ProcessHrtf(const size_t SamplesToDo);
  254. void ProcessAmbiDec(const size_t SamplesToDo);
  255. void ProcessAmbiDecStablized(const size_t SamplesToDo);
  256. void ProcessUhj(const size_t SamplesToDo);
  257. void ProcessBs2b(const size_t SamplesToDo);
  258. inline void postProcess(const size_t SamplesToDo)
  259. { if LIKELY(PostProcess) (this->*PostProcess)(SamplesToDo); }
  260. void renderSamples(void *outBuffer, const uint numSamples, const size_t frameStep);
  261. /* Caller must lock the device state, and the mixer must not be running. */
  262. [[gnu::format(printf,2,3)]] void handleDisconnect(const char *msg, ...);
  263. DEF_NEWDEL(ALCdevice)
  264. };
  265. /* Must be less than 15 characters (16 including terminating null) for
  266. * compatibility with pthread_setname_np limitations. */
  267. #define MIXER_THREAD_NAME "alsoft-mixer"
  268. #define RECORD_THREAD_NAME "alsoft-record"
  269. extern int RTPrioLevel;
  270. void SetRTPriority(void);
  271. /**
  272. * Returns the index for the given channel name (e.g. FrontCenter), or
  273. * INVALID_CHANNEL_INDEX if it doesn't exist.
  274. */
  275. inline uint GetChannelIdxByName(const RealMixParams &real, Channel chan) noexcept
  276. { return real.ChannelIndex[chan]; }
  277. #define INVALID_CHANNEL_INDEX ~0u
  278. al::vector<std::string> SearchDataFiles(const char *match, const char *subdir);
  279. #endif