ALu.c 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830
  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 <math.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <ctype.h>
  25. #include <assert.h>
  26. #include "alMain.h"
  27. #include "alSource.h"
  28. #include "alBuffer.h"
  29. #include "alListener.h"
  30. #include "alAuxEffectSlot.h"
  31. #include "alu.h"
  32. #include "bs2b.h"
  33. #include "hrtf.h"
  34. #include "uhjfilter.h"
  35. #include "bformatdec.h"
  36. #include "static_assert.h"
  37. #include "mixer_defs.h"
  38. #include "backends/base.h"
  39. struct ChanMap {
  40. enum Channel channel;
  41. ALfloat angle;
  42. ALfloat elevation;
  43. };
  44. /* Cone scalar */
  45. ALfloat ConeScale = 1.0f;
  46. /* Localized Z scalar for mono sources */
  47. ALfloat ZScale = 1.0f;
  48. extern inline ALfloat minf(ALfloat a, ALfloat b);
  49. extern inline ALfloat maxf(ALfloat a, ALfloat b);
  50. extern inline ALfloat clampf(ALfloat val, ALfloat min, ALfloat max);
  51. extern inline ALdouble mind(ALdouble a, ALdouble b);
  52. extern inline ALdouble maxd(ALdouble a, ALdouble b);
  53. extern inline ALdouble clampd(ALdouble val, ALdouble min, ALdouble max);
  54. extern inline ALuint minu(ALuint a, ALuint b);
  55. extern inline ALuint maxu(ALuint a, ALuint b);
  56. extern inline ALuint clampu(ALuint val, ALuint min, ALuint max);
  57. extern inline ALint mini(ALint a, ALint b);
  58. extern inline ALint maxi(ALint a, ALint b);
  59. extern inline ALint clampi(ALint val, ALint min, ALint max);
  60. extern inline ALint64 mini64(ALint64 a, ALint64 b);
  61. extern inline ALint64 maxi64(ALint64 a, ALint64 b);
  62. extern inline ALint64 clampi64(ALint64 val, ALint64 min, ALint64 max);
  63. extern inline ALuint64 minu64(ALuint64 a, ALuint64 b);
  64. extern inline ALuint64 maxu64(ALuint64 a, ALuint64 b);
  65. extern inline ALuint64 clampu64(ALuint64 val, ALuint64 min, ALuint64 max);
  66. extern inline ALfloat lerp(ALfloat val1, ALfloat val2, ALfloat mu);
  67. extern inline ALfloat resample_fir4(ALfloat val0, ALfloat val1, ALfloat val2, ALfloat val3, ALsizei frac);
  68. extern inline void aluVectorSet(aluVector *restrict vector, ALfloat x, ALfloat y, ALfloat z, ALfloat w);
  69. extern inline void aluMatrixfSetRow(aluMatrixf *matrix, ALuint row,
  70. ALfloat m0, ALfloat m1, ALfloat m2, ALfloat m3);
  71. extern inline void aluMatrixfSet(aluMatrixf *matrix,
  72. ALfloat m00, ALfloat m01, ALfloat m02, ALfloat m03,
  73. ALfloat m10, ALfloat m11, ALfloat m12, ALfloat m13,
  74. ALfloat m20, ALfloat m21, ALfloat m22, ALfloat m23,
  75. ALfloat m30, ALfloat m31, ALfloat m32, ALfloat m33);
  76. const aluMatrixf IdentityMatrixf = {{
  77. { 1.0f, 0.0f, 0.0f, 0.0f },
  78. { 0.0f, 1.0f, 0.0f, 0.0f },
  79. { 0.0f, 0.0f, 1.0f, 0.0f },
  80. { 0.0f, 0.0f, 0.0f, 1.0f },
  81. }};
  82. void DeinitVoice(ALvoice *voice)
  83. {
  84. struct ALvoiceProps *props;
  85. size_t count = 0;
  86. props = ATOMIC_EXCHANGE_PTR_SEQ(&voice->Update, NULL);
  87. if(props) al_free(props);
  88. props = ATOMIC_EXCHANGE_PTR(&voice->FreeList, NULL, almemory_order_relaxed);
  89. while(props)
  90. {
  91. struct ALvoiceProps *next;
  92. next = ATOMIC_LOAD(&props->next, almemory_order_relaxed);
  93. al_free(props);
  94. props = next;
  95. ++count;
  96. }
  97. /* This is excessively spammy if it traces every voice destruction, so just
  98. * warn if it was unexpectedly large.
  99. */
  100. if(count > 3)
  101. WARN("Freed "SZFMT" voice property objects\n", count);
  102. }
  103. static inline HrtfDirectMixerFunc SelectHrtfMixer(void)
  104. {
  105. #ifdef HAVE_NEON
  106. if((CPUCapFlags&CPU_CAP_NEON))
  107. return MixDirectHrtf_Neon;
  108. #endif
  109. #ifdef HAVE_SSE
  110. if((CPUCapFlags&CPU_CAP_SSE))
  111. return MixDirectHrtf_SSE;
  112. #endif
  113. return MixDirectHrtf_C;
  114. }
  115. /* Prior to VS2013, MSVC lacks the round() family of functions. */
  116. #if defined(_MSC_VER) && _MSC_VER < 1800
  117. static float roundf(float val)
  118. {
  119. if(val < 0.0f)
  120. return ceilf(val-0.5f);
  121. return floorf(val+0.5f);
  122. }
  123. #endif
  124. /* This RNG method was created based on the math found in opusdec. It's quick,
  125. * and starting with a seed value of 22222, is suitable for generating
  126. * whitenoise.
  127. */
  128. static inline ALuint dither_rng(ALuint *seed)
  129. {
  130. *seed = (*seed * 96314165) + 907633515;
  131. return *seed;
  132. }
  133. static inline void aluCrossproduct(const ALfloat *inVector1, const ALfloat *inVector2, ALfloat *outVector)
  134. {
  135. outVector[0] = inVector1[1]*inVector2[2] - inVector1[2]*inVector2[1];
  136. outVector[1] = inVector1[2]*inVector2[0] - inVector1[0]*inVector2[2];
  137. outVector[2] = inVector1[0]*inVector2[1] - inVector1[1]*inVector2[0];
  138. }
  139. static inline ALfloat aluDotproduct(const aluVector *vec1, const aluVector *vec2)
  140. {
  141. return vec1->v[0]*vec2->v[0] + vec1->v[1]*vec2->v[1] + vec1->v[2]*vec2->v[2];
  142. }
  143. static ALfloat aluNormalize(ALfloat *vec)
  144. {
  145. ALfloat length = sqrtf(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]);
  146. if(length > 0.0f)
  147. {
  148. ALfloat inv_length = 1.0f/length;
  149. vec[0] *= inv_length;
  150. vec[1] *= inv_length;
  151. vec[2] *= inv_length;
  152. }
  153. return length;
  154. }
  155. static void aluMatrixfFloat3(ALfloat *vec, ALfloat w, const aluMatrixf *mtx)
  156. {
  157. ALfloat v[4] = { vec[0], vec[1], vec[2], w };
  158. vec[0] = v[0]*mtx->m[0][0] + v[1]*mtx->m[1][0] + v[2]*mtx->m[2][0] + v[3]*mtx->m[3][0];
  159. vec[1] = v[0]*mtx->m[0][1] + v[1]*mtx->m[1][1] + v[2]*mtx->m[2][1] + v[3]*mtx->m[3][1];
  160. vec[2] = v[0]*mtx->m[0][2] + v[1]*mtx->m[1][2] + v[2]*mtx->m[2][2] + v[3]*mtx->m[3][2];
  161. }
  162. static aluVector aluMatrixfVector(const aluMatrixf *mtx, const aluVector *vec)
  163. {
  164. aluVector v;
  165. v.v[0] = vec->v[0]*mtx->m[0][0] + vec->v[1]*mtx->m[1][0] + vec->v[2]*mtx->m[2][0] + vec->v[3]*mtx->m[3][0];
  166. v.v[1] = vec->v[0]*mtx->m[0][1] + vec->v[1]*mtx->m[1][1] + vec->v[2]*mtx->m[2][1] + vec->v[3]*mtx->m[3][1];
  167. v.v[2] = vec->v[0]*mtx->m[0][2] + vec->v[1]*mtx->m[1][2] + vec->v[2]*mtx->m[2][2] + vec->v[3]*mtx->m[3][2];
  168. v.v[3] = vec->v[0]*mtx->m[0][3] + vec->v[1]*mtx->m[1][3] + vec->v[2]*mtx->m[2][3] + vec->v[3]*mtx->m[3][3];
  169. return v;
  170. }
  171. /* Prepares the interpolator for a given rate (determined by increment). A
  172. * result of AL_FALSE indicates that the filter output will completely cut
  173. * the input signal.
  174. *
  175. * With a bit of work, and a trade of memory for CPU cost, this could be
  176. * modified for use with an interpolated increment for buttery-smooth pitch
  177. * changes.
  178. */
  179. ALboolean BsincPrepare(const ALuint increment, BsincState *state)
  180. {
  181. static const ALfloat scaleBase = 1.510578918e-01f, scaleRange = 1.177936623e+00f;
  182. static const ALuint m[BSINC_SCALE_COUNT] = { 24, 24, 24, 24, 24, 24, 24, 20, 20, 20, 16, 16, 16, 12, 12, 12 };
  183. static const ALuint to[4][BSINC_SCALE_COUNT] =
  184. {
  185. { 0, 24, 408, 792, 1176, 1560, 1944, 2328, 2648, 2968, 3288, 3544, 3800, 4056, 4248, 4440 },
  186. { 4632, 5016, 5400, 5784, 6168, 6552, 6936, 7320, 7640, 7960, 8280, 8536, 8792, 9048, 9240, 0 },
  187. { 0, 9432, 9816, 10200, 10584, 10968, 11352, 11736, 12056, 12376, 12696, 12952, 13208, 13464, 13656, 13848 },
  188. { 14040, 14424, 14808, 15192, 15576, 15960, 16344, 16728, 17048, 17368, 17688, 17944, 18200, 18456, 18648, 0 }
  189. };
  190. static const ALuint tm[2][BSINC_SCALE_COUNT] =
  191. {
  192. { 0, 24, 24, 24, 24, 24, 24, 20, 20, 20, 16, 16, 16, 12, 12, 12 },
  193. { 24, 24, 24, 24, 24, 24, 24, 20, 20, 20, 16, 16, 16, 12, 12, 0 }
  194. };
  195. ALfloat sf;
  196. ALsizei si, pi;
  197. ALboolean uncut = AL_TRUE;
  198. if(increment > FRACTIONONE)
  199. {
  200. sf = (ALfloat)FRACTIONONE / increment;
  201. if(sf < scaleBase)
  202. {
  203. /* Signal has been completely cut. The return result can be used
  204. * to skip the filter (and output zeros) as an optimization.
  205. */
  206. sf = 0.0f;
  207. si = 0;
  208. uncut = AL_FALSE;
  209. }
  210. else
  211. {
  212. sf = (BSINC_SCALE_COUNT - 1) * (sf - scaleBase) * scaleRange;
  213. si = fastf2i(sf);
  214. /* The interpolation factor is fit to this diagonally-symmetric
  215. * curve to reduce the transition ripple caused by interpolating
  216. * different scales of the sinc function.
  217. */
  218. sf = 1.0f - cosf(asinf(sf - si));
  219. }
  220. }
  221. else
  222. {
  223. sf = 0.0f;
  224. si = BSINC_SCALE_COUNT - 1;
  225. }
  226. state->sf = sf;
  227. state->m = m[si];
  228. state->l = -(ALint)((m[si] / 2) - 1);
  229. /* The CPU cost of this table re-mapping could be traded for the memory
  230. * cost of a complete table map (1024 elements large).
  231. */
  232. for(pi = 0;pi < BSINC_PHASE_COUNT;pi++)
  233. {
  234. state->coeffs[pi].filter = &bsincTab[to[0][si] + tm[0][si]*pi];
  235. state->coeffs[pi].scDelta = &bsincTab[to[1][si] + tm[1][si]*pi];
  236. state->coeffs[pi].phDelta = &bsincTab[to[2][si] + tm[0][si]*pi];
  237. state->coeffs[pi].spDelta = &bsincTab[to[3][si] + tm[1][si]*pi];
  238. }
  239. return uncut;
  240. }
  241. static ALboolean CalcListenerParams(ALCcontext *Context)
  242. {
  243. ALlistener *Listener = Context->Listener;
  244. ALfloat N[3], V[3], U[3], P[3];
  245. struct ALlistenerProps *props;
  246. aluVector vel;
  247. props = ATOMIC_EXCHANGE_PTR(&Listener->Update, NULL, almemory_order_acq_rel);
  248. if(!props) return AL_FALSE;
  249. /* AT then UP */
  250. N[0] = props->Forward[0];
  251. N[1] = props->Forward[1];
  252. N[2] = props->Forward[2];
  253. aluNormalize(N);
  254. V[0] = props->Up[0];
  255. V[1] = props->Up[1];
  256. V[2] = props->Up[2];
  257. aluNormalize(V);
  258. /* Build and normalize right-vector */
  259. aluCrossproduct(N, V, U);
  260. aluNormalize(U);
  261. aluMatrixfSet(&Listener->Params.Matrix,
  262. U[0], V[0], -N[0], 0.0,
  263. U[1], V[1], -N[1], 0.0,
  264. U[2], V[2], -N[2], 0.0,
  265. 0.0, 0.0, 0.0, 1.0
  266. );
  267. P[0] = props->Position[0];
  268. P[1] = props->Position[1];
  269. P[2] = props->Position[2];
  270. aluMatrixfFloat3(P, 1.0, &Listener->Params.Matrix);
  271. aluMatrixfSetRow(&Listener->Params.Matrix, 3, -P[0], -P[1], -P[2], 1.0f);
  272. aluVectorSet(&vel, props->Velocity[0], props->Velocity[1], props->Velocity[2], 0.0f);
  273. Listener->Params.Velocity = aluMatrixfVector(&Listener->Params.Matrix, &vel);
  274. Listener->Params.Gain = props->Gain * Context->GainBoost;
  275. Listener->Params.MetersPerUnit = props->MetersPerUnit;
  276. Listener->Params.DopplerFactor = props->DopplerFactor;
  277. Listener->Params.SpeedOfSound = props->SpeedOfSound * props->DopplerVelocity;
  278. Listener->Params.SourceDistanceModel = props->SourceDistanceModel;
  279. Listener->Params.DistanceModel = props->DistanceModel;
  280. ATOMIC_REPLACE_HEAD(struct ALlistenerProps*, &Listener->FreeList, props);
  281. return AL_TRUE;
  282. }
  283. static ALboolean CalcEffectSlotParams(ALeffectslot *slot, ALCdevice *device)
  284. {
  285. struct ALeffectslotProps *props;
  286. ALeffectState *state;
  287. props = ATOMIC_EXCHANGE_PTR(&slot->Update, NULL, almemory_order_acq_rel);
  288. if(!props) return AL_FALSE;
  289. slot->Params.Gain = props->Gain;
  290. slot->Params.AuxSendAuto = props->AuxSendAuto;
  291. slot->Params.EffectType = props->Type;
  292. if(IsReverbEffect(slot->Params.EffectType))
  293. {
  294. slot->Params.RoomRolloff = props->Props.Reverb.RoomRolloffFactor;
  295. slot->Params.DecayTime = props->Props.Reverb.DecayTime;
  296. slot->Params.DecayHFRatio = props->Props.Reverb.DecayHFRatio;
  297. slot->Params.DecayHFLimit = props->Props.Reverb.DecayHFLimit;
  298. slot->Params.AirAbsorptionGainHF = props->Props.Reverb.AirAbsorptionGainHF;
  299. }
  300. else
  301. {
  302. slot->Params.RoomRolloff = 0.0f;
  303. slot->Params.DecayTime = 0.0f;
  304. slot->Params.DecayHFRatio = 0.0f;
  305. slot->Params.DecayHFLimit = AL_FALSE;
  306. slot->Params.AirAbsorptionGainHF = 1.0f;
  307. }
  308. /* Swap effect states. No need to play with the ref counts since they keep
  309. * the same number of refs.
  310. */
  311. state = props->State;
  312. props->State = slot->Params.EffectState;
  313. slot->Params.EffectState = state;
  314. V(state,update)(device, slot, &props->Props);
  315. ATOMIC_REPLACE_HEAD(struct ALeffectslotProps*, &slot->FreeList, props);
  316. return AL_TRUE;
  317. }
  318. static const struct ChanMap MonoMap[1] = {
  319. { FrontCenter, 0.0f, 0.0f }
  320. }, RearMap[2] = {
  321. { BackLeft, DEG2RAD(-150.0f), DEG2RAD(0.0f) },
  322. { BackRight, DEG2RAD( 150.0f), DEG2RAD(0.0f) }
  323. }, QuadMap[4] = {
  324. { FrontLeft, DEG2RAD( -45.0f), DEG2RAD(0.0f) },
  325. { FrontRight, DEG2RAD( 45.0f), DEG2RAD(0.0f) },
  326. { BackLeft, DEG2RAD(-135.0f), DEG2RAD(0.0f) },
  327. { BackRight, DEG2RAD( 135.0f), DEG2RAD(0.0f) }
  328. }, X51Map[6] = {
  329. { FrontLeft, DEG2RAD( -30.0f), DEG2RAD(0.0f) },
  330. { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) },
  331. { FrontCenter, DEG2RAD( 0.0f), DEG2RAD(0.0f) },
  332. { LFE, 0.0f, 0.0f },
  333. { SideLeft, DEG2RAD(-110.0f), DEG2RAD(0.0f) },
  334. { SideRight, DEG2RAD( 110.0f), DEG2RAD(0.0f) }
  335. }, X61Map[7] = {
  336. { FrontLeft, DEG2RAD(-30.0f), DEG2RAD(0.0f) },
  337. { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) },
  338. { FrontCenter, DEG2RAD( 0.0f), DEG2RAD(0.0f) },
  339. { LFE, 0.0f, 0.0f },
  340. { BackCenter, DEG2RAD(180.0f), DEG2RAD(0.0f) },
  341. { SideLeft, DEG2RAD(-90.0f), DEG2RAD(0.0f) },
  342. { SideRight, DEG2RAD( 90.0f), DEG2RAD(0.0f) }
  343. }, X71Map[8] = {
  344. { FrontLeft, DEG2RAD( -30.0f), DEG2RAD(0.0f) },
  345. { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) },
  346. { FrontCenter, DEG2RAD( 0.0f), DEG2RAD(0.0f) },
  347. { LFE, 0.0f, 0.0f },
  348. { BackLeft, DEG2RAD(-150.0f), DEG2RAD(0.0f) },
  349. { BackRight, DEG2RAD( 150.0f), DEG2RAD(0.0f) },
  350. { SideLeft, DEG2RAD( -90.0f), DEG2RAD(0.0f) },
  351. { SideRight, DEG2RAD( 90.0f), DEG2RAD(0.0f) }
  352. };
  353. static void CalcPanningAndFilters(ALvoice *voice, const ALfloat Distance, const ALfloat *Dir,
  354. const ALfloat Spread, const ALfloat DryGain,
  355. const ALfloat DryGainHF, const ALfloat DryGainLF,
  356. const ALfloat *WetGain, const ALfloat *WetGainLF,
  357. const ALfloat *WetGainHF, ALeffectslot **SendSlots,
  358. const ALbuffer *Buffer, const struct ALvoiceProps *props,
  359. const ALlistener *Listener, const ALCdevice *Device)
  360. {
  361. struct ChanMap StereoMap[2] = {
  362. { FrontLeft, DEG2RAD(-30.0f), DEG2RAD(0.0f) },
  363. { FrontRight, DEG2RAD( 30.0f), DEG2RAD(0.0f) }
  364. };
  365. bool DirectChannels = props->DirectChannels;
  366. const ALsizei NumSends = Device->NumAuxSends;
  367. const ALuint Frequency = Device->Frequency;
  368. const struct ChanMap *chans = NULL;
  369. ALsizei num_channels = 0;
  370. bool isbformat = false;
  371. ALfloat downmix_gain = 1.0f;
  372. ALsizei c, i, j;
  373. switch(Buffer->FmtChannels)
  374. {
  375. case FmtMono:
  376. chans = MonoMap;
  377. num_channels = 1;
  378. /* Mono buffers are never played direct. */
  379. DirectChannels = false;
  380. break;
  381. case FmtStereo:
  382. /* Convert counter-clockwise to clockwise. */
  383. StereoMap[0].angle = -props->StereoPan[0];
  384. StereoMap[1].angle = -props->StereoPan[1];
  385. chans = StereoMap;
  386. num_channels = 2;
  387. downmix_gain = 1.0f / 2.0f;
  388. break;
  389. case FmtRear:
  390. chans = RearMap;
  391. num_channels = 2;
  392. downmix_gain = 1.0f / 2.0f;
  393. break;
  394. case FmtQuad:
  395. chans = QuadMap;
  396. num_channels = 4;
  397. downmix_gain = 1.0f / 4.0f;
  398. break;
  399. case FmtX51:
  400. chans = X51Map;
  401. num_channels = 6;
  402. /* NOTE: Excludes LFE. */
  403. downmix_gain = 1.0f / 5.0f;
  404. break;
  405. case FmtX61:
  406. chans = X61Map;
  407. num_channels = 7;
  408. /* NOTE: Excludes LFE. */
  409. downmix_gain = 1.0f / 6.0f;
  410. break;
  411. case FmtX71:
  412. chans = X71Map;
  413. num_channels = 8;
  414. /* NOTE: Excludes LFE. */
  415. downmix_gain = 1.0f / 7.0f;
  416. break;
  417. case FmtBFormat2D:
  418. num_channels = 3;
  419. isbformat = true;
  420. DirectChannels = false;
  421. break;
  422. case FmtBFormat3D:
  423. num_channels = 4;
  424. isbformat = true;
  425. DirectChannels = false;
  426. break;
  427. }
  428. voice->Flags &= ~(VOICE_HAS_HRTF | VOICE_HAS_NFC);
  429. if(isbformat)
  430. {
  431. /* Special handling for B-Format sources. */
  432. if(Distance > FLT_EPSILON)
  433. {
  434. /* Panning a B-Format sound toward some direction is easy. Just pan
  435. * the first (W) channel as a normal mono sound and silence the
  436. * others.
  437. */
  438. ALfloat coeffs[MAX_AMBI_COEFFS];
  439. if(Device->AvgSpeakerDist > 0.0f && Listener->Params.MetersPerUnit > 0.0f)
  440. {
  441. ALfloat mdist = Distance * Listener->Params.MetersPerUnit;
  442. ALfloat w0 = SPEEDOFSOUNDMETRESPERSEC /
  443. (mdist * (ALfloat)Device->Frequency);
  444. ALfloat w1 = SPEEDOFSOUNDMETRESPERSEC /
  445. (Device->AvgSpeakerDist * (ALfloat)Device->Frequency);
  446. /* Clamp w0 for really close distances, to prevent excessive
  447. * bass.
  448. */
  449. w0 = minf(w0, w1*4.0f);
  450. /* Only need to adjust the first channel of a B-Format source. */
  451. NfcFilterAdjust1(&voice->Direct.Params[0].NFCtrlFilter[0], w0);
  452. NfcFilterAdjust2(&voice->Direct.Params[0].NFCtrlFilter[1], w0);
  453. NfcFilterAdjust3(&voice->Direct.Params[0].NFCtrlFilter[2], w0);
  454. for(i = 0;i < MAX_AMBI_ORDER+1;i++)
  455. voice->Direct.ChannelsPerOrder[i] = Device->Dry.NumChannelsPerOrder[i];
  456. voice->Flags |= VOICE_HAS_NFC;
  457. }
  458. if(Device->Render_Mode == StereoPair)
  459. {
  460. ALfloat ev = asinf(Dir[1]);
  461. ALfloat az = atan2f(Dir[0], -Dir[2]);
  462. CalcAnglePairwiseCoeffs(az, ev, Spread, coeffs);
  463. }
  464. else
  465. CalcDirectionCoeffs(Dir, Spread, coeffs);
  466. /* NOTE: W needs to be scaled by sqrt(2) due to FuMa normalization. */
  467. ComputePanningGains(Device->Dry, coeffs, DryGain*1.414213562f,
  468. voice->Direct.Params[0].Gains.Target);
  469. for(c = 1;c < num_channels;c++)
  470. {
  471. for(j = 0;j < MAX_OUTPUT_CHANNELS;j++)
  472. voice->Direct.Params[c].Gains.Target[j] = 0.0f;
  473. }
  474. for(i = 0;i < NumSends;i++)
  475. {
  476. const ALeffectslot *Slot = SendSlots[i];
  477. if(Slot)
  478. ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels,
  479. coeffs, WetGain[i]*1.414213562f, voice->Send[i].Params[0].Gains.Target
  480. );
  481. else
  482. for(j = 0;j < MAX_EFFECT_CHANNELS;j++)
  483. voice->Send[i].Params[0].Gains.Target[j] = 0.0f;
  484. for(c = 1;c < num_channels;c++)
  485. {
  486. for(j = 0;j < MAX_EFFECT_CHANNELS;j++)
  487. voice->Send[i].Params[c].Gains.Target[j] = 0.0f;
  488. }
  489. }
  490. }
  491. else
  492. {
  493. /* Local B-Format sources have their XYZ channels rotated according
  494. * to the orientation.
  495. */
  496. ALfloat N[3], V[3], U[3];
  497. aluMatrixf matrix;
  498. ALfloat scale;
  499. if(Device->AvgSpeakerDist > 0.0f)
  500. {
  501. /* NOTE: The NFCtrlFilters were created with a w0 of 0, which
  502. * is what we want for FOA input. The first channel may have
  503. * been previously re-adjusted if panned, so reset it.
  504. */
  505. NfcFilterAdjust1(&voice->Direct.Params[0].NFCtrlFilter[0], 0.0f);
  506. NfcFilterAdjust2(&voice->Direct.Params[0].NFCtrlFilter[1], 0.0f);
  507. NfcFilterAdjust3(&voice->Direct.Params[0].NFCtrlFilter[2], 0.0f);
  508. voice->Direct.ChannelsPerOrder[0] = 1;
  509. voice->Direct.ChannelsPerOrder[1] = mini(voice->Direct.Channels-1, 3);
  510. for(i = 2;i < MAX_AMBI_ORDER+1;i++)
  511. voice->Direct.ChannelsPerOrder[2] = 0;
  512. voice->Flags |= VOICE_HAS_NFC;
  513. }
  514. /* AT then UP */
  515. N[0] = props->Orientation[0][0];
  516. N[1] = props->Orientation[0][1];
  517. N[2] = props->Orientation[0][2];
  518. aluNormalize(N);
  519. V[0] = props->Orientation[1][0];
  520. V[1] = props->Orientation[1][1];
  521. V[2] = props->Orientation[1][2];
  522. aluNormalize(V);
  523. if(!props->HeadRelative)
  524. {
  525. const aluMatrixf *lmatrix = &Listener->Params.Matrix;
  526. aluMatrixfFloat3(N, 0.0f, lmatrix);
  527. aluMatrixfFloat3(V, 0.0f, lmatrix);
  528. }
  529. /* Build and normalize right-vector */
  530. aluCrossproduct(N, V, U);
  531. aluNormalize(U);
  532. /* Build a rotate + conversion matrix (FuMa -> ACN+N3D). */
  533. scale = 1.732050808f;
  534. aluMatrixfSet(&matrix,
  535. 1.414213562f, 0.0f, 0.0f, 0.0f,
  536. 0.0f, -N[0]*scale, N[1]*scale, -N[2]*scale,
  537. 0.0f, U[0]*scale, -U[1]*scale, U[2]*scale,
  538. 0.0f, -V[0]*scale, V[1]*scale, -V[2]*scale
  539. );
  540. voice->Direct.Buffer = Device->FOAOut.Buffer;
  541. voice->Direct.Channels = Device->FOAOut.NumChannels;
  542. for(c = 0;c < num_channels;c++)
  543. ComputeFirstOrderGains(Device->FOAOut, matrix.m[c], DryGain,
  544. voice->Direct.Params[c].Gains.Target);
  545. for(i = 0;i < NumSends;i++)
  546. {
  547. const ALeffectslot *Slot = SendSlots[i];
  548. if(Slot)
  549. {
  550. for(c = 0;c < num_channels;c++)
  551. ComputeFirstOrderGainsBF(Slot->ChanMap, Slot->NumChannels,
  552. matrix.m[c], WetGain[i], voice->Send[i].Params[c].Gains.Target
  553. );
  554. }
  555. else
  556. {
  557. for(c = 0;c < num_channels;c++)
  558. for(j = 0;j < MAX_EFFECT_CHANNELS;j++)
  559. voice->Send[i].Params[c].Gains.Target[j] = 0.0f;
  560. }
  561. }
  562. }
  563. }
  564. else if(DirectChannels)
  565. {
  566. /* Direct source channels always play local. Skip the virtual channels
  567. * and write inputs to the matching real outputs.
  568. */
  569. voice->Direct.Buffer = Device->RealOut.Buffer;
  570. voice->Direct.Channels = Device->RealOut.NumChannels;
  571. for(c = 0;c < num_channels;c++)
  572. {
  573. int idx;
  574. for(j = 0;j < MAX_OUTPUT_CHANNELS;j++)
  575. voice->Direct.Params[c].Gains.Target[j] = 0.0f;
  576. if((idx=GetChannelIdxByName(Device->RealOut, chans[c].channel)) != -1)
  577. voice->Direct.Params[c].Gains.Target[idx] = DryGain;
  578. }
  579. /* Auxiliary sends still use normal channel panning since they mix to
  580. * B-Format, which can't channel-match.
  581. */
  582. for(c = 0;c < num_channels;c++)
  583. {
  584. ALfloat coeffs[MAX_AMBI_COEFFS];
  585. CalcAngleCoeffs(chans[c].angle, chans[c].elevation, 0.0f, coeffs);
  586. for(i = 0;i < NumSends;i++)
  587. {
  588. const ALeffectslot *Slot = SendSlots[i];
  589. if(Slot)
  590. ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels,
  591. coeffs, WetGain[i], voice->Send[i].Params[c].Gains.Target
  592. );
  593. else
  594. for(j = 0;j < MAX_EFFECT_CHANNELS;j++)
  595. voice->Send[i].Params[c].Gains.Target[j] = 0.0f;
  596. }
  597. }
  598. }
  599. else if(Device->Render_Mode == HrtfRender)
  600. {
  601. /* Full HRTF rendering. Skip the virtual channels and render to the
  602. * real outputs.
  603. */
  604. voice->Direct.Buffer = Device->RealOut.Buffer;
  605. voice->Direct.Channels = Device->RealOut.NumChannels;
  606. if(Distance > FLT_EPSILON)
  607. {
  608. ALfloat coeffs[MAX_AMBI_COEFFS];
  609. ALfloat ev, az;
  610. ev = asinf(Dir[1]);
  611. az = atan2f(Dir[0], -Dir[2]);
  612. /* Get the HRIR coefficients and delays just once, for the given
  613. * source direction.
  614. */
  615. GetHrtfCoeffs(Device->HrtfHandle, ev, az, Spread,
  616. voice->Direct.Params[0].Hrtf.Target.Coeffs,
  617. voice->Direct.Params[0].Hrtf.Target.Delay);
  618. voice->Direct.Params[0].Hrtf.Target.Gain = DryGain * downmix_gain;
  619. /* Remaining channels use the same results as the first. */
  620. for(c = 1;c < num_channels;c++)
  621. {
  622. /* Skip LFE */
  623. if(chans[c].channel == LFE)
  624. memset(&voice->Direct.Params[c].Hrtf.Target, 0,
  625. sizeof(voice->Direct.Params[c].Hrtf.Target));
  626. else
  627. voice->Direct.Params[c].Hrtf.Target = voice->Direct.Params[0].Hrtf.Target;
  628. }
  629. /* Calculate the directional coefficients once, which apply to all
  630. * input channels of the source sends.
  631. */
  632. CalcDirectionCoeffs(Dir, Spread, coeffs);
  633. for(i = 0;i < NumSends;i++)
  634. {
  635. const ALeffectslot *Slot = SendSlots[i];
  636. if(Slot)
  637. for(c = 0;c < num_channels;c++)
  638. {
  639. /* Skip LFE */
  640. if(chans[c].channel == LFE)
  641. for(j = 0;j < MAX_EFFECT_CHANNELS;j++)
  642. voice->Send[i].Params[c].Gains.Target[j] = 0.0f;
  643. else
  644. ComputePanningGainsBF(Slot->ChanMap,
  645. Slot->NumChannels, coeffs, WetGain[i] * downmix_gain,
  646. voice->Send[i].Params[c].Gains.Target
  647. );
  648. }
  649. else
  650. for(j = 0;j < MAX_EFFECT_CHANNELS;j++)
  651. voice->Send[i].Params[c].Gains.Target[j] = 0.0f;
  652. }
  653. }
  654. else
  655. {
  656. /* Local sources on HRTF play with each channel panned to its
  657. * relative location around the listener, providing "virtual
  658. * speaker" responses.
  659. */
  660. for(c = 0;c < num_channels;c++)
  661. {
  662. ALfloat coeffs[MAX_AMBI_COEFFS];
  663. if(chans[c].channel == LFE)
  664. {
  665. /* Skip LFE */
  666. memset(&voice->Direct.Params[c].Hrtf.Target, 0,
  667. sizeof(voice->Direct.Params[c].Hrtf.Target));
  668. for(i = 0;i < NumSends;i++)
  669. {
  670. for(j = 0;j < MAX_EFFECT_CHANNELS;j++)
  671. voice->Send[i].Params[c].Gains.Target[j] = 0.0f;
  672. }
  673. continue;
  674. }
  675. /* Get the HRIR coefficients and delays for this channel
  676. * position.
  677. */
  678. GetHrtfCoeffs(Device->HrtfHandle,
  679. chans[c].elevation, chans[c].angle, Spread,
  680. voice->Direct.Params[c].Hrtf.Target.Coeffs,
  681. voice->Direct.Params[c].Hrtf.Target.Delay
  682. );
  683. voice->Direct.Params[c].Hrtf.Target.Gain = DryGain;
  684. /* Normal panning for auxiliary sends. */
  685. CalcAngleCoeffs(chans[c].angle, chans[c].elevation, Spread, coeffs);
  686. for(i = 0;i < NumSends;i++)
  687. {
  688. const ALeffectslot *Slot = SendSlots[i];
  689. if(Slot)
  690. ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels,
  691. coeffs, WetGain[i], voice->Send[i].Params[c].Gains.Target
  692. );
  693. else
  694. for(j = 0;j < MAX_EFFECT_CHANNELS;j++)
  695. voice->Send[i].Params[c].Gains.Target[j] = 0.0f;
  696. }
  697. }
  698. }
  699. voice->Flags |= VOICE_HAS_HRTF;
  700. }
  701. else
  702. {
  703. /* Non-HRTF rendering. Use normal panning to the output. */
  704. if(Distance > FLT_EPSILON)
  705. {
  706. ALfloat coeffs[MAX_AMBI_COEFFS];
  707. ALfloat w0 = 0.0f;
  708. /* Calculate NFC filter coefficient if needed. */
  709. if(Device->AvgSpeakerDist > 0.0f && Listener->Params.MetersPerUnit > 0.0f)
  710. {
  711. ALfloat mdist = Distance * Listener->Params.MetersPerUnit;
  712. ALfloat w1 = SPEEDOFSOUNDMETRESPERSEC /
  713. (Device->AvgSpeakerDist * (ALfloat)Device->Frequency);
  714. w0 = SPEEDOFSOUNDMETRESPERSEC /
  715. (mdist * (ALfloat)Device->Frequency);
  716. /* Clamp w0 for really close distances, to prevent excessive
  717. * bass.
  718. */
  719. w0 = minf(w0, w1*4.0f);
  720. for(i = 0;i < MAX_AMBI_ORDER+1;i++)
  721. voice->Direct.ChannelsPerOrder[i] = Device->Dry.NumChannelsPerOrder[i];
  722. voice->Flags |= VOICE_HAS_NFC;
  723. }
  724. /* Calculate the directional coefficients once, which apply to all
  725. * input channels.
  726. */
  727. if(Device->Render_Mode == StereoPair)
  728. {
  729. ALfloat ev = asinf(Dir[1]);
  730. ALfloat az = atan2f(Dir[0], -Dir[2]);
  731. CalcAnglePairwiseCoeffs(az, ev, Spread, coeffs);
  732. }
  733. else
  734. CalcDirectionCoeffs(Dir, Spread, coeffs);
  735. for(c = 0;c < num_channels;c++)
  736. {
  737. /* Adjust NFC filters if needed. */
  738. if((voice->Flags&VOICE_HAS_NFC))
  739. {
  740. NfcFilterAdjust1(&voice->Direct.Params[c].NFCtrlFilter[0], w0);
  741. NfcFilterAdjust2(&voice->Direct.Params[c].NFCtrlFilter[1], w0);
  742. NfcFilterAdjust3(&voice->Direct.Params[c].NFCtrlFilter[2], w0);
  743. }
  744. /* Special-case LFE */
  745. if(chans[c].channel == LFE)
  746. {
  747. for(j = 0;j < MAX_OUTPUT_CHANNELS;j++)
  748. voice->Direct.Params[c].Gains.Target[j] = 0.0f;
  749. if(Device->Dry.Buffer == Device->RealOut.Buffer)
  750. {
  751. int idx = GetChannelIdxByName(Device->RealOut, chans[c].channel);
  752. if(idx != -1) voice->Direct.Params[c].Gains.Target[idx] = DryGain;
  753. }
  754. continue;
  755. }
  756. ComputePanningGains(Device->Dry,
  757. coeffs, DryGain * downmix_gain, voice->Direct.Params[c].Gains.Target
  758. );
  759. }
  760. for(i = 0;i < NumSends;i++)
  761. {
  762. const ALeffectslot *Slot = SendSlots[i];
  763. if(Slot)
  764. for(c = 0;c < num_channels;c++)
  765. {
  766. /* Skip LFE */
  767. if(chans[c].channel == LFE)
  768. for(j = 0;j < MAX_EFFECT_CHANNELS;j++)
  769. voice->Send[i].Params[c].Gains.Target[j] = 0.0f;
  770. else
  771. ComputePanningGainsBF(Slot->ChanMap,
  772. Slot->NumChannels, coeffs, WetGain[i] * downmix_gain,
  773. voice->Send[i].Params[c].Gains.Target
  774. );
  775. }
  776. else
  777. for(c = 0;c < num_channels;c++)
  778. {
  779. for(j = 0;j < MAX_EFFECT_CHANNELS;j++)
  780. voice->Send[i].Params[c].Gains.Target[j] = 0.0f;
  781. }
  782. }
  783. }
  784. else
  785. {
  786. ALfloat w0 = 0.0f;
  787. if(Device->AvgSpeakerDist > 0.0f)
  788. {
  789. /* If the source distance is 0, set w0 to w1 to act as a pass-
  790. * through. We still want to pass the signal through the
  791. * filters so they keep an appropriate history, in case the
  792. * source moves away from the listener.
  793. */
  794. w0 = SPEEDOFSOUNDMETRESPERSEC /
  795. (Device->AvgSpeakerDist * (ALfloat)Device->Frequency);
  796. for(i = 0;i < MAX_AMBI_ORDER+1;i++)
  797. voice->Direct.ChannelsPerOrder[i] = Device->Dry.NumChannelsPerOrder[i];
  798. voice->Flags |= VOICE_HAS_NFC;
  799. }
  800. for(c = 0;c < num_channels;c++)
  801. {
  802. ALfloat coeffs[MAX_AMBI_COEFFS];
  803. if((voice->Flags&VOICE_HAS_NFC))
  804. {
  805. NfcFilterAdjust1(&voice->Direct.Params[c].NFCtrlFilter[0], w0);
  806. NfcFilterAdjust2(&voice->Direct.Params[c].NFCtrlFilter[1], w0);
  807. NfcFilterAdjust3(&voice->Direct.Params[c].NFCtrlFilter[2], w0);
  808. }
  809. /* Special-case LFE */
  810. if(chans[c].channel == LFE)
  811. {
  812. for(j = 0;j < MAX_OUTPUT_CHANNELS;j++)
  813. voice->Direct.Params[c].Gains.Target[j] = 0.0f;
  814. if(Device->Dry.Buffer == Device->RealOut.Buffer)
  815. {
  816. int idx = GetChannelIdxByName(Device->RealOut, chans[c].channel);
  817. if(idx != -1) voice->Direct.Params[c].Gains.Target[idx] = DryGain;
  818. }
  819. for(i = 0;i < NumSends;i++)
  820. {
  821. for(j = 0;j < MAX_EFFECT_CHANNELS;j++)
  822. voice->Send[i].Params[c].Gains.Target[j] = 0.0f;
  823. }
  824. continue;
  825. }
  826. if(Device->Render_Mode == StereoPair)
  827. CalcAnglePairwiseCoeffs(chans[c].angle, chans[c].elevation, Spread, coeffs);
  828. else
  829. CalcAngleCoeffs(chans[c].angle, chans[c].elevation, Spread, coeffs);
  830. ComputePanningGains(Device->Dry,
  831. coeffs, DryGain, voice->Direct.Params[c].Gains.Target
  832. );
  833. for(i = 0;i < NumSends;i++)
  834. {
  835. const ALeffectslot *Slot = SendSlots[i];
  836. if(Slot)
  837. ComputePanningGainsBF(Slot->ChanMap, Slot->NumChannels,
  838. coeffs, WetGain[i], voice->Send[i].Params[c].Gains.Target
  839. );
  840. else
  841. for(j = 0;j < MAX_EFFECT_CHANNELS;j++)
  842. voice->Send[i].Params[c].Gains.Target[j] = 0.0f;
  843. }
  844. }
  845. }
  846. }
  847. {
  848. ALfloat hfScale = props->Direct.HFReference / Frequency;
  849. ALfloat lfScale = props->Direct.LFReference / Frequency;
  850. ALfloat gainHF = maxf(DryGainHF, 0.001f); /* Limit -60dB */
  851. ALfloat gainLF = maxf(DryGainLF, 0.001f);
  852. voice->Direct.FilterType = AF_None;
  853. if(gainHF != 1.0f) voice->Direct.FilterType |= AF_LowPass;
  854. if(gainLF != 1.0f) voice->Direct.FilterType |= AF_HighPass;
  855. ALfilterState_setParams(
  856. &voice->Direct.Params[0].LowPass, ALfilterType_HighShelf,
  857. gainHF, hfScale, calc_rcpQ_from_slope(gainHF, 1.0f)
  858. );
  859. ALfilterState_setParams(
  860. &voice->Direct.Params[0].HighPass, ALfilterType_LowShelf,
  861. gainLF, lfScale, calc_rcpQ_from_slope(gainLF, 1.0f)
  862. );
  863. for(c = 1;c < num_channels;c++)
  864. {
  865. ALfilterState_copyParams(&voice->Direct.Params[c].LowPass,
  866. &voice->Direct.Params[0].LowPass);
  867. ALfilterState_copyParams(&voice->Direct.Params[c].HighPass,
  868. &voice->Direct.Params[0].HighPass);
  869. }
  870. }
  871. for(i = 0;i < NumSends;i++)
  872. {
  873. ALfloat hfScale = props->Send[i].HFReference / Frequency;
  874. ALfloat lfScale = props->Send[i].LFReference / Frequency;
  875. ALfloat gainHF = maxf(WetGainHF[i], 0.001f);
  876. ALfloat gainLF = maxf(WetGainLF[i], 0.001f);
  877. voice->Send[i].FilterType = AF_None;
  878. if(gainHF != 1.0f) voice->Send[i].FilterType |= AF_LowPass;
  879. if(gainLF != 1.0f) voice->Send[i].FilterType |= AF_HighPass;
  880. ALfilterState_setParams(
  881. &voice->Send[i].Params[0].LowPass, ALfilterType_HighShelf,
  882. gainHF, hfScale, calc_rcpQ_from_slope(gainHF, 1.0f)
  883. );
  884. ALfilterState_setParams(
  885. &voice->Send[i].Params[0].HighPass, ALfilterType_LowShelf,
  886. gainLF, lfScale, calc_rcpQ_from_slope(gainLF, 1.0f)
  887. );
  888. for(c = 1;c < num_channels;c++)
  889. {
  890. ALfilterState_copyParams(&voice->Send[i].Params[c].LowPass,
  891. &voice->Send[i].Params[0].LowPass);
  892. ALfilterState_copyParams(&voice->Send[i].Params[c].HighPass,
  893. &voice->Send[i].Params[0].HighPass);
  894. }
  895. }
  896. }
  897. static void CalcNonAttnSourceParams(ALvoice *voice, const struct ALvoiceProps *props, const ALbuffer *ALBuffer, const ALCcontext *ALContext)
  898. {
  899. static const ALfloat dir[3] = { 0.0f, 0.0f, -1.0f };
  900. const ALCdevice *Device = ALContext->Device;
  901. const ALlistener *Listener = ALContext->Listener;
  902. ALfloat DryGain, DryGainHF, DryGainLF;
  903. ALfloat WetGain[MAX_SENDS];
  904. ALfloat WetGainHF[MAX_SENDS];
  905. ALfloat WetGainLF[MAX_SENDS];
  906. ALeffectslot *SendSlots[MAX_SENDS];
  907. ALfloat Pitch;
  908. ALsizei i;
  909. voice->Direct.Buffer = Device->Dry.Buffer;
  910. voice->Direct.Channels = Device->Dry.NumChannels;
  911. for(i = 0;i < Device->NumAuxSends;i++)
  912. {
  913. SendSlots[i] = props->Send[i].Slot;
  914. if(!SendSlots[i] && i == 0)
  915. SendSlots[i] = ALContext->DefaultSlot;
  916. if(!SendSlots[i] || SendSlots[i]->Params.EffectType == AL_EFFECT_NULL)
  917. {
  918. SendSlots[i] = NULL;
  919. voice->Send[i].Buffer = NULL;
  920. voice->Send[i].Channels = 0;
  921. }
  922. else
  923. {
  924. voice->Send[i].Buffer = SendSlots[i]->WetBuffer;
  925. voice->Send[i].Channels = SendSlots[i]->NumChannels;
  926. }
  927. }
  928. /* Calculate the stepping value */
  929. Pitch = (ALfloat)ALBuffer->Frequency/(ALfloat)Device->Frequency * props->Pitch;
  930. if(Pitch > (ALfloat)MAX_PITCH)
  931. voice->Step = MAX_PITCH<<FRACTIONBITS;
  932. else
  933. voice->Step = maxi(fastf2i(Pitch*FRACTIONONE + 0.5f), 1);
  934. BsincPrepare(voice->Step, &voice->ResampleState.bsinc);
  935. voice->Resampler = SelectResampler(props->Resampler);
  936. /* Calculate gains */
  937. DryGain = clampf(props->Gain, props->MinGain, props->MaxGain);
  938. DryGain *= props->Direct.Gain * Listener->Params.Gain;
  939. DryGain = minf(DryGain, GAIN_MIX_MAX);
  940. DryGainHF = props->Direct.GainHF;
  941. DryGainLF = props->Direct.GainLF;
  942. for(i = 0;i < Device->NumAuxSends;i++)
  943. {
  944. WetGain[i] = clampf(props->Gain, props->MinGain, props->MaxGain);
  945. WetGain[i] *= props->Send[i].Gain * Listener->Params.Gain;
  946. WetGain[i] = minf(WetGain[i], GAIN_MIX_MAX);
  947. WetGainHF[i] = props->Send[i].GainHF;
  948. WetGainLF[i] = props->Send[i].GainLF;
  949. }
  950. CalcPanningAndFilters(voice, 0.0f, dir, 0.0f, DryGain, DryGainHF, DryGainLF, WetGain,
  951. WetGainLF, WetGainHF, SendSlots, ALBuffer, props, Listener, Device);
  952. }
  953. static void CalcAttnSourceParams(ALvoice *voice, const struct ALvoiceProps *props, const ALbuffer *ALBuffer, const ALCcontext *ALContext)
  954. {
  955. const ALCdevice *Device = ALContext->Device;
  956. const ALlistener *Listener = ALContext->Listener;
  957. const ALsizei NumSends = Device->NumAuxSends;
  958. aluVector Position, Velocity, Direction, SourceToListener;
  959. ALfloat Distance, ClampedDist, DopplerFactor;
  960. ALeffectslot *SendSlots[MAX_SENDS];
  961. ALfloat RoomRolloff[MAX_SENDS];
  962. ALfloat DecayDistance[MAX_SENDS];
  963. ALfloat DecayHFDistance[MAX_SENDS];
  964. ALfloat DryGain, DryGainHF, DryGainLF;
  965. ALfloat WetGain[MAX_SENDS];
  966. ALfloat WetGainHF[MAX_SENDS];
  967. ALfloat WetGainLF[MAX_SENDS];
  968. bool directional;
  969. ALfloat dir[3];
  970. ALfloat spread;
  971. ALfloat Pitch;
  972. ALint i;
  973. /* Set mixing buffers and get send parameters. */
  974. voice->Direct.Buffer = Device->Dry.Buffer;
  975. voice->Direct.Channels = Device->Dry.NumChannels;
  976. for(i = 0;i < NumSends;i++)
  977. {
  978. SendSlots[i] = props->Send[i].Slot;
  979. if(!SendSlots[i] && i == 0)
  980. SendSlots[i] = ALContext->DefaultSlot;
  981. if(!SendSlots[i] || SendSlots[i]->Params.EffectType == AL_EFFECT_NULL)
  982. {
  983. SendSlots[i] = NULL;
  984. RoomRolloff[i] = 0.0f;
  985. DecayDistance[i] = 0.0f;
  986. DecayHFDistance[i] = 0.0f;
  987. }
  988. else if(SendSlots[i]->Params.AuxSendAuto)
  989. {
  990. RoomRolloff[i] = SendSlots[i]->Params.RoomRolloff + props->RoomRolloffFactor;
  991. DecayDistance[i] = SendSlots[i]->Params.DecayTime * SPEEDOFSOUNDMETRESPERSEC;
  992. DecayHFDistance[i] = DecayDistance[i] * SendSlots[i]->Params.DecayHFRatio;
  993. if(SendSlots[i]->Params.DecayHFLimit)
  994. {
  995. ALfloat airAbsorption = SendSlots[i]->Params.AirAbsorptionGainHF;
  996. if(airAbsorption < 1.0f)
  997. {
  998. ALfloat limitRatio = log10f(REVERB_DECAY_GAIN) / log10f(airAbsorption);
  999. DecayHFDistance[i] = minf(limitRatio, DecayHFDistance[i]);
  1000. }
  1001. }
  1002. }
  1003. else
  1004. {
  1005. /* If the slot's auxiliary send auto is off, the data sent to the
  1006. * effect slot is the same as the dry path, sans filter effects */
  1007. RoomRolloff[i] = props->RolloffFactor;
  1008. DecayDistance[i] = 0.0f;
  1009. DecayHFDistance[i] = 0.0f;
  1010. }
  1011. if(!SendSlots[i])
  1012. {
  1013. voice->Send[i].Buffer = NULL;
  1014. voice->Send[i].Channels = 0;
  1015. }
  1016. else
  1017. {
  1018. voice->Send[i].Buffer = SendSlots[i]->WetBuffer;
  1019. voice->Send[i].Channels = SendSlots[i]->NumChannels;
  1020. }
  1021. }
  1022. /* Transform source to listener space (convert to head relative) */
  1023. aluVectorSet(&Position, props->Position[0], props->Position[1], props->Position[2], 1.0f);
  1024. aluVectorSet(&Direction, props->Direction[0], props->Direction[1], props->Direction[2], 0.0f);
  1025. aluVectorSet(&Velocity, props->Velocity[0], props->Velocity[1], props->Velocity[2], 0.0f);
  1026. if(props->HeadRelative == AL_FALSE)
  1027. {
  1028. const aluMatrixf *Matrix = &Listener->Params.Matrix;
  1029. /* Transform source vectors */
  1030. Position = aluMatrixfVector(Matrix, &Position);
  1031. Velocity = aluMatrixfVector(Matrix, &Velocity);
  1032. Direction = aluMatrixfVector(Matrix, &Direction);
  1033. }
  1034. else
  1035. {
  1036. const aluVector *lvelocity = &Listener->Params.Velocity;
  1037. /* Offset the source velocity to be relative of the listener velocity */
  1038. Velocity.v[0] += lvelocity->v[0];
  1039. Velocity.v[1] += lvelocity->v[1];
  1040. Velocity.v[2] += lvelocity->v[2];
  1041. }
  1042. directional = aluNormalize(Direction.v) > FLT_EPSILON;
  1043. SourceToListener.v[0] = -Position.v[0];
  1044. SourceToListener.v[1] = -Position.v[1];
  1045. SourceToListener.v[2] = -Position.v[2];
  1046. SourceToListener.v[3] = 0.0f;
  1047. Distance = aluNormalize(SourceToListener.v);
  1048. /* Initial source gain */
  1049. DryGain = props->Gain;
  1050. DryGainHF = 1.0f;
  1051. DryGainLF = 1.0f;
  1052. for(i = 0;i < NumSends;i++)
  1053. {
  1054. WetGain[i] = props->Gain;
  1055. WetGainHF[i] = 1.0f;
  1056. WetGainLF[i] = 1.0f;
  1057. }
  1058. /* Calculate distance attenuation */
  1059. ClampedDist = Distance;
  1060. switch(Listener->Params.SourceDistanceModel ?
  1061. props->DistanceModel : Listener->Params.DistanceModel)
  1062. {
  1063. case InverseDistanceClamped:
  1064. ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
  1065. if(props->MaxDistance < props->RefDistance)
  1066. break;
  1067. /*fall-through*/
  1068. case InverseDistance:
  1069. if(!(props->RefDistance > 0.0f))
  1070. ClampedDist = props->RefDistance;
  1071. else
  1072. {
  1073. ALfloat dist = lerp(props->RefDistance, ClampedDist, props->RolloffFactor);
  1074. if(dist > 0.0f) DryGain *= props->RefDistance / dist;
  1075. for(i = 0;i < NumSends;i++)
  1076. {
  1077. dist = lerp(props->RefDistance, ClampedDist, RoomRolloff[i]);
  1078. if(dist > 0.0f) WetGain[i] *= props->RefDistance / dist;
  1079. }
  1080. }
  1081. break;
  1082. case LinearDistanceClamped:
  1083. ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
  1084. if(props->MaxDistance < props->RefDistance)
  1085. break;
  1086. /*fall-through*/
  1087. case LinearDistance:
  1088. if(!(props->MaxDistance != props->RefDistance))
  1089. ClampedDist = props->RefDistance;
  1090. else
  1091. {
  1092. ALfloat attn = props->RolloffFactor * (ClampedDist-props->RefDistance) /
  1093. (props->MaxDistance-props->RefDistance);
  1094. DryGain *= maxf(1.0f - attn, 0.0f);
  1095. for(i = 0;i < NumSends;i++)
  1096. {
  1097. attn = RoomRolloff[i] * (ClampedDist-props->RefDistance) /
  1098. (props->MaxDistance-props->RefDistance);
  1099. WetGain[i] *= maxf(1.0f - attn, 0.0f);
  1100. }
  1101. }
  1102. break;
  1103. case ExponentDistanceClamped:
  1104. ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
  1105. if(props->MaxDistance < props->RefDistance)
  1106. break;
  1107. /*fall-through*/
  1108. case ExponentDistance:
  1109. if(!(ClampedDist > 0.0f && props->RefDistance > 0.0f))
  1110. ClampedDist = props->RefDistance;
  1111. else
  1112. {
  1113. DryGain *= powf(ClampedDist/props->RefDistance, -props->RolloffFactor);
  1114. for(i = 0;i < NumSends;i++)
  1115. WetGain[i] *= powf(ClampedDist/props->RefDistance, -RoomRolloff[i]);
  1116. }
  1117. break;
  1118. case DisableDistance:
  1119. ClampedDist = props->RefDistance;
  1120. break;
  1121. }
  1122. /* Distance-based air absorption */
  1123. if(ClampedDist > props->RefDistance && props->RolloffFactor > 0.0f)
  1124. {
  1125. ALfloat meters_base = (ClampedDist-props->RefDistance) * props->RolloffFactor *
  1126. Listener->Params.MetersPerUnit;
  1127. if(props->AirAbsorptionFactor > 0.0f)
  1128. {
  1129. ALfloat hfattn = powf(AIRABSORBGAINHF, meters_base * props->AirAbsorptionFactor);
  1130. DryGainHF *= hfattn;
  1131. for(i = 0;i < NumSends;i++)
  1132. WetGainHF[i] *= hfattn;
  1133. }
  1134. if(props->WetGainAuto)
  1135. {
  1136. /* Apply a decay-time transformation to the wet path, based on the
  1137. * source distance in meters. The initial decay of the reverb
  1138. * effect is calculated and applied to the wet path.
  1139. */
  1140. for(i = 0;i < NumSends;i++)
  1141. {
  1142. ALfloat gain;
  1143. if(!(DecayDistance[i] > 0.0f))
  1144. continue;
  1145. gain = powf(REVERB_DECAY_GAIN, meters_base/DecayDistance[i]);
  1146. WetGain[i] *= gain;
  1147. /* Yes, the wet path's air absorption is applied with
  1148. * WetGainAuto on, rather than WetGainHFAuto.
  1149. */
  1150. if(gain > 0.0f)
  1151. {
  1152. ALfloat gainhf = powf(REVERB_DECAY_GAIN, meters_base/DecayHFDistance[i]);
  1153. WetGainHF[i] *= minf(gainhf / gain, 1.0f);
  1154. }
  1155. }
  1156. }
  1157. }
  1158. /* Calculate directional soundcones */
  1159. if(directional && props->InnerAngle < 360.0f)
  1160. {
  1161. ALfloat ConeVolume;
  1162. ALfloat ConeHF;
  1163. ALfloat Angle;
  1164. Angle = acosf(aluDotproduct(&Direction, &SourceToListener));
  1165. Angle = RAD2DEG(Angle * ConeScale * 2.0f);
  1166. if(!(Angle > props->InnerAngle))
  1167. {
  1168. ConeVolume = 1.0f;
  1169. ConeHF = 1.0f;
  1170. }
  1171. else if(Angle < props->OuterAngle)
  1172. {
  1173. ALfloat scale = ( Angle-props->InnerAngle) /
  1174. (props->OuterAngle-props->InnerAngle);
  1175. ConeVolume = lerp(1.0f, props->OuterGain, scale);
  1176. ConeHF = lerp(1.0f, props->OuterGainHF, scale);
  1177. }
  1178. else
  1179. {
  1180. ConeVolume = props->OuterGain;
  1181. ConeHF = props->OuterGainHF;
  1182. }
  1183. DryGain *= ConeVolume;
  1184. if(props->DryGainHFAuto)
  1185. DryGainHF *= ConeHF;
  1186. if(props->WetGainAuto)
  1187. {
  1188. for(i = 0;i < NumSends;i++)
  1189. WetGain[i] *= ConeVolume;
  1190. }
  1191. if(props->WetGainHFAuto)
  1192. {
  1193. for(i = 0;i < NumSends;i++)
  1194. WetGainHF[i] *= ConeHF;
  1195. }
  1196. }
  1197. /* Apply gain and frequency filters */
  1198. DryGain = clampf(DryGain, props->MinGain, props->MaxGain);
  1199. DryGain = minf(DryGain*props->Direct.Gain*Listener->Params.Gain, GAIN_MIX_MAX);
  1200. DryGainHF *= props->Direct.GainHF;
  1201. DryGainLF *= props->Direct.GainLF;
  1202. for(i = 0;i < NumSends;i++)
  1203. {
  1204. WetGain[i] = clampf(WetGain[i], props->MinGain, props->MaxGain);
  1205. WetGain[i] = minf(WetGain[i]*props->Send[i].Gain*Listener->Params.Gain, GAIN_MIX_MAX);
  1206. WetGainHF[i] *= props->Send[i].GainHF;
  1207. WetGainLF[i] *= props->Send[i].GainLF;
  1208. }
  1209. /* Initial source pitch */
  1210. Pitch = props->Pitch;
  1211. /* Calculate velocity-based doppler effect */
  1212. DopplerFactor = props->DopplerFactor * Listener->Params.DopplerFactor;
  1213. if(DopplerFactor > 0.0f)
  1214. {
  1215. const aluVector *lvelocity = &Listener->Params.Velocity;
  1216. const ALfloat SpeedOfSound = Listener->Params.SpeedOfSound;
  1217. ALfloat vss, vls;
  1218. vss = aluDotproduct(&Velocity, &SourceToListener) * DopplerFactor;
  1219. vls = aluDotproduct(lvelocity, &SourceToListener) * DopplerFactor;
  1220. if(!(vls < SpeedOfSound))
  1221. {
  1222. /* Listener moving away from the source at the speed of sound.
  1223. * Sound waves can't catch it.
  1224. */
  1225. Pitch = 0.0f;
  1226. }
  1227. else if(!(vss < SpeedOfSound))
  1228. {
  1229. /* Source moving toward the listener at the speed of sound. Sound
  1230. * waves bunch up to extreme frequencies.
  1231. */
  1232. Pitch = HUGE_VALF;
  1233. }
  1234. else
  1235. {
  1236. /* Source and listener movement is nominal. Calculate the proper
  1237. * doppler shift.
  1238. */
  1239. Pitch *= (SpeedOfSound-vls) / (SpeedOfSound-vss);
  1240. }
  1241. }
  1242. /* Adjust pitch based on the buffer and output frequencies, and calculate
  1243. * fixed-point stepping value.
  1244. */
  1245. Pitch *= (ALfloat)ALBuffer->Frequency/(ALfloat)Device->Frequency;
  1246. if(Pitch > (ALfloat)MAX_PITCH)
  1247. voice->Step = MAX_PITCH<<FRACTIONBITS;
  1248. else
  1249. voice->Step = maxi(fastf2i(Pitch*FRACTIONONE + 0.5f), 1);
  1250. BsincPrepare(voice->Step, &voice->ResampleState.bsinc);
  1251. voice->Resampler = SelectResampler(props->Resampler);
  1252. if(Distance > FLT_EPSILON)
  1253. {
  1254. dir[0] = -SourceToListener.v[0];
  1255. /* Clamp Y, in case rounding errors caused it to end up outside of
  1256. * -1...+1.
  1257. */
  1258. dir[1] = clampf(-SourceToListener.v[1], -1.0f, 1.0f);
  1259. dir[2] = -SourceToListener.v[2] * ZScale;
  1260. }
  1261. else
  1262. {
  1263. dir[0] = 0.0f;
  1264. dir[1] = 0.0f;
  1265. dir[2] = -1.0f;
  1266. }
  1267. if(props->Radius > Distance)
  1268. spread = F_TAU - Distance/props->Radius*F_PI;
  1269. else if(Distance > FLT_EPSILON)
  1270. spread = asinf(props->Radius / Distance) * 2.0f;
  1271. else
  1272. spread = 0.0f;
  1273. CalcPanningAndFilters(voice, Distance, dir, spread, DryGain, DryGainHF, DryGainLF, WetGain,
  1274. WetGainLF, WetGainHF, SendSlots, ALBuffer, props, Listener, Device);
  1275. }
  1276. static void CalcSourceParams(ALvoice *voice, ALCcontext *context, ALboolean force)
  1277. {
  1278. ALbufferlistitem *BufferListItem;
  1279. struct ALvoiceProps *props;
  1280. props = ATOMIC_EXCHANGE_PTR(&voice->Update, NULL, almemory_order_acq_rel);
  1281. if(!props && !force) return;
  1282. if(props)
  1283. {
  1284. memcpy(voice->Props, props,
  1285. FAM_SIZE(struct ALvoiceProps, Send, context->Device->NumAuxSends)
  1286. );
  1287. ATOMIC_REPLACE_HEAD(struct ALvoiceProps*, &voice->FreeList, props);
  1288. }
  1289. props = voice->Props;
  1290. BufferListItem = ATOMIC_LOAD(&voice->current_buffer, almemory_order_relaxed);
  1291. while(BufferListItem != NULL)
  1292. {
  1293. const ALbuffer *buffer;
  1294. if((buffer=BufferListItem->buffer) != NULL)
  1295. {
  1296. if(props->SpatializeMode == SpatializeOn ||
  1297. (props->SpatializeMode == SpatializeAuto && buffer->FmtChannels == FmtMono))
  1298. CalcAttnSourceParams(voice, props, buffer, context);
  1299. else
  1300. CalcNonAttnSourceParams(voice, props, buffer, context);
  1301. break;
  1302. }
  1303. BufferListItem = ATOMIC_LOAD(&BufferListItem->next, almemory_order_acquire);
  1304. }
  1305. }
  1306. static void UpdateContextSources(ALCcontext *ctx, const struct ALeffectslotArray *slots)
  1307. {
  1308. ALvoice **voice, **voice_end;
  1309. ALsource *source;
  1310. ALsizei i;
  1311. IncrementRef(&ctx->UpdateCount);
  1312. if(!ATOMIC_LOAD(&ctx->HoldUpdates, almemory_order_acquire))
  1313. {
  1314. ALboolean force = CalcListenerParams(ctx);
  1315. for(i = 0;i < slots->count;i++)
  1316. force |= CalcEffectSlotParams(slots->slot[i], ctx->Device);
  1317. voice = ctx->Voices;
  1318. voice_end = voice + ctx->VoiceCount;
  1319. for(;voice != voice_end;++voice)
  1320. {
  1321. source = ATOMIC_LOAD(&(*voice)->Source, almemory_order_acquire);
  1322. if(source) CalcSourceParams(*voice, ctx, force);
  1323. }
  1324. }
  1325. IncrementRef(&ctx->UpdateCount);
  1326. }
  1327. static void ApplyDistanceComp(ALfloatBUFFERSIZE *restrict Samples, DistanceComp *distcomp,
  1328. ALfloat *restrict Values, ALsizei SamplesToDo, ALsizei numchans)
  1329. {
  1330. ALsizei i, c;
  1331. Values = ASSUME_ALIGNED(Values, 16);
  1332. for(c = 0;c < numchans;c++)
  1333. {
  1334. ALfloat *restrict inout = ASSUME_ALIGNED(Samples[c], 16);
  1335. const ALfloat gain = distcomp[c].Gain;
  1336. const ALsizei base = distcomp[c].Length;
  1337. ALfloat *restrict distbuf = ASSUME_ALIGNED(distcomp[c].Buffer, 16);
  1338. if(base == 0)
  1339. {
  1340. if(gain < 1.0f)
  1341. {
  1342. for(i = 0;i < SamplesToDo;i++)
  1343. inout[i] *= gain;
  1344. }
  1345. continue;
  1346. }
  1347. if(SamplesToDo >= base)
  1348. {
  1349. for(i = 0;i < base;i++)
  1350. Values[i] = distbuf[i];
  1351. for(;i < SamplesToDo;i++)
  1352. Values[i] = inout[i-base];
  1353. memcpy(distbuf, &inout[SamplesToDo-base], base*sizeof(ALfloat));
  1354. }
  1355. else
  1356. {
  1357. for(i = 0;i < SamplesToDo;i++)
  1358. Values[i] = distbuf[i];
  1359. memmove(distbuf, distbuf+SamplesToDo, (base-SamplesToDo)*sizeof(ALfloat));
  1360. memcpy(distbuf+base-SamplesToDo, inout, SamplesToDo*sizeof(ALfloat));
  1361. }
  1362. for(i = 0;i < SamplesToDo;i++)
  1363. inout[i] = Values[i]*gain;
  1364. }
  1365. }
  1366. static void ApplyDither(ALfloatBUFFERSIZE *restrict Samples, ALuint *dither_seed,
  1367. const ALfloat quant_scale, const ALsizei SamplesToDo,
  1368. const ALsizei numchans)
  1369. {
  1370. const ALfloat invscale = 1.0f / quant_scale;
  1371. ALuint seed = *dither_seed;
  1372. ALsizei c, i;
  1373. /* Dithering. Step 1, generate whitenoise (uniform distribution of random
  1374. * values between -1 and +1). Step 2 is to add the noise to the samples,
  1375. * before rounding and after scaling up to the desired quantization depth.
  1376. */
  1377. for(c = 0;c < numchans;c++)
  1378. {
  1379. ALfloat *restrict samples = Samples[c];
  1380. for(i = 0;i < SamplesToDo;i++)
  1381. {
  1382. ALfloat val = samples[i] * quant_scale;
  1383. ALuint rng0 = dither_rng(&seed);
  1384. ALuint rng1 = dither_rng(&seed);
  1385. val += (ALfloat)(rng0*(1.0/UINT_MAX) - rng1*(1.0/UINT_MAX));
  1386. samples[i] = roundf(val) * invscale;
  1387. }
  1388. }
  1389. *dither_seed = seed;
  1390. }
  1391. static inline ALfloat Conv_ALfloat(ALfloat val)
  1392. { return val; }
  1393. static inline ALint Conv_ALint(ALfloat val)
  1394. {
  1395. /* Floats only have a 24-bit mantissa, so [-16777216, +16777216] is the max
  1396. * integer range normalized floats can be safely converted to (a bit of the
  1397. * exponent helps out, effectively giving 25 bits).
  1398. */
  1399. return fastf2i(clampf(val*16777216.0f, -16777216.0f, 16777215.0f))<<7;
  1400. }
  1401. static inline ALshort Conv_ALshort(ALfloat val)
  1402. { return fastf2i(clampf(val*32768.0f, -32768.0f, 32767.0f)); }
  1403. static inline ALbyte Conv_ALbyte(ALfloat val)
  1404. { return fastf2i(clampf(val*128.0f, -128.0f, 127.0f)); }
  1405. /* Define unsigned output variations. */
  1406. #define DECL_TEMPLATE(T, func, O) \
  1407. static inline T Conv_##T(ALfloat val) { return func(val)+O; }
  1408. DECL_TEMPLATE(ALubyte, Conv_ALbyte, 128)
  1409. DECL_TEMPLATE(ALushort, Conv_ALshort, 32768)
  1410. DECL_TEMPLATE(ALuint, Conv_ALint, 2147483648u)
  1411. #undef DECL_TEMPLATE
  1412. #define DECL_TEMPLATE(T, A) \
  1413. static void Write##A(const ALfloatBUFFERSIZE *InBuffer, ALvoid *OutBuffer, \
  1414. ALsizei Offset, ALsizei SamplesToDo, ALsizei numchans) \
  1415. { \
  1416. ALsizei i, j; \
  1417. for(j = 0;j < numchans;j++) \
  1418. { \
  1419. const ALfloat *restrict in = ASSUME_ALIGNED(InBuffer[j], 16); \
  1420. T *restrict out = (T*)OutBuffer + Offset*numchans + j; \
  1421. \
  1422. for(i = 0;i < SamplesToDo;i++) \
  1423. out[i*numchans] = Conv_##T(in[i]); \
  1424. } \
  1425. }
  1426. DECL_TEMPLATE(ALfloat, F32)
  1427. DECL_TEMPLATE(ALuint, UI32)
  1428. DECL_TEMPLATE(ALint, I32)
  1429. DECL_TEMPLATE(ALushort, UI16)
  1430. DECL_TEMPLATE(ALshort, I16)
  1431. DECL_TEMPLATE(ALubyte, UI8)
  1432. DECL_TEMPLATE(ALbyte, I8)
  1433. #undef DECL_TEMPLATE
  1434. void aluMixData(ALCdevice *device, ALvoid *OutBuffer, ALsizei NumSamples)
  1435. {
  1436. ALsizei SamplesToDo;
  1437. ALsizei SamplesDone;
  1438. ALCcontext *ctx;
  1439. ALsizei i, c;
  1440. START_MIXER_MODE();
  1441. for(SamplesDone = 0;SamplesDone < NumSamples;)
  1442. {
  1443. SamplesToDo = mini(NumSamples-SamplesDone, BUFFERSIZE);
  1444. for(c = 0;c < device->Dry.NumChannels;c++)
  1445. memset(device->Dry.Buffer[c], 0, SamplesToDo*sizeof(ALfloat));
  1446. if(device->Dry.Buffer != device->FOAOut.Buffer)
  1447. for(c = 0;c < device->FOAOut.NumChannels;c++)
  1448. memset(device->FOAOut.Buffer[c], 0, SamplesToDo*sizeof(ALfloat));
  1449. if(device->Dry.Buffer != device->RealOut.Buffer)
  1450. for(c = 0;c < device->RealOut.NumChannels;c++)
  1451. memset(device->RealOut.Buffer[c], 0, SamplesToDo*sizeof(ALfloat));
  1452. IncrementRef(&device->MixCount);
  1453. ctx = ATOMIC_LOAD(&device->ContextList, almemory_order_acquire);
  1454. while(ctx)
  1455. {
  1456. const struct ALeffectslotArray *auxslots;
  1457. auxslots = ATOMIC_LOAD(&ctx->ActiveAuxSlots, almemory_order_acquire);
  1458. UpdateContextSources(ctx, auxslots);
  1459. for(i = 0;i < auxslots->count;i++)
  1460. {
  1461. ALeffectslot *slot = auxslots->slot[i];
  1462. for(c = 0;c < slot->NumChannels;c++)
  1463. memset(slot->WetBuffer[c], 0, SamplesToDo*sizeof(ALfloat));
  1464. }
  1465. /* source processing */
  1466. for(i = 0;i < ctx->VoiceCount;i++)
  1467. {
  1468. ALvoice *voice = ctx->Voices[i];
  1469. ALsource *source = ATOMIC_LOAD(&voice->Source, almemory_order_acquire);
  1470. if(source && ATOMIC_LOAD(&voice->Playing, almemory_order_relaxed) &&
  1471. voice->Step > 0)
  1472. {
  1473. if(!MixSource(voice, source, device, SamplesToDo))
  1474. {
  1475. ATOMIC_STORE(&voice->Source, NULL, almemory_order_relaxed);
  1476. ATOMIC_STORE(&voice->Playing, false, almemory_order_release);
  1477. }
  1478. }
  1479. }
  1480. /* effect slot processing */
  1481. for(i = 0;i < auxslots->count;i++)
  1482. {
  1483. const ALeffectslot *slot = auxslots->slot[i];
  1484. ALeffectState *state = slot->Params.EffectState;
  1485. V(state,process)(SamplesToDo, slot->WetBuffer, state->OutBuffer,
  1486. state->OutChannels);
  1487. }
  1488. ctx = ctx->next;
  1489. }
  1490. /* Increment the clock time. Every second's worth of samples is
  1491. * converted and added to clock base so that large sample counts don't
  1492. * overflow during conversion. This also guarantees an exact, stable
  1493. * conversion. */
  1494. device->SamplesDone += SamplesToDo;
  1495. device->ClockBase += (device->SamplesDone/device->Frequency) * DEVICE_CLOCK_RES;
  1496. device->SamplesDone %= device->Frequency;
  1497. IncrementRef(&device->MixCount);
  1498. if(device->HrtfHandle)
  1499. {
  1500. HrtfDirectMixerFunc HrtfMix;
  1501. DirectHrtfState *state;
  1502. int lidx, ridx;
  1503. if(device->AmbiUp)
  1504. ambiup_process(device->AmbiUp,
  1505. device->Dry.Buffer, device->Dry.NumChannels,
  1506. SAFE_CONST(ALfloatBUFFERSIZE*,device->FOAOut.Buffer), SamplesToDo
  1507. );
  1508. lidx = GetChannelIdxByName(device->RealOut, FrontLeft);
  1509. ridx = GetChannelIdxByName(device->RealOut, FrontRight);
  1510. assert(lidx != -1 && ridx != -1);
  1511. HrtfMix = SelectHrtfMixer();
  1512. state = device->Hrtf;
  1513. for(c = 0;c < device->Dry.NumChannels;c++)
  1514. {
  1515. HrtfMix(device->RealOut.Buffer[lidx], device->RealOut.Buffer[ridx],
  1516. device->Dry.Buffer[c], state->Offset, state->IrSize,
  1517. SAFE_CONST(ALfloat2*,state->Chan[c].Coeffs),
  1518. state->Chan[c].Values, SamplesToDo
  1519. );
  1520. }
  1521. state->Offset += SamplesToDo;
  1522. }
  1523. else if(device->AmbiDecoder)
  1524. {
  1525. if(device->Dry.Buffer != device->FOAOut.Buffer)
  1526. bformatdec_upSample(device->AmbiDecoder,
  1527. device->Dry.Buffer, SAFE_CONST(ALfloatBUFFERSIZE*,device->FOAOut.Buffer),
  1528. device->FOAOut.NumChannels, SamplesToDo
  1529. );
  1530. bformatdec_process(device->AmbiDecoder,
  1531. device->RealOut.Buffer, device->RealOut.NumChannels,
  1532. SAFE_CONST(ALfloatBUFFERSIZE*,device->Dry.Buffer), SamplesToDo
  1533. );
  1534. }
  1535. else if(device->AmbiUp)
  1536. {
  1537. ambiup_process(device->AmbiUp,
  1538. device->RealOut.Buffer, device->RealOut.NumChannels,
  1539. SAFE_CONST(ALfloatBUFFERSIZE*,device->FOAOut.Buffer), SamplesToDo
  1540. );
  1541. }
  1542. else if(device->Uhj_Encoder)
  1543. {
  1544. int lidx = GetChannelIdxByName(device->RealOut, FrontLeft);
  1545. int ridx = GetChannelIdxByName(device->RealOut, FrontRight);
  1546. if(lidx != -1 && ridx != -1)
  1547. {
  1548. /* Encode to stereo-compatible 2-channel UHJ output. */
  1549. EncodeUhj2(device->Uhj_Encoder,
  1550. device->RealOut.Buffer[lidx], device->RealOut.Buffer[ridx],
  1551. device->Dry.Buffer, SamplesToDo
  1552. );
  1553. }
  1554. }
  1555. else if(device->Bs2b)
  1556. {
  1557. int lidx = GetChannelIdxByName(device->RealOut, FrontLeft);
  1558. int ridx = GetChannelIdxByName(device->RealOut, FrontRight);
  1559. if(lidx != -1 && ridx != -1)
  1560. {
  1561. /* Apply binaural/crossfeed filter */
  1562. bs2b_cross_feed(device->Bs2b, device->RealOut.Buffer[lidx],
  1563. device->RealOut.Buffer[ridx], SamplesToDo);
  1564. }
  1565. }
  1566. if(OutBuffer)
  1567. {
  1568. ALfloat (*Buffer)[BUFFERSIZE] = device->RealOut.Buffer;
  1569. ALsizei Channels = device->RealOut.NumChannels;
  1570. /* Use NFCtrlData for temp value storage. */
  1571. ApplyDistanceComp(Buffer, device->ChannelDelay, device->NFCtrlData,
  1572. SamplesToDo, Channels);
  1573. if(device->Limiter)
  1574. ApplyCompression(device->Limiter, Channels, SamplesToDo, Buffer);
  1575. if(device->DitherDepth > 0.0f)
  1576. ApplyDither(Buffer, &device->DitherSeed, device->DitherDepth, SamplesToDo,
  1577. Channels);
  1578. switch(device->FmtType)
  1579. {
  1580. case DevFmtByte:
  1581. WriteI8(Buffer, OutBuffer, SamplesDone, SamplesToDo, Channels);
  1582. break;
  1583. case DevFmtUByte:
  1584. WriteUI8(Buffer, OutBuffer, SamplesDone, SamplesToDo, Channels);
  1585. break;
  1586. case DevFmtShort:
  1587. WriteI16(Buffer, OutBuffer, SamplesDone, SamplesToDo, Channels);
  1588. break;
  1589. case DevFmtUShort:
  1590. WriteUI16(Buffer, OutBuffer, SamplesDone, SamplesToDo, Channels);
  1591. break;
  1592. case DevFmtInt:
  1593. WriteI32(Buffer, OutBuffer, SamplesDone, SamplesToDo, Channels);
  1594. break;
  1595. case DevFmtUInt:
  1596. WriteUI32(Buffer, OutBuffer, SamplesDone, SamplesToDo, Channels);
  1597. break;
  1598. case DevFmtFloat:
  1599. WriteF32(Buffer, OutBuffer, SamplesDone, SamplesToDo, Channels);
  1600. break;
  1601. }
  1602. }
  1603. SamplesDone += SamplesToDo;
  1604. }
  1605. END_MIXER_MODE();
  1606. }
  1607. void aluHandleDisconnect(ALCdevice *device)
  1608. {
  1609. ALCcontext *ctx;
  1610. device->Connected = ALC_FALSE;
  1611. ctx = ATOMIC_LOAD_SEQ(&device->ContextList);
  1612. while(ctx)
  1613. {
  1614. ALsizei i;
  1615. for(i = 0;i < ctx->VoiceCount;i++)
  1616. {
  1617. ALvoice *voice = ctx->Voices[i];
  1618. ALsource *source;
  1619. source = ATOMIC_EXCHANGE_PTR(&voice->Source, NULL, almemory_order_acq_rel);
  1620. ATOMIC_STORE(&voice->Playing, false, almemory_order_release);
  1621. if(source)
  1622. {
  1623. ALenum playing = AL_PLAYING;
  1624. (void)(ATOMIC_COMPARE_EXCHANGE_STRONG_SEQ(&source->state, &playing, AL_STOPPED));
  1625. }
  1626. }
  1627. ctx->VoiceCount = 0;
  1628. ctx = ctx->next;
  1629. }
  1630. }