mastering.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. #include "config.h"
  2. #include <math.h>
  3. #include "mastering.h"
  4. #include "alu.h"
  5. #include "almalloc.h"
  6. #include "static_assert.h"
  7. /* These structures assume BUFFERSIZE is a power of 2. */
  8. static_assert((BUFFERSIZE & (BUFFERSIZE-1)) == 0, "BUFFERSIZE is not a power of 2");
  9. typedef struct SlidingHold {
  10. ALfloat Values[BUFFERSIZE];
  11. ALsizei Expiries[BUFFERSIZE];
  12. ALsizei LowerIndex;
  13. ALsizei UpperIndex;
  14. ALsizei Length;
  15. } SlidingHold;
  16. /* General topology and basic automation was based on the following paper:
  17. *
  18. * D. Giannoulis, M. Massberg and J. D. Reiss,
  19. * "Parameter Automation in a Dynamic Range Compressor,"
  20. * Journal of the Audio Engineering Society, v61 (10), Oct. 2013
  21. *
  22. * Available (along with supplemental reading) at:
  23. *
  24. * http://c4dm.eecs.qmul.ac.uk/audioengineering/compressors/
  25. */
  26. typedef struct Compressor {
  27. ALsizei NumChans;
  28. ALuint SampleRate;
  29. struct {
  30. ALuint Knee : 1;
  31. ALuint Attack : 1;
  32. ALuint Release : 1;
  33. ALuint PostGain : 1;
  34. ALuint Declip : 1;
  35. } Auto;
  36. ALsizei LookAhead;
  37. ALfloat PreGain;
  38. ALfloat PostGain;
  39. ALfloat Threshold;
  40. ALfloat Slope;
  41. ALfloat Knee;
  42. ALfloat Attack;
  43. ALfloat Release;
  44. alignas(16) ALfloat SideChain[2*BUFFERSIZE];
  45. alignas(16) ALfloat CrestFactor[BUFFERSIZE];
  46. SlidingHold *Hold;
  47. ALfloat (*Delay)[BUFFERSIZE];
  48. ALsizei DelayIndex;
  49. ALfloat CrestCoeff;
  50. ALfloat GainEstimate;
  51. ALfloat AdaptCoeff;
  52. ALfloat LastPeakSq;
  53. ALfloat LastRmsSq;
  54. ALfloat LastRelease;
  55. ALfloat LastAttack;
  56. ALfloat LastGainDev;
  57. } Compressor;
  58. /* This sliding hold follows the input level with an instant attack and a
  59. * fixed duration hold before an instant release to the next highest level.
  60. * It is a sliding window maximum (descending maxima) implementation based on
  61. * Richard Harter's ascending minima algorithm available at:
  62. *
  63. * http://www.richardhartersworld.com/cri/2001/slidingmin.html
  64. */
  65. static ALfloat UpdateSlidingHold(SlidingHold *Hold, const ALsizei i, const ALfloat in)
  66. {
  67. const ALsizei mask = BUFFERSIZE - 1;
  68. const ALsizei length = Hold->Length;
  69. ALfloat *restrict values = Hold->Values;
  70. ALsizei *restrict expiries = Hold->Expiries;
  71. ALsizei lowerIndex = Hold->LowerIndex;
  72. ALsizei upperIndex = Hold->UpperIndex;
  73. if(i >= expiries[upperIndex])
  74. upperIndex = (upperIndex + 1) & mask;
  75. if(in >= values[upperIndex])
  76. {
  77. values[upperIndex] = in;
  78. expiries[upperIndex] = i + length;
  79. lowerIndex = upperIndex;
  80. }
  81. else
  82. {
  83. do {
  84. do {
  85. if(!(in >= values[lowerIndex]))
  86. goto found_place;
  87. } while(lowerIndex--);
  88. lowerIndex = mask;
  89. } while(1);
  90. found_place:
  91. lowerIndex = (lowerIndex + 1) & mask;
  92. values[lowerIndex] = in;
  93. expiries[lowerIndex] = i + length;
  94. }
  95. Hold->LowerIndex = lowerIndex;
  96. Hold->UpperIndex = upperIndex;
  97. return values[upperIndex];
  98. }
  99. static void ShiftSlidingHold(SlidingHold *Hold, const ALsizei n)
  100. {
  101. const ALsizei lowerIndex = Hold->LowerIndex;
  102. ALsizei *restrict expiries = Hold->Expiries;
  103. ALsizei i = Hold->UpperIndex;
  104. if(lowerIndex < i)
  105. {
  106. for(;i < BUFFERSIZE;i++)
  107. expiries[i] -= n;
  108. i = 0;
  109. }
  110. for(;i < lowerIndex;i++)
  111. expiries[i] -= n;
  112. expiries[i] -= n;
  113. }
  114. /* Multichannel compression is linked via the absolute maximum of all
  115. * channels.
  116. */
  117. static void LinkChannels(Compressor *Comp, const ALsizei SamplesToDo, ALfloat (*restrict OutBuffer)[BUFFERSIZE])
  118. {
  119. const ALsizei index = Comp->LookAhead;
  120. const ALsizei numChans = Comp->NumChans;
  121. ALfloat *restrict sideChain = Comp->SideChain;
  122. ALsizei c, i;
  123. ASSUME(SamplesToDo > 0);
  124. ASSUME(numChans > 0);
  125. for(i = 0;i < SamplesToDo;i++)
  126. sideChain[index + i] = 0.0f;
  127. for(c = 0;c < numChans;c++)
  128. {
  129. ALsizei offset = index;
  130. for(i = 0;i < SamplesToDo;i++)
  131. {
  132. sideChain[offset] = maxf(sideChain[offset], fabsf(OutBuffer[c][i]));
  133. ++offset;
  134. }
  135. }
  136. }
  137. /* This calculates the squared crest factor of the control signal for the
  138. * basic automation of the attack/release times. As suggested by the paper,
  139. * it uses an instantaneous squared peak detector and a squared RMS detector
  140. * both with 200ms release times.
  141. */
  142. static void CrestDetector(Compressor *Comp, const ALsizei SamplesToDo)
  143. {
  144. const ALfloat a_crest = Comp->CrestCoeff;
  145. const ALsizei index = Comp->LookAhead;
  146. const ALfloat *restrict sideChain = Comp->SideChain;
  147. ALfloat *restrict crestFactor = Comp->CrestFactor;
  148. ALfloat y2_peak = Comp->LastPeakSq;
  149. ALfloat y2_rms = Comp->LastRmsSq;
  150. ALsizei i;
  151. ASSUME(SamplesToDo > 0);
  152. for(i = 0;i < SamplesToDo;i++)
  153. {
  154. ALfloat x_abs = sideChain[index + i];
  155. ALfloat x2 = maxf(0.000001f, x_abs * x_abs);
  156. y2_peak = maxf(x2, lerp(x2, y2_peak, a_crest));
  157. y2_rms = lerp(x2, y2_rms, a_crest);
  158. crestFactor[i] = y2_peak / y2_rms;
  159. }
  160. Comp->LastPeakSq = y2_peak;
  161. Comp->LastRmsSq = y2_rms;
  162. }
  163. /* The side-chain starts with a simple peak detector (based on the absolute
  164. * value of the incoming signal) and performs most of its operations in the
  165. * log domain.
  166. */
  167. static void PeakDetector(Compressor *Comp, const ALsizei SamplesToDo)
  168. {
  169. const ALsizei index = Comp->LookAhead;
  170. ALfloat *restrict sideChain = Comp->SideChain;
  171. ALsizei i;
  172. ASSUME(SamplesToDo > 0);
  173. for(i = 0;i < SamplesToDo;i++)
  174. {
  175. const ALuint offset = index + i;
  176. const ALfloat x_abs = sideChain[offset];
  177. sideChain[offset] = logf(maxf(0.000001f, x_abs));
  178. }
  179. }
  180. /* An optional hold can be used to extend the peak detector so it can more
  181. * solidly detect fast transients. This is best used when operating as a
  182. * limiter.
  183. */
  184. static void PeakHoldDetector(Compressor *Comp, const ALsizei SamplesToDo)
  185. {
  186. const ALsizei index = Comp->LookAhead;
  187. ALfloat *restrict sideChain = Comp->SideChain;
  188. SlidingHold *hold = Comp->Hold;
  189. ALsizei i;
  190. ASSUME(SamplesToDo > 0);
  191. for(i = 0;i < SamplesToDo;i++)
  192. {
  193. const ALsizei offset = index + i;
  194. const ALfloat x_abs = sideChain[offset];
  195. const ALfloat x_G = logf(maxf(0.000001f, x_abs));
  196. sideChain[offset] = UpdateSlidingHold(hold, i, x_G);
  197. }
  198. ShiftSlidingHold(hold, SamplesToDo);
  199. }
  200. /* This is the heart of the feed-forward compressor. It operates in the log
  201. * domain (to better match human hearing) and can apply some basic automation
  202. * to knee width, attack/release times, make-up/post gain, and clipping
  203. * reduction.
  204. */
  205. static void GainCompressor(Compressor *Comp, const ALsizei SamplesToDo)
  206. {
  207. const bool autoKnee = Comp->Auto.Knee;
  208. const bool autoAttack = Comp->Auto.Attack;
  209. const bool autoRelease = Comp->Auto.Release;
  210. const bool autoPostGain = Comp->Auto.PostGain;
  211. const bool autoDeclip = Comp->Auto.Declip;
  212. const ALsizei lookAhead = Comp->LookAhead;
  213. const ALfloat threshold = Comp->Threshold;
  214. const ALfloat slope = Comp->Slope;
  215. const ALfloat attack = Comp->Attack;
  216. const ALfloat release = Comp->Release;
  217. const ALfloat c_est = Comp->GainEstimate;
  218. const ALfloat a_adp = Comp->AdaptCoeff;
  219. const ALfloat *restrict crestFactor = Comp->CrestFactor;
  220. ALfloat *restrict sideChain = Comp->SideChain;
  221. ALfloat postGain = Comp->PostGain;
  222. ALfloat knee = Comp->Knee;
  223. ALfloat t_att = attack;
  224. ALfloat t_rel = release - attack;
  225. ALfloat a_att = expf(-1.0f / t_att);
  226. ALfloat a_rel = expf(-1.0f / t_rel);
  227. ALfloat y_1 = Comp->LastRelease;
  228. ALfloat y_L = Comp->LastAttack;
  229. ALfloat c_dev = Comp->LastGainDev;
  230. ALsizei i;
  231. ASSUME(SamplesToDo > 0);
  232. for(i = 0;i < SamplesToDo;i++)
  233. {
  234. const ALfloat y2_crest = crestFactor[i];
  235. const ALfloat x_G = sideChain[lookAhead + i];
  236. const ALfloat x_over = x_G - threshold;
  237. ALfloat knee_h;
  238. ALfloat y_G;
  239. ALfloat x_L;
  240. if(autoKnee)
  241. knee = maxf(0.0f, 2.5f * (c_dev + c_est));
  242. knee_h = 0.5f * knee;
  243. /* This is the gain computer. It applies a static compression curve
  244. * to the control signal.
  245. */
  246. if(x_over <= -knee_h)
  247. y_G = 0.0f;
  248. else if(fabsf(x_over) < knee_h)
  249. y_G = (x_over + knee_h) * (x_over + knee_h) / (2.0f * knee);
  250. else
  251. y_G = x_over;
  252. x_L = -slope * y_G;
  253. if(autoAttack)
  254. {
  255. t_att = 2.0f * attack / y2_crest;
  256. a_att = expf(-1.0f / t_att);
  257. }
  258. if(autoRelease)
  259. {
  260. t_rel = 2.0f * release / y2_crest - t_att;
  261. a_rel = expf(-1.0f / t_rel);
  262. }
  263. /* Gain smoothing (ballistics) is done via a smooth decoupled peak
  264. * detector. The attack time is subtracted from the release time
  265. * above to compensate for the chained operating mode.
  266. */
  267. y_1 = maxf(x_L, lerp(x_L, y_1, a_rel));
  268. y_L = lerp(y_1, y_L, a_att);
  269. /* Knee width and make-up gain automation make use of a smoothed
  270. * measurement of deviation between the control signal and estimate.
  271. * The estimate is also used to bias the measurement to hot-start its
  272. * average.
  273. */
  274. c_dev = lerp(-y_L - c_est, c_dev, a_adp);
  275. if(autoPostGain)
  276. {
  277. /* Clipping reduction is only viable when make-up gain is being
  278. * automated. It modifies the deviation to further attenuate the
  279. * control signal when clipping is detected. The adaptation
  280. * time is sufficiently long enough to suppress further clipping
  281. * at the same output level.
  282. */
  283. if(autoDeclip)
  284. c_dev = maxf(c_dev, sideChain[i] - y_L - threshold - c_est);
  285. postGain = -(c_dev + c_est);
  286. }
  287. sideChain[i] = expf(postGain - y_L);
  288. }
  289. Comp->LastRelease = y_1;
  290. Comp->LastAttack = y_L;
  291. Comp->LastGainDev = c_dev;
  292. }
  293. /* Combined with the hold time, a look-ahead delay can improve handling of
  294. * fast transients by allowing the envelope time to converge prior to
  295. * reaching the offending impulse. This is best used when operating as a
  296. * limiter.
  297. */
  298. static void SignalDelay(Compressor *Comp, const ALsizei SamplesToDo, ALfloat (*restrict OutBuffer)[BUFFERSIZE])
  299. {
  300. const ALsizei mask = BUFFERSIZE - 1;
  301. const ALsizei numChans = Comp->NumChans;
  302. const ALsizei indexIn = Comp->DelayIndex;
  303. const ALsizei indexOut = Comp->DelayIndex - Comp->LookAhead;
  304. ALfloat (*restrict delay)[BUFFERSIZE] = Comp->Delay;
  305. ALsizei c, i;
  306. ASSUME(SamplesToDo > 0);
  307. ASSUME(numChans > 0);
  308. for(c = 0;c < numChans;c++)
  309. {
  310. for(i = 0;i < SamplesToDo;i++)
  311. {
  312. ALfloat sig = OutBuffer[c][i];
  313. OutBuffer[c][i] = delay[c][(indexOut + i) & mask];
  314. delay[c][(indexIn + i) & mask] = sig;
  315. }
  316. }
  317. Comp->DelayIndex = (indexIn + SamplesToDo) & mask;
  318. }
  319. /* The compressor is initialized with the following settings:
  320. *
  321. * NumChans - Number of channels to process.
  322. * SampleRate - Sample rate to process.
  323. * AutoKnee - Whether to automate the knee width parameter.
  324. * AutoAttack - Whether to automate the attack time parameter.
  325. * AutoRelease - Whether to automate the release time parameter.
  326. * AutoPostGain - Whether to automate the make-up (post) gain parameter.
  327. * AutoDeclip - Whether to automate clipping reduction. Ignored when
  328. * not automating make-up gain.
  329. * LookAheadTime - Look-ahead time (in seconds).
  330. * HoldTime - Peak hold-time (in seconds).
  331. * PreGainDb - Gain applied before detection (in dB).
  332. * PostGainDb - Make-up gain applied after compression (in dB).
  333. * ThresholdDb - Triggering threshold (in dB).
  334. * Ratio - Compression ratio (x:1). Set to INFINITY for true
  335. * limiting. Ignored when automating knee width.
  336. * KneeDb - Knee width (in dB). Ignored when automating knee
  337. * width.
  338. * AttackTimeMin - Attack time (in seconds). Acts as a maximum when
  339. * automating attack time.
  340. * ReleaseTimeMin - Release time (in seconds). Acts as a maximum when
  341. * automating release time.
  342. */
  343. Compressor* CompressorInit(const ALsizei NumChans, const ALuint SampleRate,
  344. const ALboolean AutoKnee, const ALboolean AutoAttack,
  345. const ALboolean AutoRelease, const ALboolean AutoPostGain,
  346. const ALboolean AutoDeclip, const ALfloat LookAheadTime,
  347. const ALfloat HoldTime, const ALfloat PreGainDb,
  348. const ALfloat PostGainDb, const ALfloat ThresholdDb,
  349. const ALfloat Ratio, const ALfloat KneeDb,
  350. const ALfloat AttackTime, const ALfloat ReleaseTime)
  351. {
  352. Compressor *Comp;
  353. ALsizei lookAhead;
  354. ALsizei hold;
  355. size_t size;
  356. lookAhead = (ALsizei)clampf(roundf(LookAheadTime*SampleRate), 0.0f, BUFFERSIZE-1);
  357. hold = (ALsizei)clampf(roundf(HoldTime*SampleRate), 0.0f, BUFFERSIZE-1);
  358. /* The sliding hold implementation doesn't handle a length of 1. A 1-sample
  359. * hold is useless anyway, it would only ever give back what was just given
  360. * to it.
  361. */
  362. if(hold == 1)
  363. hold = 0;
  364. size = sizeof(*Comp);
  365. if(lookAhead > 0)
  366. {
  367. size += sizeof(*Comp->Delay) * NumChans;
  368. if(hold > 0)
  369. size += sizeof(*Comp->Hold);
  370. }
  371. Comp = al_calloc(16, size);
  372. Comp->NumChans = NumChans;
  373. Comp->SampleRate = SampleRate;
  374. Comp->Auto.Knee = AutoKnee;
  375. Comp->Auto.Attack = AutoAttack;
  376. Comp->Auto.Release = AutoRelease;
  377. Comp->Auto.PostGain = AutoPostGain;
  378. Comp->Auto.Declip = AutoPostGain && AutoDeclip;
  379. Comp->LookAhead = lookAhead;
  380. Comp->PreGain = powf(10.0f, PreGainDb / 20.0f);
  381. Comp->PostGain = PostGainDb * logf(10.0f) / 20.0f;
  382. Comp->Threshold = ThresholdDb * logf(10.0f) / 20.0f;
  383. Comp->Slope = 1.0f / maxf(1.0f, Ratio) - 1.0f;
  384. Comp->Knee = maxf(0.0f, KneeDb * logf(10.0f) / 20.0f);
  385. Comp->Attack = maxf(1.0f, AttackTime * SampleRate);
  386. Comp->Release = maxf(1.0f, ReleaseTime * SampleRate);
  387. /* Knee width automation actually treats the compressor as a limiter. By
  388. * varying the knee width, it can effectively be seen as applying
  389. * compression over a wide range of ratios.
  390. */
  391. if(AutoKnee)
  392. Comp->Slope = -1.0f;
  393. if(lookAhead > 0)
  394. {
  395. if(hold > 0)
  396. {
  397. Comp->Hold = (SlidingHold*)(Comp + 1);
  398. Comp->Hold->Values[0] = -INFINITY;
  399. Comp->Hold->Expiries[0] = hold;
  400. Comp->Hold->Length = hold;
  401. Comp->Delay = (ALfloat(*)[])(Comp->Hold + 1);
  402. }
  403. else
  404. {
  405. Comp->Delay = (ALfloat(*)[])(Comp + 1);
  406. }
  407. }
  408. Comp->CrestCoeff = expf(-1.0f / (0.200f * SampleRate)); // 200ms
  409. Comp->GainEstimate = Comp->Threshold * -0.5f * Comp->Slope;
  410. Comp->AdaptCoeff = expf(-1.0f / (2.0f * SampleRate)); // 2s
  411. return Comp;
  412. }
  413. void ApplyCompression(Compressor *Comp, const ALsizei SamplesToDo, ALfloat (*restrict OutBuffer)[BUFFERSIZE])
  414. {
  415. const ALsizei numChans = Comp->NumChans;
  416. const ALfloat preGain = Comp->PreGain;
  417. ALfloat *restrict sideChain;
  418. ALsizei c, i;
  419. ASSUME(SamplesToDo > 0);
  420. ASSUME(numChans > 0);
  421. if(preGain != 1.0f)
  422. {
  423. for(c = 0;c < numChans;c++)
  424. {
  425. for(i = 0;i < SamplesToDo;i++)
  426. OutBuffer[c][i] *= preGain;
  427. }
  428. }
  429. LinkChannels(Comp, SamplesToDo, OutBuffer);
  430. if(Comp->Auto.Attack || Comp->Auto.Release)
  431. CrestDetector(Comp, SamplesToDo);
  432. if(Comp->Hold)
  433. PeakHoldDetector(Comp, SamplesToDo);
  434. else
  435. PeakDetector(Comp, SamplesToDo);
  436. GainCompressor(Comp, SamplesToDo);
  437. if(Comp->Delay)
  438. SignalDelay(Comp, SamplesToDo, OutBuffer);
  439. sideChain = Comp->SideChain;
  440. for(c = 0;c < numChans;c++)
  441. {
  442. for(i = 0;i < SamplesToDo;i++)
  443. OutBuffer[c][i] *= sideChain[i];
  444. }
  445. memmove(sideChain, sideChain+SamplesToDo, Comp->LookAhead*sizeof(ALfloat));
  446. }
  447. ALsizei GetCompressorLookAhead(const Compressor *Comp)
  448. { return Comp->LookAhead; }