convolution.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. #include "config.h"
  2. #include <stdint.h>
  3. #ifdef HAVE_SSE_INTRINSICS
  4. #include <xmmintrin.h>
  5. #elif defined(HAVE_NEON)
  6. #include <arm_neon.h>
  7. #endif
  8. #include "alcmain.h"
  9. #include "alcomplex.h"
  10. #include "alcontext.h"
  11. #include "almalloc.h"
  12. #include "alspan.h"
  13. #include "bformatdec.h"
  14. #include "buffer_storage.h"
  15. #include "core/ambidefs.h"
  16. #include "core/filters/splitter.h"
  17. #include "core/fmt_traits.h"
  18. #include "core/logging.h"
  19. #include "effects/base.h"
  20. #include "effectslot.h"
  21. #include "math_defs.h"
  22. #include "polyphase_resampler.h"
  23. namespace {
  24. /* Convolution reverb is implemented using a segmented overlap-add method. The
  25. * impulse response is broken up into multiple segments of 128 samples, and
  26. * each segment has an FFT applied with a 256-sample buffer (the latter half
  27. * left silent) to get its frequency-domain response. The resulting response
  28. * has its positive/non-mirrored frequencies saved (129 bins) in each segment.
  29. *
  30. * Input samples are similarly broken up into 128-sample segments, with an FFT
  31. * applied to each new incoming segment to get its 129 bins. A history of FFT'd
  32. * input segments is maintained, equal to the length of the impulse response.
  33. *
  34. * To apply the reverberation, each impulse response segment is convolved with
  35. * its paired input segment (using complex multiplies, far cheaper than FIRs),
  36. * accumulating into a 256-bin FFT buffer. The input history is then shifted to
  37. * align with later impulse response segments for next time.
  38. *
  39. * An inverse FFT is then applied to the accumulated FFT buffer to get a 256-
  40. * sample time-domain response for output, which is split in two halves. The
  41. * first half is the 128-sample output, and the second half is a 128-sample
  42. * (really, 127) delayed extension, which gets added to the output next time.
  43. * Convolving two time-domain responses of lengths N and M results in a time-
  44. * domain signal of length N+M-1, and this holds true regardless of the
  45. * convolution being applied in the frequency domain, so these "overflow"
  46. * samples need to be accounted for.
  47. *
  48. * To avoid a delay with gathering enough input samples to apply an FFT with,
  49. * the first segment is applied directly in the time-domain as the samples come
  50. * in. Once enough have been retrieved, the FFT is applied on the input and
  51. * it's paired with the remaining (FFT'd) filter segments for processing.
  52. */
  53. void LoadSamples(double *RESTRICT dst, const al::byte *src, const size_t srcstep, FmtType srctype,
  54. const size_t samples) noexcept
  55. {
  56. #define HANDLE_FMT(T) case T: al::LoadSampleArray<T>(dst, src, srcstep, samples); break
  57. switch(srctype)
  58. {
  59. HANDLE_FMT(FmtUByte);
  60. HANDLE_FMT(FmtShort);
  61. HANDLE_FMT(FmtFloat);
  62. HANDLE_FMT(FmtDouble);
  63. HANDLE_FMT(FmtMulaw);
  64. HANDLE_FMT(FmtAlaw);
  65. }
  66. #undef HANDLE_FMT
  67. }
  68. inline auto& GetAmbiScales(AmbiScaling scaletype) noexcept
  69. {
  70. if(scaletype == AmbiScaling::FuMa) return AmbiScale::FromFuMa();
  71. if(scaletype == AmbiScaling::SN3D) return AmbiScale::FromSN3D();
  72. return AmbiScale::FromN3D();
  73. }
  74. inline auto& GetAmbiLayout(AmbiLayout layouttype) noexcept
  75. {
  76. if(layouttype == AmbiLayout::FuMa) return AmbiIndex::FromFuMa();
  77. return AmbiIndex::FromACN();
  78. }
  79. inline auto& GetAmbi2DLayout(AmbiLayout layouttype) noexcept
  80. {
  81. if(layouttype == AmbiLayout::FuMa) return AmbiIndex::FromFuMa2D();
  82. return AmbiIndex::FromACN2D();
  83. }
  84. struct ChanMap {
  85. Channel channel;
  86. float angle;
  87. float elevation;
  88. };
  89. using complex_d = std::complex<double>;
  90. constexpr size_t ConvolveUpdateSize{256};
  91. constexpr size_t ConvolveUpdateSamples{ConvolveUpdateSize / 2};
  92. void apply_fir(al::span<float> dst, const float *RESTRICT src, const float *RESTRICT filter)
  93. {
  94. #ifdef HAVE_SSE_INTRINSICS
  95. for(float &output : dst)
  96. {
  97. __m128 r4{_mm_setzero_ps()};
  98. for(size_t j{0};j < ConvolveUpdateSamples;j+=4)
  99. {
  100. const __m128 coeffs{_mm_load_ps(&filter[j])};
  101. const __m128 s{_mm_loadu_ps(&src[j])};
  102. r4 = _mm_add_ps(r4, _mm_mul_ps(s, coeffs));
  103. }
  104. r4 = _mm_add_ps(r4, _mm_shuffle_ps(r4, r4, _MM_SHUFFLE(0, 1, 2, 3)));
  105. r4 = _mm_add_ps(r4, _mm_movehl_ps(r4, r4));
  106. output = _mm_cvtss_f32(r4);
  107. ++src;
  108. }
  109. #elif defined(HAVE_NEON)
  110. for(float &output : dst)
  111. {
  112. float32x4_t r4{vdupq_n_f32(0.0f)};
  113. for(size_t j{0};j < ConvolveUpdateSamples;j+=4)
  114. r4 = vmlaq_f32(r4, vld1q_f32(&src[j]), vld1q_f32(&filter[j]));
  115. r4 = vaddq_f32(r4, vrev64q_f32(r4));
  116. output = vget_lane_f32(vadd_f32(vget_low_f32(r4), vget_high_f32(r4)), 0);
  117. ++src;
  118. }
  119. #else
  120. for(float &output : dst)
  121. {
  122. float ret{0.0f};
  123. for(size_t j{0};j < ConvolveUpdateSamples;++j)
  124. ret += src[j] * filter[j];
  125. output = ret;
  126. ++src;
  127. }
  128. #endif
  129. }
  130. struct ConvolutionState final : public EffectState {
  131. FmtChannels mChannels{};
  132. AmbiLayout mAmbiLayout{};
  133. AmbiScaling mAmbiScaling{};
  134. uint mAmbiOrder{};
  135. size_t mFifoPos{0};
  136. std::array<float,ConvolveUpdateSamples*2> mInput{};
  137. al::vector<std::array<float,ConvolveUpdateSamples>,16> mFilter;
  138. al::vector<std::array<float,ConvolveUpdateSamples*2>,16> mOutput;
  139. alignas(16) std::array<complex_d,ConvolveUpdateSize> mFftBuffer{};
  140. size_t mCurrentSegment{0};
  141. size_t mNumConvolveSegs{0};
  142. struct ChannelData {
  143. alignas(16) FloatBufferLine mBuffer{};
  144. float mHfScale{};
  145. BandSplitter mFilter{};
  146. float Current[MAX_OUTPUT_CHANNELS]{};
  147. float Target[MAX_OUTPUT_CHANNELS]{};
  148. };
  149. using ChannelDataArray = al::FlexArray<ChannelData>;
  150. std::unique_ptr<ChannelDataArray> mChans;
  151. std::unique_ptr<complex_d[]> mComplexData;
  152. ConvolutionState() = default;
  153. ~ConvolutionState() override = default;
  154. void NormalMix(const al::span<FloatBufferLine> samplesOut, const size_t samplesToDo);
  155. void UpsampleMix(const al::span<FloatBufferLine> samplesOut, const size_t samplesToDo);
  156. void (ConvolutionState::*mMix)(const al::span<FloatBufferLine>,const size_t)
  157. {&ConvolutionState::NormalMix};
  158. void deviceUpdate(const ALCdevice *device, const Buffer &buffer) override;
  159. void update(const ALCcontext *context, const EffectSlot *slot, const EffectProps *props,
  160. const EffectTarget target) override;
  161. void process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn,
  162. const al::span<FloatBufferLine> samplesOut) override;
  163. DEF_NEWDEL(ConvolutionState)
  164. };
  165. void ConvolutionState::NormalMix(const al::span<FloatBufferLine> samplesOut,
  166. const size_t samplesToDo)
  167. {
  168. for(auto &chan : *mChans)
  169. MixSamples({chan.mBuffer.data(), samplesToDo}, samplesOut, chan.Current, chan.Target,
  170. samplesToDo, 0);
  171. }
  172. void ConvolutionState::UpsampleMix(const al::span<FloatBufferLine> samplesOut,
  173. const size_t samplesToDo)
  174. {
  175. for(auto &chan : *mChans)
  176. {
  177. const al::span<float> src{chan.mBuffer.data(), samplesToDo};
  178. chan.mFilter.processHfScale(src, chan.mHfScale);
  179. MixSamples(src, samplesOut, chan.Current, chan.Target, samplesToDo, 0);
  180. }
  181. }
  182. void ConvolutionState::deviceUpdate(const ALCdevice *device, const Buffer &buffer)
  183. {
  184. constexpr uint MaxConvolveAmbiOrder{1u};
  185. mFifoPos = 0;
  186. mInput.fill(0.0f);
  187. decltype(mFilter){}.swap(mFilter);
  188. decltype(mOutput){}.swap(mOutput);
  189. mFftBuffer.fill(complex_d{});
  190. mCurrentSegment = 0;
  191. mNumConvolveSegs = 0;
  192. mChans = nullptr;
  193. mComplexData = nullptr;
  194. /* An empty buffer doesn't need a convolution filter. */
  195. if(!buffer.storage || buffer.storage->mSampleLen < 1) return;
  196. constexpr size_t m{ConvolveUpdateSize/2 + 1};
  197. auto bytesPerSample = BytesFromFmt(buffer.storage->mType);
  198. auto realChannels = ChannelsFromFmt(buffer.storage->mChannels, buffer.storage->mAmbiOrder);
  199. auto numChannels = ChannelsFromFmt(buffer.storage->mChannels,
  200. minu(buffer.storage->mAmbiOrder, MaxConvolveAmbiOrder));
  201. mChans = ChannelDataArray::Create(numChannels);
  202. /* The impulse response needs to have the same sample rate as the input and
  203. * output. The bsinc24 resampler is decent, but there is high-frequency
  204. * attenation that some people may be able to pick up on. Since this is
  205. * called very infrequently, go ahead and use the polyphase resampler.
  206. */
  207. PPhaseResampler resampler;
  208. if(device->Frequency != buffer.storage->mSampleRate)
  209. resampler.init(buffer.storage->mSampleRate, device->Frequency);
  210. const auto resampledCount = static_cast<uint>(
  211. (uint64_t{buffer.storage->mSampleLen}*device->Frequency+(buffer.storage->mSampleRate-1)) /
  212. buffer.storage->mSampleRate);
  213. const BandSplitter splitter{device->mXOverFreq / static_cast<float>(device->Frequency)};
  214. for(auto &e : *mChans)
  215. e.mFilter = splitter;
  216. mFilter.resize(numChannels, {});
  217. mOutput.resize(numChannels, {});
  218. /* Calculate the number of segments needed to hold the impulse response and
  219. * the input history (rounded up), and allocate them. Exclude one segment
  220. * which gets applied as a time-domain FIR filter. Make sure at least one
  221. * segment is allocated to simplify handling.
  222. */
  223. mNumConvolveSegs = (resampledCount+(ConvolveUpdateSamples-1)) / ConvolveUpdateSamples;
  224. mNumConvolveSegs = maxz(mNumConvolveSegs, 2) - 1;
  225. const size_t complex_length{mNumConvolveSegs * m * (numChannels+1)};
  226. mComplexData = std::make_unique<complex_d[]>(complex_length);
  227. std::fill_n(mComplexData.get(), complex_length, complex_d{});
  228. mChannels = buffer.storage->mChannels;
  229. mAmbiLayout = buffer.storage->mAmbiLayout;
  230. mAmbiScaling = buffer.storage->mAmbiScaling;
  231. mAmbiOrder = minu(buffer.storage->mAmbiOrder, MaxConvolveAmbiOrder);
  232. auto srcsamples = std::make_unique<double[]>(maxz(buffer.storage->mSampleLen, resampledCount));
  233. complex_d *filteriter = mComplexData.get() + mNumConvolveSegs*m;
  234. for(size_t c{0};c < numChannels;++c)
  235. {
  236. /* Load the samples from the buffer, and resample to match the device. */
  237. LoadSamples(srcsamples.get(), buffer.samples.data() + bytesPerSample*c, realChannels,
  238. buffer.storage->mType, buffer.storage->mSampleLen);
  239. if(device->Frequency != buffer.storage->mSampleRate)
  240. resampler.process(buffer.storage->mSampleLen, srcsamples.get(), resampledCount,
  241. srcsamples.get());
  242. /* Store the first segment's samples in reverse in the time-domain, to
  243. * apply as a FIR filter.
  244. */
  245. const size_t first_size{minz(resampledCount, ConvolveUpdateSamples)};
  246. std::transform(srcsamples.get(), srcsamples.get()+first_size, mFilter[c].rbegin(),
  247. [](const double d) noexcept -> float { return static_cast<float>(d); });
  248. size_t done{first_size};
  249. for(size_t s{0};s < mNumConvolveSegs;++s)
  250. {
  251. const size_t todo{minz(resampledCount-done, ConvolveUpdateSamples)};
  252. auto iter = std::copy_n(&srcsamples[done], todo, mFftBuffer.begin());
  253. done += todo;
  254. std::fill(iter, mFftBuffer.end(), complex_d{});
  255. forward_fft(mFftBuffer);
  256. filteriter = std::copy_n(mFftBuffer.cbegin(), m, filteriter);
  257. }
  258. }
  259. }
  260. void ConvolutionState::update(const ALCcontext *context, const EffectSlot *slot,
  261. const EffectProps* /*props*/, const EffectTarget target)
  262. {
  263. /* NOTE: Stereo and Rear are slightly different from normal mixing (as
  264. * defined in alu.cpp). These are 45 degrees from center, rather than the
  265. * 30 degrees used there.
  266. *
  267. * TODO: LFE is not mixed to output. This will require each buffer channel
  268. * to have its own output target since the main mixing buffer won't have an
  269. * LFE channel (due to being B-Format).
  270. */
  271. static const ChanMap MonoMap[1]{
  272. { FrontCenter, 0.0f, 0.0f }
  273. }, StereoMap[2]{
  274. { FrontLeft, Deg2Rad(-45.0f), Deg2Rad(0.0f) },
  275. { FrontRight, Deg2Rad( 45.0f), Deg2Rad(0.0f) }
  276. }, RearMap[2]{
  277. { BackLeft, Deg2Rad(-135.0f), Deg2Rad(0.0f) },
  278. { BackRight, Deg2Rad( 135.0f), Deg2Rad(0.0f) }
  279. }, QuadMap[4]{
  280. { FrontLeft, Deg2Rad( -45.0f), Deg2Rad(0.0f) },
  281. { FrontRight, Deg2Rad( 45.0f), Deg2Rad(0.0f) },
  282. { BackLeft, Deg2Rad(-135.0f), Deg2Rad(0.0f) },
  283. { BackRight, Deg2Rad( 135.0f), Deg2Rad(0.0f) }
  284. }, X51Map[6]{
  285. { FrontLeft, Deg2Rad( -30.0f), Deg2Rad(0.0f) },
  286. { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) },
  287. { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) },
  288. { LFE, 0.0f, 0.0f },
  289. { SideLeft, Deg2Rad(-110.0f), Deg2Rad(0.0f) },
  290. { SideRight, Deg2Rad( 110.0f), Deg2Rad(0.0f) }
  291. }, X61Map[7]{
  292. { FrontLeft, Deg2Rad(-30.0f), Deg2Rad(0.0f) },
  293. { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) },
  294. { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) },
  295. { LFE, 0.0f, 0.0f },
  296. { BackCenter, Deg2Rad(180.0f), Deg2Rad(0.0f) },
  297. { SideLeft, Deg2Rad(-90.0f), Deg2Rad(0.0f) },
  298. { SideRight, Deg2Rad( 90.0f), Deg2Rad(0.0f) }
  299. }, X71Map[8]{
  300. { FrontLeft, Deg2Rad( -30.0f), Deg2Rad(0.0f) },
  301. { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) },
  302. { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) },
  303. { LFE, 0.0f, 0.0f },
  304. { BackLeft, Deg2Rad(-150.0f), Deg2Rad(0.0f) },
  305. { BackRight, Deg2Rad( 150.0f), Deg2Rad(0.0f) },
  306. { SideLeft, Deg2Rad( -90.0f), Deg2Rad(0.0f) },
  307. { SideRight, Deg2Rad( 90.0f), Deg2Rad(0.0f) }
  308. };
  309. if(mNumConvolveSegs < 1)
  310. return;
  311. mMix = &ConvolutionState::NormalMix;
  312. for(auto &chan : *mChans)
  313. std::fill(std::begin(chan.Target), std::end(chan.Target), 0.0f);
  314. const float gain{slot->Gain};
  315. if(mChannels == FmtBFormat3D || mChannels == FmtBFormat2D)
  316. {
  317. ALCdevice *device{context->mDevice.get()};
  318. if(device->mAmbiOrder > mAmbiOrder)
  319. {
  320. mMix = &ConvolutionState::UpsampleMix;
  321. const auto scales = BFormatDec::GetHFOrderScales(mAmbiOrder, device->mAmbiOrder);
  322. (*mChans)[0].mHfScale = scales[0];
  323. for(size_t i{1};i < mChans->size();++i)
  324. (*mChans)[i].mHfScale = scales[1];
  325. }
  326. mOutTarget = target.Main->Buffer;
  327. auto&& scales = GetAmbiScales(mAmbiScaling);
  328. const uint8_t *index_map{(mChannels == FmtBFormat2D) ?
  329. GetAmbi2DLayout(mAmbiLayout).data() :
  330. GetAmbiLayout(mAmbiLayout).data()};
  331. std::array<float,MaxAmbiChannels> coeffs{};
  332. for(size_t c{0u};c < mChans->size();++c)
  333. {
  334. const size_t acn{index_map[c]};
  335. coeffs[acn] = scales[acn];
  336. ComputePanGains(target.Main, coeffs.data(), gain, (*mChans)[c].Target);
  337. coeffs[acn] = 0.0f;
  338. }
  339. }
  340. else
  341. {
  342. ALCdevice *device{context->mDevice.get()};
  343. al::span<const ChanMap> chanmap{};
  344. switch(mChannels)
  345. {
  346. case FmtMono: chanmap = MonoMap; break;
  347. case FmtStereo: chanmap = StereoMap; break;
  348. case FmtRear: chanmap = RearMap; break;
  349. case FmtQuad: chanmap = QuadMap; break;
  350. case FmtX51: chanmap = X51Map; break;
  351. case FmtX61: chanmap = X61Map; break;
  352. case FmtX71: chanmap = X71Map; break;
  353. case FmtBFormat2D:
  354. case FmtBFormat3D:
  355. break;
  356. }
  357. mOutTarget = target.Main->Buffer;
  358. if(device->mRenderMode == RenderMode::Pairwise)
  359. {
  360. auto ScaleAzimuthFront = [](float azimuth, float scale) -> float
  361. {
  362. const float abs_azi{std::fabs(azimuth)};
  363. if(!(abs_azi >= al::MathDefs<float>::Pi()*0.5f))
  364. return std::copysign(minf(abs_azi*scale, al::MathDefs<float>::Pi()*0.5f), azimuth);
  365. return azimuth;
  366. };
  367. for(size_t i{0};i < chanmap.size();++i)
  368. {
  369. if(chanmap[i].channel == LFE) continue;
  370. const auto coeffs = CalcAngleCoeffs(ScaleAzimuthFront(chanmap[i].angle, 2.0f),
  371. chanmap[i].elevation, 0.0f);
  372. ComputePanGains(target.Main, coeffs.data(), gain, (*mChans)[i].Target);
  373. }
  374. }
  375. else for(size_t i{0};i < chanmap.size();++i)
  376. {
  377. if(chanmap[i].channel == LFE) continue;
  378. const auto coeffs = CalcAngleCoeffs(chanmap[i].angle, chanmap[i].elevation, 0.0f);
  379. ComputePanGains(target.Main, coeffs.data(), gain, (*mChans)[i].Target);
  380. }
  381. }
  382. }
  383. void ConvolutionState::process(const size_t samplesToDo,
  384. const al::span<const FloatBufferLine> samplesIn, const al::span<FloatBufferLine> samplesOut)
  385. {
  386. if(mNumConvolveSegs < 1)
  387. return;
  388. constexpr size_t m{ConvolveUpdateSize/2 + 1};
  389. size_t curseg{mCurrentSegment};
  390. auto &chans = *mChans;
  391. for(size_t base{0u};base < samplesToDo;)
  392. {
  393. const size_t todo{minz(ConvolveUpdateSamples-mFifoPos, samplesToDo-base)};
  394. std::copy_n(samplesIn[0].begin() + base, todo,
  395. mInput.begin()+ConvolveUpdateSamples+mFifoPos);
  396. /* Apply the FIR for the newly retrieved input samples, and combine it
  397. * with the inverse FFT'd output samples.
  398. */
  399. for(size_t c{0};c < chans.size();++c)
  400. {
  401. auto buf_iter = chans[c].mBuffer.begin() + base;
  402. apply_fir({std::addressof(*buf_iter), todo}, mInput.data()+1 + mFifoPos,
  403. mFilter[c].data());
  404. auto fifo_iter = mOutput[c].begin() + mFifoPos;
  405. std::transform(fifo_iter, fifo_iter+todo, buf_iter, buf_iter, std::plus<>{});
  406. }
  407. mFifoPos += todo;
  408. base += todo;
  409. /* Check whether the input buffer is filled with new samples. */
  410. if(mFifoPos < ConvolveUpdateSamples) break;
  411. mFifoPos = 0;
  412. /* Move the newest input to the front for the next iteration's history. */
  413. std::copy(mInput.cbegin()+ConvolveUpdateSamples, mInput.cend(), mInput.begin());
  414. /* Calculate the frequency domain response and add the relevant
  415. * frequency bins to the FFT history.
  416. */
  417. auto fftiter = std::copy_n(mInput.cbegin(), ConvolveUpdateSamples, mFftBuffer.begin());
  418. std::fill(fftiter, mFftBuffer.end(), complex_d{});
  419. forward_fft(mFftBuffer);
  420. std::copy_n(mFftBuffer.cbegin(), m, &mComplexData[curseg*m]);
  421. const complex_d *RESTRICT filter{mComplexData.get() + mNumConvolveSegs*m};
  422. for(size_t c{0};c < chans.size();++c)
  423. {
  424. std::fill_n(mFftBuffer.begin(), m, complex_d{});
  425. /* Convolve each input segment with its IR filter counterpart
  426. * (aligned in time).
  427. */
  428. const complex_d *RESTRICT input{&mComplexData[curseg*m]};
  429. for(size_t s{curseg};s < mNumConvolveSegs;++s)
  430. {
  431. for(size_t i{0};i < m;++i,++input,++filter)
  432. mFftBuffer[i] += *input * *filter;
  433. }
  434. input = mComplexData.get();
  435. for(size_t s{0};s < curseg;++s)
  436. {
  437. for(size_t i{0};i < m;++i,++input,++filter)
  438. mFftBuffer[i] += *input * *filter;
  439. }
  440. /* Reconstruct the mirrored/negative frequencies to do a proper
  441. * inverse FFT.
  442. */
  443. for(size_t i{m};i < ConvolveUpdateSize;++i)
  444. mFftBuffer[i] = std::conj(mFftBuffer[ConvolveUpdateSize-i]);
  445. /* Apply iFFT to get the 256 (really 255) samples for output. The
  446. * 128 output samples are combined with the last output's 127
  447. * second-half samples (and this output's second half is
  448. * subsequently saved for next time).
  449. */
  450. inverse_fft(mFftBuffer);
  451. /* The iFFT'd response is scaled up by the number of bins, so apply
  452. * the inverse to normalize the output.
  453. */
  454. for(size_t i{0};i < ConvolveUpdateSamples;++i)
  455. mOutput[c][i] =
  456. static_cast<float>(mFftBuffer[i].real() * (1.0/double{ConvolveUpdateSize})) +
  457. mOutput[c][ConvolveUpdateSamples+i];
  458. for(size_t i{0};i < ConvolveUpdateSamples;++i)
  459. mOutput[c][ConvolveUpdateSamples+i] =
  460. static_cast<float>(mFftBuffer[ConvolveUpdateSamples+i].real() *
  461. (1.0/double{ConvolveUpdateSize}));
  462. }
  463. /* Shift the input history. */
  464. curseg = curseg ? (curseg-1) : (mNumConvolveSegs-1);
  465. }
  466. mCurrentSegment = curseg;
  467. /* Finally, mix to the output. */
  468. (this->*mMix)(samplesOut, samplesToDo);
  469. }
  470. struct ConvolutionStateFactory final : public EffectStateFactory {
  471. al::intrusive_ptr<EffectState> create() override
  472. { return al::intrusive_ptr<EffectState>{new ConvolutionState{}}; }
  473. };
  474. } // namespace
  475. EffectStateFactory *ConvolutionStateFactory_getFactory()
  476. {
  477. static ConvolutionStateFactory ConvolutionFactory{};
  478. return &ConvolutionFactory;
  479. }