compressor.cpp 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. /**
  2. * This file is part of the OpenAL Soft cross platform audio library
  3. *
  4. * Copyright (C) 2013 by Anis A. Hireche
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * * Redistributions of source code must retain the above copyright notice,
  10. * this list of conditions and the following disclaimer.
  11. *
  12. * * Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * * Neither the name of Spherical-Harmonic-Transform nor the names of its
  17. * contributors may be used to endorse or promote products derived from
  18. * this software without specific prior written permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  21. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  22. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  23. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  24. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  25. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  26. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  27. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  28. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  29. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  30. * POSSIBILITY OF SUCH DAMAGE.
  31. */
  32. #include "config.h"
  33. #include <algorithm>
  34. #include <array>
  35. #include <cmath>
  36. #include <cstdlib>
  37. #include <variant>
  38. #include "alc/effects/base.h"
  39. #include "alspan.h"
  40. #include "core/ambidefs.h"
  41. #include "core/bufferline.h"
  42. #include "core/device.h"
  43. #include "core/effects/base.h"
  44. #include "core/effectslot.h"
  45. #include "core/mixer/defs.h"
  46. #include "intrusive_ptr.h"
  47. struct BufferStorage;
  48. struct ContextBase;
  49. namespace {
  50. constexpr float AmpEnvelopeMin{0.5f};
  51. constexpr float AmpEnvelopeMax{2.0f};
  52. constexpr float AttackTime{0.1f}; /* 100ms to rise from min to max */
  53. constexpr float ReleaseTime{0.2f}; /* 200ms to drop from max to min */
  54. struct CompressorState final : public EffectState {
  55. /* Effect gains for each channel */
  56. struct TargetGain {
  57. uint mTarget{InvalidChannelIndex};
  58. float mGain{1.0f};
  59. };
  60. std::array<TargetGain,MaxAmbiChannels> mChans;
  61. /* Effect parameters */
  62. bool mEnabled{true};
  63. float mAttackMult{1.0f};
  64. float mReleaseMult{1.0f};
  65. float mEnvFollower{1.0f};
  66. alignas(16) FloatBufferLine mGains{};
  67. void deviceUpdate(const DeviceBase *device, const BufferStorage *buffer) override;
  68. void update(const ContextBase *context, const EffectSlot *slot, const EffectProps *props,
  69. const EffectTarget target) override;
  70. void process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn,
  71. const al::span<FloatBufferLine> samplesOut) override;
  72. };
  73. void CompressorState::deviceUpdate(const DeviceBase *device, const BufferStorage*)
  74. {
  75. /* Number of samples to do a full attack and release (non-integer sample
  76. * counts are okay).
  77. */
  78. const float attackCount{static_cast<float>(device->Frequency) * AttackTime};
  79. const float releaseCount{static_cast<float>(device->Frequency) * ReleaseTime};
  80. /* Calculate per-sample multipliers to attack and release at the desired
  81. * rates.
  82. */
  83. mAttackMult = std::pow(AmpEnvelopeMax/AmpEnvelopeMin, 1.0f/attackCount);
  84. mReleaseMult = std::pow(AmpEnvelopeMin/AmpEnvelopeMax, 1.0f/releaseCount);
  85. }
  86. void CompressorState::update(const ContextBase*, const EffectSlot *slot,
  87. const EffectProps *props, const EffectTarget target)
  88. {
  89. mEnabled = std::get<CompressorProps>(*props).OnOff;
  90. mOutTarget = target.Main->Buffer;
  91. auto set_channel = [this](size_t idx, uint outchan, float outgain)
  92. {
  93. mChans[idx].mTarget = outchan;
  94. mChans[idx].mGain = outgain;
  95. };
  96. target.Main->setAmbiMixParams(slot->Wet, slot->Gain, set_channel);
  97. }
  98. void CompressorState::process(const size_t samplesToDo,
  99. const al::span<const FloatBufferLine> samplesIn, const al::span<FloatBufferLine> samplesOut)
  100. {
  101. /* Generate the per-sample gains from the signal envelope. */
  102. float env{mEnvFollower};
  103. if(mEnabled)
  104. {
  105. for(size_t i{0u};i < samplesToDo;++i)
  106. {
  107. /* Clamp the absolute amplitude to the defined envelope limits,
  108. * then attack or release the envelope to reach it.
  109. */
  110. const float amplitude{std::clamp(std::fabs(samplesIn[0][i]), AmpEnvelopeMin,
  111. AmpEnvelopeMax)};
  112. if(amplitude > env)
  113. env = std::min(env*mAttackMult, amplitude);
  114. else if(amplitude < env)
  115. env = std::max(env*mReleaseMult, amplitude);
  116. /* Apply the reciprocal of the envelope to normalize the volume
  117. * (compress the dynamic range).
  118. */
  119. mGains[i] = 1.0f / env;
  120. }
  121. }
  122. else
  123. {
  124. /* Same as above, except the amplitude is forced to 1. This helps
  125. * ensure smooth gain changes when the compressor is turned on and off.
  126. */
  127. for(size_t i{0u};i < samplesToDo;++i)
  128. {
  129. const float amplitude{1.0f};
  130. if(amplitude > env)
  131. env = std::min(env*mAttackMult, amplitude);
  132. else if(amplitude < env)
  133. env = std::max(env*mReleaseMult, amplitude);
  134. mGains[i] = 1.0f / env;
  135. }
  136. }
  137. mEnvFollower = env;
  138. /* Now compress the signal amplitude to output. */
  139. auto chan = mChans.cbegin();
  140. for(const auto &input : samplesIn)
  141. {
  142. const size_t outidx{chan->mTarget};
  143. if(outidx != InvalidChannelIndex)
  144. {
  145. const auto dst = al::span{samplesOut[outidx]};
  146. const float gain{chan->mGain};
  147. if(!(std::fabs(gain) > GainSilenceThreshold))
  148. {
  149. for(size_t i{0u};i < samplesToDo;++i)
  150. dst[i] += input[i] * mGains[i] * gain;
  151. }
  152. }
  153. ++chan;
  154. }
  155. }
  156. struct CompressorStateFactory final : public EffectStateFactory {
  157. al::intrusive_ptr<EffectState> create() override
  158. { return al::intrusive_ptr<EffectState>{new CompressorState{}}; }
  159. };
  160. } // namespace
  161. EffectStateFactory *CompressorStateFactory_getFactory()
  162. {
  163. static CompressorStateFactory CompressorFactory{};
  164. return &CompressorFactory;
  165. }