Home | History | Annotate | Download | only in audio
      1 /*
      2  * Copyright (C) 2010 Google Inc. All rights reserved.
      3  *
      4  * Redistribution and use in source and binary forms, with or without
      5  * modification, are permitted provided that the following conditions
      6  * are met:
      7  *
      8  * 1.  Redistributions of source code must retain the above copyright
      9  *     notice, this list of conditions and the following disclaimer.
     10  * 2.  Redistributions in binary form must reproduce the above copyright
     11  *     notice, this list of conditions and the following disclaimer in the
     12  *     documentation and/or other materials provided with the distribution.
     13  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
     14  *     its contributors may be used to endorse or promote products derived
     15  *     from this software without specific prior written permission.
     16  *
     17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
     18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
     19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
     20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
     21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
     22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
     24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 #include "config.h"
     30 
     31 #if ENABLE(WEB_AUDIO)
     32 
     33 #include "platform/audio/Reverb.h"
     34 
     35 #include <math.h>
     36 #include "platform/audio/AudioBus.h"
     37 #include "platform/audio/VectorMath.h"
     38 #include "wtf/MathExtras.h"
     39 #include "wtf/OwnPtr.h"
     40 #include "wtf/PassOwnPtr.h"
     41 
     42 #if OS(MACOSX)
     43 using namespace std;
     44 #endif
     45 
     46 namespace blink {
     47 
     48 using namespace VectorMath;
     49 
     50 // Empirical gain calibration tested across many impulse responses to ensure perceived volume is same as dry (unprocessed) signal
     51 const float GainCalibration = -58;
     52 const float GainCalibrationSampleRate = 44100;
     53 
     54 // A minimum power value to when normalizing a silent (or very quiet) impulse response
     55 const float MinPower = 0.000125f;
     56 
     57 static float calculateNormalizationScale(AudioBus* response)
     58 {
     59     // Normalize by RMS power
     60     size_t numberOfChannels = response->numberOfChannels();
     61     size_t length = response->length();
     62 
     63     float power = 0;
     64 
     65     for (size_t i = 0; i < numberOfChannels; ++i) {
     66         float channelPower = 0;
     67         vsvesq(response->channel(i)->data(), 1, &channelPower, length);
     68         power += channelPower;
     69     }
     70 
     71     power = sqrt(power / (numberOfChannels * length));
     72 
     73     // Protect against accidental overload
     74     if (std::isinf(power) || std::isnan(power) || power < MinPower)
     75         power = MinPower;
     76 
     77     float scale = 1 / power;
     78 
     79     scale *= powf(10, GainCalibration * 0.05f); // calibrate to make perceived volume same as unprocessed
     80 
     81     // Scale depends on sample-rate.
     82     if (response->sampleRate())
     83         scale *= GainCalibrationSampleRate / response->sampleRate();
     84 
     85     // True-stereo compensation
     86     if (response->numberOfChannels() == 4)
     87         scale *= 0.5f;
     88 
     89     return scale;
     90 }
     91 
     92 Reverb::Reverb(AudioBus* impulseResponse, size_t renderSliceSize, size_t maxFFTSize, size_t numberOfChannels, bool useBackgroundThreads, bool normalize)
     93 {
     94     float scale = 1;
     95 
     96     if (normalize) {
     97         scale = calculateNormalizationScale(impulseResponse);
     98 
     99         if (scale)
    100             impulseResponse->scale(scale);
    101     }
    102 
    103     initialize(impulseResponse, renderSliceSize, maxFFTSize, numberOfChannels, useBackgroundThreads);
    104 
    105     // Undo scaling since this shouldn't be a destructive operation on impulseResponse.
    106     // FIXME: What about roundoff? Perhaps consider making a temporary scaled copy
    107     // instead of scaling and unscaling in place.
    108     if (normalize && scale)
    109         impulseResponse->scale(1 / scale);
    110 }
    111 
    112 void Reverb::initialize(AudioBus* impulseResponseBuffer, size_t renderSliceSize, size_t maxFFTSize, size_t numberOfChannels, bool useBackgroundThreads)
    113 {
    114     m_impulseResponseLength = impulseResponseBuffer->length();
    115 
    116     // The reverb can handle a mono impulse response and still do stereo processing
    117     size_t numResponseChannels = impulseResponseBuffer->numberOfChannels();
    118     m_convolvers.reserveCapacity(numberOfChannels);
    119 
    120     int convolverRenderPhase = 0;
    121     for (size_t i = 0; i < numResponseChannels; ++i) {
    122         AudioChannel* channel = impulseResponseBuffer->channel(i);
    123 
    124         OwnPtr<ReverbConvolver> convolver = adoptPtr(new ReverbConvolver(channel, renderSliceSize, maxFFTSize, convolverRenderPhase, useBackgroundThreads));
    125         m_convolvers.append(convolver.release());
    126 
    127         convolverRenderPhase += renderSliceSize;
    128     }
    129 
    130     // For "True" stereo processing we allocate a temporary buffer to avoid repeatedly allocating it in the process() method.
    131     // It can be bad to allocate memory in a real-time thread.
    132     if (numResponseChannels == 4)
    133         m_tempBuffer = AudioBus::create(2, MaxFrameSize);
    134 }
    135 
    136 void Reverb::process(const AudioBus* sourceBus, AudioBus* destinationBus, size_t framesToProcess)
    137 {
    138     // Do a fairly comprehensive sanity check.
    139     // If these conditions are satisfied, all of the source and destination pointers will be valid for the various matrixing cases.
    140     bool isSafeToProcess = sourceBus && destinationBus && sourceBus->numberOfChannels() > 0 && destinationBus->numberOfChannels() > 0
    141         && framesToProcess <= MaxFrameSize && framesToProcess <= sourceBus->length() && framesToProcess <= destinationBus->length();
    142 
    143     ASSERT(isSafeToProcess);
    144     if (!isSafeToProcess)
    145         return;
    146 
    147     // For now only handle mono or stereo output
    148     if (destinationBus->numberOfChannels() > 2) {
    149         destinationBus->zero();
    150         return;
    151     }
    152 
    153     AudioChannel* destinationChannelL = destinationBus->channel(0);
    154     const AudioChannel* sourceChannelL = sourceBus->channel(0);
    155 
    156     // Handle input -> output matrixing...
    157     size_t numInputChannels = sourceBus->numberOfChannels();
    158     size_t numOutputChannels = destinationBus->numberOfChannels();
    159     size_t numReverbChannels = m_convolvers.size();
    160 
    161     if (numInputChannels == 2 && numReverbChannels == 2 && numOutputChannels == 2) {
    162         // 2 -> 2 -> 2
    163         const AudioChannel* sourceChannelR = sourceBus->channel(1);
    164         AudioChannel* destinationChannelR = destinationBus->channel(1);
    165         m_convolvers[0]->process(sourceChannelL, destinationChannelL, framesToProcess);
    166         m_convolvers[1]->process(sourceChannelR, destinationChannelR, framesToProcess);
    167     } else  if (numInputChannels == 1 && numOutputChannels == 2 && numReverbChannels == 2) {
    168         // 1 -> 2 -> 2
    169         for (int i = 0; i < 2; ++i) {
    170             AudioChannel* destinationChannel = destinationBus->channel(i);
    171             m_convolvers[i]->process(sourceChannelL, destinationChannel, framesToProcess);
    172         }
    173     } else if (numInputChannels == 1 && numReverbChannels == 1 && numOutputChannels == 2) {
    174         // 1 -> 1 -> 2
    175         m_convolvers[0]->process(sourceChannelL, destinationChannelL, framesToProcess);
    176 
    177         // simply copy L -> R
    178         AudioChannel* destinationChannelR = destinationBus->channel(1);
    179         bool isCopySafe = destinationChannelL->data() && destinationChannelR->data() && destinationChannelL->length() >= framesToProcess && destinationChannelR->length() >= framesToProcess;
    180         ASSERT(isCopySafe);
    181         if (!isCopySafe)
    182             return;
    183         memcpy(destinationChannelR->mutableData(), destinationChannelL->data(), sizeof(float) * framesToProcess);
    184     } else if (numInputChannels == 1 && numReverbChannels == 1 && numOutputChannels == 1) {
    185         // 1 -> 1 -> 1
    186         m_convolvers[0]->process(sourceChannelL, destinationChannelL, framesToProcess);
    187     } else if (numInputChannels == 2 && numReverbChannels == 4 && numOutputChannels == 2) {
    188         // 2 -> 4 -> 2 ("True" stereo)
    189         const AudioChannel* sourceChannelR = sourceBus->channel(1);
    190         AudioChannel* destinationChannelR = destinationBus->channel(1);
    191 
    192         AudioChannel* tempChannelL = m_tempBuffer->channel(0);
    193         AudioChannel* tempChannelR = m_tempBuffer->channel(1);
    194 
    195         // Process left virtual source
    196         m_convolvers[0]->process(sourceChannelL, destinationChannelL, framesToProcess);
    197         m_convolvers[1]->process(sourceChannelL, destinationChannelR, framesToProcess);
    198 
    199         // Process right virtual source
    200         m_convolvers[2]->process(sourceChannelR, tempChannelL, framesToProcess);
    201         m_convolvers[3]->process(sourceChannelR, tempChannelR, framesToProcess);
    202 
    203         destinationBus->sumFrom(*m_tempBuffer);
    204     } else if (numInputChannels == 1 && numReverbChannels == 4 && numOutputChannels == 2) {
    205         // 1 -> 4 -> 2 (Processing mono with "True" stereo impulse response)
    206         // This is an inefficient use of a four-channel impulse response, but we should handle the case.
    207         AudioChannel* destinationChannelR = destinationBus->channel(1);
    208 
    209         AudioChannel* tempChannelL = m_tempBuffer->channel(0);
    210         AudioChannel* tempChannelR = m_tempBuffer->channel(1);
    211 
    212         // Process left virtual source
    213         m_convolvers[0]->process(sourceChannelL, destinationChannelL, framesToProcess);
    214         m_convolvers[1]->process(sourceChannelL, destinationChannelR, framesToProcess);
    215 
    216         // Process right virtual source
    217         m_convolvers[2]->process(sourceChannelL, tempChannelL, framesToProcess);
    218         m_convolvers[3]->process(sourceChannelL, tempChannelR, framesToProcess);
    219 
    220         destinationBus->sumFrom(*m_tempBuffer);
    221     } else {
    222         // Handle gracefully any unexpected / unsupported matrixing
    223         // FIXME: add code for 5.1 support...
    224         destinationBus->zero();
    225     }
    226 }
    227 
    228 void Reverb::reset()
    229 {
    230     for (size_t i = 0; i < m_convolvers.size(); ++i)
    231         m_convolvers[i]->reset();
    232 }
    233 
    234 size_t Reverb::latencyFrames() const
    235 {
    236     return !m_convolvers.isEmpty() ? m_convolvers.first()->latencyFrames() : 0;
    237 }
    238 
    239 } // namespace blink
    240 
    241 #endif // ENABLE(WEB_AUDIO)
    242