distortion.cpp 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. /**
  2. * OpenAL cross platform audio library
  3. * Copyright (C) 2013 by Mike Gorchak
  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 <cmath>
  23. #include <cstdlib>
  24. #include "alcmain.h"
  25. #include "alcontext.h"
  26. #include "core/filters/biquad.h"
  27. #include "effectslot.h"
  28. namespace {
  29. struct DistortionState final : public EffectState {
  30. /* Effect gains for each channel */
  31. float mGain[MAX_OUTPUT_CHANNELS]{};
  32. /* Effect parameters */
  33. BiquadFilter mLowpass;
  34. BiquadFilter mBandpass;
  35. float mAttenuation{};
  36. float mEdgeCoeff{};
  37. float mBuffer[2][BufferLineSize]{};
  38. void deviceUpdate(const ALCdevice *device, const Buffer &buffer) override;
  39. void update(const ALCcontext *context, const EffectSlot *slot, const EffectProps *props,
  40. const EffectTarget target) override;
  41. void process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn,
  42. const al::span<FloatBufferLine> samplesOut) override;
  43. DEF_NEWDEL(DistortionState)
  44. };
  45. void DistortionState::deviceUpdate(const ALCdevice*, const Buffer&)
  46. {
  47. mLowpass.clear();
  48. mBandpass.clear();
  49. }
  50. void DistortionState::update(const ALCcontext *context, const EffectSlot *slot,
  51. const EffectProps *props, const EffectTarget target)
  52. {
  53. const ALCdevice *device{context->mDevice.get()};
  54. /* Store waveshaper edge settings. */
  55. const float edge{minf(std::sin(al::MathDefs<float>::Pi()*0.5f * props->Distortion.Edge),
  56. 0.99f)};
  57. mEdgeCoeff = 2.0f * edge / (1.0f-edge);
  58. float cutoff{props->Distortion.LowpassCutoff};
  59. /* Bandwidth value is constant in octaves. */
  60. float bandwidth{(cutoff / 2.0f) / (cutoff * 0.67f)};
  61. /* Divide normalized frequency by the amount of oversampling done during
  62. * processing.
  63. */
  64. auto frequency = static_cast<float>(device->Frequency);
  65. mLowpass.setParamsFromBandwidth(BiquadType::LowPass, cutoff/frequency/4.0f, 1.0f, bandwidth);
  66. cutoff = props->Distortion.EQCenter;
  67. /* Convert bandwidth in Hz to octaves. */
  68. bandwidth = props->Distortion.EQBandwidth / (cutoff * 0.67f);
  69. mBandpass.setParamsFromBandwidth(BiquadType::BandPass, cutoff/frequency/4.0f, 1.0f, bandwidth);
  70. const auto coeffs = CalcDirectionCoeffs({0.0f, 0.0f, -1.0f}, 0.0f);
  71. mOutTarget = target.Main->Buffer;
  72. ComputePanGains(target.Main, coeffs.data(), slot->Gain*props->Distortion.Gain, mGain);
  73. }
  74. void DistortionState::process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn, const al::span<FloatBufferLine> samplesOut)
  75. {
  76. const float fc{mEdgeCoeff};
  77. for(size_t base{0u};base < samplesToDo;)
  78. {
  79. /* Perform 4x oversampling to avoid aliasing. Oversampling greatly
  80. * improves distortion quality and allows to implement lowpass and
  81. * bandpass filters using high frequencies, at which classic IIR
  82. * filters became unstable.
  83. */
  84. size_t todo{minz(BufferLineSize, (samplesToDo-base) * 4)};
  85. /* Fill oversample buffer using zero stuffing. Multiply the sample by
  86. * the amount of oversampling to maintain the signal's power.
  87. */
  88. for(size_t i{0u};i < todo;i++)
  89. mBuffer[0][i] = !(i&3) ? samplesIn[0][(i>>2)+base] * 4.0f : 0.0f;
  90. /* First step, do lowpass filtering of original signal. Additionally
  91. * perform buffer interpolation and lowpass cutoff for oversampling
  92. * (which is fortunately first step of distortion). So combine three
  93. * operations into the one.
  94. */
  95. mLowpass.process({mBuffer[0], todo}, mBuffer[1]);
  96. /* Second step, do distortion using waveshaper function to emulate
  97. * signal processing during tube overdriving. Three steps of
  98. * waveshaping are intended to modify waveform without boost/clipping/
  99. * attenuation process.
  100. */
  101. auto proc_sample = [fc](float smp) -> float
  102. {
  103. smp = (1.0f + fc) * smp/(1.0f + fc*std::abs(smp));
  104. smp = (1.0f + fc) * smp/(1.0f + fc*std::abs(smp)) * -1.0f;
  105. smp = (1.0f + fc) * smp/(1.0f + fc*std::abs(smp));
  106. return smp;
  107. };
  108. std::transform(std::begin(mBuffer[1]), std::begin(mBuffer[1])+todo, std::begin(mBuffer[0]),
  109. proc_sample);
  110. /* Third step, do bandpass filtering of distorted signal. */
  111. mBandpass.process({mBuffer[0], todo}, mBuffer[1]);
  112. todo >>= 2;
  113. const float *outgains{mGain};
  114. for(FloatBufferLine &output : samplesOut)
  115. {
  116. /* Fourth step, final, do attenuation and perform decimation,
  117. * storing only one sample out of four.
  118. */
  119. const float gain{*(outgains++)};
  120. if(!(std::fabs(gain) > GainSilenceThreshold))
  121. continue;
  122. for(size_t i{0u};i < todo;i++)
  123. output[base+i] += gain * mBuffer[1][i*4];
  124. }
  125. base += todo;
  126. }
  127. }
  128. struct DistortionStateFactory final : public EffectStateFactory {
  129. al::intrusive_ptr<EffectState> create() override
  130. { return al::intrusive_ptr<EffectState>{new DistortionState{}}; }
  131. };
  132. } // namespace
  133. EffectStateFactory *DistortionStateFactory_getFactory()
  134. {
  135. static DistortionStateFactory DistortionFactory{};
  136. return &DistortionFactory;
  137. }