convolution.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. #include "config.h"
  2. #include <algorithm>
  3. #include <array>
  4. #include <cassert>
  5. #include <cmath>
  6. #include <complex>
  7. #include <cstddef>
  8. #include <cstdint>
  9. #include <functional>
  10. #include <memory>
  11. #include <vector>
  12. #include <variant>
  13. #ifdef HAVE_SSE_INTRINSICS
  14. #include <xmmintrin.h>
  15. #elif defined(HAVE_NEON)
  16. #include <arm_neon.h>
  17. #endif
  18. #include "alcomplex.h"
  19. #include "almalloc.h"
  20. #include "alnumbers.h"
  21. #include "alnumeric.h"
  22. #include "alspan.h"
  23. #include "base.h"
  24. #include "core/ambidefs.h"
  25. #include "core/bufferline.h"
  26. #include "core/buffer_storage.h"
  27. #include "core/context.h"
  28. #include "core/devformat.h"
  29. #include "core/device.h"
  30. #include "core/effects/base.h"
  31. #include "core/effectslot.h"
  32. #include "core/filters/splitter.h"
  33. #include "core/fmt_traits.h"
  34. #include "core/mixer.h"
  35. #include "core/uhjfilter.h"
  36. #include "intrusive_ptr.h"
  37. #include "opthelpers.h"
  38. #include "pffft.h"
  39. #include "polyphase_resampler.h"
  40. #include "vecmat.h"
  41. #include "vector.h"
  42. namespace {
  43. /* Convolution is implemented using a segmented overlap-add method. The impulse
  44. * response is split into multiple segments of 128 samples, and each segment
  45. * has an FFT applied with a 256-sample buffer (the latter half left silent) to
  46. * get its frequency-domain response. The resulting response has its positive/
  47. * non-mirrored frequencies saved (129 bins) in each segment. Note that since
  48. * the 0- and half-frequency bins are real for a real signal, their imaginary
  49. * components are always 0 and can be dropped, allowing their real components
  50. * to be combined so only 128 complex values are stored for the 129 bins.
  51. *
  52. * Input samples are similarly broken up into 128-sample segments, with a 256-
  53. * sample FFT applied to each new incoming segment to get its 129 bins. A
  54. * history of FFT'd input segments is maintained, equal to the number of
  55. * impulse response segments.
  56. *
  57. * To apply the convolution, each impulse response segment is convolved with
  58. * its paired input segment (using complex multiplies, far cheaper than FIRs),
  59. * accumulating into a 129-bin FFT buffer. The input history is then shifted to
  60. * align with later impulse response segments for the next input segment.
  61. *
  62. * An inverse FFT is then applied to the accumulated FFT buffer to get a 256-
  63. * sample time-domain response for output, which is split in two halves. The
  64. * first half is the 128-sample output, and the second half is a 128-sample
  65. * (really, 127) delayed extension, which gets added to the output next time.
  66. * Convolving two time-domain responses of length N results in a time-domain
  67. * signal of length N*2 - 1, and this holds true regardless of the convolution
  68. * being applied in the frequency domain, so these "overflow" samples need to
  69. * be accounted for.
  70. *
  71. * To avoid a delay with gathering enough input samples for the FFT, the first
  72. * segment is applied directly in the time-domain as the samples come in. Once
  73. * enough have been retrieved, the FFT is applied on the input and it's paired
  74. * with the remaining (FFT'd) filter segments for processing.
  75. */
  76. template<FmtType SrcType>
  77. inline void LoadSampleArray(const al::span<float> dst, const std::byte *src,
  78. const std::size_t channel, const std::size_t srcstep) noexcept
  79. {
  80. using TypeTraits = al::FmtTypeTraits<SrcType>;
  81. using SampleType = typename TypeTraits::Type;
  82. const auto converter = TypeTraits{};
  83. assert(channel < srcstep);
  84. const auto srcspan = al::span{reinterpret_cast<const SampleType*>(src), dst.size()*srcstep};
  85. auto ssrc = srcspan.cbegin();
  86. std::generate(dst.begin(), dst.end(), [converter,channel,srcstep,&ssrc]
  87. {
  88. const auto ret = converter(ssrc[channel]);
  89. ssrc += ptrdiff_t(srcstep);
  90. return ret;
  91. });
  92. }
  93. void LoadSamples(const al::span<float> dst, const std::byte *src, const size_t channel,
  94. const size_t srcstep, const FmtType srctype) noexcept
  95. {
  96. #define HANDLE_FMT(T) case T: LoadSampleArray<T>(dst, src, channel, srcstep); break
  97. switch(srctype)
  98. {
  99. HANDLE_FMT(FmtUByte);
  100. HANDLE_FMT(FmtShort);
  101. HANDLE_FMT(FmtInt);
  102. HANDLE_FMT(FmtFloat);
  103. HANDLE_FMT(FmtDouble);
  104. HANDLE_FMT(FmtMulaw);
  105. HANDLE_FMT(FmtAlaw);
  106. /* FIXME: Handle ADPCM decoding here. */
  107. case FmtIMA4:
  108. case FmtMSADPCM:
  109. std::fill(dst.begin(), dst.end(), 0.0f);
  110. break;
  111. }
  112. #undef HANDLE_FMT
  113. }
  114. constexpr auto GetAmbiScales(AmbiScaling scaletype) noexcept
  115. {
  116. switch(scaletype)
  117. {
  118. case AmbiScaling::FuMa: return al::span{AmbiScale::FromFuMa};
  119. case AmbiScaling::SN3D: return al::span{AmbiScale::FromSN3D};
  120. case AmbiScaling::UHJ: return al::span{AmbiScale::FromUHJ};
  121. case AmbiScaling::N3D: break;
  122. }
  123. return al::span{AmbiScale::FromN3D};
  124. }
  125. constexpr auto GetAmbiLayout(AmbiLayout layouttype) noexcept
  126. {
  127. if(layouttype == AmbiLayout::FuMa) return al::span{AmbiIndex::FromFuMa};
  128. return al::span{AmbiIndex::FromACN};
  129. }
  130. constexpr auto GetAmbi2DLayout(AmbiLayout layouttype) noexcept
  131. {
  132. if(layouttype == AmbiLayout::FuMa) return al::span{AmbiIndex::FromFuMa2D};
  133. return al::span{AmbiIndex::FromACN2D};
  134. }
  135. constexpr float sin30{0.5f};
  136. constexpr float cos30{0.866025403785f};
  137. constexpr float sin45{al::numbers::sqrt2_v<float>*0.5f};
  138. constexpr float cos45{al::numbers::sqrt2_v<float>*0.5f};
  139. constexpr float sin110{ 0.939692620786f};
  140. constexpr float cos110{-0.342020143326f};
  141. struct ChanPosMap {
  142. Channel channel;
  143. std::array<float,3> pos;
  144. };
  145. using complex_f = std::complex<float>;
  146. constexpr size_t ConvolveUpdateSize{256};
  147. constexpr size_t ConvolveUpdateSamples{ConvolveUpdateSize / 2};
  148. void apply_fir(al::span<float> dst, const al::span<const float> input, const al::span<const float,ConvolveUpdateSamples> filter)
  149. {
  150. auto src = input.begin();
  151. #ifdef HAVE_SSE_INTRINSICS
  152. std::generate(dst.begin(), dst.end(), [&src,filter]
  153. {
  154. __m128 r4{_mm_setzero_ps()};
  155. for(size_t j{0};j < ConvolveUpdateSamples;j+=4)
  156. {
  157. const __m128 coeffs{_mm_load_ps(&filter[j])};
  158. const __m128 s{_mm_loadu_ps(&src[j])};
  159. r4 = _mm_add_ps(r4, _mm_mul_ps(s, coeffs));
  160. }
  161. ++src;
  162. r4 = _mm_add_ps(r4, _mm_shuffle_ps(r4, r4, _MM_SHUFFLE(0, 1, 2, 3)));
  163. r4 = _mm_add_ps(r4, _mm_movehl_ps(r4, r4));
  164. return _mm_cvtss_f32(r4);
  165. });
  166. #elif defined(HAVE_NEON)
  167. std::generate(dst.begin(), dst.end(), [&src,filter]
  168. {
  169. float32x4_t r4{vdupq_n_f32(0.0f)};
  170. for(size_t j{0};j < ConvolveUpdateSamples;j+=4)
  171. r4 = vmlaq_f32(r4, vld1q_f32(&src[j]), vld1q_f32(&filter[j]));
  172. ++src;
  173. r4 = vaddq_f32(r4, vrev64q_f32(r4));
  174. return vget_lane_f32(vadd_f32(vget_low_f32(r4), vget_high_f32(r4)), 0);
  175. });
  176. #else
  177. std::generate(dst.begin(), dst.end(), [&src,filter]
  178. {
  179. float ret{0.0f};
  180. for(size_t j{0};j < ConvolveUpdateSamples;++j)
  181. ret += src[j] * filter[j];
  182. ++src;
  183. return ret;
  184. });
  185. #endif
  186. }
  187. struct ConvolutionState final : public EffectState {
  188. FmtChannels mChannels{};
  189. AmbiLayout mAmbiLayout{};
  190. AmbiScaling mAmbiScaling{};
  191. uint mAmbiOrder{};
  192. size_t mFifoPos{0};
  193. alignas(16) std::array<float,ConvolveUpdateSamples*2> mInput{};
  194. al::vector<std::array<float,ConvolveUpdateSamples>,16> mFilter;
  195. al::vector<std::array<float,ConvolveUpdateSamples*2>,16> mOutput;
  196. PFFFTSetup mFft{};
  197. alignas(16) std::array<float,ConvolveUpdateSize> mFftBuffer{};
  198. alignas(16) std::array<float,ConvolveUpdateSize> mFftWorkBuffer{};
  199. size_t mCurrentSegment{0};
  200. size_t mNumConvolveSegs{0};
  201. struct ChannelData {
  202. alignas(16) FloatBufferLine mBuffer{};
  203. float mHfScale{}, mLfScale{};
  204. BandSplitter mFilter{};
  205. std::array<float,MaxOutputChannels> Current{};
  206. std::array<float,MaxOutputChannels> Target{};
  207. };
  208. std::vector<ChannelData> mChans;
  209. al::vector<float,16> mComplexData;
  210. ConvolutionState() = default;
  211. ~ConvolutionState() override = default;
  212. void NormalMix(const al::span<FloatBufferLine> samplesOut, const size_t samplesToDo);
  213. void UpsampleMix(const al::span<FloatBufferLine> samplesOut, const size_t samplesToDo);
  214. void (ConvolutionState::*mMix)(const al::span<FloatBufferLine>,const size_t)
  215. {&ConvolutionState::NormalMix};
  216. void deviceUpdate(const DeviceBase *device, const BufferStorage *buffer) override;
  217. void update(const ContextBase *context, const EffectSlot *slot, const EffectProps *props,
  218. const EffectTarget target) override;
  219. void process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn,
  220. const al::span<FloatBufferLine> samplesOut) override;
  221. };
  222. void ConvolutionState::NormalMix(const al::span<FloatBufferLine> samplesOut,
  223. const size_t samplesToDo)
  224. {
  225. for(auto &chan : mChans)
  226. MixSamples(al::span{chan.mBuffer}.first(samplesToDo), samplesOut, chan.Current,
  227. chan.Target, samplesToDo, 0);
  228. }
  229. void ConvolutionState::UpsampleMix(const al::span<FloatBufferLine> samplesOut,
  230. const size_t samplesToDo)
  231. {
  232. for(auto &chan : mChans)
  233. {
  234. const auto src = al::span{chan.mBuffer}.first(samplesToDo);
  235. chan.mFilter.processScale(src, chan.mHfScale, chan.mLfScale);
  236. MixSamples(src, samplesOut, chan.Current, chan.Target, samplesToDo, 0);
  237. }
  238. }
  239. void ConvolutionState::deviceUpdate(const DeviceBase *device, const BufferStorage *buffer)
  240. {
  241. using UhjDecoderType = UhjDecoder<512>;
  242. static constexpr auto DecoderPadding = UhjDecoderType::sInputPadding;
  243. static constexpr uint MaxConvolveAmbiOrder{1u};
  244. if(!mFft)
  245. mFft = PFFFTSetup{ConvolveUpdateSize, PFFFT_REAL};
  246. mFifoPos = 0;
  247. mInput.fill(0.0f);
  248. decltype(mFilter){}.swap(mFilter);
  249. decltype(mOutput){}.swap(mOutput);
  250. mFftBuffer.fill(0.0f);
  251. mFftWorkBuffer.fill(0.0f);
  252. mCurrentSegment = 0;
  253. mNumConvolveSegs = 0;
  254. decltype(mChans){}.swap(mChans);
  255. decltype(mComplexData){}.swap(mComplexData);
  256. /* An empty buffer doesn't need a convolution filter. */
  257. if(!buffer || buffer->mSampleLen < 1) return;
  258. mChannels = buffer->mChannels;
  259. mAmbiLayout = IsUHJ(mChannels) ? AmbiLayout::FuMa : buffer->mAmbiLayout;
  260. mAmbiScaling = IsUHJ(mChannels) ? AmbiScaling::UHJ : buffer->mAmbiScaling;
  261. mAmbiOrder = std::min(buffer->mAmbiOrder, MaxConvolveAmbiOrder);
  262. const auto realChannels = buffer->channelsFromFmt();
  263. const auto numChannels = (mChannels == FmtUHJ2) ? 3u : ChannelsFromFmt(mChannels, mAmbiOrder);
  264. mChans.resize(numChannels);
  265. /* The impulse response needs to have the same sample rate as the input and
  266. * output. The bsinc24 resampler is decent, but there is high-frequency
  267. * attenuation that some people may be able to pick up on. Since this is
  268. * called very infrequently, go ahead and use the polyphase resampler.
  269. */
  270. PPhaseResampler resampler;
  271. if(device->Frequency != buffer->mSampleRate)
  272. resampler.init(buffer->mSampleRate, device->Frequency);
  273. const auto resampledCount = static_cast<uint>(
  274. (uint64_t{buffer->mSampleLen}*device->Frequency+(buffer->mSampleRate-1)) /
  275. buffer->mSampleRate);
  276. const BandSplitter splitter{device->mXOverFreq / static_cast<float>(device->Frequency)};
  277. for(auto &e : mChans)
  278. e.mFilter = splitter;
  279. mFilter.resize(numChannels, {});
  280. mOutput.resize(numChannels, {});
  281. /* Calculate the number of segments needed to hold the impulse response and
  282. * the input history (rounded up), and allocate them. Exclude one segment
  283. * which gets applied as a time-domain FIR filter. Make sure at least one
  284. * segment is allocated to simplify handling.
  285. */
  286. mNumConvolveSegs = (resampledCount+(ConvolveUpdateSamples-1)) / ConvolveUpdateSamples;
  287. mNumConvolveSegs = std::max(mNumConvolveSegs, 2_uz) - 1_uz;
  288. const size_t complex_length{mNumConvolveSegs * ConvolveUpdateSize * (numChannels+1)};
  289. mComplexData.resize(complex_length, 0.0f);
  290. /* Load the samples from the buffer. */
  291. const size_t srclinelength{RoundUp(buffer->mSampleLen+DecoderPadding, 16)};
  292. auto srcsamples = std::vector<float>(srclinelength * numChannels);
  293. std::fill(srcsamples.begin(), srcsamples.end(), 0.0f);
  294. for(size_t c{0};c < numChannels && c < realChannels;++c)
  295. LoadSamples(al::span{srcsamples}.subspan(srclinelength*c, buffer->mSampleLen),
  296. buffer->mData.data(), c, realChannels, buffer->mType);
  297. if(IsUHJ(mChannels))
  298. {
  299. auto decoder = std::make_unique<UhjDecoderType>();
  300. std::array<float*,4> samples{};
  301. for(size_t c{0};c < numChannels;++c)
  302. samples[c] = al::to_address(srcsamples.begin() + ptrdiff_t(srclinelength*c));
  303. decoder->decode({samples.data(), numChannels}, buffer->mSampleLen, buffer->mSampleLen);
  304. }
  305. auto ressamples = std::vector<double>(buffer->mSampleLen + (resampler ? resampledCount : 0));
  306. auto ffttmp = al::vector<float,16>(ConvolveUpdateSize);
  307. auto fftbuffer = std::vector<std::complex<double>>(ConvolveUpdateSize);
  308. auto filteriter = mComplexData.begin() + ptrdiff_t(mNumConvolveSegs*ConvolveUpdateSize);
  309. for(size_t c{0};c < numChannels;++c)
  310. {
  311. auto bufsamples = al::span{srcsamples}.subspan(srclinelength*c, buffer->mSampleLen);
  312. /* Resample to match the device. */
  313. if(resampler)
  314. {
  315. auto restmp = al::span{ressamples}.subspan(resampledCount, buffer->mSampleLen);
  316. std::copy(bufsamples.cbegin(), bufsamples.cend(), restmp.begin());
  317. resampler.process(restmp, al::span{ressamples}.first(resampledCount));
  318. }
  319. else
  320. std::copy(bufsamples.cbegin(), bufsamples.cend(), ressamples.begin());
  321. /* Store the first segment's samples in reverse in the time-domain, to
  322. * apply as a FIR filter.
  323. */
  324. const size_t first_size{std::min(size_t{resampledCount}, ConvolveUpdateSamples)};
  325. auto sampleseg = al::span{ressamples.cbegin(), first_size};
  326. std::transform(sampleseg.cbegin(), sampleseg.cend(), mFilter[c].rbegin(),
  327. [](const double d) noexcept -> float { return static_cast<float>(d); });
  328. size_t done{first_size};
  329. for(size_t s{0};s < mNumConvolveSegs;++s)
  330. {
  331. const size_t todo{std::min(resampledCount-done, ConvolveUpdateSamples)};
  332. sampleseg = al::span{ressamples}.subspan(done, todo);
  333. /* Apply a double-precision forward FFT for more precise frequency
  334. * measurements.
  335. */
  336. auto iter = std::copy(sampleseg.cbegin(), sampleseg.cend(), fftbuffer.begin());
  337. done += todo;
  338. std::fill(iter, fftbuffer.end(), std::complex<double>{});
  339. forward_fft(al::span{fftbuffer});
  340. /* Convert to, and pack in, a float buffer for PFFFT. Note that the
  341. * first bin stores the real component of the half-frequency bin in
  342. * the imaginary component. Also scale the FFT by its length so the
  343. * iFFT'd output will be normalized.
  344. */
  345. static constexpr float fftscale{1.0f / float{ConvolveUpdateSize}};
  346. for(size_t i{0};i < ConvolveUpdateSamples;++i)
  347. {
  348. ffttmp[i*2 ] = static_cast<float>(fftbuffer[i].real()) * fftscale;
  349. ffttmp[i*2 + 1] = static_cast<float>((i == 0) ?
  350. fftbuffer[ConvolveUpdateSamples].real() : fftbuffer[i].imag()) * fftscale;
  351. }
  352. /* Reorder backward to make it suitable for pffft_zconvolve and the
  353. * subsequent pffft_transform(..., PFFFT_BACKWARD).
  354. */
  355. mFft.zreorder(ffttmp.data(), al::to_address(filteriter), PFFFT_BACKWARD);
  356. filteriter += ConvolveUpdateSize;
  357. }
  358. }
  359. }
  360. void ConvolutionState::update(const ContextBase *context, const EffectSlot *slot,
  361. const EffectProps *props_, const EffectTarget target)
  362. {
  363. /* TODO: LFE is not mixed to output. This will require each buffer channel
  364. * to have its own output target since the main mixing buffer won't have an
  365. * LFE channel (due to being B-Format).
  366. */
  367. static constexpr std::array MonoMap{
  368. ChanPosMap{FrontCenter, std::array{0.0f, 0.0f, -1.0f}}
  369. };
  370. static constexpr std::array StereoMap{
  371. ChanPosMap{FrontLeft, std::array{-sin30, 0.0f, -cos30}},
  372. ChanPosMap{FrontRight, std::array{ sin30, 0.0f, -cos30}},
  373. };
  374. static constexpr std::array RearMap{
  375. ChanPosMap{BackLeft, std::array{-sin30, 0.0f, cos30}},
  376. ChanPosMap{BackRight, std::array{ sin30, 0.0f, cos30}},
  377. };
  378. static constexpr std::array QuadMap{
  379. ChanPosMap{FrontLeft, std::array{-sin45, 0.0f, -cos45}},
  380. ChanPosMap{FrontRight, std::array{ sin45, 0.0f, -cos45}},
  381. ChanPosMap{BackLeft, std::array{-sin45, 0.0f, cos45}},
  382. ChanPosMap{BackRight, std::array{ sin45, 0.0f, cos45}},
  383. };
  384. static constexpr std::array X51Map{
  385. ChanPosMap{FrontLeft, std::array{-sin30, 0.0f, -cos30}},
  386. ChanPosMap{FrontRight, std::array{ sin30, 0.0f, -cos30}},
  387. ChanPosMap{FrontCenter, std::array{ 0.0f, 0.0f, -1.0f}},
  388. ChanPosMap{LFE, {}},
  389. ChanPosMap{SideLeft, std::array{-sin110, 0.0f, -cos110}},
  390. ChanPosMap{SideRight, std::array{ sin110, 0.0f, -cos110}},
  391. };
  392. static constexpr std::array X61Map{
  393. ChanPosMap{FrontLeft, std::array{-sin30, 0.0f, -cos30}},
  394. ChanPosMap{FrontRight, std::array{ sin30, 0.0f, -cos30}},
  395. ChanPosMap{FrontCenter, std::array{ 0.0f, 0.0f, -1.0f}},
  396. ChanPosMap{LFE, {}},
  397. ChanPosMap{BackCenter, std::array{ 0.0f, 0.0f, 1.0f} },
  398. ChanPosMap{SideLeft, std::array{-1.0f, 0.0f, 0.0f} },
  399. ChanPosMap{SideRight, std::array{ 1.0f, 0.0f, 0.0f} },
  400. };
  401. static constexpr std::array X71Map{
  402. ChanPosMap{FrontLeft, std::array{-sin30, 0.0f, -cos30}},
  403. ChanPosMap{FrontRight, std::array{ sin30, 0.0f, -cos30}},
  404. ChanPosMap{FrontCenter, std::array{ 0.0f, 0.0f, -1.0f}},
  405. ChanPosMap{LFE, {}},
  406. ChanPosMap{BackLeft, std::array{-sin30, 0.0f, cos30}},
  407. ChanPosMap{BackRight, std::array{ sin30, 0.0f, cos30}},
  408. ChanPosMap{SideLeft, std::array{ -1.0f, 0.0f, 0.0f}},
  409. ChanPosMap{SideRight, std::array{ 1.0f, 0.0f, 0.0f}},
  410. };
  411. if(mNumConvolveSegs < 1) UNLIKELY
  412. return;
  413. auto &props = std::get<ConvolutionProps>(*props_);
  414. mMix = &ConvolutionState::NormalMix;
  415. for(auto &chan : mChans)
  416. std::fill(chan.Target.begin(), chan.Target.end(), 0.0f);
  417. const float gain{slot->Gain};
  418. if(IsAmbisonic(mChannels))
  419. {
  420. DeviceBase *device{context->mDevice};
  421. if(mChannels == FmtUHJ2 && !device->mUhjEncoder)
  422. {
  423. mMix = &ConvolutionState::UpsampleMix;
  424. mChans[0].mHfScale = 1.0f;
  425. mChans[0].mLfScale = DecoderBase::sWLFScale;
  426. mChans[1].mHfScale = 1.0f;
  427. mChans[1].mLfScale = DecoderBase::sXYLFScale;
  428. mChans[2].mHfScale = 1.0f;
  429. mChans[2].mLfScale = DecoderBase::sXYLFScale;
  430. }
  431. else if(device->mAmbiOrder > mAmbiOrder)
  432. {
  433. mMix = &ConvolutionState::UpsampleMix;
  434. const auto scales = AmbiScale::GetHFOrderScales(mAmbiOrder, device->mAmbiOrder,
  435. device->m2DMixing);
  436. mChans[0].mHfScale = scales[0];
  437. mChans[0].mLfScale = 1.0f;
  438. for(size_t i{1};i < mChans.size();++i)
  439. {
  440. mChans[i].mHfScale = scales[1];
  441. mChans[i].mLfScale = 1.0f;
  442. }
  443. }
  444. mOutTarget = target.Main->Buffer;
  445. alu::Vector N{props.OrientAt[0], props.OrientAt[1], props.OrientAt[2], 0.0f};
  446. N.normalize();
  447. alu::Vector V{props.OrientUp[0], props.OrientUp[1], props.OrientUp[2], 0.0f};
  448. V.normalize();
  449. /* Build and normalize right-vector */
  450. alu::Vector U{N.cross_product(V)};
  451. U.normalize();
  452. const std::array mixmatrix{
  453. std::array{1.0f, 0.0f, 0.0f, 0.0f},
  454. std::array{0.0f, U[0], -U[1], U[2]},
  455. std::array{0.0f, -V[0], V[1], -V[2]},
  456. std::array{0.0f, -N[0], N[1], -N[2]},
  457. };
  458. const auto scales = GetAmbiScales(mAmbiScaling);
  459. const auto index_map = Is2DAmbisonic(mChannels) ?
  460. al::span{GetAmbi2DLayout(mAmbiLayout)}.subspan(0) :
  461. al::span{GetAmbiLayout(mAmbiLayout)}.subspan(0);
  462. std::array<float,MaxAmbiChannels> coeffs{};
  463. for(size_t c{0u};c < mChans.size();++c)
  464. {
  465. const size_t acn{index_map[c]};
  466. const float scale{scales[acn]};
  467. std::transform(mixmatrix[acn].cbegin(), mixmatrix[acn].cend(), coeffs.begin(),
  468. [scale](const float in) noexcept -> float { return in * scale; });
  469. ComputePanGains(target.Main, coeffs, gain, mChans[c].Target);
  470. }
  471. }
  472. else
  473. {
  474. DeviceBase *device{context->mDevice};
  475. al::span<const ChanPosMap> chanmap{};
  476. switch(mChannels)
  477. {
  478. case FmtMono: chanmap = MonoMap; break;
  479. case FmtMonoDup: chanmap = MonoMap; break;
  480. case FmtSuperStereo:
  481. case FmtStereo: chanmap = StereoMap; break;
  482. case FmtRear: chanmap = RearMap; break;
  483. case FmtQuad: chanmap = QuadMap; break;
  484. case FmtX51: chanmap = X51Map; break;
  485. case FmtX61: chanmap = X61Map; break;
  486. case FmtX71: chanmap = X71Map; break;
  487. case FmtBFormat2D:
  488. case FmtBFormat3D:
  489. case FmtUHJ2:
  490. case FmtUHJ3:
  491. case FmtUHJ4:
  492. break;
  493. }
  494. mOutTarget = target.Main->Buffer;
  495. if(device->mRenderMode == RenderMode::Pairwise)
  496. {
  497. /* Scales the azimuth of the given vector by 3 if it's in front.
  498. * Effectively scales +/-30 degrees to +/-90 degrees, leaving > +90
  499. * and < -90 alone.
  500. */
  501. auto ScaleAzimuthFront = [](std::array<float,3> pos) -> std::array<float,3>
  502. {
  503. if(pos[2] < 0.0f)
  504. {
  505. /* Normalize the length of the x,z components for a 2D
  506. * vector of the azimuth angle. Negate Z since {0,0,-1} is
  507. * angle 0.
  508. */
  509. const float len2d{std::sqrt(pos[0]*pos[0] + pos[2]*pos[2])};
  510. float x{pos[0] / len2d};
  511. float z{-pos[2] / len2d};
  512. /* Z > cos(pi/6) = -30 < azimuth < 30 degrees. */
  513. if(z > cos30)
  514. {
  515. /* Triple the angle represented by x,z. */
  516. x = x*3.0f - x*x*x*4.0f;
  517. z = z*z*z*4.0f - z*3.0f;
  518. /* Scale the vector back to fit in 3D. */
  519. pos[0] = x * len2d;
  520. pos[2] = -z * len2d;
  521. }
  522. else
  523. {
  524. /* If azimuth >= 30 degrees, clamp to 90 degrees. */
  525. pos[0] = std::copysign(len2d, pos[0]);
  526. pos[2] = 0.0f;
  527. }
  528. }
  529. return pos;
  530. };
  531. for(size_t i{0};i < chanmap.size();++i)
  532. {
  533. if(chanmap[i].channel == LFE) continue;
  534. const auto coeffs = CalcDirectionCoeffs(ScaleAzimuthFront(chanmap[i].pos), 0.0f);
  535. ComputePanGains(target.Main, coeffs, gain, mChans[i].Target);
  536. }
  537. }
  538. else for(size_t i{0};i < chanmap.size();++i)
  539. {
  540. if(chanmap[i].channel == LFE) continue;
  541. const auto coeffs = CalcDirectionCoeffs(chanmap[i].pos, 0.0f);
  542. ComputePanGains(target.Main, coeffs, gain, mChans[i].Target);
  543. }
  544. }
  545. }
  546. void ConvolutionState::process(const size_t samplesToDo,
  547. const al::span<const FloatBufferLine> samplesIn, const al::span<FloatBufferLine> samplesOut)
  548. {
  549. if(mNumConvolveSegs < 1) UNLIKELY
  550. return;
  551. size_t curseg{mCurrentSegment};
  552. for(size_t base{0u};base < samplesToDo;)
  553. {
  554. const size_t todo{std::min(ConvolveUpdateSamples-mFifoPos, samplesToDo-base)};
  555. std::copy_n(samplesIn[0].begin() + ptrdiff_t(base), todo,
  556. mInput.begin()+ptrdiff_t(ConvolveUpdateSamples+mFifoPos));
  557. /* Apply the FIR for the newly retrieved input samples, and combine it
  558. * with the inverse FFT'd output samples.
  559. */
  560. for(size_t c{0};c < mChans.size();++c)
  561. {
  562. auto outspan = al::span{mChans[c].mBuffer}.subspan(base, todo);
  563. apply_fir(outspan, al::span{mInput}.subspan(1+mFifoPos), mFilter[c]);
  564. auto fifospan = al::span{mOutput[c]}.subspan(mFifoPos, todo);
  565. std::transform(fifospan.cbegin(), fifospan.cend(), outspan.cbegin(), outspan.begin(),
  566. std::plus{});
  567. }
  568. mFifoPos += todo;
  569. base += todo;
  570. /* Check whether the input buffer is filled with new samples. */
  571. if(mFifoPos < ConvolveUpdateSamples) break;
  572. mFifoPos = 0;
  573. /* Move the newest input to the front for the next iteration's history. */
  574. std::copy(mInput.cbegin()+ConvolveUpdateSamples, mInput.cend(), mInput.begin());
  575. std::fill(mInput.begin()+ConvolveUpdateSamples, mInput.end(), 0.0f);
  576. /* Calculate the frequency-domain response and add the relevant
  577. * frequency bins to the FFT history.
  578. */
  579. mFft.transform(mInput.data(), &mComplexData[curseg*ConvolveUpdateSize],
  580. mFftWorkBuffer.data(), PFFFT_FORWARD);
  581. auto filter = mComplexData.cbegin() + ptrdiff_t(mNumConvolveSegs*ConvolveUpdateSize);
  582. for(size_t c{0};c < mChans.size();++c)
  583. {
  584. /* Convolve each input segment with its IR filter counterpart
  585. * (aligned in time).
  586. */
  587. mFftBuffer.fill(0.0f);
  588. auto input = mComplexData.cbegin() + ptrdiff_t(curseg*ConvolveUpdateSize);
  589. for(size_t s{curseg};s < mNumConvolveSegs;++s)
  590. {
  591. mFft.zconvolve_accumulate(al::to_address(input), al::to_address(filter),
  592. mFftBuffer.data());
  593. input += ConvolveUpdateSize;
  594. filter += ConvolveUpdateSize;
  595. }
  596. input = mComplexData.cbegin();
  597. for(size_t s{0};s < curseg;++s)
  598. {
  599. mFft.zconvolve_accumulate(al::to_address(input), al::to_address(filter),
  600. mFftBuffer.data());
  601. input += ConvolveUpdateSize;
  602. filter += ConvolveUpdateSize;
  603. }
  604. /* Apply iFFT to get the 256 (really 255) samples for output. The
  605. * 128 output samples are combined with the last output's 127
  606. * second-half samples (and this output's second half is
  607. * subsequently saved for next time).
  608. */
  609. mFft.transform(mFftBuffer.data(), mFftBuffer.data(), mFftWorkBuffer.data(),
  610. PFFFT_BACKWARD);
  611. /* The filter was attenuated, so the response is already scaled. */
  612. std::transform(mFftBuffer.cbegin(), mFftBuffer.cbegin()+ConvolveUpdateSamples,
  613. mOutput[c].cbegin()+ConvolveUpdateSamples, mOutput[c].begin(), std::plus{});
  614. std::copy(mFftBuffer.cbegin()+ConvolveUpdateSamples, mFftBuffer.cend(),
  615. mOutput[c].begin()+ConvolveUpdateSamples);
  616. }
  617. /* Shift the input history. */
  618. curseg = curseg ? (curseg-1) : (mNumConvolveSegs-1);
  619. }
  620. mCurrentSegment = curseg;
  621. /* Finally, mix to the output. */
  622. (this->*mMix)(samplesOut, samplesToDo);
  623. }
  624. struct ConvolutionStateFactory final : public EffectStateFactory {
  625. al::intrusive_ptr<EffectState> create() override
  626. { return al::intrusive_ptr<EffectState>{new ConvolutionState{}}; }
  627. };
  628. } // namespace
  629. EffectStateFactory *ConvolutionStateFactory_getFactory()
  630. {
  631. static ConvolutionStateFactory ConvolutionFactory{};
  632. return &ConvolutionFactory;
  633. }