🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

573 lines
15 KiB

  1. #ifndef AL_MAIN_H
  2. #define AL_MAIN_H
  3. #include <string.h>
  4. #include <stdio.h>
  5. #include <stddef.h>
  6. #include <stdarg.h>
  7. #include <assert.h>
  8. #include <math.h>
  9. #include <limits.h>
  10. #ifdef HAVE_STRINGS_H
  11. #include <strings.h>
  12. #endif
  13. #include <array>
  14. #include <vector>
  15. #include <string>
  16. #include <chrono>
  17. #include <algorithm>
  18. #include "AL/al.h"
  19. #include "AL/alc.h"
  20. #include "AL/alext.h"
  21. #include "inprogext.h"
  22. #include "atomic.h"
  23. #include "vector.h"
  24. #include "almalloc.h"
  25. #include "alnumeric.h"
  26. #include "threads.h"
  27. #include "ambidefs.h"
  28. #include "hrtf.h"
  29. template<typename T, size_t N>
  30. constexpr inline size_t countof(const T(&)[N]) noexcept
  31. { return N; }
  32. #define COUNTOF countof
  33. #ifndef UNUSED
  34. #if defined(__cplusplus)
  35. #define UNUSED(x)
  36. #elif defined(__GNUC__)
  37. #define UNUSED(x) UNUSED_##x __attribute__((unused))
  38. #elif defined(__LCLINT__)
  39. #define UNUSED(x) /*@unused@*/ x
  40. #else
  41. #define UNUSED(x) x
  42. #endif
  43. #endif
  44. #if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__)
  45. #define IS_LITTLE_ENDIAN (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
  46. #else
  47. static const union {
  48. ALuint u;
  49. ALubyte b[sizeof(ALuint)];
  50. } EndianTest = { 1 };
  51. #define IS_LITTLE_ENDIAN (EndianTest.b[0] == 1)
  52. #endif
  53. struct HrtfEntry;
  54. struct HrtfHandle;
  55. struct EnumeratedHrtf;
  56. struct DirectHrtfState;
  57. struct FrontStablizer;
  58. struct Compressor;
  59. struct BackendBase;
  60. struct ALbuffer;
  61. struct ALeffect;
  62. struct ALfilter;
  63. struct EffectState;
  64. struct Uhj2Encoder;
  65. class BFormatDec;
  66. class AmbiUpsampler;
  67. struct bs2b;
  68. #define MIN_OUTPUT_RATE 8000
  69. #define DEFAULT_OUTPUT_RATE 44100
  70. #define DEFAULT_UPDATE_SIZE 882 /* 20ms */
  71. #define DEFAULT_NUM_UPDATES 3
  72. enum Channel {
  73. FrontLeft = 0,
  74. FrontRight,
  75. FrontCenter,
  76. LFE,
  77. BackLeft,
  78. BackRight,
  79. BackCenter,
  80. SideLeft,
  81. SideRight,
  82. UpperFrontLeft,
  83. UpperFrontRight,
  84. UpperBackLeft,
  85. UpperBackRight,
  86. LowerFrontLeft,
  87. LowerFrontRight,
  88. LowerBackLeft,
  89. LowerBackRight,
  90. Aux0,
  91. Aux1,
  92. Aux2,
  93. Aux3,
  94. Aux4,
  95. Aux5,
  96. Aux6,
  97. Aux7,
  98. Aux8,
  99. Aux9,
  100. Aux10,
  101. Aux11,
  102. Aux12,
  103. Aux13,
  104. Aux14,
  105. Aux15,
  106. MaxChannels
  107. };
  108. /* Device formats */
  109. enum DevFmtType {
  110. DevFmtByte = ALC_BYTE_SOFT,
  111. DevFmtUByte = ALC_UNSIGNED_BYTE_SOFT,
  112. DevFmtShort = ALC_SHORT_SOFT,
  113. DevFmtUShort = ALC_UNSIGNED_SHORT_SOFT,
  114. DevFmtInt = ALC_INT_SOFT,
  115. DevFmtUInt = ALC_UNSIGNED_INT_SOFT,
  116. DevFmtFloat = ALC_FLOAT_SOFT,
  117. DevFmtTypeDefault = DevFmtFloat
  118. };
  119. enum DevFmtChannels {
  120. DevFmtMono = ALC_MONO_SOFT,
  121. DevFmtStereo = ALC_STEREO_SOFT,
  122. DevFmtQuad = ALC_QUAD_SOFT,
  123. DevFmtX51 = ALC_5POINT1_SOFT,
  124. DevFmtX61 = ALC_6POINT1_SOFT,
  125. DevFmtX71 = ALC_7POINT1_SOFT,
  126. DevFmtAmbi3D = ALC_BFORMAT3D_SOFT,
  127. /* Similar to 5.1, except using rear channels instead of sides */
  128. DevFmtX51Rear = 0x80000000,
  129. DevFmtChannelsDefault = DevFmtStereo
  130. };
  131. #define MAX_OUTPUT_CHANNELS (16)
  132. /* DevFmtType traits, providing the type, etc given a DevFmtType. */
  133. template<DevFmtType T>
  134. struct DevFmtTypeTraits { };
  135. template<>
  136. struct DevFmtTypeTraits<DevFmtByte> { using Type = ALbyte; };
  137. template<>
  138. struct DevFmtTypeTraits<DevFmtUByte> { using Type = ALubyte; };
  139. template<>
  140. struct DevFmtTypeTraits<DevFmtShort> { using Type = ALshort; };
  141. template<>
  142. struct DevFmtTypeTraits<DevFmtUShort> { using Type = ALushort; };
  143. template<>
  144. struct DevFmtTypeTraits<DevFmtInt> { using Type = ALint; };
  145. template<>
  146. struct DevFmtTypeTraits<DevFmtUInt> { using Type = ALuint; };
  147. template<>
  148. struct DevFmtTypeTraits<DevFmtFloat> { using Type = ALfloat; };
  149. ALsizei BytesFromDevFmt(DevFmtType type) noexcept;
  150. ALsizei ChannelsFromDevFmt(DevFmtChannels chans, ALsizei ambiorder) noexcept;
  151. inline ALsizei FrameSizeFromDevFmt(DevFmtChannels chans, DevFmtType type, ALsizei ambiorder) noexcept
  152. { return ChannelsFromDevFmt(chans, ambiorder) * BytesFromDevFmt(type); }
  153. enum class AmbiLayout {
  154. FuMa = ALC_FUMA_SOFT, /* FuMa channel order */
  155. ACN = ALC_ACN_SOFT, /* ACN channel order */
  156. Default = ACN
  157. };
  158. enum class AmbiNorm {
  159. FuMa = ALC_FUMA_SOFT, /* FuMa normalization */
  160. SN3D = ALC_SN3D_SOFT, /* SN3D normalization */
  161. N3D = ALC_N3D_SOFT, /* N3D normalization */
  162. Default = SN3D
  163. };
  164. enum DeviceType {
  165. Playback,
  166. Capture,
  167. Loopback
  168. };
  169. enum RenderMode {
  170. NormalRender,
  171. StereoPair,
  172. HrtfRender
  173. };
  174. struct BufferSubList {
  175. uint64_t FreeMask{~0_u64};
  176. ALbuffer *Buffers{nullptr}; /* 64 */
  177. BufferSubList() noexcept = default;
  178. BufferSubList(const BufferSubList&) = delete;
  179. BufferSubList(BufferSubList&& rhs) noexcept : FreeMask{rhs.FreeMask}, Buffers{rhs.Buffers}
  180. { rhs.FreeMask = ~0_u64; rhs.Buffers = nullptr; }
  181. ~BufferSubList();
  182. BufferSubList& operator=(const BufferSubList&) = delete;
  183. BufferSubList& operator=(BufferSubList&& rhs) noexcept
  184. { std::swap(FreeMask, rhs.FreeMask); std::swap(Buffers, rhs.Buffers); return *this; }
  185. };
  186. struct EffectSubList {
  187. uint64_t FreeMask{~0_u64};
  188. ALeffect *Effects{nullptr}; /* 64 */
  189. EffectSubList() noexcept = default;
  190. EffectSubList(const EffectSubList&) = delete;
  191. EffectSubList(EffectSubList&& rhs) noexcept : FreeMask{rhs.FreeMask}, Effects{rhs.Effects}
  192. { rhs.FreeMask = ~0_u64; rhs.Effects = nullptr; }
  193. ~EffectSubList();
  194. EffectSubList& operator=(const EffectSubList&) = delete;
  195. EffectSubList& operator=(EffectSubList&& rhs) noexcept
  196. { std::swap(FreeMask, rhs.FreeMask); std::swap(Effects, rhs.Effects); return *this; }
  197. };
  198. struct FilterSubList {
  199. uint64_t FreeMask{~0_u64};
  200. ALfilter *Filters{nullptr}; /* 64 */
  201. FilterSubList() noexcept = default;
  202. FilterSubList(const FilterSubList&) = delete;
  203. FilterSubList(FilterSubList&& rhs) noexcept : FreeMask{rhs.FreeMask}, Filters{rhs.Filters}
  204. { rhs.FreeMask = ~0_u64; rhs.Filters = nullptr; }
  205. ~FilterSubList();
  206. FilterSubList& operator=(const FilterSubList&) = delete;
  207. FilterSubList& operator=(FilterSubList&& rhs) noexcept
  208. { std::swap(FreeMask, rhs.FreeMask); std::swap(Filters, rhs.Filters); return *this; }
  209. };
  210. /* Maximum delay in samples for speaker distance compensation. */
  211. #define MAX_DELAY_LENGTH 1024
  212. class DistanceComp {
  213. public:
  214. struct DistData {
  215. ALfloat Gain{1.0f};
  216. ALsizei Length{0}; /* Valid range is [0...MAX_DELAY_LENGTH). */
  217. ALfloat *Buffer{nullptr};
  218. };
  219. private:
  220. DistData mChannel[MAX_OUTPUT_CHANNELS];
  221. al::vector<ALfloat,16> mSamples;
  222. public:
  223. void resize(size_t new_size) { mSamples.resize(new_size); }
  224. void shrink_to_fit() { mSamples.shrink_to_fit(); }
  225. void clear() noexcept
  226. {
  227. for(auto &chan : mChannel)
  228. {
  229. chan.Gain = 1.0f;
  230. chan.Length = 0;
  231. chan.Buffer = nullptr;
  232. }
  233. mSamples.clear();
  234. }
  235. DistData *begin() noexcept { return std::begin(mChannel); }
  236. const DistData *begin() const noexcept { return std::begin(mChannel); }
  237. const DistData *cbegin() const noexcept { return std::begin(mChannel); }
  238. DistData *end() noexcept { return std::end(mChannel); }
  239. const DistData *end() const noexcept { return std::end(mChannel); }
  240. const DistData *cend() const noexcept { return std::end(mChannel); }
  241. ALfloat *data() noexcept { return mSamples.data(); }
  242. const ALfloat *data() const noexcept { return mSamples.data(); }
  243. DistData& operator[](size_t o) noexcept { return mChannel[o]; }
  244. const DistData& operator[](size_t o) const noexcept { return mChannel[o]; }
  245. };
  246. struct BFChannelConfig {
  247. ALfloat Scale;
  248. ALsizei Index;
  249. };
  250. /* Size for temporary storage of buffer data, in ALfloats. Larger values need
  251. * more memory, while smaller values may need more iterations. The value needs
  252. * to be a sensible size, however, as it constrains the max stepping value used
  253. * for mixing, as well as the maximum number of samples per mixing iteration.
  254. */
  255. #define BUFFERSIZE 1024
  256. /* Maximum number of samples to pad on either end of a buffer for resampling.
  257. * Note that both the beginning and end need padding!
  258. */
  259. #define MAX_RESAMPLE_PADDING 24
  260. struct MixParams {
  261. /* Coefficient channel mapping for mixing to the buffer. */
  262. std::array<BFChannelConfig,MAX_OUTPUT_CHANNELS> AmbiMap;
  263. ALfloat (*Buffer)[BUFFERSIZE]{nullptr};
  264. ALsizei NumChannels{0};
  265. };
  266. struct RealMixParams {
  267. std::array<ALint,MaxChannels> ChannelIndex{};
  268. ALfloat (*Buffer)[BUFFERSIZE]{nullptr};
  269. ALsizei NumChannels{0};
  270. };
  271. using POSTPROCESS = void(*)(ALCdevice *device, const ALsizei SamplesToDo);
  272. struct ALCdevice {
  273. RefCount ref{1u};
  274. std::atomic<bool> Connected{true};
  275. const DeviceType Type{};
  276. ALuint Frequency{};
  277. ALuint UpdateSize{};
  278. ALuint BufferSize{};
  279. DevFmtChannels FmtChans{};
  280. DevFmtType FmtType{};
  281. ALboolean IsHeadphones{AL_FALSE};
  282. ALsizei mAmbiOrder{0};
  283. /* For DevFmtAmbi* output only, specifies the channel order and
  284. * normalization.
  285. */
  286. AmbiLayout mAmbiLayout{AmbiLayout::Default};
  287. AmbiNorm mAmbiScale{AmbiNorm::Default};
  288. ALCenum LimiterState{ALC_DONT_CARE_SOFT};
  289. std::string DeviceName;
  290. // Device flags
  291. ALuint Flags{0u};
  292. std::string HrtfName;
  293. al::vector<EnumeratedHrtf> HrtfList;
  294. ALCenum HrtfStatus{ALC_FALSE};
  295. std::atomic<ALCenum> LastError{ALC_NO_ERROR};
  296. // Maximum number of sources that can be created
  297. ALuint SourcesMax{};
  298. // Maximum number of slots that can be created
  299. ALuint AuxiliaryEffectSlotMax{};
  300. ALCuint NumMonoSources{};
  301. ALCuint NumStereoSources{};
  302. ALsizei NumAuxSends{};
  303. // Map of Buffers for this device
  304. std::mutex BufferLock;
  305. al::vector<BufferSubList> BufferList;
  306. // Map of Effects for this device
  307. std::mutex EffectLock;
  308. al::vector<EffectSubList> EffectList;
  309. // Map of Filters for this device
  310. std::mutex FilterLock;
  311. al::vector<FilterSubList> FilterList;
  312. /* Rendering mode. */
  313. RenderMode mRenderMode{NormalRender};
  314. /* The average speaker distance as determined by the ambdec configuration
  315. * (or alternatively, by the NFC-HOA reference delay). Only used for NFC.
  316. */
  317. ALfloat AvgSpeakerDist{0.0f};
  318. ALuint SamplesDone{0u};
  319. std::chrono::nanoseconds ClockBase{0};
  320. std::chrono::nanoseconds FixedLatency{0};
  321. /* Temp storage used for mixer processing. */
  322. alignas(16) ALfloat SourceData[BUFFERSIZE + MAX_RESAMPLE_PADDING*2];
  323. alignas(16) ALfloat ResampledData[BUFFERSIZE];
  324. alignas(16) ALfloat FilteredData[BUFFERSIZE];
  325. union {
  326. alignas(16) ALfloat HrtfSourceData[BUFFERSIZE + HRTF_HISTORY_LENGTH];
  327. alignas(16) ALfloat NfcSampleData[BUFFERSIZE];
  328. };
  329. alignas(16) float2 HrtfAccumData[BUFFERSIZE + HRIR_LENGTH];
  330. /* Mixing buffer used by the Dry mix and Real output. */
  331. al::vector<std::array<ALfloat,BUFFERSIZE>, 16> MixBuffer;
  332. /* The "dry" path corresponds to the main output. */
  333. MixParams Dry;
  334. ALsizei NumChannelsPerOrder[MAX_AMBI_ORDER+1]{};
  335. /* "Real" output, which will be written to the device buffer. May alias the
  336. * dry buffer.
  337. */
  338. RealMixParams RealOut;
  339. /* HRTF state and info */
  340. std::unique_ptr<DirectHrtfState> mHrtfState;
  341. HrtfEntry *mHrtf{nullptr};
  342. /* Ambisonic-to-UHJ encoder */
  343. std::unique_ptr<Uhj2Encoder> Uhj_Encoder;
  344. /* Ambisonic decoder for speakers */
  345. std::unique_ptr<BFormatDec> AmbiDecoder;
  346. /* Stereo-to-binaural filter */
  347. std::unique_ptr<bs2b> Bs2b;
  348. POSTPROCESS PostProcess{};
  349. std::unique_ptr<FrontStablizer> Stablizer;
  350. std::unique_ptr<Compressor> Limiter;
  351. /* Delay buffers used to compensate for speaker distances. */
  352. DistanceComp ChannelDelay;
  353. /* Dithering control. */
  354. ALfloat DitherDepth{0.0f};
  355. ALuint DitherSeed{0u};
  356. /* Running count of the mixer invocations, in 31.1 fixed point. This
  357. * actually increments *twice* when mixing, first at the start and then at
  358. * the end, so the bottom bit indicates if the device is currently mixing
  359. * and the upper bits indicates how many mixes have been done.
  360. */
  361. RefCount MixCount{0u};
  362. // Contexts created on this device
  363. std::atomic<ALCcontext*> ContextList{nullptr};
  364. /* This lock protects the device state (format, update size, etc) from
  365. * being from being changed in multiple threads, or being accessed while
  366. * being changed. It's also used to serialize calls to the backend.
  367. */
  368. std::mutex StateLock;
  369. std::unique_ptr<BackendBase> Backend;
  370. ALCdevice(DeviceType type);
  371. ALCdevice(const ALCdevice&) = delete;
  372. ALCdevice& operator=(const ALCdevice&) = delete;
  373. ~ALCdevice();
  374. ALsizei bytesFromFmt() const noexcept { return BytesFromDevFmt(FmtType); }
  375. ALsizei channelsFromFmt() const noexcept { return ChannelsFromDevFmt(FmtChans, mAmbiOrder); }
  376. ALsizei frameSizeFromFmt() const noexcept { return bytesFromFmt() * channelsFromFmt(); }
  377. static constexpr inline const char *CurrentPrefix() noexcept { return "ALCdevice::"; }
  378. DEF_NEWDEL(ALCdevice)
  379. };
  380. // Frequency was requested by the app or config file
  381. #define DEVICE_FREQUENCY_REQUEST (1u<<1)
  382. // Channel configuration was requested by the config file
  383. #define DEVICE_CHANNELS_REQUEST (1u<<2)
  384. // Sample type was requested by the config file
  385. #define DEVICE_SAMPLE_TYPE_REQUEST (1u<<3)
  386. // Specifies if the DSP is paused at user request
  387. #define DEVICE_PAUSED (1u<<30)
  388. // Specifies if the device is currently running
  389. #define DEVICE_RUNNING (1u<<31)
  390. /* Must be less than 15 characters (16 including terminating null) for
  391. * compatibility with pthread_setname_np limitations. */
  392. #define MIXER_THREAD_NAME "alsoft-mixer"
  393. #define RECORD_THREAD_NAME "alsoft-record"
  394. enum {
  395. /* End event thread processing. */
  396. EventType_KillThread = 0,
  397. /* User event types. */
  398. EventType_SourceStateChange = 1<<0,
  399. EventType_BufferCompleted = 1<<1,
  400. EventType_Error = 1<<2,
  401. EventType_Performance = 1<<3,
  402. EventType_Deprecated = 1<<4,
  403. EventType_Disconnected = 1<<5,
  404. /* Internal events. */
  405. EventType_ReleaseEffectState = 65536,
  406. };
  407. struct AsyncEvent {
  408. unsigned int EnumType{0u};
  409. union {
  410. char dummy;
  411. struct {
  412. ALuint id;
  413. ALenum state;
  414. } srcstate;
  415. struct {
  416. ALuint id;
  417. ALsizei count;
  418. } bufcomp;
  419. struct {
  420. ALenum type;
  421. ALuint id;
  422. ALuint param;
  423. ALchar msg[1008];
  424. } user;
  425. EffectState *mEffectState;
  426. } u{};
  427. AsyncEvent() noexcept = default;
  428. constexpr AsyncEvent(unsigned int type) noexcept : EnumType{type} { }
  429. };
  430. void AllocateVoices(ALCcontext *context, ALsizei num_voices, ALsizei old_sends);
  431. extern ALint RTPrioLevel;
  432. void SetRTPriority(void);
  433. void SetDefaultChannelOrder(ALCdevice *device);
  434. void SetDefaultWFXChannelOrder(ALCdevice *device);
  435. const ALCchar *DevFmtTypeString(DevFmtType type) noexcept;
  436. const ALCchar *DevFmtChannelsString(DevFmtChannels chans) noexcept;
  437. /**
  438. * GetChannelIdxByName
  439. *
  440. * Returns the index for the given channel name (e.g. FrontCenter), or -1 if it
  441. * doesn't exist.
  442. */
  443. inline ALint GetChannelIdxByName(const RealMixParams &real, Channel chan) noexcept
  444. { return real.ChannelIndex[chan]; }
  445. void StartEventThrd(ALCcontext *ctx);
  446. void StopEventThrd(ALCcontext *ctx);
  447. al::vector<std::string> SearchDataFiles(const char *match, const char *subdir);
  448. #endif