panning.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  1. /**
  2. * OpenAL cross platform audio library
  3. * Copyright (C) 1999-2010 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 <algorithm>
  22. #include <array>
  23. #include <chrono>
  24. #include <cmath>
  25. #include <cstdio>
  26. #include <cstring>
  27. #include <functional>
  28. #include <iterator>
  29. #include <memory>
  30. #include <new>
  31. #include <numeric>
  32. #include <string>
  33. #include "AL/al.h"
  34. #include "AL/alc.h"
  35. #include "AL/alext.h"
  36. #include "al/auxeffectslot.h"
  37. #include "alcmain.h"
  38. #include "alconfig.h"
  39. #include "alcontext.h"
  40. #include "almalloc.h"
  41. #include "alnumeric.h"
  42. #include "aloptional.h"
  43. #include "alspan.h"
  44. #include "alstring.h"
  45. #include "alu.h"
  46. #include "bformatdec.h"
  47. #include "core/ambdec.h"
  48. #include "core/ambidefs.h"
  49. #include "core/bs2b.h"
  50. #include "core/devformat.h"
  51. #include "core/logging.h"
  52. #include "core/uhjfilter.h"
  53. #include "front_stablizer.h"
  54. #include "hrtf.h"
  55. #include "math_defs.h"
  56. #include "opthelpers.h"
  57. namespace {
  58. using namespace std::placeholders;
  59. using std::chrono::seconds;
  60. using std::chrono::nanoseconds;
  61. inline const char *GetLabelFromChannel(Channel channel)
  62. {
  63. switch(channel)
  64. {
  65. case FrontLeft: return "front-left";
  66. case FrontRight: return "front-right";
  67. case FrontCenter: return "front-center";
  68. case LFE: return "lfe";
  69. case BackLeft: return "back-left";
  70. case BackRight: return "back-right";
  71. case BackCenter: return "back-center";
  72. case SideLeft: return "side-left";
  73. case SideRight: return "side-right";
  74. case TopFrontLeft: return "top-front-left";
  75. case TopFrontCenter: return "top-front-center";
  76. case TopFrontRight: return "top-front-right";
  77. case TopCenter: return "top-center";
  78. case TopBackLeft: return "top-back-left";
  79. case TopBackCenter: return "top-back-center";
  80. case TopBackRight: return "top-back-right";
  81. case MaxChannels: break;
  82. }
  83. return "(unknown)";
  84. }
  85. std::unique_ptr<FrontStablizer> CreateStablizer(const size_t outchans, const uint srate)
  86. {
  87. auto stablizer = FrontStablizer::Create(outchans);
  88. for(auto &buf : stablizer->DelayBuf)
  89. std::fill(buf.begin(), buf.end(), 0.0f);
  90. /* Initialize band-splitting filter for the mid signal, with a crossover at
  91. * 5khz (could be higher).
  92. */
  93. stablizer->MidFilter.init(5000.0f / static_cast<float>(srate));
  94. return stablizer;
  95. }
  96. void AllocChannels(ALCdevice *device, const size_t main_chans, const size_t real_chans)
  97. {
  98. TRACE("Channel config, Main: %zu, Real: %zu\n", main_chans, real_chans);
  99. /* Allocate extra channels for any post-filter output. */
  100. const size_t num_chans{main_chans + real_chans};
  101. TRACE("Allocating %zu channels, %zu bytes\n", num_chans,
  102. num_chans*sizeof(device->MixBuffer[0]));
  103. device->MixBuffer.resize(num_chans);
  104. al::span<FloatBufferLine> buffer{device->MixBuffer};
  105. device->Dry.Buffer = buffer.first(main_chans);
  106. buffer = buffer.subspan(main_chans);
  107. if(real_chans != 0)
  108. {
  109. device->RealOut.Buffer = buffer.first(real_chans);
  110. buffer = buffer.subspan(real_chans);
  111. }
  112. else
  113. device->RealOut.Buffer = device->Dry.Buffer;
  114. }
  115. struct ChannelMap {
  116. Channel ChanName;
  117. float Config[MaxAmbi2DChannels];
  118. };
  119. bool MakeSpeakerMap(ALCdevice *device, const AmbDecConf *conf, uint (&speakermap)[MAX_OUTPUT_CHANNELS])
  120. {
  121. auto map_spkr = [device](const AmbDecConf::SpeakerConf &speaker) -> uint
  122. {
  123. /* NOTE: AmbDec does not define any standard speaker names, however
  124. * for this to work we have to by able to find the output channel
  125. * the speaker definition corresponds to. Therefore, OpenAL Soft
  126. * requires these channel labels to be recognized:
  127. *
  128. * LF = Front left
  129. * RF = Front right
  130. * LS = Side left
  131. * RS = Side right
  132. * LB = Back left
  133. * RB = Back right
  134. * CE = Front center
  135. * CB = Back center
  136. *
  137. * Additionally, surround51 will acknowledge back speakers for side
  138. * channels, and surround51rear will acknowledge side speakers for
  139. * back channels, to avoid issues with an ambdec expecting 5.1 to
  140. * use the side channels when the device is configured for back,
  141. * and vice-versa.
  142. */
  143. Channel ch{};
  144. if(speaker.Name == "LF")
  145. ch = FrontLeft;
  146. else if(speaker.Name == "RF")
  147. ch = FrontRight;
  148. else if(speaker.Name == "CE")
  149. ch = FrontCenter;
  150. else if(speaker.Name == "LS")
  151. {
  152. if(device->FmtChans == DevFmtX51Rear)
  153. ch = BackLeft;
  154. else
  155. ch = SideLeft;
  156. }
  157. else if(speaker.Name == "RS")
  158. {
  159. if(device->FmtChans == DevFmtX51Rear)
  160. ch = BackRight;
  161. else
  162. ch = SideRight;
  163. }
  164. else if(speaker.Name == "LB")
  165. {
  166. if(device->FmtChans == DevFmtX51)
  167. ch = SideLeft;
  168. else
  169. ch = BackLeft;
  170. }
  171. else if(speaker.Name == "RB")
  172. {
  173. if(device->FmtChans == DevFmtX51)
  174. ch = SideRight;
  175. else
  176. ch = BackRight;
  177. }
  178. else if(speaker.Name == "CB")
  179. ch = BackCenter;
  180. else
  181. {
  182. ERR("AmbDec speaker label \"%s\" not recognized\n", speaker.Name.c_str());
  183. return INVALID_CHANNEL_INDEX;
  184. }
  185. const uint chidx{GetChannelIdxByName(device->RealOut, ch)};
  186. if(chidx == INVALID_CHANNEL_INDEX)
  187. ERR("Failed to lookup AmbDec speaker label %s\n", speaker.Name.c_str());
  188. return chidx;
  189. };
  190. std::transform(conf->Speakers.get(), conf->Speakers.get()+conf->NumSpeakers,
  191. std::begin(speakermap), map_spkr);
  192. /* Return success if no invalid entries are found. */
  193. auto spkrmap_end = std::begin(speakermap) + conf->NumSpeakers;
  194. return std::find(std::begin(speakermap), spkrmap_end, INVALID_CHANNEL_INDEX) == spkrmap_end;
  195. }
  196. void InitNearFieldCtrl(ALCdevice *device, float ctrl_dist, uint order, bool is3d)
  197. {
  198. static const uint chans_per_order2d[MaxAmbiOrder+1]{ 1, 2, 2, 2 };
  199. static const uint chans_per_order3d[MaxAmbiOrder+1]{ 1, 3, 5, 7 };
  200. /* NFC is only used when AvgSpeakerDist is greater than 0. */
  201. const char *devname{device->DeviceName.c_str()};
  202. if(!GetConfigValueBool(devname, "decoder", "nfc", 0) || !(ctrl_dist > 0.0f))
  203. return;
  204. device->AvgSpeakerDist = clampf(ctrl_dist, 0.1f, 10.0f);
  205. TRACE("Using near-field reference distance: %.2f meters\n", device->AvgSpeakerDist);
  206. auto iter = std::copy_n(is3d ? chans_per_order3d : chans_per_order2d, order+1u,
  207. std::begin(device->NumChannelsPerOrder));
  208. std::fill(iter, std::end(device->NumChannelsPerOrder), 0u);
  209. }
  210. void InitDistanceComp(ALCdevice *device, const AmbDecConf *conf,
  211. const uint (&speakermap)[MAX_OUTPUT_CHANNELS])
  212. {
  213. auto get_max = std::bind(maxf, _1,
  214. std::bind(std::mem_fn(&AmbDecConf::SpeakerConf::Distance), _2));
  215. const float maxdist{std::accumulate(conf->Speakers.get(),
  216. conf->Speakers.get()+conf->NumSpeakers, 0.0f, get_max)};
  217. const char *devname{device->DeviceName.c_str()};
  218. if(!GetConfigValueBool(devname, "decoder", "distance-comp", 1) || !(maxdist > 0.0f))
  219. return;
  220. const auto distSampleScale = static_cast<float>(device->Frequency) / SpeedOfSoundMetersPerSec;
  221. std::vector<DistanceComp::ChanData> ChanDelay;
  222. size_t total{0u};
  223. ChanDelay.reserve(conf->NumSpeakers + 1);
  224. for(size_t i{0u};i < conf->NumSpeakers;i++)
  225. {
  226. const AmbDecConf::SpeakerConf &speaker = conf->Speakers[i];
  227. const uint chan{speakermap[i]};
  228. /* Distance compensation only delays in steps of the sample rate. This
  229. * is a bit less accurate since the delay time falls to the nearest
  230. * sample time, but it's far simpler as it doesn't have to deal with
  231. * phase offsets. This means at 48khz, for instance, the distance delay
  232. * will be in steps of about 7 millimeters.
  233. */
  234. float delay{std::floor((maxdist - speaker.Distance)*distSampleScale + 0.5f)};
  235. if(delay > float{MAX_DELAY_LENGTH-1})
  236. {
  237. ERR("Delay for speaker \"%s\" exceeds buffer length (%f > %d)\n",
  238. speaker.Name.c_str(), delay, MAX_DELAY_LENGTH-1);
  239. delay = float{MAX_DELAY_LENGTH-1};
  240. }
  241. ChanDelay.resize(maxz(ChanDelay.size(), chan+1));
  242. ChanDelay[chan].Length = static_cast<uint>(delay);
  243. ChanDelay[chan].Gain = speaker.Distance / maxdist;
  244. TRACE("Channel %u \"%s\" distance compensation: %u samples, %f gain\n", chan,
  245. speaker.Name.c_str(), ChanDelay[chan].Length, ChanDelay[chan].Gain);
  246. /* Round up to the next 4th sample, so each channel buffer starts
  247. * 16-byte aligned.
  248. */
  249. total += RoundUp(ChanDelay[chan].Length, 4);
  250. }
  251. if(total > 0)
  252. {
  253. auto chandelays = DistanceComp::Create(total);
  254. std::copy(ChanDelay.cbegin(), ChanDelay.cend(), chandelays->mChannels.begin());
  255. chandelays->mChannels[0].Buffer = chandelays->mSamples.data();
  256. auto set_bufptr = [](const DistanceComp::ChanData &last, const DistanceComp::ChanData &cur)
  257. -> DistanceComp::ChanData
  258. {
  259. DistanceComp::ChanData ret{cur};
  260. ret.Buffer = last.Buffer + RoundUp(last.Length, 4);
  261. return ret;
  262. };
  263. std::partial_sum(ChanDelay.begin(), ChanDelay.end(), ChanDelay.begin(), set_bufptr);
  264. device->ChannelDelays = std::move(chandelays);
  265. }
  266. }
  267. inline auto& GetAmbiScales(DevAmbiScaling scaletype) noexcept
  268. {
  269. if(scaletype == DevAmbiScaling::FuMa) return AmbiScale::FromFuMa();
  270. if(scaletype == DevAmbiScaling::SN3D) return AmbiScale::FromSN3D();
  271. return AmbiScale::FromN3D();
  272. }
  273. inline auto& GetAmbiLayout(DevAmbiLayout layouttype) noexcept
  274. {
  275. if(layouttype == DevAmbiLayout::FuMa) return AmbiIndex::FromFuMa();
  276. return AmbiIndex::FromACN();
  277. }
  278. using ChannelCoeffs = std::array<float,MaxAmbi2DChannels>;
  279. enum DecoderMode : bool {
  280. SingleBand = false,
  281. DualBand = true
  282. };
  283. template<DecoderMode Mode, size_t N>
  284. struct DecoderConfig;
  285. template<size_t N>
  286. struct DecoderConfig<SingleBand, N> {
  287. uint mOrder;
  288. std::array<Channel,N> mChannels;
  289. std::array<float,MaxAmbiOrder+1> mOrderGain;
  290. std::array<ChannelCoeffs,N> mCoeffs;
  291. };
  292. template<size_t N>
  293. struct DecoderConfig<DualBand, N> {
  294. uint mOrder;
  295. std::array<Channel,N> mChannels;
  296. std::array<float,MaxAmbiOrder+1> mOrderGain;
  297. std::array<ChannelCoeffs,N> mCoeffs;
  298. std::array<float,MaxAmbiOrder+1> mOrderGainLF;
  299. std::array<ChannelCoeffs,N> mCoeffsLF;
  300. };
  301. template<>
  302. struct DecoderConfig<DualBand, 0> {
  303. uint mOrder;
  304. al::span<const Channel> mChannels;
  305. al::span<const float> mOrderGain;
  306. al::span<const ChannelCoeffs> mCoeffs;
  307. al::span<const float> mOrderGainLF;
  308. al::span<const ChannelCoeffs> mCoeffsLF;
  309. template<size_t N>
  310. DecoderConfig& operator=(const DecoderConfig<SingleBand,N> &rhs) noexcept
  311. {
  312. mOrder = rhs.mOrder;
  313. mChannels = rhs.mChannels;
  314. mOrderGain = rhs.mOrderGain;
  315. mCoeffs = rhs.mCoeffs;
  316. mOrderGainLF = {};
  317. mCoeffsLF = {};
  318. return *this;
  319. }
  320. template<size_t N>
  321. DecoderConfig& operator=(const DecoderConfig<DualBand,N> &rhs) noexcept
  322. {
  323. mOrder = rhs.mOrder;
  324. mChannels = rhs.mChannels;
  325. mOrderGain = rhs.mOrderGain;
  326. mCoeffs = rhs.mCoeffs;
  327. mOrderGainLF = rhs.mOrderGainLF;
  328. mCoeffsLF = rhs.mCoeffsLF;
  329. return *this;
  330. }
  331. };
  332. using DecoderView = DecoderConfig<DualBand, 0>;
  333. constexpr DecoderConfig<SingleBand, 1> MonoConfig{
  334. 0, {{FrontCenter}},
  335. {{1.0f}},
  336. {{ {{1.0f}} }}
  337. };
  338. constexpr DecoderConfig<SingleBand, 2> StereoConfig{
  339. 1, {{FrontLeft, FrontRight}},
  340. {{1.0f, 1.0f}},
  341. {{
  342. {{5.00000000e-1f, 2.88675135e-1f, 5.52305643e-2f}},
  343. {{5.00000000e-1f, -2.88675135e-1f, 5.52305643e-2f}},
  344. }}
  345. };
  346. constexpr DecoderConfig<DualBand, 4> QuadConfig{
  347. 2, {{BackLeft, FrontLeft, FrontRight, BackRight}},
  348. /*HF*/{{1.15470054e+0f, 1.00000000e+0f, 5.77350269e-1f}},
  349. {{
  350. {{2.50000000e-1f, 2.04124145e-1f, -2.04124145e-1f, -1.29099445e-1f, 0.00000000e+0f}},
  351. {{2.50000000e-1f, 2.04124145e-1f, 2.04124145e-1f, 1.29099445e-1f, 0.00000000e+0f}},
  352. {{2.50000000e-1f, -2.04124145e-1f, 2.04124145e-1f, -1.29099445e-1f, 0.00000000e+0f}},
  353. {{2.50000000e-1f, -2.04124145e-1f, -2.04124145e-1f, 1.29099445e-1f, 0.00000000e+0f}},
  354. }},
  355. /*LF*/{{1.00000000e+0f, 1.00000000e+0f, 1.00000000e+0f}},
  356. {{
  357. {{2.50000000e-1f, 2.04124145e-1f, -2.04124145e-1f, -1.29099445e-1f, 0.00000000e+0f}},
  358. {{2.50000000e-1f, 2.04124145e-1f, 2.04124145e-1f, 1.29099445e-1f, 0.00000000e+0f}},
  359. {{2.50000000e-1f, -2.04124145e-1f, 2.04124145e-1f, -1.29099445e-1f, 0.00000000e+0f}},
  360. {{2.50000000e-1f, -2.04124145e-1f, -2.04124145e-1f, 1.29099445e-1f, 0.00000000e+0f}},
  361. }}
  362. };
  363. constexpr DecoderConfig<SingleBand, 4> X51Config{
  364. 2, {{SideLeft, FrontLeft, FrontRight, SideRight}},
  365. {{1.0f, 1.0f, 1.0f}},
  366. {{
  367. {{3.33000782e-1f, 1.89084803e-1f, -2.00042375e-1f, -2.12307769e-2f, -1.14579885e-2f}},
  368. {{1.88542860e-1f, 1.27709292e-1f, 1.66295695e-1f, 7.30571517e-2f, 2.10901184e-2f}},
  369. {{1.88542860e-1f, -1.27709292e-1f, 1.66295695e-1f, -7.30571517e-2f, 2.10901184e-2f}},
  370. {{3.33000782e-1f, -1.89084803e-1f, -2.00042375e-1f, 2.12307769e-2f, -1.14579885e-2f}},
  371. }}
  372. };
  373. constexpr DecoderConfig<SingleBand, 4> X51RearConfig{
  374. 2, {{BackLeft, FrontLeft, FrontRight, BackRight}},
  375. {{1.0f, 1.0f, 1.0f}},
  376. {{
  377. {{3.33000782e-1f, 1.89084803e-1f, -2.00042375e-1f, -2.12307769e-2f, -1.14579885e-2f}},
  378. {{1.88542860e-1f, 1.27709292e-1f, 1.66295695e-1f, 7.30571517e-2f, 2.10901184e-2f}},
  379. {{1.88542860e-1f, -1.27709292e-1f, 1.66295695e-1f, -7.30571517e-2f, 2.10901184e-2f}},
  380. {{3.33000782e-1f, -1.89084803e-1f, -2.00042375e-1f, 2.12307769e-2f, -1.14579885e-2f}},
  381. }}
  382. };
  383. constexpr DecoderConfig<SingleBand, 5> X61Config{
  384. 2, {{SideLeft, FrontLeft, FrontRight, SideRight, BackCenter}},
  385. {{1.0f, 1.0f, 1.0f}},
  386. {{
  387. {{2.04460341e-1f, 2.17177926e-1f, -4.39996780e-2f, -2.60790269e-2f, -6.87239792e-2f}},
  388. {{1.58923161e-1f, 9.21772680e-2f, 1.59658796e-1f, 6.66278083e-2f, 3.84686854e-2f}},
  389. {{1.58923161e-1f, -9.21772680e-2f, 1.59658796e-1f, -6.66278083e-2f, 3.84686854e-2f}},
  390. {{2.04460341e-1f, -2.17177926e-1f, -4.39996780e-2f, 2.60790269e-2f, -6.87239792e-2f}},
  391. {{2.50001688e-1f, 0.00000000e+0f, -2.50000094e-1f, 0.00000000e+0f, 6.05133395e-2f}},
  392. }}
  393. };
  394. constexpr DecoderConfig<DualBand, 6> X71Config{
  395. 3, {{BackLeft, SideLeft, FrontLeft, FrontRight, SideRight, BackRight}},
  396. /*HF*/{{1.22474487e+0f, 1.13151672e+0f, 8.66025404e-1f, 4.68689571e-1f}},
  397. {{
  398. {{1.66666667e-1f, 9.62250449e-2f, -1.66666667e-1f, -1.49071198e-1f, 8.60662966e-2f, 7.96819073e-2f, 0.00000000e+0f}},
  399. {{1.66666667e-1f, 1.92450090e-1f, 0.00000000e+0f, 0.00000000e+0f, -1.72132593e-1f, -7.96819073e-2f, 0.00000000e+0f}},
  400. {{1.66666667e-1f, 9.62250449e-2f, 1.66666667e-1f, 1.49071198e-1f, 8.60662966e-2f, 7.96819073e-2f, 0.00000000e+0f}},
  401. {{1.66666667e-1f, -9.62250449e-2f, 1.66666667e-1f, -1.49071198e-1f, 8.60662966e-2f, -7.96819073e-2f, 0.00000000e+0f}},
  402. {{1.66666667e-1f, -1.92450090e-1f, 0.00000000e+0f, 0.00000000e+0f, -1.72132593e-1f, 7.96819073e-2f, 0.00000000e+0f}},
  403. {{1.66666667e-1f, -9.62250449e-2f, -1.66666667e-1f, 1.49071198e-1f, 8.60662966e-2f, -7.96819073e-2f, 0.00000000e+0f}},
  404. }},
  405. /*LF*/{{1.00000000e+0f, 1.00000000e+0f, 1.00000000e+0f, 1.00000000e+0f}},
  406. {{
  407. {{1.66666667e-1f, 9.62250449e-2f, -1.66666667e-1f, -1.49071198e-1f, 8.60662966e-2f, 7.96819073e-2f, 0.00000000e+0f}},
  408. {{1.66666667e-1f, 1.92450090e-1f, 0.00000000e+0f, 0.00000000e+0f, -1.72132593e-1f, -7.96819073e-2f, 0.00000000e+0f}},
  409. {{1.66666667e-1f, 9.62250449e-2f, 1.66666667e-1f, 1.49071198e-1f, 8.60662966e-2f, 7.96819073e-2f, 0.00000000e+0f}},
  410. {{1.66666667e-1f, -9.62250449e-2f, 1.66666667e-1f, -1.49071198e-1f, 8.60662966e-2f, -7.96819073e-2f, 0.00000000e+0f}},
  411. {{1.66666667e-1f, -1.92450090e-1f, 0.00000000e+0f, 0.00000000e+0f, -1.72132593e-1f, 7.96819073e-2f, 0.00000000e+0f}},
  412. {{1.66666667e-1f, -9.62250449e-2f, -1.66666667e-1f, 1.49071198e-1f, 8.60662966e-2f, -7.96819073e-2f, 0.00000000e+0f}},
  413. }}
  414. };
  415. void InitPanning(ALCdevice *device, const bool hqdec=false, const bool stablize=false)
  416. {
  417. DecoderView decoder{};
  418. switch(device->FmtChans)
  419. {
  420. case DevFmtMono:
  421. decoder = MonoConfig;
  422. break;
  423. case DevFmtStereo:
  424. decoder = StereoConfig;
  425. break;
  426. case DevFmtQuad:
  427. decoder = QuadConfig;
  428. break;
  429. case DevFmtX51:
  430. decoder = X51Config;
  431. break;
  432. case DevFmtX51Rear:
  433. decoder = X51RearConfig;
  434. break;
  435. case DevFmtX61:
  436. decoder = X61Config;
  437. break;
  438. case DevFmtX71:
  439. decoder = X71Config;
  440. break;
  441. case DevFmtAmbi3D:
  442. break;
  443. }
  444. if(device->FmtChans == DevFmtAmbi3D)
  445. {
  446. const char *devname{device->DeviceName.c_str()};
  447. auto&& acnmap = GetAmbiLayout(device->mAmbiLayout);
  448. auto&& n3dscale = GetAmbiScales(device->mAmbiScale);
  449. /* For DevFmtAmbi3D, the ambisonic order is already set. */
  450. const size_t count{AmbiChannelsFromOrder(device->mAmbiOrder)};
  451. std::transform(acnmap.begin(), acnmap.begin()+count, std::begin(device->Dry.AmbiMap),
  452. [&n3dscale](const uint8_t &acn) noexcept -> BFChannelConfig
  453. { return BFChannelConfig{1.0f/n3dscale[acn], acn}; }
  454. );
  455. AllocChannels(device, count, 0);
  456. float nfc_delay{ConfigValueFloat(devname, "decoder", "nfc-ref-delay").value_or(0.0f)};
  457. if(nfc_delay > 0.0f)
  458. InitNearFieldCtrl(device, nfc_delay * SpeedOfSoundMetersPerSec, device->mAmbiOrder,
  459. true);
  460. }
  461. else
  462. {
  463. const bool dual_band{hqdec && !decoder.mCoeffsLF.empty()};
  464. al::vector<ChannelDec> chancoeffs, chancoeffslf;
  465. for(size_t i{0u};i < decoder.mChannels.size();++i)
  466. {
  467. const uint idx{GetChannelIdxByName(device->RealOut, decoder.mChannels[i])};
  468. if(idx == INVALID_CHANNEL_INDEX)
  469. {
  470. ERR("Failed to find %s channel in device\n",
  471. GetLabelFromChannel(decoder.mChannels[i]));
  472. continue;
  473. }
  474. chancoeffs.resize(maxz(chancoeffs.size(), idx+1u), ChannelDec{});
  475. al::span<float,MaxAmbiChannels> coeffs{chancoeffs[idx]};
  476. size_t start{0};
  477. for(uint o{0};o <= decoder.mOrder;++o)
  478. {
  479. size_t count{o ? 2u : 1u};
  480. do {
  481. coeffs[start] = decoder.mCoeffs[i][start] * decoder.mOrderGain[o];
  482. ++start;
  483. } while(--count);
  484. }
  485. if(!dual_band)
  486. continue;
  487. chancoeffslf.resize(maxz(chancoeffslf.size(), idx+1u), ChannelDec{});
  488. coeffs = chancoeffslf[idx];
  489. start = 0;
  490. for(uint o{0};o <= decoder.mOrder;++o)
  491. {
  492. size_t count{o ? 2u : 1u};
  493. do {
  494. coeffs[start] = decoder.mCoeffsLF[i][start] * decoder.mOrderGainLF[o];
  495. ++start;
  496. } while(--count);
  497. }
  498. }
  499. /* For non-DevFmtAmbi3D, set the ambisonic order. */
  500. device->mAmbiOrder = decoder.mOrder;
  501. /* Built-in speaker decoders are always 2D. */
  502. const size_t ambicount{Ambi2DChannelsFromOrder(decoder.mOrder)};
  503. std::transform(AmbiIndex::FromACN2D().begin(), AmbiIndex::FromACN2D().begin()+ambicount,
  504. std::begin(device->Dry.AmbiMap),
  505. [](const uint8_t &index) noexcept { return BFChannelConfig{1.0f, index}; }
  506. );
  507. AllocChannels(device, ambicount, device->channelsFromFmt());
  508. std::unique_ptr<FrontStablizer> stablizer;
  509. if(stablize)
  510. {
  511. /* Only enable the stablizer if the decoder does not output to the
  512. * front-center channel.
  513. */
  514. const auto cidx = device->RealOut.ChannelIndex[FrontCenter];
  515. bool hasfc{false};
  516. if(cidx < chancoeffs.size())
  517. {
  518. for(const auto &coeff : chancoeffs[cidx])
  519. hasfc |= coeff != 0.0f;
  520. }
  521. if(!hasfc && cidx < chancoeffslf.size())
  522. {
  523. for(const auto &coeff : chancoeffslf[cidx])
  524. hasfc |= coeff != 0.0f;
  525. }
  526. if(!hasfc)
  527. {
  528. stablizer = CreateStablizer(device->channelsFromFmt(), device->Frequency);
  529. TRACE("Front stablizer enabled\n");
  530. }
  531. }
  532. TRACE("Enabling %s-band %s-order%s ambisonic decoder\n",
  533. !dual_band ? "single" : "dual",
  534. (decoder.mOrder > 2) ? "third" :
  535. (decoder.mOrder > 1) ? "second" : "first",
  536. "");
  537. device->AmbiDecoder = BFormatDec::Create(ambicount, chancoeffs, chancoeffslf,
  538. std::move(stablizer));
  539. }
  540. }
  541. void InitCustomPanning(ALCdevice *device, const bool hqdec, const bool stablize,
  542. const AmbDecConf *conf, const uint (&speakermap)[MAX_OUTPUT_CHANNELS])
  543. {
  544. if(!hqdec && conf->FreqBands != 1)
  545. ERR("Basic renderer uses the high-frequency matrix as single-band (xover_freq = %.0fhz)\n",
  546. conf->XOverFreq);
  547. device->mXOverFreq = conf->XOverFreq;
  548. const uint order{(conf->ChanMask > Ambi2OrderMask) ? 3u :
  549. (conf->ChanMask > Ambi1OrderMask) ? 2u : 1u};
  550. device->mAmbiOrder = order;
  551. size_t count;
  552. if((conf->ChanMask&AmbiPeriphonicMask))
  553. {
  554. count = AmbiChannelsFromOrder(order);
  555. std::transform(AmbiIndex::FromACN().begin(), AmbiIndex::FromACN().begin()+count,
  556. std::begin(device->Dry.AmbiMap),
  557. [](const uint8_t &index) noexcept { return BFChannelConfig{1.0f, index}; }
  558. );
  559. }
  560. else
  561. {
  562. count = Ambi2DChannelsFromOrder(order);
  563. std::transform(AmbiIndex::FromACN2D().begin(), AmbiIndex::FromACN2D().begin()+count,
  564. std::begin(device->Dry.AmbiMap),
  565. [](const uint8_t &index) noexcept { return BFChannelConfig{1.0f, index}; }
  566. );
  567. }
  568. AllocChannels(device, count, device->channelsFromFmt());
  569. std::unique_ptr<FrontStablizer> stablizer;
  570. if(stablize)
  571. {
  572. /* Only enable the stablizer if the decoder does not output to the
  573. * front-center channel.
  574. */
  575. size_t cidx{0};
  576. for(;cidx < conf->NumSpeakers;++cidx)
  577. {
  578. if(speakermap[cidx] == FrontCenter)
  579. break;
  580. }
  581. bool hasfc{false};
  582. if(cidx < conf->NumSpeakers && conf->FreqBands != 1)
  583. {
  584. for(const auto &coeff : conf->LFMatrix[cidx])
  585. hasfc |= coeff != 0.0f;
  586. }
  587. if(!hasfc && cidx < conf->NumSpeakers)
  588. {
  589. for(const auto &coeff : conf->HFMatrix[cidx])
  590. hasfc |= coeff != 0.0f;
  591. }
  592. if(!hasfc)
  593. {
  594. stablizer = CreateStablizer(device->channelsFromFmt(), device->Frequency);
  595. TRACE("Front stablizer enabled\n");
  596. }
  597. }
  598. TRACE("Enabling %s-band %s-order%s ambisonic decoder\n",
  599. (!hqdec || conf->FreqBands == 1) ? "single" : "dual",
  600. (conf->ChanMask > Ambi2OrderMask) ? "third" :
  601. (conf->ChanMask > Ambi1OrderMask) ? "second" : "first",
  602. (conf->ChanMask&AmbiPeriphonicMask) ? " periphonic" : ""
  603. );
  604. device->AmbiDecoder = BFormatDec::Create(conf, hqdec, count, device->Frequency, speakermap,
  605. std::move(stablizer));
  606. auto accum_spkr_dist = std::bind(std::plus<float>{}, _1,
  607. std::bind(std::mem_fn(&AmbDecConf::SpeakerConf::Distance), _2));
  608. const float accum_dist{std::accumulate(conf->Speakers.get(),
  609. conf->Speakers.get()+conf->NumSpeakers, 0.0f, accum_spkr_dist)};
  610. InitNearFieldCtrl(device, accum_dist / static_cast<float>(conf->NumSpeakers), order,
  611. !!(conf->ChanMask&AmbiPeriphonicMask));
  612. InitDistanceComp(device, conf, speakermap);
  613. }
  614. void InitHrtfPanning(ALCdevice *device)
  615. {
  616. constexpr float Deg180{al::MathDefs<float>::Pi()};
  617. constexpr float Deg_90{Deg180 / 2.0f /* 90 degrees*/};
  618. constexpr float Deg_45{Deg_90 / 2.0f /* 45 degrees*/};
  619. constexpr float Deg135{Deg_45 * 3.0f /*135 degrees*/};
  620. constexpr float Deg_35{6.154797086e-01f /* 35~ 36 degrees*/};
  621. constexpr float Deg_69{1.205932499e+00f /* 69~ 70 degrees*/};
  622. constexpr float Deg111{1.935660155e+00f /*110~111 degrees*/};
  623. constexpr float Deg_21{3.648638281e-01f /* 20~ 21 degrees*/};
  624. static const AngularPoint AmbiPoints1O[]{
  625. { EvRadians{ Deg_35}, AzRadians{-Deg_45} },
  626. { EvRadians{ Deg_35}, AzRadians{-Deg135} },
  627. { EvRadians{ Deg_35}, AzRadians{ Deg_45} },
  628. { EvRadians{ Deg_35}, AzRadians{ Deg135} },
  629. { EvRadians{-Deg_35}, AzRadians{-Deg_45} },
  630. { EvRadians{-Deg_35}, AzRadians{-Deg135} },
  631. { EvRadians{-Deg_35}, AzRadians{ Deg_45} },
  632. { EvRadians{-Deg_35}, AzRadians{ Deg135} },
  633. }, AmbiPoints2O[]{
  634. { EvRadians{-Deg_35}, AzRadians{-Deg_45} },
  635. { EvRadians{-Deg_35}, AzRadians{-Deg135} },
  636. { EvRadians{ Deg_35}, AzRadians{-Deg135} },
  637. { EvRadians{ Deg_35}, AzRadians{ Deg135} },
  638. { EvRadians{ Deg_35}, AzRadians{ Deg_45} },
  639. { EvRadians{-Deg_35}, AzRadians{ Deg_45} },
  640. { EvRadians{-Deg_35}, AzRadians{ Deg135} },
  641. { EvRadians{ Deg_35}, AzRadians{-Deg_45} },
  642. { EvRadians{-Deg_69}, AzRadians{-Deg_90} },
  643. { EvRadians{ Deg_69}, AzRadians{ Deg_90} },
  644. { EvRadians{-Deg_69}, AzRadians{ Deg_90} },
  645. { EvRadians{ Deg_69}, AzRadians{-Deg_90} },
  646. { EvRadians{ 0.0f}, AzRadians{-Deg_69} },
  647. { EvRadians{ 0.0f}, AzRadians{-Deg111} },
  648. { EvRadians{ 0.0f}, AzRadians{ Deg_69} },
  649. { EvRadians{ 0.0f}, AzRadians{ Deg111} },
  650. { EvRadians{-Deg_21}, AzRadians{ Deg180} },
  651. { EvRadians{ Deg_21}, AzRadians{ Deg180} },
  652. { EvRadians{ Deg_21}, AzRadians{ 0.0f} },
  653. { EvRadians{-Deg_21}, AzRadians{ 0.0f} },
  654. };
  655. static const float AmbiMatrix1O[][MaxAmbiChannels]{
  656. { 1.250000000e-01f, 1.250000000e-01f, 1.250000000e-01f, 1.250000000e-01f },
  657. { 1.250000000e-01f, 1.250000000e-01f, 1.250000000e-01f, -1.250000000e-01f },
  658. { 1.250000000e-01f, -1.250000000e-01f, 1.250000000e-01f, 1.250000000e-01f },
  659. { 1.250000000e-01f, -1.250000000e-01f, 1.250000000e-01f, -1.250000000e-01f },
  660. { 1.250000000e-01f, 1.250000000e-01f, -1.250000000e-01f, 1.250000000e-01f },
  661. { 1.250000000e-01f, 1.250000000e-01f, -1.250000000e-01f, -1.250000000e-01f },
  662. { 1.250000000e-01f, -1.250000000e-01f, -1.250000000e-01f, 1.250000000e-01f },
  663. { 1.250000000e-01f, -1.250000000e-01f, -1.250000000e-01f, -1.250000000e-01f },
  664. }, AmbiMatrix2O[][MaxAmbiChannels]{
  665. { 5.000000000e-02f, 5.000000000e-02f, -5.000000000e-02f, 5.000000000e-02f, 6.454972244e-02f, -6.454972244e-02f, 0.000000000e+00f, -6.454972244e-02f, 0.000000000e+00f },
  666. { 5.000000000e-02f, 5.000000000e-02f, -5.000000000e-02f, -5.000000000e-02f, -6.454972244e-02f, -6.454972244e-02f, 0.000000000e+00f, 6.454972244e-02f, 0.000000000e+00f },
  667. { 5.000000000e-02f, 5.000000000e-02f, 5.000000000e-02f, -5.000000000e-02f, -6.454972244e-02f, 6.454972244e-02f, 0.000000000e+00f, -6.454972244e-02f, 0.000000000e+00f },
  668. { 5.000000000e-02f, -5.000000000e-02f, 5.000000000e-02f, -5.000000000e-02f, 6.454972244e-02f, -6.454972244e-02f, 0.000000000e+00f, -6.454972244e-02f, 0.000000000e+00f },
  669. { 5.000000000e-02f, -5.000000000e-02f, 5.000000000e-02f, 5.000000000e-02f, -6.454972244e-02f, -6.454972244e-02f, 0.000000000e+00f, 6.454972244e-02f, 0.000000000e+00f },
  670. { 5.000000000e-02f, -5.000000000e-02f, -5.000000000e-02f, 5.000000000e-02f, -6.454972244e-02f, 6.454972244e-02f, 0.000000000e+00f, -6.454972244e-02f, 0.000000000e+00f },
  671. { 5.000000000e-02f, -5.000000000e-02f, -5.000000000e-02f, -5.000000000e-02f, 6.454972244e-02f, 6.454972244e-02f, 0.000000000e+00f, 6.454972244e-02f, 0.000000000e+00f },
  672. { 5.000000000e-02f, 5.000000000e-02f, 5.000000000e-02f, 5.000000000e-02f, 6.454972244e-02f, 6.454972244e-02f, 0.000000000e+00f, 6.454972244e-02f, 0.000000000e+00f },
  673. { 5.000000000e-02f, 3.090169944e-02f, -8.090169944e-02f, 0.000000000e+00f, 0.000000000e+00f, -6.454972244e-02f, 9.045084972e-02f, 0.000000000e+00f, -1.232790000e-02f },
  674. { 5.000000000e-02f, -3.090169944e-02f, 8.090169944e-02f, 0.000000000e+00f, 0.000000000e+00f, -6.454972244e-02f, 9.045084972e-02f, 0.000000000e+00f, -1.232790000e-02f },
  675. { 5.000000000e-02f, -3.090169944e-02f, -8.090169944e-02f, 0.000000000e+00f, 0.000000000e+00f, 6.454972244e-02f, 9.045084972e-02f, 0.000000000e+00f, -1.232790000e-02f },
  676. { 5.000000000e-02f, 3.090169944e-02f, 8.090169944e-02f, 0.000000000e+00f, 0.000000000e+00f, 6.454972244e-02f, 9.045084972e-02f, 0.000000000e+00f, -1.232790000e-02f },
  677. { 5.000000000e-02f, 8.090169944e-02f, 0.000000000e+00f, 3.090169944e-02f, 6.454972244e-02f, 0.000000000e+00f, -5.590169944e-02f, 0.000000000e+00f, -7.216878365e-02f },
  678. { 5.000000000e-02f, 8.090169944e-02f, 0.000000000e+00f, -3.090169944e-02f, -6.454972244e-02f, 0.000000000e+00f, -5.590169944e-02f, 0.000000000e+00f, -7.216878365e-02f },
  679. { 5.000000000e-02f, -8.090169944e-02f, 0.000000000e+00f, 3.090169944e-02f, -6.454972244e-02f, 0.000000000e+00f, -5.590169944e-02f, 0.000000000e+00f, -7.216878365e-02f },
  680. { 5.000000000e-02f, -8.090169944e-02f, 0.000000000e+00f, -3.090169944e-02f, 6.454972244e-02f, 0.000000000e+00f, -5.590169944e-02f, 0.000000000e+00f, -7.216878365e-02f },
  681. { 5.000000000e-02f, 0.000000000e+00f, -3.090169944e-02f, -8.090169944e-02f, 0.000000000e+00f, 0.000000000e+00f, -3.454915028e-02f, 6.454972244e-02f, 8.449668365e-02f },
  682. { 5.000000000e-02f, 0.000000000e+00f, 3.090169944e-02f, -8.090169944e-02f, 0.000000000e+00f, 0.000000000e+00f, -3.454915028e-02f, -6.454972244e-02f, 8.449668365e-02f },
  683. { 5.000000000e-02f, 0.000000000e+00f, 3.090169944e-02f, 8.090169944e-02f, 0.000000000e+00f, 0.000000000e+00f, -3.454915028e-02f, 6.454972244e-02f, 8.449668365e-02f },
  684. { 5.000000000e-02f, 0.000000000e+00f, -3.090169944e-02f, 8.090169944e-02f, 0.000000000e+00f, 0.000000000e+00f, -3.454915028e-02f, -6.454972244e-02f, 8.449668365e-02f },
  685. };
  686. static const float AmbiOrderHFGain1O[MaxAmbiOrder+1]{
  687. 2.000000000e+00f, 1.154700538e+00f
  688. }, AmbiOrderHFGain2O[MaxAmbiOrder+1]{
  689. 2.357022604e+00f, 1.825741858e+00f, 9.428090416e-01f
  690. };
  691. static_assert(al::size(AmbiPoints1O) == al::size(AmbiMatrix1O), "First-Order Ambisonic HRTF mismatch");
  692. static_assert(al::size(AmbiPoints2O) == al::size(AmbiMatrix2O), "Second-Order Ambisonic HRTF mismatch");
  693. /* Don't bother with HOA when using full HRTF rendering. Nothing needs it,
  694. * and it eases the CPU/memory load.
  695. */
  696. device->mRenderMode = RenderMode::Hrtf;
  697. uint ambi_order{1};
  698. if(auto modeopt = ConfigValueStr(device->DeviceName.c_str(), nullptr, "hrtf-mode"))
  699. {
  700. struct HrtfModeEntry {
  701. char name[8];
  702. RenderMode mode;
  703. uint order;
  704. };
  705. static const HrtfModeEntry hrtf_modes[]{
  706. { "full", RenderMode::Hrtf, 1 },
  707. { "ambi1", RenderMode::Normal, 1 },
  708. { "ambi2", RenderMode::Normal, 2 },
  709. };
  710. const char *mode{modeopt->c_str()};
  711. if(al::strcasecmp(mode, "basic") == 0 || al::strcasecmp(mode, "ambi3") == 0)
  712. {
  713. ERR("HRTF mode \"%s\" deprecated, substituting \"%s\"\n", mode, "ambi2");
  714. mode = "ambi2";
  715. }
  716. auto match_entry = [mode](const HrtfModeEntry &entry) -> bool
  717. { return al::strcasecmp(mode, entry.name) == 0; };
  718. auto iter = std::find_if(std::begin(hrtf_modes), std::end(hrtf_modes), match_entry);
  719. if(iter == std::end(hrtf_modes))
  720. ERR("Unexpected hrtf-mode: %s\n", mode);
  721. else
  722. {
  723. device->mRenderMode = iter->mode;
  724. ambi_order = iter->order;
  725. }
  726. }
  727. TRACE("%u%s order %sHRTF rendering enabled, using \"%s\"\n", ambi_order,
  728. (((ambi_order%100)/10) == 1) ? "th" :
  729. ((ambi_order%10) == 1) ? "st" :
  730. ((ambi_order%10) == 2) ? "nd" :
  731. ((ambi_order%10) == 3) ? "rd" : "th",
  732. (device->mRenderMode == RenderMode::Hrtf) ? "+ Full " : "",
  733. device->HrtfName.c_str());
  734. al::span<const AngularPoint> AmbiPoints{AmbiPoints1O};
  735. const float (*AmbiMatrix)[MaxAmbiChannels]{AmbiMatrix1O};
  736. al::span<const float,MaxAmbiOrder+1> AmbiOrderHFGain{AmbiOrderHFGain1O};
  737. if(ambi_order >= 2)
  738. {
  739. AmbiPoints = AmbiPoints2O;
  740. AmbiMatrix = AmbiMatrix2O;
  741. AmbiOrderHFGain = AmbiOrderHFGain2O;
  742. }
  743. device->mAmbiOrder = ambi_order;
  744. const size_t count{AmbiChannelsFromOrder(ambi_order)};
  745. std::transform(AmbiIndex::FromACN().begin(), AmbiIndex::FromACN().begin()+count,
  746. std::begin(device->Dry.AmbiMap),
  747. [](const uint8_t &index) noexcept { return BFChannelConfig{1.0f, index}; }
  748. );
  749. AllocChannels(device, count, device->channelsFromFmt());
  750. HrtfStore *Hrtf{device->mHrtf.get()};
  751. auto hrtfstate = DirectHrtfState::Create(count);
  752. hrtfstate->build(Hrtf, device->mIrSize, AmbiPoints, AmbiMatrix, device->mXOverFreq,
  753. AmbiOrderHFGain);
  754. device->mHrtfState = std::move(hrtfstate);
  755. InitNearFieldCtrl(device, Hrtf->field[0].distance, ambi_order, true);
  756. }
  757. void InitUhjPanning(ALCdevice *device)
  758. {
  759. /* UHJ is always 2D first-order. */
  760. constexpr size_t count{Ambi2DChannelsFromOrder(1)};
  761. device->mAmbiOrder = 1;
  762. auto acnmap_begin = AmbiIndex::FromFuMa().begin();
  763. std::transform(acnmap_begin, acnmap_begin + count, std::begin(device->Dry.AmbiMap),
  764. [](const uint8_t &acn) noexcept -> BFChannelConfig
  765. { return BFChannelConfig{1.0f/AmbiScale::FromFuMa()[acn], acn}; });
  766. AllocChannels(device, count, device->channelsFromFmt());
  767. }
  768. } // namespace
  769. void aluInitRenderer(ALCdevice *device, int hrtf_id, HrtfRequestMode hrtf_appreq,
  770. HrtfRequestMode hrtf_userreq)
  771. {
  772. const char *devname{device->DeviceName.c_str()};
  773. /* Hold the HRTF the device last used, in case it's used again. */
  774. HrtfStorePtr old_hrtf{std::move(device->mHrtf)};
  775. device->mHrtfState = nullptr;
  776. device->mHrtf = nullptr;
  777. device->mIrSize = 0;
  778. device->HrtfName.clear();
  779. device->mXOverFreq = 400.0f;
  780. device->mRenderMode = RenderMode::Normal;
  781. if(device->FmtChans != DevFmtStereo)
  782. {
  783. old_hrtf = nullptr;
  784. if(hrtf_appreq == Hrtf_Enable)
  785. device->HrtfStatus = ALC_HRTF_UNSUPPORTED_FORMAT_SOFT;
  786. const char *layout{nullptr};
  787. switch(device->FmtChans)
  788. {
  789. case DevFmtQuad: layout = "quad"; break;
  790. case DevFmtX51: /* fall-through */
  791. case DevFmtX51Rear: layout = "surround51"; break;
  792. case DevFmtX61: layout = "surround61"; break;
  793. case DevFmtX71: layout = "surround71"; break;
  794. /* Mono, Stereo, and Ambisonics output don't use custom decoders. */
  795. case DevFmtMono:
  796. case DevFmtStereo:
  797. case DevFmtAmbi3D:
  798. break;
  799. }
  800. uint speakermap[MAX_OUTPUT_CHANNELS];
  801. AmbDecConf *pconf{nullptr};
  802. AmbDecConf conf{};
  803. if(layout)
  804. {
  805. if(auto decopt = ConfigValueStr(devname, "decoder", layout))
  806. {
  807. if(auto err = conf.load(decopt->c_str()))
  808. {
  809. ERR("Failed to load layout file %s\n", decopt->c_str());
  810. ERR(" %s\n", err->c_str());
  811. }
  812. else if(conf.NumSpeakers > MAX_OUTPUT_CHANNELS)
  813. ERR("Unsupported decoder speaker count %zu (max %d)\n", conf.NumSpeakers,
  814. MAX_OUTPUT_CHANNELS);
  815. else if(conf.ChanMask > Ambi3OrderMask)
  816. ERR("Unsupported decoder channel mask 0x%04x (max 0x%x)\n", conf.ChanMask,
  817. Ambi3OrderMask);
  818. else if(MakeSpeakerMap(device, &conf, speakermap))
  819. pconf = &conf;
  820. }
  821. }
  822. /* Enable the stablizer only for formats that have front-left, front-
  823. * right, and front-center outputs.
  824. */
  825. const bool stablize{device->RealOut.ChannelIndex[FrontCenter] != INVALID_CHANNEL_INDEX
  826. && device->RealOut.ChannelIndex[FrontLeft] != INVALID_CHANNEL_INDEX
  827. && device->RealOut.ChannelIndex[FrontRight] != INVALID_CHANNEL_INDEX
  828. && GetConfigValueBool(devname, nullptr, "front-stablizer", 0) != 0};
  829. const bool hqdec{GetConfigValueBool(devname, "decoder", "hq-mode", 1) != 0};
  830. if(!pconf)
  831. InitPanning(device, hqdec, stablize);
  832. else
  833. InitCustomPanning(device, hqdec, stablize, pconf, speakermap);
  834. if(auto *ambidec{device->AmbiDecoder.get()})
  835. {
  836. device->PostProcess = ambidec->hasStablizer() ? &ALCdevice::ProcessAmbiDecStablized
  837. : &ALCdevice::ProcessAmbiDec;
  838. }
  839. return;
  840. }
  841. bool headphones{device->IsHeadphones};
  842. if(device->Type != DeviceType::Loopback)
  843. {
  844. if(auto modeopt = ConfigValueStr(device->DeviceName.c_str(), nullptr, "stereo-mode"))
  845. {
  846. const char *mode{modeopt->c_str()};
  847. if(al::strcasecmp(mode, "headphones") == 0)
  848. headphones = true;
  849. else if(al::strcasecmp(mode, "speakers") == 0)
  850. headphones = false;
  851. else if(al::strcasecmp(mode, "auto") != 0)
  852. ERR("Unexpected stereo-mode: %s\n", mode);
  853. }
  854. }
  855. if(hrtf_userreq == Hrtf_Default)
  856. {
  857. bool usehrtf = (headphones && hrtf_appreq != Hrtf_Disable) ||
  858. (hrtf_appreq == Hrtf_Enable);
  859. if(!usehrtf) goto no_hrtf;
  860. device->HrtfStatus = ALC_HRTF_ENABLED_SOFT;
  861. if(headphones && hrtf_appreq != Hrtf_Disable)
  862. device->HrtfStatus = ALC_HRTF_HEADPHONES_DETECTED_SOFT;
  863. }
  864. else
  865. {
  866. if(hrtf_userreq != Hrtf_Enable)
  867. {
  868. if(hrtf_appreq == Hrtf_Enable)
  869. device->HrtfStatus = ALC_HRTF_DENIED_SOFT;
  870. goto no_hrtf;
  871. }
  872. device->HrtfStatus = ALC_HRTF_REQUIRED_SOFT;
  873. }
  874. if(device->HrtfList.empty())
  875. device->HrtfList = EnumerateHrtf(device->DeviceName.c_str());
  876. if(hrtf_id >= 0 && static_cast<uint>(hrtf_id) < device->HrtfList.size())
  877. {
  878. const std::string &hrtfname = device->HrtfList[static_cast<uint>(hrtf_id)];
  879. if(HrtfStorePtr hrtf{GetLoadedHrtf(hrtfname, device->Frequency)})
  880. {
  881. device->mHrtf = std::move(hrtf);
  882. device->HrtfName = hrtfname;
  883. }
  884. }
  885. if(!device->mHrtf)
  886. {
  887. for(const auto &hrtfname : device->HrtfList)
  888. {
  889. if(HrtfStorePtr hrtf{GetLoadedHrtf(hrtfname, device->Frequency)})
  890. {
  891. device->mHrtf = std::move(hrtf);
  892. device->HrtfName = hrtfname;
  893. break;
  894. }
  895. }
  896. }
  897. if(device->mHrtf)
  898. {
  899. old_hrtf = nullptr;
  900. HrtfStore *hrtf{device->mHrtf.get()};
  901. device->mIrSize = hrtf->irSize;
  902. if(auto hrtfsizeopt = ConfigValueUInt(devname, nullptr, "hrtf-size"))
  903. {
  904. if(*hrtfsizeopt > 0 && *hrtfsizeopt < device->mIrSize)
  905. device->mIrSize = maxu(*hrtfsizeopt, MinIrLength);
  906. }
  907. InitHrtfPanning(device);
  908. device->PostProcess = &ALCdevice::ProcessHrtf;
  909. return;
  910. }
  911. device->HrtfStatus = ALC_HRTF_UNSUPPORTED_FORMAT_SOFT;
  912. no_hrtf:
  913. old_hrtf = nullptr;
  914. device->mRenderMode = RenderMode::Pairwise;
  915. if(device->Type != DeviceType::Loopback)
  916. {
  917. if(auto cflevopt = ConfigValueInt(device->DeviceName.c_str(), nullptr, "cf_level"))
  918. {
  919. if(*cflevopt > 0 && *cflevopt <= 6)
  920. {
  921. device->Bs2b = std::make_unique<bs2b>();
  922. bs2b_set_params(device->Bs2b.get(), *cflevopt,
  923. static_cast<int>(device->Frequency));
  924. TRACE("BS2B enabled\n");
  925. InitPanning(device);
  926. device->PostProcess = &ALCdevice::ProcessBs2b;
  927. return;
  928. }
  929. }
  930. }
  931. if(auto encopt = ConfigValueStr(device->DeviceName.c_str(), nullptr, "stereo-encoding"))
  932. {
  933. const char *mode{encopt->c_str()};
  934. if(al::strcasecmp(mode, "uhj") == 0)
  935. device->mRenderMode = RenderMode::Normal;
  936. else if(al::strcasecmp(mode, "panpot") != 0)
  937. ERR("Unexpected stereo-encoding: %s\n", mode);
  938. }
  939. if(device->mRenderMode == RenderMode::Normal)
  940. {
  941. device->Uhj_Encoder = std::make_unique<Uhj2Encoder>();
  942. TRACE("UHJ enabled\n");
  943. InitUhjPanning(device);
  944. device->PostProcess = &ALCdevice::ProcessUhj;
  945. return;
  946. }
  947. TRACE("Stereo rendering\n");
  948. InitPanning(device);
  949. device->PostProcess = &ALCdevice::ProcessAmbiDec;
  950. }
  951. void aluInitEffectPanning(EffectSlot *slot, ALCcontext *context)
  952. {
  953. ALCdevice *device{context->mDevice.get()};
  954. const size_t count{AmbiChannelsFromOrder(device->mAmbiOrder)};
  955. auto wetbuffer_iter = context->mWetBuffers.end();
  956. if(slot->mWetBuffer)
  957. {
  958. /* If the effect slot already has a wet buffer attached, allocate a new
  959. * one in its place.
  960. */
  961. wetbuffer_iter = context->mWetBuffers.begin();
  962. for(;wetbuffer_iter != context->mWetBuffers.end();++wetbuffer_iter)
  963. {
  964. if(wetbuffer_iter->get() == slot->mWetBuffer)
  965. {
  966. slot->mWetBuffer = nullptr;
  967. slot->Wet.Buffer = {};
  968. *wetbuffer_iter = WetBufferPtr{new(FamCount(count)) WetBuffer{count}};
  969. break;
  970. }
  971. }
  972. }
  973. if(wetbuffer_iter == context->mWetBuffers.end())
  974. {
  975. /* Otherwise, search for an unused wet buffer. */
  976. wetbuffer_iter = context->mWetBuffers.begin();
  977. for(;wetbuffer_iter != context->mWetBuffers.end();++wetbuffer_iter)
  978. {
  979. if(!(*wetbuffer_iter)->mInUse)
  980. break;
  981. }
  982. if(wetbuffer_iter == context->mWetBuffers.end())
  983. {
  984. /* Otherwise, allocate a new one to use. */
  985. context->mWetBuffers.emplace_back(WetBufferPtr{new(FamCount(count)) WetBuffer{count}});
  986. wetbuffer_iter = context->mWetBuffers.end()-1;
  987. }
  988. }
  989. WetBuffer *wetbuffer{slot->mWetBuffer = wetbuffer_iter->get()};
  990. wetbuffer->mInUse = true;
  991. auto acnmap_begin = AmbiIndex::FromACN().begin();
  992. auto iter = std::transform(acnmap_begin, acnmap_begin + count, slot->Wet.AmbiMap.begin(),
  993. [](const uint8_t &acn) noexcept -> BFChannelConfig
  994. { return BFChannelConfig{1.0f, acn}; });
  995. std::fill(iter, slot->Wet.AmbiMap.end(), BFChannelConfig{});
  996. slot->Wet.Buffer = wetbuffer->mBuffer;
  997. }
  998. std::array<float,MaxAmbiChannels> CalcAmbiCoeffs(const float y, const float z, const float x,
  999. const float spread)
  1000. {
  1001. std::array<float,MaxAmbiChannels> coeffs;
  1002. /* Zeroth-order */
  1003. coeffs[0] = 1.0f; /* ACN 0 = 1 */
  1004. /* First-order */
  1005. coeffs[1] = 1.732050808f * y; /* ACN 1 = sqrt(3) * Y */
  1006. coeffs[2] = 1.732050808f * z; /* ACN 2 = sqrt(3) * Z */
  1007. coeffs[3] = 1.732050808f * x; /* ACN 3 = sqrt(3) * X */
  1008. /* Second-order */
  1009. const float xx{x*x}, yy{y*y}, zz{z*z}, xy{x*y}, yz{y*z}, xz{x*z};
  1010. coeffs[4] = 3.872983346f * xy; /* ACN 4 = sqrt(15) * X * Y */
  1011. coeffs[5] = 3.872983346f * yz; /* ACN 5 = sqrt(15) * Y * Z */
  1012. coeffs[6] = 1.118033989f * (3.0f*zz - 1.0f); /* ACN 6 = sqrt(5)/2 * (3*Z*Z - 1) */
  1013. coeffs[7] = 3.872983346f * xz; /* ACN 7 = sqrt(15) * X * Z */
  1014. coeffs[8] = 1.936491673f * (xx - yy); /* ACN 8 = sqrt(15)/2 * (X*X - Y*Y) */
  1015. /* Third-order */
  1016. coeffs[9] = 2.091650066f * (y*(3.0f*xx - yy)); /* ACN 9 = sqrt(35/8) * Y * (3*X*X - Y*Y) */
  1017. coeffs[10] = 10.246950766f * (z*xy); /* ACN 10 = sqrt(105) * Z * X * Y */
  1018. coeffs[11] = 1.620185175f * (y*(5.0f*zz - 1.0f)); /* ACN 11 = sqrt(21/8) * Y * (5*Z*Z - 1) */
  1019. coeffs[12] = 1.322875656f * (z*(5.0f*zz - 3.0f)); /* ACN 12 = sqrt(7)/2 * Z * (5*Z*Z - 3) */
  1020. coeffs[13] = 1.620185175f * (x*(5.0f*zz - 1.0f)); /* ACN 13 = sqrt(21/8) * X * (5*Z*Z - 1) */
  1021. coeffs[14] = 5.123475383f * (z*(xx - yy)); /* ACN 14 = sqrt(105)/2 * Z * (X*X - Y*Y) */
  1022. coeffs[15] = 2.091650066f * (x*(xx - 3.0f*yy)); /* ACN 15 = sqrt(35/8) * X * (X*X - 3*Y*Y) */
  1023. /* Fourth-order */
  1024. /* ACN 16 = sqrt(35)*3/2 * X * Y * (X*X - Y*Y) */
  1025. /* ACN 17 = sqrt(35/2)*3/2 * (3*X*X - Y*Y) * Y * Z */
  1026. /* ACN 18 = sqrt(5)*3/2 * X * Y * (7*Z*Z - 1) */
  1027. /* ACN 19 = sqrt(5/2)*3/2 * Y * Z * (7*Z*Z - 3) */
  1028. /* ACN 20 = 3/8 * (35*Z*Z*Z*Z - 30*Z*Z + 3) */
  1029. /* ACN 21 = sqrt(5/2)*3/2 * X * Z * (7*Z*Z - 3) */
  1030. /* ACN 22 = sqrt(5)*3/4 * (X*X - Y*Y) * (7*Z*Z - 1) */
  1031. /* ACN 23 = sqrt(35/2)*3/2 * (X*X - 3*Y*Y) * X * Z */
  1032. /* ACN 24 = sqrt(35)*3/8 * (X*X*X*X - 6*X*X*Y*Y + Y*Y*Y*Y) */
  1033. if(spread > 0.0f)
  1034. {
  1035. /* Implement the spread by using a spherical source that subtends the
  1036. * angle spread. See:
  1037. * http://www.ppsloan.org/publications/StupidSH36.pdf - Appendix A3
  1038. *
  1039. * When adjusted for N3D normalization instead of SN3D, these
  1040. * calculations are:
  1041. *
  1042. * ZH0 = -sqrt(pi) * (-1+ca);
  1043. * ZH1 = 0.5*sqrt(pi) * sa*sa;
  1044. * ZH2 = -0.5*sqrt(pi) * ca*(-1+ca)*(ca+1);
  1045. * ZH3 = -0.125*sqrt(pi) * (-1+ca)*(ca+1)*(5*ca*ca - 1);
  1046. * ZH4 = -0.125*sqrt(pi) * ca*(-1+ca)*(ca+1)*(7*ca*ca - 3);
  1047. * ZH5 = -0.0625*sqrt(pi) * (-1+ca)*(ca+1)*(21*ca*ca*ca*ca - 14*ca*ca + 1);
  1048. *
  1049. * The gain of the source is compensated for size, so that the
  1050. * loudness doesn't depend on the spread. Thus:
  1051. *
  1052. * ZH0 = 1.0f;
  1053. * ZH1 = 0.5f * (ca+1.0f);
  1054. * ZH2 = 0.5f * (ca+1.0f)*ca;
  1055. * ZH3 = 0.125f * (ca+1.0f)*(5.0f*ca*ca - 1.0f);
  1056. * ZH4 = 0.125f * (ca+1.0f)*(7.0f*ca*ca - 3.0f)*ca;
  1057. * ZH5 = 0.0625f * (ca+1.0f)*(21.0f*ca*ca*ca*ca - 14.0f*ca*ca + 1.0f);
  1058. */
  1059. const float ca{std::cos(spread * 0.5f)};
  1060. /* Increase the source volume by up to +3dB for a full spread. */
  1061. const float scale{std::sqrt(1.0f + spread/al::MathDefs<float>::Tau())};
  1062. const float ZH0_norm{scale};
  1063. const float ZH1_norm{scale * 0.5f * (ca+1.f)};
  1064. const float ZH2_norm{scale * 0.5f * (ca+1.f)*ca};
  1065. const float ZH3_norm{scale * 0.125f * (ca+1.f)*(5.f*ca*ca-1.f)};
  1066. /* Zeroth-order */
  1067. coeffs[0] *= ZH0_norm;
  1068. /* First-order */
  1069. coeffs[1] *= ZH1_norm;
  1070. coeffs[2] *= ZH1_norm;
  1071. coeffs[3] *= ZH1_norm;
  1072. /* Second-order */
  1073. coeffs[4] *= ZH2_norm;
  1074. coeffs[5] *= ZH2_norm;
  1075. coeffs[6] *= ZH2_norm;
  1076. coeffs[7] *= ZH2_norm;
  1077. coeffs[8] *= ZH2_norm;
  1078. /* Third-order */
  1079. coeffs[9] *= ZH3_norm;
  1080. coeffs[10] *= ZH3_norm;
  1081. coeffs[11] *= ZH3_norm;
  1082. coeffs[12] *= ZH3_norm;
  1083. coeffs[13] *= ZH3_norm;
  1084. coeffs[14] *= ZH3_norm;
  1085. coeffs[15] *= ZH3_norm;
  1086. }
  1087. return coeffs;
  1088. }
  1089. void ComputePanGains(const MixParams *mix, const float*RESTRICT coeffs, const float ingain,
  1090. const al::span<float,MAX_OUTPUT_CHANNELS> gains)
  1091. {
  1092. auto ambimap = mix->AmbiMap.cbegin();
  1093. auto iter = std::transform(ambimap, ambimap+mix->Buffer.size(), gains.begin(),
  1094. [coeffs,ingain](const BFChannelConfig &chanmap) noexcept -> float
  1095. { return chanmap.Scale * coeffs[chanmap.Index] * ingain; }
  1096. );
  1097. std::fill(iter, gains.end(), 0.0f);
  1098. }