voice.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. /**
  2. * OpenAL cross platform audio library
  3. * Copyright (C) 1999-2007 by authors.
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Library General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Library General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Library General Public
  15. * License along with this library; if not, write to the
  16. * Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. * Or go to http://www.gnu.org/copyleft/lgpl.html
  19. */
  20. #include "config.h"
  21. #include "voice.h"
  22. #include <algorithm>
  23. #include <array>
  24. #include <atomic>
  25. #include <cassert>
  26. #include <climits>
  27. #include <cstddef>
  28. #include <cstdint>
  29. #include <iterator>
  30. #include <memory>
  31. #include <new>
  32. #include <utility>
  33. #include "AL/al.h"
  34. #include "AL/alc.h"
  35. #include "al/buffer.h"
  36. #include "al/event.h"
  37. #include "al/source.h"
  38. #include "alcmain.h"
  39. #include "albyte.h"
  40. #include "alconfig.h"
  41. #include "alcontext.h"
  42. #include "alnumeric.h"
  43. #include "aloptional.h"
  44. #include "alspan.h"
  45. #include "alstring.h"
  46. #include "alu.h"
  47. #include "cpu_caps.h"
  48. #include "devformat.h"
  49. #include "filters/biquad.h"
  50. #include "filters/nfc.h"
  51. #include "filters/splitter.h"
  52. #include "hrtf.h"
  53. #include "inprogext.h"
  54. #include "logging.h"
  55. #include "mixer/defs.h"
  56. #include "opthelpers.h"
  57. #include "ringbuffer.h"
  58. #include "threads.h"
  59. #include "vector.h"
  60. static_assert((INT_MAX>>FRACTIONBITS)/MAX_PITCH > BUFFERSIZE,
  61. "MAX_PITCH and/or BUFFERSIZE are too large for FRACTIONBITS!");
  62. Resampler ResamplerDefault{Resampler::Linear};
  63. namespace {
  64. using HrtfMixerFunc = void(*)(const ALfloat *InSamples, float2 *AccumSamples, const ALuint IrSize,
  65. MixHrtfFilter *hrtfparams, const size_t BufferSize);
  66. using HrtfMixerBlendFunc = void(*)(const ALfloat *InSamples, float2 *AccumSamples,
  67. const ALuint IrSize, const HrtfFilter *oldparams, MixHrtfFilter *newparams,
  68. const size_t BufferSize);
  69. HrtfMixerFunc MixHrtfSamples = MixHrtf_<CTag>;
  70. HrtfMixerBlendFunc MixHrtfBlendSamples = MixHrtfBlend_<CTag>;
  71. inline HrtfMixerFunc SelectHrtfMixer()
  72. {
  73. #ifdef HAVE_NEON
  74. if((CPUCapFlags&CPU_CAP_NEON))
  75. return MixHrtf_<NEONTag>;
  76. #endif
  77. #ifdef HAVE_SSE
  78. if((CPUCapFlags&CPU_CAP_SSE))
  79. return MixHrtf_<SSETag>;
  80. #endif
  81. return MixHrtf_<CTag>;
  82. }
  83. inline HrtfMixerBlendFunc SelectHrtfBlendMixer()
  84. {
  85. #ifdef HAVE_NEON
  86. if((CPUCapFlags&CPU_CAP_NEON))
  87. return MixHrtfBlend_<NEONTag>;
  88. #endif
  89. #ifdef HAVE_SSE
  90. if((CPUCapFlags&CPU_CAP_SSE))
  91. return MixHrtfBlend_<SSETag>;
  92. #endif
  93. return MixHrtfBlend_<CTag>;
  94. }
  95. } // namespace
  96. void aluInitMixer()
  97. {
  98. if(auto resopt = ConfigValueStr(nullptr, nullptr, "resampler"))
  99. {
  100. struct ResamplerEntry {
  101. const char name[16];
  102. const Resampler resampler;
  103. };
  104. constexpr ResamplerEntry ResamplerList[]{
  105. { "none", Resampler::Point },
  106. { "point", Resampler::Point },
  107. { "cubic", Resampler::Cubic },
  108. { "bsinc12", Resampler::BSinc12 },
  109. { "fast_bsinc12", Resampler::FastBSinc12 },
  110. { "bsinc24", Resampler::BSinc24 },
  111. { "fast_bsinc24", Resampler::FastBSinc24 },
  112. };
  113. const char *str{resopt->c_str()};
  114. if(al::strcasecmp(str, "bsinc") == 0)
  115. {
  116. WARN("Resampler option \"%s\" is deprecated, using bsinc12\n", str);
  117. str = "bsinc12";
  118. }
  119. else if(al::strcasecmp(str, "sinc4") == 0 || al::strcasecmp(str, "sinc8") == 0)
  120. {
  121. WARN("Resampler option \"%s\" is deprecated, using cubic\n", str);
  122. str = "cubic";
  123. }
  124. auto iter = std::find_if(std::begin(ResamplerList), std::end(ResamplerList),
  125. [str](const ResamplerEntry &entry) -> bool
  126. { return al::strcasecmp(str, entry.name) == 0; });
  127. if(iter == std::end(ResamplerList))
  128. ERR("Invalid resampler: %s\n", str);
  129. else
  130. ResamplerDefault = iter->resampler;
  131. }
  132. MixHrtfBlendSamples = SelectHrtfBlendMixer();
  133. MixHrtfSamples = SelectHrtfMixer();
  134. }
  135. namespace {
  136. /* A quick'n'dirty lookup table to decode a muLaw-encoded byte sample into a
  137. * signed 16-bit sample */
  138. constexpr ALshort muLawDecompressionTable[256] = {
  139. -32124,-31100,-30076,-29052,-28028,-27004,-25980,-24956,
  140. -23932,-22908,-21884,-20860,-19836,-18812,-17788,-16764,
  141. -15996,-15484,-14972,-14460,-13948,-13436,-12924,-12412,
  142. -11900,-11388,-10876,-10364, -9852, -9340, -8828, -8316,
  143. -7932, -7676, -7420, -7164, -6908, -6652, -6396, -6140,
  144. -5884, -5628, -5372, -5116, -4860, -4604, -4348, -4092,
  145. -3900, -3772, -3644, -3516, -3388, -3260, -3132, -3004,
  146. -2876, -2748, -2620, -2492, -2364, -2236, -2108, -1980,
  147. -1884, -1820, -1756, -1692, -1628, -1564, -1500, -1436,
  148. -1372, -1308, -1244, -1180, -1116, -1052, -988, -924,
  149. -876, -844, -812, -780, -748, -716, -684, -652,
  150. -620, -588, -556, -524, -492, -460, -428, -396,
  151. -372, -356, -340, -324, -308, -292, -276, -260,
  152. -244, -228, -212, -196, -180, -164, -148, -132,
  153. -120, -112, -104, -96, -88, -80, -72, -64,
  154. -56, -48, -40, -32, -24, -16, -8, 0,
  155. 32124, 31100, 30076, 29052, 28028, 27004, 25980, 24956,
  156. 23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764,
  157. 15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412,
  158. 11900, 11388, 10876, 10364, 9852, 9340, 8828, 8316,
  159. 7932, 7676, 7420, 7164, 6908, 6652, 6396, 6140,
  160. 5884, 5628, 5372, 5116, 4860, 4604, 4348, 4092,
  161. 3900, 3772, 3644, 3516, 3388, 3260, 3132, 3004,
  162. 2876, 2748, 2620, 2492, 2364, 2236, 2108, 1980,
  163. 1884, 1820, 1756, 1692, 1628, 1564, 1500, 1436,
  164. 1372, 1308, 1244, 1180, 1116, 1052, 988, 924,
  165. 876, 844, 812, 780, 748, 716, 684, 652,
  166. 620, 588, 556, 524, 492, 460, 428, 396,
  167. 372, 356, 340, 324, 308, 292, 276, 260,
  168. 244, 228, 212, 196, 180, 164, 148, 132,
  169. 120, 112, 104, 96, 88, 80, 72, 64,
  170. 56, 48, 40, 32, 24, 16, 8, 0
  171. };
  172. /* A quick'n'dirty lookup table to decode an aLaw-encoded byte sample into a
  173. * signed 16-bit sample */
  174. constexpr ALshort aLawDecompressionTable[256] = {
  175. -5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736,
  176. -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784,
  177. -2752, -2624, -3008, -2880, -2240, -2112, -2496, -2368,
  178. -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392,
  179. -22016,-20992,-24064,-23040,-17920,-16896,-19968,-18944,
  180. -30208,-29184,-32256,-31232,-26112,-25088,-28160,-27136,
  181. -11008,-10496,-12032,-11520, -8960, -8448, -9984, -9472,
  182. -15104,-14592,-16128,-15616,-13056,-12544,-14080,-13568,
  183. -344, -328, -376, -360, -280, -264, -312, -296,
  184. -472, -456, -504, -488, -408, -392, -440, -424,
  185. -88, -72, -120, -104, -24, -8, -56, -40,
  186. -216, -200, -248, -232, -152, -136, -184, -168,
  187. -1376, -1312, -1504, -1440, -1120, -1056, -1248, -1184,
  188. -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696,
  189. -688, -656, -752, -720, -560, -528, -624, -592,
  190. -944, -912, -1008, -976, -816, -784, -880, -848,
  191. 5504, 5248, 6016, 5760, 4480, 4224, 4992, 4736,
  192. 7552, 7296, 8064, 7808, 6528, 6272, 7040, 6784,
  193. 2752, 2624, 3008, 2880, 2240, 2112, 2496, 2368,
  194. 3776, 3648, 4032, 3904, 3264, 3136, 3520, 3392,
  195. 22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944,
  196. 30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136,
  197. 11008, 10496, 12032, 11520, 8960, 8448, 9984, 9472,
  198. 15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568,
  199. 344, 328, 376, 360, 280, 264, 312, 296,
  200. 472, 456, 504, 488, 408, 392, 440, 424,
  201. 88, 72, 120, 104, 24, 8, 56, 40,
  202. 216, 200, 248, 232, 152, 136, 184, 168,
  203. 1376, 1312, 1504, 1440, 1120, 1056, 1248, 1184,
  204. 1888, 1824, 2016, 1952, 1632, 1568, 1760, 1696,
  205. 688, 656, 752, 720, 560, 528, 624, 592,
  206. 944, 912, 1008, 976, 816, 784, 880, 848
  207. };
  208. template<FmtType T>
  209. struct FmtTypeTraits { };
  210. template<>
  211. struct FmtTypeTraits<FmtUByte> {
  212. using Type = ALubyte;
  213. static constexpr inline float to_float(const Type val) noexcept
  214. { return val*(1.0f/128.0f) - 1.0f; }
  215. };
  216. template<>
  217. struct FmtTypeTraits<FmtShort> {
  218. using Type = ALshort;
  219. static constexpr inline float to_float(const Type val) noexcept { return val*(1.0f/32768.0f); }
  220. };
  221. template<>
  222. struct FmtTypeTraits<FmtFloat> {
  223. using Type = ALfloat;
  224. static constexpr inline float to_float(const Type val) noexcept { return val; }
  225. };
  226. template<>
  227. struct FmtTypeTraits<FmtDouble> {
  228. using Type = ALdouble;
  229. static constexpr inline float to_float(const Type val) noexcept
  230. { return static_cast<ALfloat>(val); }
  231. };
  232. template<>
  233. struct FmtTypeTraits<FmtMulaw> {
  234. using Type = ALubyte;
  235. static constexpr inline float to_float(const Type val) noexcept
  236. { return muLawDecompressionTable[val] * (1.0f/32768.0f); }
  237. };
  238. template<>
  239. struct FmtTypeTraits<FmtAlaw> {
  240. using Type = ALubyte;
  241. static constexpr inline float to_float(const Type val) noexcept
  242. { return aLawDecompressionTable[val] * (1.0f/32768.0f); }
  243. };
  244. void SendSourceStoppedEvent(ALCcontext *context, ALuint id)
  245. {
  246. RingBuffer *ring{context->mAsyncEvents.get()};
  247. auto evt_vec = ring->getWriteVector();
  248. if(evt_vec.first.len < 1) return;
  249. AsyncEvent *evt{new (evt_vec.first.buf) AsyncEvent{EventType_SourceStateChange}};
  250. evt->u.srcstate.id = id;
  251. evt->u.srcstate.state = AL_STOPPED;
  252. ring->writeAdvance(1);
  253. context->mEventSem.post();
  254. }
  255. const ALfloat *DoFilters(BiquadFilter *lpfilter, BiquadFilter *hpfilter, ALfloat *dst,
  256. const ALfloat *src, const size_t numsamples, int type)
  257. {
  258. switch(type)
  259. {
  260. case AF_None:
  261. lpfilter->clear();
  262. hpfilter->clear();
  263. break;
  264. case AF_LowPass:
  265. lpfilter->process(dst, src, numsamples);
  266. hpfilter->clear();
  267. return dst;
  268. case AF_HighPass:
  269. lpfilter->clear();
  270. hpfilter->process(dst, src, numsamples);
  271. return dst;
  272. case AF_BandPass:
  273. lpfilter->process(dst, src, numsamples);
  274. hpfilter->process(dst, dst, numsamples);
  275. return dst;
  276. }
  277. return src;
  278. }
  279. template<FmtType T>
  280. inline void LoadSampleArray(ALfloat *RESTRICT dst, const al::byte *src, const size_t srcstep,
  281. const size_t samples) noexcept
  282. {
  283. using SampleType = typename FmtTypeTraits<T>::Type;
  284. const SampleType *RESTRICT ssrc{reinterpret_cast<const SampleType*>(src)};
  285. for(size_t i{0u};i < samples;i++)
  286. dst[i] = FmtTypeTraits<T>::to_float(ssrc[i*srcstep]);
  287. }
  288. void LoadSamples(ALfloat *RESTRICT dst, const al::byte *src, const size_t srcstep, FmtType srctype,
  289. const size_t samples) noexcept
  290. {
  291. #define HANDLE_FMT(T) case T: LoadSampleArray<T>(dst, src, srcstep, samples); break
  292. switch(srctype)
  293. {
  294. HANDLE_FMT(FmtUByte);
  295. HANDLE_FMT(FmtShort);
  296. HANDLE_FMT(FmtFloat);
  297. HANDLE_FMT(FmtDouble);
  298. HANDLE_FMT(FmtMulaw);
  299. HANDLE_FMT(FmtAlaw);
  300. }
  301. #undef HANDLE_FMT
  302. }
  303. ALfloat *LoadBufferStatic(ALbufferlistitem *BufferListItem, ALbufferlistitem *&BufferLoopItem,
  304. const size_t NumChannels, const size_t SampleSize, const size_t chan, size_t DataPosInt,
  305. al::span<ALfloat> SrcBuffer)
  306. {
  307. const ALbuffer *Buffer{BufferListItem->mBuffer};
  308. const ALuint LoopStart{Buffer->LoopStart};
  309. const ALuint LoopEnd{Buffer->LoopEnd};
  310. ASSUME(LoopEnd > LoopStart);
  311. /* If current pos is beyond the loop range, do not loop */
  312. if(!BufferLoopItem || DataPosInt >= LoopEnd)
  313. {
  314. BufferLoopItem = nullptr;
  315. /* Load what's left to play from the buffer */
  316. const size_t DataRem{minz(SrcBuffer.size(), Buffer->SampleLen-DataPosInt)};
  317. const al::byte *Data{Buffer->mData.data()};
  318. Data += (DataPosInt*NumChannels + chan)*SampleSize;
  319. LoadSamples(SrcBuffer.data(), Data, NumChannels, Buffer->mFmtType, DataRem);
  320. SrcBuffer = SrcBuffer.subspan(DataRem);
  321. }
  322. else
  323. {
  324. /* Load what's left of this loop iteration */
  325. const size_t DataRem{minz(SrcBuffer.size(), LoopEnd-DataPosInt)};
  326. const al::byte *Data{Buffer->mData.data()};
  327. Data += (DataPosInt*NumChannels + chan)*SampleSize;
  328. LoadSamples(SrcBuffer.data(), Data, NumChannels, Buffer->mFmtType, DataRem);
  329. SrcBuffer = SrcBuffer.subspan(DataRem);
  330. /* Load any repeats of the loop we can to fill the buffer. */
  331. const auto LoopSize = static_cast<size_t>(LoopEnd - LoopStart);
  332. while(!SrcBuffer.empty())
  333. {
  334. const size_t DataSize{minz(SrcBuffer.size(), LoopSize)};
  335. Data = Buffer->mData.data() + (LoopStart*NumChannels + chan)*SampleSize;
  336. LoadSamples(SrcBuffer.data(), Data, NumChannels, Buffer->mFmtType, DataSize);
  337. SrcBuffer = SrcBuffer.subspan(DataSize);
  338. }
  339. }
  340. return SrcBuffer.begin();
  341. }
  342. ALfloat *LoadBufferQueue(ALbufferlistitem *BufferListItem, ALbufferlistitem *BufferLoopItem,
  343. const size_t NumChannels, const size_t SampleSize, const size_t chan, size_t DataPosInt,
  344. al::span<ALfloat> SrcBuffer)
  345. {
  346. /* Crawl the buffer queue to fill in the temp buffer */
  347. while(BufferListItem && !SrcBuffer.empty())
  348. {
  349. ALbuffer *Buffer{BufferListItem->mBuffer};
  350. if(!(Buffer && DataPosInt < Buffer->SampleLen))
  351. {
  352. if(Buffer) DataPosInt -= Buffer->SampleLen;
  353. BufferListItem = BufferListItem->mNext.load(std::memory_order_acquire);
  354. if(!BufferListItem) BufferListItem = BufferLoopItem;
  355. continue;
  356. }
  357. const size_t DataSize{minz(SrcBuffer.size(), Buffer->SampleLen-DataPosInt)};
  358. const al::byte *Data{Buffer->mData.data()};
  359. Data += (DataPosInt*NumChannels + chan)*SampleSize;
  360. LoadSamples(SrcBuffer.data(), Data, NumChannels, Buffer->mFmtType, DataSize);
  361. SrcBuffer = SrcBuffer.subspan(DataSize);
  362. if(SrcBuffer.empty()) break;
  363. DataPosInt = 0;
  364. BufferListItem = BufferListItem->mNext.load(std::memory_order_acquire);
  365. if(!BufferListItem) BufferListItem = BufferLoopItem;
  366. }
  367. return SrcBuffer.begin();
  368. }
  369. void DoHrtfMix(const float TargetGain, DirectParams &parms, const float *samples,
  370. const ALuint DstBufferSize, const ALuint Counter, ALuint OutPos, const ALuint IrSize,
  371. ALCdevice *Device)
  372. {
  373. auto &HrtfSamples = Device->HrtfSourceData;
  374. auto &AccumSamples = Device->HrtfAccumData;
  375. /* Copy the HRTF history and new input samples into a temp buffer. */
  376. auto src_iter = std::copy(parms.Hrtf.State.History.begin(), parms.Hrtf.State.History.end(),
  377. std::begin(HrtfSamples));
  378. std::copy_n(samples, DstBufferSize, src_iter);
  379. /* Copy the last used samples back into the history buffer for later. */
  380. std::copy_n(std::begin(HrtfSamples) + DstBufferSize, parms.Hrtf.State.History.size(),
  381. parms.Hrtf.State.History.begin());
  382. /* If fading, the old gain is not silence, and this is the first mixing
  383. * pass, fade between the IRs.
  384. */
  385. ALuint fademix{0u};
  386. if(Counter && parms.Hrtf.Old.Gain > GAIN_SILENCE_THRESHOLD && OutPos == 0)
  387. {
  388. fademix = minu(DstBufferSize, 128);
  389. float gain{TargetGain};
  390. /* The new coefficients need to fade in completely since they're
  391. * replacing the old ones. To keep the gain fading consistent,
  392. * interpolate between the old and new target gains given how much of
  393. * the fade time this mix handles.
  394. */
  395. if LIKELY(Counter > fademix)
  396. {
  397. const ALfloat a{static_cast<float>(fademix) / static_cast<float>(Counter)};
  398. gain = lerp(parms.Hrtf.Old.Gain, TargetGain, a);
  399. }
  400. MixHrtfFilter hrtfparams;
  401. hrtfparams.Coeffs = &parms.Hrtf.Target.Coeffs;
  402. hrtfparams.Delay[0] = parms.Hrtf.Target.Delay[0];
  403. hrtfparams.Delay[1] = parms.Hrtf.Target.Delay[1];
  404. hrtfparams.Gain = 0.0f;
  405. hrtfparams.GainStep = gain / static_cast<float>(fademix);
  406. MixHrtfBlendSamples(HrtfSamples, AccumSamples+OutPos, IrSize, &parms.Hrtf.Old, &hrtfparams,
  407. fademix);
  408. /* Update the old parameters with the result. */
  409. parms.Hrtf.Old = parms.Hrtf.Target;
  410. if(fademix < Counter)
  411. parms.Hrtf.Old.Gain = hrtfparams.Gain;
  412. else
  413. parms.Hrtf.Old.Gain = TargetGain;
  414. OutPos += fademix;
  415. }
  416. if LIKELY(fademix < DstBufferSize)
  417. {
  418. const ALuint todo{DstBufferSize - fademix};
  419. float gain{TargetGain};
  420. /* Interpolate the target gain if the gain fading lasts longer than
  421. * this mix.
  422. */
  423. if(Counter > DstBufferSize)
  424. {
  425. const float a{static_cast<float>(todo) / static_cast<float>(Counter-fademix)};
  426. gain = lerp(parms.Hrtf.Old.Gain, TargetGain, a);
  427. }
  428. MixHrtfFilter hrtfparams;
  429. hrtfparams.Coeffs = &parms.Hrtf.Target.Coeffs;
  430. hrtfparams.Delay[0] = parms.Hrtf.Target.Delay[0];
  431. hrtfparams.Delay[1] = parms.Hrtf.Target.Delay[1];
  432. hrtfparams.Gain = parms.Hrtf.Old.Gain;
  433. hrtfparams.GainStep = (gain - parms.Hrtf.Old.Gain) / static_cast<float>(todo);
  434. MixHrtfSamples(HrtfSamples+fademix, AccumSamples+OutPos, IrSize, &hrtfparams, todo);
  435. /* Store the interpolated gain or the final target gain depending if
  436. * the fade is done.
  437. */
  438. if(DstBufferSize < Counter)
  439. parms.Hrtf.Old.Gain = gain;
  440. else
  441. parms.Hrtf.Old.Gain = TargetGain;
  442. }
  443. }
  444. void DoNfcMix(ALvoice::TargetData &Direct, const float *TargetGains, DirectParams &parms,
  445. const float *samples, const ALuint DstBufferSize, const ALuint Counter, const ALuint OutPos,
  446. ALCdevice *Device)
  447. {
  448. const size_t outcount{Device->NumChannelsPerOrder[0]};
  449. MixSamples({samples, DstBufferSize}, Direct.Buffer.first(outcount),
  450. parms.Gains.Current.data(), TargetGains, Counter, OutPos);
  451. const al::span<float> nfcsamples{Device->NfcSampleData, DstBufferSize};
  452. size_t chanoffset{outcount};
  453. using FilterProc = void (NfcFilter::*)(float*,const float*,const size_t);
  454. auto apply_nfc = [&Direct,&parms,samples,TargetGains,Counter,OutPos,&chanoffset,nfcsamples](
  455. const FilterProc process, const size_t chancount) -> void
  456. {
  457. if(chancount < 1) return;
  458. (parms.NFCtrlFilter.*process)(nfcsamples.data(), samples, nfcsamples.size());
  459. MixSamples(nfcsamples, Direct.Buffer.subspan(chanoffset, chancount),
  460. &parms.Gains.Current[chanoffset], &TargetGains[chanoffset], Counter, OutPos);
  461. chanoffset += chancount;
  462. };
  463. apply_nfc(&NfcFilter::process1, Device->NumChannelsPerOrder[1]);
  464. apply_nfc(&NfcFilter::process2, Device->NumChannelsPerOrder[2]);
  465. apply_nfc(&NfcFilter::process3, Device->NumChannelsPerOrder[3]);
  466. }
  467. } // namespace
  468. void ALvoice::mix(const State vstate, ALCcontext *Context, const ALuint SamplesToDo)
  469. {
  470. static constexpr std::array<float,MAX_OUTPUT_CHANNELS> SilentTarget{};
  471. ASSUME(SamplesToDo > 0);
  472. /* Get voice info */
  473. const bool isstatic{(mFlags&VOICE_IS_STATIC) != 0};
  474. ALuint DataPosInt{mPosition.load(std::memory_order_relaxed)};
  475. ALuint DataPosFrac{mPositionFrac.load(std::memory_order_relaxed)};
  476. ALbufferlistitem *BufferListItem{mCurrentBuffer.load(std::memory_order_relaxed)};
  477. ALbufferlistitem *BufferLoopItem{mLoopBuffer.load(std::memory_order_relaxed)};
  478. const ALuint NumChannels{mNumChannels};
  479. const ALuint SampleSize{mSampleSize};
  480. const ALuint increment{mStep};
  481. if(increment < 1) return;
  482. ASSUME(NumChannels > 0);
  483. ASSUME(SampleSize > 0);
  484. ASSUME(increment > 0);
  485. ALCdevice *Device{Context->mDevice.get()};
  486. const ALuint NumSends{Device->NumAuxSends};
  487. const ALuint IrSize{Device->mHrtf ? Device->mHrtf->irSize : 0};
  488. ResamplerFunc Resample{(increment == FRACTIONONE && DataPosFrac == 0) ?
  489. Resample_<CopyTag,CTag> : mResampler};
  490. ALuint Counter{(mFlags&VOICE_IS_FADING) ? SamplesToDo : 0};
  491. if(!Counter)
  492. {
  493. /* No fading, just overwrite the old/current params. */
  494. for(ALuint chan{0};chan < NumChannels;chan++)
  495. {
  496. ChannelData &chandata = mChans[chan];
  497. {
  498. DirectParams &parms = chandata.mDryParams;
  499. if(!(mFlags&VOICE_HAS_HRTF))
  500. parms.Gains.Current = parms.Gains.Target;
  501. else
  502. parms.Hrtf.Old = parms.Hrtf.Target;
  503. }
  504. for(ALuint send{0};send < NumSends;++send)
  505. {
  506. if(mSend[send].Buffer.empty())
  507. continue;
  508. SendParams &parms = chandata.mWetParams[send];
  509. parms.Gains.Current = parms.Gains.Target;
  510. }
  511. }
  512. }
  513. else if((mFlags&VOICE_HAS_HRTF))
  514. {
  515. for(ALuint chan{0};chan < NumChannels;chan++)
  516. {
  517. DirectParams &parms = mChans[chan].mDryParams;
  518. if(!(parms.Hrtf.Old.Gain > GAIN_SILENCE_THRESHOLD))
  519. {
  520. /* The old HRTF params are silent, so overwrite the old
  521. * coefficients with the new, and reset the old gain to 0. The
  522. * future mix will then fade from silence.
  523. */
  524. parms.Hrtf.Old = parms.Hrtf.Target;
  525. parms.Hrtf.Old.Gain = 0.0f;
  526. }
  527. }
  528. }
  529. ALuint buffers_done{0u};
  530. ALuint OutPos{0u};
  531. do {
  532. /* Figure out how many buffer samples will be needed */
  533. ALuint DstBufferSize{SamplesToDo - OutPos};
  534. /* Calculate the last written dst sample pos. */
  535. uint64_t DataSize64{DstBufferSize - 1};
  536. /* Calculate the last read src sample pos. */
  537. DataSize64 = (DataSize64*increment + DataPosFrac) >> FRACTIONBITS;
  538. /* +1 to get the src sample count, include padding. */
  539. DataSize64 += 1 + MAX_RESAMPLER_PADDING;
  540. auto SrcBufferSize = static_cast<ALuint>(
  541. minu64(DataSize64, BUFFERSIZE + MAX_RESAMPLER_PADDING + 1));
  542. if(SrcBufferSize > BUFFERSIZE + MAX_RESAMPLER_PADDING)
  543. {
  544. SrcBufferSize = BUFFERSIZE + MAX_RESAMPLER_PADDING;
  545. /* If the source buffer got saturated, we can't fill the desired
  546. * dst size. Figure out how many samples we can actually mix from
  547. * this.
  548. */
  549. DataSize64 = SrcBufferSize - MAX_RESAMPLER_PADDING;
  550. DataSize64 = ((DataSize64<<FRACTIONBITS) - DataPosFrac + increment-1) / increment;
  551. DstBufferSize = static_cast<ALuint>(minu64(DataSize64, DstBufferSize));
  552. /* Some mixers like having a multiple of 4, so try to give that
  553. * unless this is the last update.
  554. */
  555. if(DstBufferSize < SamplesToDo-OutPos)
  556. DstBufferSize &= ~3u;
  557. }
  558. ASSUME(DstBufferSize > 0);
  559. for(ALuint chan{0};chan < NumChannels;chan++)
  560. {
  561. ChannelData &chandata = mChans[chan];
  562. const al::span<ALfloat> SrcData{Device->SourceData, SrcBufferSize};
  563. /* Load the previous samples into the source data first, then load
  564. * what we can from the buffer queue.
  565. */
  566. auto srciter = std::copy_n(chandata.mPrevSamples.begin(), MAX_RESAMPLER_PADDING>>1,
  567. SrcData.begin());
  568. if UNLIKELY(!BufferListItem)
  569. srciter = std::copy(chandata.mPrevSamples.begin()+(MAX_RESAMPLER_PADDING>>1),
  570. chandata.mPrevSamples.end(), srciter);
  571. else if(isstatic)
  572. srciter = LoadBufferStatic(BufferListItem, BufferLoopItem, NumChannels,
  573. SampleSize, chan, DataPosInt, {srciter, SrcData.end()});
  574. else
  575. srciter = LoadBufferQueue(BufferListItem, BufferLoopItem, NumChannels,
  576. SampleSize, chan, DataPosInt, {srciter, SrcData.end()});
  577. if UNLIKELY(srciter != SrcData.end())
  578. {
  579. /* If the source buffer wasn't filled, copy the last sample for
  580. * the remaining buffer. Ideally it should have ended with
  581. * silence, but if not the gain fading should help avoid clicks
  582. * from sudden amplitude changes.
  583. */
  584. const ALfloat sample{*(srciter-1)};
  585. std::fill(srciter, SrcData.end(), sample);
  586. }
  587. /* Store the last source samples used for next time. */
  588. std::copy_n(&SrcData[(increment*DstBufferSize + DataPosFrac)>>FRACTIONBITS],
  589. chandata.mPrevSamples.size(), chandata.mPrevSamples.begin());
  590. /* Resample, then apply ambisonic upsampling as needed. */
  591. const ALfloat *ResampledData{Resample(&mResampleState,
  592. &SrcData[MAX_RESAMPLER_PADDING>>1], DataPosFrac, increment,
  593. {Device->ResampledData, DstBufferSize})};
  594. if((mFlags&VOICE_IS_AMBISONIC))
  595. {
  596. const ALfloat hfscale{chandata.mAmbiScale};
  597. /* Beware the evil const_cast. It's safe since it's pointing to
  598. * either SourceData or ResampledData (both non-const), but the
  599. * resample method takes the source as const float* and may
  600. * return it without copying to output, making it currently
  601. * unavoidable.
  602. */
  603. chandata.mAmbiSplitter.applyHfScale(const_cast<ALfloat*>(ResampledData), hfscale,
  604. DstBufferSize);
  605. }
  606. /* Now filter and mix to the appropriate outputs. */
  607. ALfloat (&FilterBuf)[BUFFERSIZE] = Device->FilteredData;
  608. {
  609. DirectParams &parms = chandata.mDryParams;
  610. const ALfloat *samples{DoFilters(&parms.LowPass, &parms.HighPass, FilterBuf,
  611. ResampledData, DstBufferSize, mDirect.FilterType)};
  612. if((mFlags&VOICE_HAS_HRTF))
  613. {
  614. const ALfloat TargetGain{UNLIKELY(vstate == ALvoice::Stopping) ? 0.0f :
  615. parms.Hrtf.Target.Gain};
  616. DoHrtfMix(TargetGain, parms, samples, DstBufferSize, Counter, OutPos, IrSize,
  617. Device);
  618. }
  619. else if((mFlags&VOICE_HAS_NFC))
  620. {
  621. const float *TargetGains{UNLIKELY(vstate == ALvoice::Stopping) ?
  622. SilentTarget.data() : parms.Gains.Target.data()};
  623. DoNfcMix(mDirect, TargetGains, parms, samples, DstBufferSize, Counter, OutPos,
  624. Device);
  625. }
  626. else
  627. {
  628. const float *TargetGains{UNLIKELY(vstate == ALvoice::Stopping) ?
  629. SilentTarget.data() : parms.Gains.Target.data()};
  630. MixSamples({samples, DstBufferSize}, mDirect.Buffer,
  631. parms.Gains.Current.data(), TargetGains, Counter, OutPos);
  632. }
  633. }
  634. for(ALuint send{0};send < NumSends;++send)
  635. {
  636. if(mSend[send].Buffer.empty())
  637. continue;
  638. SendParams &parms = chandata.mWetParams[send];
  639. const ALfloat *samples{DoFilters(&parms.LowPass, &parms.HighPass, FilterBuf,
  640. ResampledData, DstBufferSize, mSend[send].FilterType)};
  641. const float *TargetGains{UNLIKELY(vstate == ALvoice::Stopping) ?
  642. SilentTarget.data() : parms.Gains.Target.data()};
  643. MixSamples({samples, DstBufferSize}, mSend[send].Buffer,
  644. parms.Gains.Current.data(), TargetGains, Counter, OutPos);
  645. }
  646. }
  647. /* Update positions */
  648. DataPosFrac += increment*DstBufferSize;
  649. DataPosInt += DataPosFrac>>FRACTIONBITS;
  650. DataPosFrac &= FRACTIONMASK;
  651. OutPos += DstBufferSize;
  652. Counter = maxu(DstBufferSize, Counter) - DstBufferSize;
  653. if UNLIKELY(!BufferListItem)
  654. {
  655. /* Do nothing extra when there's no buffers. */
  656. }
  657. else if(isstatic)
  658. {
  659. if(BufferLoopItem)
  660. {
  661. /* Handle looping static source */
  662. const ALbuffer *Buffer{BufferListItem->mBuffer};
  663. const ALuint LoopStart{Buffer->LoopStart};
  664. const ALuint LoopEnd{Buffer->LoopEnd};
  665. if(DataPosInt >= LoopEnd)
  666. {
  667. assert(LoopEnd > LoopStart);
  668. DataPosInt = ((DataPosInt-LoopStart)%(LoopEnd-LoopStart)) + LoopStart;
  669. }
  670. }
  671. else
  672. {
  673. /* Handle non-looping static source */
  674. if(DataPosInt >= BufferListItem->mSampleLen)
  675. {
  676. BufferListItem = nullptr;
  677. break;
  678. }
  679. }
  680. }
  681. else
  682. {
  683. /* Handle streaming source */
  684. do {
  685. if(BufferListItem->mSampleLen > DataPosInt)
  686. break;
  687. DataPosInt -= BufferListItem->mSampleLen;
  688. ++buffers_done;
  689. BufferListItem = BufferListItem->mNext.load(std::memory_order_relaxed);
  690. if(!BufferListItem) BufferListItem = BufferLoopItem;
  691. } while(BufferListItem);
  692. }
  693. } while(OutPos < SamplesToDo);
  694. mFlags |= VOICE_IS_FADING;
  695. /* Don't update positions and buffers if we were stopping. */
  696. if UNLIKELY(vstate == ALvoice::Stopping)
  697. {
  698. mPlayState.store(ALvoice::Stopped, std::memory_order_release);
  699. return;
  700. }
  701. /* Capture the source ID in case it's reset for stopping. */
  702. const ALuint SourceID{mSourceID.load(std::memory_order_relaxed)};
  703. /* Update voice info */
  704. mPosition.store(DataPosInt, std::memory_order_relaxed);
  705. mPositionFrac.store(DataPosFrac, std::memory_order_relaxed);
  706. mCurrentBuffer.store(BufferListItem, std::memory_order_relaxed);
  707. if(!BufferListItem)
  708. {
  709. mLoopBuffer.store(nullptr, std::memory_order_relaxed);
  710. mSourceID.store(0u, std::memory_order_relaxed);
  711. }
  712. std::atomic_thread_fence(std::memory_order_release);
  713. /* Send any events now, after the position/buffer info was updated. */
  714. const ALbitfieldSOFT enabledevt{Context->mEnabledEvts.load(std::memory_order_acquire)};
  715. if(buffers_done > 0 && (enabledevt&EventType_BufferCompleted))
  716. {
  717. RingBuffer *ring{Context->mAsyncEvents.get()};
  718. auto evt_vec = ring->getWriteVector();
  719. if(evt_vec.first.len > 0)
  720. {
  721. AsyncEvent *evt{new (evt_vec.first.buf) AsyncEvent{EventType_BufferCompleted}};
  722. evt->u.bufcomp.id = SourceID;
  723. evt->u.bufcomp.count = buffers_done;
  724. ring->writeAdvance(1);
  725. Context->mEventSem.post();
  726. }
  727. }
  728. if(!BufferListItem)
  729. {
  730. /* If the voice just ended, set it to Stopping so the next render
  731. * ensures any residual noise fades to 0 amplitude.
  732. */
  733. mPlayState.store(ALvoice::Stopping, std::memory_order_release);
  734. if((enabledevt&EventType_SourceStateChange))
  735. SendSourceStoppedEvent(Context, SourceID);
  736. }
  737. }