1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
|
/*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if ENABLE(WEB_AUDIO)
#include "DynamicsCompressorKernel.h"
#include "AudioUtilities.h"
#include "DenormalDisabler.h"
#include <algorithm>
#include <wtf/MathExtras.h>
using namespace std;
namespace WebCore {
using namespace AudioUtilities;
// Metering hits peaks instantly, but releases this fast (in seconds).
const float meteringReleaseTimeConstant = 0.325f;
// Exponential saturation curve.
static float saturate(float x, float k)
{
return 1 - exp(-k * x);
}
DynamicsCompressorKernel::DynamicsCompressorKernel(float sampleRate)
: m_sampleRate(sampleRate)
, m_lastPreDelayFrames(DefaultPreDelayFrames)
, m_preDelayBufferL(MaxPreDelayFrames)
, m_preDelayBufferR(MaxPreDelayFrames)
, m_preDelayReadIndex(0)
, m_preDelayWriteIndex(DefaultPreDelayFrames)
{
// Initializes most member variables
reset();
m_meteringReleaseK = discreteTimeConstantForSampleRate(meteringReleaseTimeConstant, sampleRate);
}
void DynamicsCompressorKernel::setPreDelayTime(float preDelayTime)
{
// Re-configure look-ahead section pre-delay if delay time has changed.
unsigned preDelayFrames = preDelayTime * sampleRate();
if (preDelayFrames > MaxPreDelayFrames - 1)
preDelayFrames = MaxPreDelayFrames - 1;
if (m_lastPreDelayFrames != preDelayFrames) {
m_lastPreDelayFrames = preDelayFrames;
m_preDelayBufferL.zero();
m_preDelayBufferR.zero();
m_preDelayReadIndex = 0;
m_preDelayWriteIndex = preDelayFrames;
}
}
void DynamicsCompressorKernel::process(const float* sourceL,
float* destinationL,
const float* sourceR, /* stereo-linked */
float* destinationR,
unsigned framesToProcess,
float dbThreshold,
float dbHeadroom,
float attackTime,
float releaseTime,
float preDelayTime,
float dbPostGain,
float effectBlend, /* equal power crossfade */
float releaseZone1,
float releaseZone2,
float releaseZone3,
float releaseZone4
)
{
bool isStereo = destinationR;
float sampleRate = this->sampleRate();
float dryMix = 1 - effectBlend;
float wetMix = effectBlend;
// Threshold and headroom.
float linearThreshold = decibelsToLinear(dbThreshold);
float linearHeadroom = decibelsToLinear(dbHeadroom);
// Makeup gain.
float maximum = 1.05f * linearHeadroom * linearThreshold;
float kk = (maximum - linearThreshold);
float inverseKK = 1 / kk;
float fullRangeGain = (linearThreshold + kk * saturate(1 - linearThreshold, 1));
float fullRangeMakeupGain = 1 / fullRangeGain;
// Empirical/perceptual tuning.
fullRangeMakeupGain = powf(fullRangeMakeupGain, 0.6f);
float masterLinearGain = decibelsToLinear(dbPostGain) * fullRangeMakeupGain;
// Attack parameters.
attackTime = max(0.001f, attackTime);
float attackFrames = attackTime * sampleRate;
// Release parameters.
float releaseFrames = sampleRate * releaseTime;
// Detector release time.
float satReleaseTime = 0.0025f;
float satReleaseFrames = satReleaseTime * sampleRate;
// Create a smooth function which passes through four points.
// Polynomial of the form
// y = a + b*x + c*x^2 + d*x^3 + e*x^4;
float y1 = releaseFrames * releaseZone1;
float y2 = releaseFrames * releaseZone2;
float y3 = releaseFrames * releaseZone3;
float y4 = releaseFrames * releaseZone4;
// All of these coefficients were derived for 4th order polynomial curve fitting where the y values
// match the evenly spaced x values as follows: (y1 : x == 0, y2 : x == 1, y3 : x == 2, y4 : x == 3)
float kA = 0.9999999999999998f*y1 + 1.8432219684323923e-16f*y2 - 1.9373394351676423e-16f*y3 + 8.824516011816245e-18f*y4;
float kB = -1.5788320352845888f*y1 + 2.3305837032074286f*y2 - 0.9141194204840429f*y3 + 0.1623677525612032f*y4;
float kC = 0.5334142869106424f*y1 - 1.272736789213631f*y2 + 0.9258856042207512f*y3 - 0.18656310191776226f*y4;
float kD = 0.08783463138207234f*y1 - 0.1694162967925622f*y2 + 0.08588057951595272f*y3 - 0.00429891410546283f*y4;
float kE = -0.042416883008123074f*y1 + 0.1115693827987602f*y2 - 0.09764676325265872f*y3 + 0.028494263462021576f*y4;
// x ranges from 0 -> 3 0 1 2 3
// -15 -10 -5 0db
// y calculates adaptive release frames depending on the amount of compression.
setPreDelayTime(preDelayTime);
const int nDivisionFrames = 32;
const int nDivisions = framesToProcess / nDivisionFrames;
for (int i = 0; i < nDivisions; ++i) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Calculate desired gain
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Fix gremlins.
if (isnan(m_detectorAverage))
m_detectorAverage = 1;
if (isinf(m_detectorAverage))
m_detectorAverage = 1;
float desiredGain = m_detectorAverage;
// Pre-warp so we get desiredGain after sin() warp below.
float scaledDesiredGain = asinf(desiredGain) / (0.5f * piFloat);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Deal with envelopes
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// envelopeRate is the rate we slew from current compressor level to the desired level.
// The exact rate depends on if we're attacking or releasing and by how much.
float envelopeRate;
bool isReleasing = scaledDesiredGain > m_compressorGain;
// compressionDiffDb is the difference between current compression level and the desired level.
float compressionDiffDb = linearToDecibels(m_compressorGain / scaledDesiredGain);
if (isReleasing) {
// Release mode - compressionDiffDb should be negative dB
m_maxAttackCompressionDiffDb = -1;
// Fix gremlins.
if (isnan(compressionDiffDb))
compressionDiffDb = -1;
if (isinf(compressionDiffDb))
compressionDiffDb = -1;
// Adaptive release - higher compression (lower compressionDiffDb) releases faster.
// Contain within range: -12 -> 0 then scale to go from 0 -> 3
float x = compressionDiffDb;
x = max(-12.0f, x);
x = min(0.0f, x);
x = 0.25f * (x + 12);
// Compute adaptive release curve using 4th order polynomial.
// Normal values for the polynomial coefficients would create a monotonically increasing function.
float x2 = x * x;
float x3 = x2 * x;
float x4 = x2 * x2;
float releaseFrames = kA + kB * x + kC * x2 + kD * x3 + kE * x4;
#define kSpacingDb 5
float dbPerFrame = kSpacingDb / releaseFrames;
envelopeRate = decibelsToLinear(dbPerFrame);
} else {
// Attack mode - compressionDiffDb should be positive dB
// Fix gremlins.
if (isnan(compressionDiffDb))
compressionDiffDb = 1;
if (isinf(compressionDiffDb))
compressionDiffDb = 1;
// As long as we're still in attack mode, use a rate based off
// the largest compressionDiffDb we've encountered so far.
if (m_maxAttackCompressionDiffDb == -1 || m_maxAttackCompressionDiffDb < compressionDiffDb)
m_maxAttackCompressionDiffDb = compressionDiffDb;
float effAttenDiffDb = max(0.5f, m_maxAttackCompressionDiffDb);
float x = 0.25f / effAttenDiffDb;
envelopeRate = 1 - powf(x, 1 / attackFrames);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Inner loop - calculate shaped power average - apply compression.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
{
float* delayBufferL = m_preDelayBufferL.data();
float* delayBufferR = m_preDelayBufferR.data();
int preDelayReadIndex = m_preDelayReadIndex;
int preDelayWriteIndex = m_preDelayWriteIndex;
float detectorAverage = m_detectorAverage;
float compressorGain = m_compressorGain;
int loopFrames = nDivisionFrames;
while (loopFrames--) {
float compressorInput;
float inputL;
float inputR = 0;
// Predelay signal, computing compression amount from un-delayed version.
if (isStereo) {
float undelayedL = *sourceL++;
float undelayedR = *sourceR++;
compressorInput = 0.5f * (undelayedL + undelayedR);
inputL = delayBufferL[preDelayReadIndex];
inputR = delayBufferR[preDelayReadIndex];
delayBufferL[preDelayWriteIndex] = undelayedL;
delayBufferR[preDelayWriteIndex] = undelayedR;
} else {
compressorInput = *sourceL++;
inputL = delayBufferL[preDelayReadIndex];
delayBufferL[preDelayWriteIndex] = compressorInput;
}
preDelayReadIndex = (preDelayReadIndex + 1) & MaxPreDelayFramesMask;
preDelayWriteIndex = (preDelayWriteIndex + 1) & MaxPreDelayFramesMask;
// Calculate shaped power on undelayed input.
float scaledInput = compressorInput;
float absInput = scaledInput > 0 ? scaledInput : -scaledInput;
// Put through shaping curve.
// This is linear up to the threshold, then exponentially approaches the maximum (headroom amount above threshold).
// The transition from the threshold to the exponential portion is smooth (1st derivative matched).
float shapedInput = absInput < linearThreshold ? absInput : linearThreshold + kk * saturate(absInput - linearThreshold, inverseKK);
float attenuation = absInput <= 0.0001f ? 1 : shapedInput / absInput;
float attenuationDb = -linearToDecibels(attenuation);
attenuationDb = max(2.0f, attenuationDb);
float dbPerFrame = attenuationDb / satReleaseFrames;
float satReleaseRate = decibelsToLinear(dbPerFrame) - 1;
bool isRelease = (attenuation > detectorAverage);
float rate = isRelease ? satReleaseRate : 1;
detectorAverage += (attenuation - detectorAverage) * rate;
detectorAverage = min(1.0f, detectorAverage);
// Fix gremlins.
if (isnan(detectorAverage))
detectorAverage = 1;
if (isinf(detectorAverage))
detectorAverage = 1;
// Exponential approach to desired gain.
if (envelopeRate < 1) {
// Attack - reduce gain to desired.
compressorGain += (scaledDesiredGain - compressorGain) * envelopeRate;
} else {
// Release - exponentially increase gain to 1.0
compressorGain *= envelopeRate;
compressorGain = min(1.0f, compressorGain);
}
// Warp pre-compression gain to smooth out sharp exponential transition points.
float postWarpCompressorGain = sinf(0.5f * piFloat * compressorGain);
// Calculate total gain using master gain and effect blend.
float totalGain = dryMix + wetMix * masterLinearGain * postWarpCompressorGain;
// Calculate metering.
float dbRealGain = 20 * log10(postWarpCompressorGain);
if (dbRealGain < m_meteringGain)
m_meteringGain = dbRealGain;
else
m_meteringGain += (dbRealGain - m_meteringGain) * m_meteringReleaseK;
// Apply final gain.
if (isStereo) {
float outputL = inputL;
float outputR = inputR;
outputL *= totalGain;
outputR *= totalGain;
*destinationL++ = outputL;
*destinationR++ = outputR;
} else
*destinationL++ = inputL * totalGain;
}
// Locals back to member variables.
m_preDelayReadIndex = preDelayReadIndex;
m_preDelayWriteIndex = preDelayWriteIndex;
m_detectorAverage = DenormalDisabler::flushDenormalFloatToZero(detectorAverage);
m_compressorGain = DenormalDisabler::flushDenormalFloatToZero(compressorGain);
}
}
}
void DynamicsCompressorKernel::reset()
{
m_detectorAverage = 0;
m_compressorGain = 1;
m_meteringGain = 1;
// Predelay section.
m_preDelayBufferL.zero();
m_preDelayBufferR.zero();
m_preDelayReadIndex = 0;
m_preDelayWriteIndex = DefaultPreDelayFrames;
m_maxAttackCompressionDiffDb = -1; // uninitialized state
}
} // namespace WebCore
#endif // ENABLE(WEB_AUDIO)
|