🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

439 lines
15 KiB

  1. #include "config.h"
  2. #include "mastering.h"
  3. #include <algorithm>
  4. #include <cmath>
  5. #include <cstddef>
  6. #include <functional>
  7. #include <iterator>
  8. #include <limits>
  9. #include <new>
  10. #include "almalloc.h"
  11. #include "alnumeric.h"
  12. #include "alspan.h"
  13. #include "opthelpers.h"
  14. /* These structures assume BufferLineSize is a power of 2. */
  15. static_assert((BufferLineSize & (BufferLineSize-1)) == 0, "BufferLineSize is not a power of 2");
  16. struct SlidingHold {
  17. alignas(16) float mValues[BufferLineSize];
  18. uint mExpiries[BufferLineSize];
  19. uint mLowerIndex;
  20. uint mUpperIndex;
  21. uint mLength;
  22. };
  23. namespace {
  24. using namespace std::placeholders;
  25. /* This sliding hold follows the input level with an instant attack and a
  26. * fixed duration hold before an instant release to the next highest level.
  27. * It is a sliding window maximum (descending maxima) implementation based on
  28. * Richard Harter's ascending minima algorithm available at:
  29. *
  30. * http://www.richardhartersworld.com/cri/2001/slidingmin.html
  31. */
  32. float UpdateSlidingHold(SlidingHold *Hold, const uint i, const float in)
  33. {
  34. static constexpr uint mask{BufferLineSize - 1};
  35. const uint length{Hold->mLength};
  36. float (&values)[BufferLineSize] = Hold->mValues;
  37. uint (&expiries)[BufferLineSize] = Hold->mExpiries;
  38. uint lowerIndex{Hold->mLowerIndex};
  39. uint upperIndex{Hold->mUpperIndex};
  40. if(i >= expiries[upperIndex])
  41. upperIndex = (upperIndex + 1) & mask;
  42. if(in >= values[upperIndex])
  43. {
  44. values[upperIndex] = in;
  45. expiries[upperIndex] = i + length;
  46. lowerIndex = upperIndex;
  47. }
  48. else
  49. {
  50. do {
  51. do {
  52. if(!(in >= values[lowerIndex]))
  53. goto found_place;
  54. } while(lowerIndex--);
  55. lowerIndex = mask;
  56. } while(1);
  57. found_place:
  58. lowerIndex = (lowerIndex + 1) & mask;
  59. values[lowerIndex] = in;
  60. expiries[lowerIndex] = i + length;
  61. }
  62. Hold->mLowerIndex = lowerIndex;
  63. Hold->mUpperIndex = upperIndex;
  64. return values[upperIndex];
  65. }
  66. void ShiftSlidingHold(SlidingHold *Hold, const uint n)
  67. {
  68. auto exp_begin = std::begin(Hold->mExpiries) + Hold->mUpperIndex;
  69. auto exp_last = std::begin(Hold->mExpiries) + Hold->mLowerIndex;
  70. if(exp_last-exp_begin < 0)
  71. {
  72. std::transform(exp_begin, std::end(Hold->mExpiries), exp_begin,
  73. std::bind(std::minus<>{}, _1, n));
  74. exp_begin = std::begin(Hold->mExpiries);
  75. }
  76. std::transform(exp_begin, exp_last+1, exp_begin, std::bind(std::minus<>{}, _1, n));
  77. }
  78. /* Multichannel compression is linked via the absolute maximum of all
  79. * channels.
  80. */
  81. void LinkChannels(Compressor *Comp, const uint SamplesToDo, const FloatBufferLine *OutBuffer)
  82. {
  83. const size_t numChans{Comp->mNumChans};
  84. ASSUME(SamplesToDo > 0);
  85. ASSUME(numChans > 0);
  86. auto side_begin = std::begin(Comp->mSideChain) + Comp->mLookAhead;
  87. std::fill(side_begin, side_begin+SamplesToDo, 0.0f);
  88. auto fill_max = [SamplesToDo,side_begin](const FloatBufferLine &input) -> void
  89. {
  90. const float *RESTRICT buffer{al::assume_aligned<16>(input.data())};
  91. auto max_abs = std::bind(maxf, _1, std::bind(static_cast<float(&)(float)>(std::fabs), _2));
  92. std::transform(side_begin, side_begin+SamplesToDo, buffer, side_begin, max_abs);
  93. };
  94. std::for_each(OutBuffer, OutBuffer+numChans, fill_max);
  95. }
  96. /* This calculates the squared crest factor of the control signal for the
  97. * basic automation of the attack/release times. As suggested by the paper,
  98. * it uses an instantaneous squared peak detector and a squared RMS detector
  99. * both with 200ms release times.
  100. */
  101. static void CrestDetector(Compressor *Comp, const uint SamplesToDo)
  102. {
  103. const float a_crest{Comp->mCrestCoeff};
  104. float y2_peak{Comp->mLastPeakSq};
  105. float y2_rms{Comp->mLastRmsSq};
  106. ASSUME(SamplesToDo > 0);
  107. auto calc_crest = [&y2_rms,&y2_peak,a_crest](const float x_abs) noexcept -> float
  108. {
  109. const float x2{clampf(x_abs * x_abs, 0.000001f, 1000000.0f)};
  110. y2_peak = maxf(x2, lerpf(x2, y2_peak, a_crest));
  111. y2_rms = lerpf(x2, y2_rms, a_crest);
  112. return y2_peak / y2_rms;
  113. };
  114. auto side_begin = std::begin(Comp->mSideChain) + Comp->mLookAhead;
  115. std::transform(side_begin, side_begin+SamplesToDo, std::begin(Comp->mCrestFactor), calc_crest);
  116. Comp->mLastPeakSq = y2_peak;
  117. Comp->mLastRmsSq = y2_rms;
  118. }
  119. /* The side-chain starts with a simple peak detector (based on the absolute
  120. * value of the incoming signal) and performs most of its operations in the
  121. * log domain.
  122. */
  123. void PeakDetector(Compressor *Comp, const uint SamplesToDo)
  124. {
  125. ASSUME(SamplesToDo > 0);
  126. /* Clamp the minimum amplitude to near-zero and convert to logarithm. */
  127. auto side_begin = std::begin(Comp->mSideChain) + Comp->mLookAhead;
  128. std::transform(side_begin, side_begin+SamplesToDo, side_begin,
  129. [](const float s) -> float { return std::log(maxf(0.000001f, s)); });
  130. }
  131. /* An optional hold can be used to extend the peak detector so it can more
  132. * solidly detect fast transients. This is best used when operating as a
  133. * limiter.
  134. */
  135. void PeakHoldDetector(Compressor *Comp, const uint SamplesToDo)
  136. {
  137. ASSUME(SamplesToDo > 0);
  138. SlidingHold *hold{Comp->mHold};
  139. uint i{0};
  140. auto detect_peak = [&i,hold](const float x_abs) -> float
  141. {
  142. const float x_G{std::log(maxf(0.000001f, x_abs))};
  143. return UpdateSlidingHold(hold, i++, x_G);
  144. };
  145. auto side_begin = std::begin(Comp->mSideChain) + Comp->mLookAhead;
  146. std::transform(side_begin, side_begin+SamplesToDo, side_begin, detect_peak);
  147. ShiftSlidingHold(hold, SamplesToDo);
  148. }
  149. /* This is the heart of the feed-forward compressor. It operates in the log
  150. * domain (to better match human hearing) and can apply some basic automation
  151. * to knee width, attack/release times, make-up/post gain, and clipping
  152. * reduction.
  153. */
  154. void GainCompressor(Compressor *Comp, const uint SamplesToDo)
  155. {
  156. const bool autoKnee{Comp->mAuto.Knee};
  157. const bool autoAttack{Comp->mAuto.Attack};
  158. const bool autoRelease{Comp->mAuto.Release};
  159. const bool autoPostGain{Comp->mAuto.PostGain};
  160. const bool autoDeclip{Comp->mAuto.Declip};
  161. const uint lookAhead{Comp->mLookAhead};
  162. const float threshold{Comp->mThreshold};
  163. const float slope{Comp->mSlope};
  164. const float attack{Comp->mAttack};
  165. const float release{Comp->mRelease};
  166. const float c_est{Comp->mGainEstimate};
  167. const float a_adp{Comp->mAdaptCoeff};
  168. const float *crestFactor{Comp->mCrestFactor};
  169. float postGain{Comp->mPostGain};
  170. float knee{Comp->mKnee};
  171. float t_att{attack};
  172. float t_rel{release - attack};
  173. float a_att{std::exp(-1.0f / t_att)};
  174. float a_rel{std::exp(-1.0f / t_rel)};
  175. float y_1{Comp->mLastRelease};
  176. float y_L{Comp->mLastAttack};
  177. float c_dev{Comp->mLastGainDev};
  178. ASSUME(SamplesToDo > 0);
  179. for(float &sideChain : al::span<float>{Comp->mSideChain, SamplesToDo})
  180. {
  181. if(autoKnee)
  182. knee = maxf(0.0f, 2.5f * (c_dev + c_est));
  183. const float knee_h{0.5f * knee};
  184. /* This is the gain computer. It applies a static compression curve
  185. * to the control signal.
  186. */
  187. const float x_over{std::addressof(sideChain)[lookAhead] - threshold};
  188. const float y_G{
  189. (x_over <= -knee_h) ? 0.0f :
  190. (std::fabs(x_over) < knee_h) ? (x_over + knee_h) * (x_over + knee_h) / (2.0f * knee) :
  191. x_over};
  192. const float y2_crest{*(crestFactor++)};
  193. if(autoAttack)
  194. {
  195. t_att = 2.0f*attack/y2_crest;
  196. a_att = std::exp(-1.0f / t_att);
  197. }
  198. if(autoRelease)
  199. {
  200. t_rel = 2.0f*release/y2_crest - t_att;
  201. a_rel = std::exp(-1.0f / t_rel);
  202. }
  203. /* Gain smoothing (ballistics) is done via a smooth decoupled peak
  204. * detector. The attack time is subtracted from the release time
  205. * above to compensate for the chained operating mode.
  206. */
  207. const float x_L{-slope * y_G};
  208. y_1 = maxf(x_L, lerpf(x_L, y_1, a_rel));
  209. y_L = lerpf(y_1, y_L, a_att);
  210. /* Knee width and make-up gain automation make use of a smoothed
  211. * measurement of deviation between the control signal and estimate.
  212. * The estimate is also used to bias the measurement to hot-start its
  213. * average.
  214. */
  215. c_dev = lerpf(-(y_L+c_est), c_dev, a_adp);
  216. if(autoPostGain)
  217. {
  218. /* Clipping reduction is only viable when make-up gain is being
  219. * automated. It modifies the deviation to further attenuate the
  220. * control signal when clipping is detected. The adaptation time
  221. * is sufficiently long enough to suppress further clipping at the
  222. * same output level.
  223. */
  224. if(autoDeclip)
  225. c_dev = maxf(c_dev, sideChain - y_L - threshold - c_est);
  226. postGain = -(c_dev + c_est);
  227. }
  228. sideChain = std::exp(postGain - y_L);
  229. }
  230. Comp->mLastRelease = y_1;
  231. Comp->mLastAttack = y_L;
  232. Comp->mLastGainDev = c_dev;
  233. }
  234. /* Combined with the hold time, a look-ahead delay can improve handling of
  235. * fast transients by allowing the envelope time to converge prior to
  236. * reaching the offending impulse. This is best used when operating as a
  237. * limiter.
  238. */
  239. void SignalDelay(Compressor *Comp, const uint SamplesToDo, FloatBufferLine *OutBuffer)
  240. {
  241. const size_t numChans{Comp->mNumChans};
  242. const uint lookAhead{Comp->mLookAhead};
  243. ASSUME(SamplesToDo > 0);
  244. ASSUME(numChans > 0);
  245. ASSUME(lookAhead > 0);
  246. for(size_t c{0};c < numChans;c++)
  247. {
  248. float *inout{al::assume_aligned<16>(OutBuffer[c].data())};
  249. float *delaybuf{al::assume_aligned<16>(Comp->mDelay[c].data())};
  250. auto inout_end = inout + SamplesToDo;
  251. if LIKELY(SamplesToDo >= lookAhead)
  252. {
  253. auto delay_end = std::rotate(inout, inout_end - lookAhead, inout_end);
  254. std::swap_ranges(inout, delay_end, delaybuf);
  255. }
  256. else
  257. {
  258. auto delay_start = std::swap_ranges(inout, inout_end, delaybuf);
  259. std::rotate(delaybuf, delay_start, delaybuf + lookAhead);
  260. }
  261. }
  262. }
  263. } // namespace
  264. std::unique_ptr<Compressor> Compressor::Create(const size_t NumChans, const float SampleRate,
  265. const bool AutoKnee, const bool AutoAttack, const bool AutoRelease, const bool AutoPostGain,
  266. const bool AutoDeclip, const float LookAheadTime, const float HoldTime, const float PreGainDb,
  267. const float PostGainDb, const float ThresholdDb, const float Ratio, const float KneeDb,
  268. const float AttackTime, const float ReleaseTime)
  269. {
  270. const auto lookAhead = static_cast<uint>(
  271. clampf(std::round(LookAheadTime*SampleRate), 0.0f, BufferLineSize-1));
  272. const auto hold = static_cast<uint>(
  273. clampf(std::round(HoldTime*SampleRate), 0.0f, BufferLineSize-1));
  274. size_t size{sizeof(Compressor)};
  275. if(lookAhead > 0)
  276. {
  277. size += sizeof(*Compressor::mDelay) * NumChans;
  278. /* The sliding hold implementation doesn't handle a length of 1. A 1-
  279. * sample hold is useless anyway, it would only ever give back what was
  280. * just given to it.
  281. */
  282. if(hold > 1)
  283. size += sizeof(*Compressor::mHold);
  284. }
  285. auto Comp = CompressorPtr{al::construct_at(static_cast<Compressor*>(al_calloc(16, size)))};
  286. Comp->mNumChans = NumChans;
  287. Comp->mAuto.Knee = AutoKnee;
  288. Comp->mAuto.Attack = AutoAttack;
  289. Comp->mAuto.Release = AutoRelease;
  290. Comp->mAuto.PostGain = AutoPostGain;
  291. Comp->mAuto.Declip = AutoPostGain && AutoDeclip;
  292. Comp->mLookAhead = lookAhead;
  293. Comp->mPreGain = std::pow(10.0f, PreGainDb / 20.0f);
  294. Comp->mPostGain = PostGainDb * std::log(10.0f) / 20.0f;
  295. Comp->mThreshold = ThresholdDb * std::log(10.0f) / 20.0f;
  296. Comp->mSlope = 1.0f / maxf(1.0f, Ratio) - 1.0f;
  297. Comp->mKnee = maxf(0.0f, KneeDb * std::log(10.0f) / 20.0f);
  298. Comp->mAttack = maxf(1.0f, AttackTime * SampleRate);
  299. Comp->mRelease = maxf(1.0f, ReleaseTime * SampleRate);
  300. /* Knee width automation actually treats the compressor as a limiter. By
  301. * varying the knee width, it can effectively be seen as applying
  302. * compression over a wide range of ratios.
  303. */
  304. if(AutoKnee)
  305. Comp->mSlope = -1.0f;
  306. if(lookAhead > 0)
  307. {
  308. if(hold > 1)
  309. {
  310. Comp->mHold = al::construct_at(reinterpret_cast<SlidingHold*>(Comp.get() + 1));
  311. Comp->mHold->mValues[0] = -std::numeric_limits<float>::infinity();
  312. Comp->mHold->mExpiries[0] = hold;
  313. Comp->mHold->mLength = hold;
  314. Comp->mDelay = reinterpret_cast<FloatBufferLine*>(Comp->mHold + 1);
  315. }
  316. else
  317. Comp->mDelay = reinterpret_cast<FloatBufferLine*>(Comp.get() + 1);
  318. std::uninitialized_fill_n(Comp->mDelay, NumChans, FloatBufferLine{});
  319. }
  320. Comp->mCrestCoeff = std::exp(-1.0f / (0.200f * SampleRate)); // 200ms
  321. Comp->mGainEstimate = Comp->mThreshold * -0.5f * Comp->mSlope;
  322. Comp->mAdaptCoeff = std::exp(-1.0f / (2.0f * SampleRate)); // 2s
  323. return Comp;
  324. }
  325. Compressor::~Compressor()
  326. {
  327. if(mHold)
  328. al::destroy_at(mHold);
  329. mHold = nullptr;
  330. if(mDelay)
  331. al::destroy_n(mDelay, mNumChans);
  332. mDelay = nullptr;
  333. }
  334. void Compressor::process(const uint SamplesToDo, FloatBufferLine *OutBuffer)
  335. {
  336. const size_t numChans{mNumChans};
  337. ASSUME(SamplesToDo > 0);
  338. ASSUME(numChans > 0);
  339. const float preGain{mPreGain};
  340. if(preGain != 1.0f)
  341. {
  342. auto apply_gain = [SamplesToDo,preGain](FloatBufferLine &input) noexcept -> void
  343. {
  344. float *buffer{al::assume_aligned<16>(input.data())};
  345. std::transform(buffer, buffer+SamplesToDo, buffer,
  346. std::bind(std::multiplies<float>{}, _1, preGain));
  347. };
  348. std::for_each(OutBuffer, OutBuffer+numChans, apply_gain);
  349. }
  350. LinkChannels(this, SamplesToDo, OutBuffer);
  351. if(mAuto.Attack || mAuto.Release)
  352. CrestDetector(this, SamplesToDo);
  353. if(mHold)
  354. PeakHoldDetector(this, SamplesToDo);
  355. else
  356. PeakDetector(this, SamplesToDo);
  357. GainCompressor(this, SamplesToDo);
  358. if(mDelay)
  359. SignalDelay(this, SamplesToDo, OutBuffer);
  360. const float (&sideChain)[BufferLineSize*2] = mSideChain;
  361. auto apply_comp = [SamplesToDo,&sideChain](FloatBufferLine &input) noexcept -> void
  362. {
  363. float *buffer{al::assume_aligned<16>(input.data())};
  364. const float *gains{al::assume_aligned<16>(&sideChain[0])};
  365. std::transform(gains, gains+SamplesToDo, buffer, buffer,
  366. std::bind(std::multiplies<float>{}, _1, _2));
  367. };
  368. std::for_each(OutBuffer, OutBuffer+numChans, apply_comp);
  369. auto side_begin = std::begin(mSideChain) + SamplesToDo;
  370. std::copy(side_begin, side_begin+mLookAhead, std::begin(mSideChain));
  371. }