2 * Copyright (C) 2010, Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16 * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
17 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
18 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
19 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
20 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
22 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 #include "modules/webaudio/RealtimeAnalyser.h"
31 #include "platform/audio/AudioBus.h"
32 #include "platform/audio/AudioUtilities.h"
33 #include "platform/audio/FFTFrame.h"
34 #include "platform/audio/VectorMath.h"
38 #include "wtf/Complex.h"
39 #include "wtf/Float32Array.h"
40 #include "wtf/MainThread.h"
41 #include "wtf/MathExtras.h"
42 #include "wtf/Uint8Array.h"
48 const double RealtimeAnalyser::DefaultSmoothingTimeConstant = 0.8;
49 const double RealtimeAnalyser::DefaultMinDecibels = -100;
50 const double RealtimeAnalyser::DefaultMaxDecibels = -30;
52 const unsigned RealtimeAnalyser::DefaultFFTSize = 2048;
53 // All FFT implementations are expected to handle power-of-two sizes MinFFTSize <= size <= MaxFFTSize.
54 const unsigned RealtimeAnalyser::MinFFTSize = 32;
55 const unsigned RealtimeAnalyser::MaxFFTSize = 2048;
56 const unsigned RealtimeAnalyser::InputBufferSize = RealtimeAnalyser::MaxFFTSize * 2;
58 RealtimeAnalyser::RealtimeAnalyser()
59 : m_inputBuffer(InputBufferSize)
61 , m_fftSize(DefaultFFTSize)
62 , m_magnitudeBuffer(DefaultFFTSize / 2)
63 , m_smoothingTimeConstant(DefaultSmoothingTimeConstant)
64 , m_minDecibels(DefaultMinDecibels)
65 , m_maxDecibels(DefaultMaxDecibels)
67 m_analysisFrame = adoptPtr(new FFTFrame(DefaultFFTSize));
70 bool RealtimeAnalyser::setFftSize(size_t size)
72 ASSERT(isMainThread());
74 // Only allow powers of two.
75 unsigned log2size = static_cast<unsigned>(log2(size));
76 bool isPOT(1UL << log2size == size);
78 if (!isPOT || size > MaxFFTSize || size < MinFFTSize)
81 if (m_fftSize != size) {
82 m_analysisFrame = adoptPtr(new FFTFrame(size));
83 // m_magnitudeBuffer has size = fftSize / 2 because it contains floats reduced from complex values in m_analysisFrame.
84 m_magnitudeBuffer.allocate(size / 2);
91 void RealtimeAnalyser::writeInput(AudioBus* bus, size_t framesToProcess)
93 bool isBusGood = bus && bus->numberOfChannels() > 0 && bus->channel(0)->length() >= framesToProcess;
98 // FIXME : allow to work with non-FFTSize divisible chunking
99 bool isDestinationGood = m_writeIndex < m_inputBuffer.size() && m_writeIndex + framesToProcess <= m_inputBuffer.size();
100 ASSERT(isDestinationGood);
101 if (!isDestinationGood)
104 // Perform real-time analysis
105 const float* source = bus->channel(0)->data();
106 float* dest = m_inputBuffer.data() + m_writeIndex;
108 // The source has already been sanity checked with isBusGood above.
109 memcpy(dest, source, sizeof(float) * framesToProcess);
111 // Sum all channels in one if numberOfChannels > 1.
112 unsigned numberOfChannels = bus->numberOfChannels();
113 if (numberOfChannels > 1) {
114 for (unsigned i = 1; i < numberOfChannels; i++) {
115 source = bus->channel(i)->data();
116 VectorMath::vadd(dest, 1, source, 1, dest, 1, framesToProcess);
118 const float scale = 1.0 / numberOfChannels;
119 VectorMath::vsmul(dest, 1, &scale, dest, 1, framesToProcess);
122 m_writeIndex += framesToProcess;
123 if (m_writeIndex >= InputBufferSize)
129 void applyWindow(float* p, size_t n)
131 ASSERT(isMainThread());
135 double a0 = 0.5 * (1 - alpha);
137 double a2 = 0.5 * alpha;
139 for (unsigned i = 0; i < n; ++i) {
140 double x = static_cast<double>(i) / static_cast<double>(n);
141 double window = a0 - a1 * cos(2 * piDouble * x) + a2 * cos(4 * piDouble * x);
142 p[i] *= float(window);
148 void RealtimeAnalyser::doFFTAnalysis()
150 ASSERT(isMainThread());
152 // Unroll the input buffer into a temporary buffer, where we'll apply an analysis window followed by an FFT.
153 size_t fftSize = this->fftSize();
155 AudioFloatArray temporaryBuffer(fftSize);
156 float* inputBuffer = m_inputBuffer.data();
157 float* tempP = temporaryBuffer.data();
159 // Take the previous fftSize values from the input buffer and copy into the temporary buffer.
160 unsigned writeIndex = m_writeIndex;
161 if (writeIndex < fftSize) {
162 memcpy(tempP, inputBuffer + writeIndex - fftSize + InputBufferSize, sizeof(*tempP) * (fftSize - writeIndex));
163 memcpy(tempP + fftSize - writeIndex, inputBuffer, sizeof(*tempP) * writeIndex);
165 memcpy(tempP, inputBuffer + writeIndex - fftSize, sizeof(*tempP) * fftSize);
168 // Window the input samples.
169 applyWindow(tempP, fftSize);
172 m_analysisFrame->doFFT(tempP);
174 float* realP = m_analysisFrame->realData();
175 float* imagP = m_analysisFrame->imagData();
177 // Blow away the packed nyquist component.
180 // Normalize so than an input sine wave at 0dBfs registers as 0dBfs (undo FFT scaling factor).
181 const double magnitudeScale = 1.0 / DefaultFFTSize;
183 // A value of 0 does no averaging with the previous result. Larger values produce slower, but smoother changes.
184 double k = m_smoothingTimeConstant;
188 // Convert the analysis data from complex to magnitude and average with the previous result.
189 float* destination = magnitudeBuffer().data();
190 size_t n = magnitudeBuffer().size();
191 for (size_t i = 0; i < n; ++i) {
192 Complex c(realP[i], imagP[i]);
193 double scalarMagnitude = abs(c) * magnitudeScale;
194 destination[i] = float(k * destination[i] + (1 - k) * scalarMagnitude);
198 void RealtimeAnalyser::getFloatFrequencyData(Float32Array* destinationArray)
200 ASSERT(isMainThread());
202 if (!destinationArray)
207 // Convert from linear magnitude to floating-point decibels.
208 const double minDecibels = m_minDecibels;
209 unsigned sourceLength = magnitudeBuffer().size();
210 size_t len = min(sourceLength, destinationArray->length());
212 const float* source = magnitudeBuffer().data();
213 float* destination = destinationArray->data();
215 for (unsigned i = 0; i < len; ++i) {
216 float linearValue = source[i];
217 double dbMag = !linearValue ? minDecibels : AudioUtilities::linearToDecibels(linearValue);
218 destination[i] = float(dbMag);
223 void RealtimeAnalyser::getByteFrequencyData(Uint8Array* destinationArray)
225 ASSERT(isMainThread());
227 if (!destinationArray)
232 // Convert from linear magnitude to unsigned-byte decibels.
233 unsigned sourceLength = magnitudeBuffer().size();
234 size_t len = min(sourceLength, destinationArray->length());
236 const double rangeScaleFactor = m_maxDecibels == m_minDecibels ? 1 : 1 / (m_maxDecibels - m_minDecibels);
237 const double minDecibels = m_minDecibels;
239 const float* source = magnitudeBuffer().data();
240 unsigned char* destination = destinationArray->data();
242 for (unsigned i = 0; i < len; ++i) {
243 float linearValue = source[i];
244 double dbMag = !linearValue ? minDecibels : AudioUtilities::linearToDecibels(linearValue);
246 // The range m_minDecibels to m_maxDecibels will be scaled to byte values from 0 to UCHAR_MAX.
247 double scaledValue = UCHAR_MAX * (dbMag - minDecibels) * rangeScaleFactor;
249 // Clip to valid range.
252 if (scaledValue > UCHAR_MAX)
253 scaledValue = UCHAR_MAX;
255 destination[i] = static_cast<unsigned char>(scaledValue);
260 void RealtimeAnalyser::getByteTimeDomainData(Uint8Array* destinationArray)
262 ASSERT(isMainThread());
264 if (!destinationArray)
267 unsigned fftSize = this->fftSize();
268 size_t len = min(fftSize, destinationArray->length());
270 bool isInputBufferGood = m_inputBuffer.size() == InputBufferSize && m_inputBuffer.size() > fftSize;
271 ASSERT(isInputBufferGood);
272 if (!isInputBufferGood)
275 float* inputBuffer = m_inputBuffer.data();
276 unsigned char* destination = destinationArray->data();
278 unsigned writeIndex = m_writeIndex;
280 for (unsigned i = 0; i < len; ++i) {
281 // Buffer access is protected due to modulo operation.
282 float value = inputBuffer[(i + writeIndex - fftSize + InputBufferSize) % InputBufferSize];
284 // Scale from nominal -1 -> +1 to unsigned byte.
285 double scaledValue = 128 * (value + 1);
287 // Clip to valid range.
290 if (scaledValue > UCHAR_MAX)
291 scaledValue = UCHAR_MAX;
293 destination[i] = static_cast<unsigned char>(scaledValue);
298 } // namespace WebCore
300 #endif // ENABLE(WEB_AUDIO)