mastering.cpp 16 KB

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