🛠️🐜 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.

479 lines
17 KiB

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