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 * 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.
12 *
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.
23 */
24
25#include "config.h"
26
27#if ENABLE(WEB_AUDIO)
28
29#include "DelayDSPKernel.h"
30
31#include "AudioUtilities.h"
32#include <algorithm>
33
34namespace WebCore {
35
36const float SmoothingTimeConstant = 0.020f; // 20ms
37
38DelayDSPKernel::DelayDSPKernel(DelayProcessor* processor)
39    : AudioDSPKernel(processor)
40    , m_writeIndex(0)
41    , m_firstTime(true)
42    , m_delayTimes(AudioNode::ProcessingSizeInFrames)
43{
44    ASSERT(processor && processor->sampleRate() > 0);
45    if (!(processor && processor->sampleRate() > 0))
46        return;
47
48    m_maxDelayTime = processor->maxDelayTime();
49    ASSERT(m_maxDelayTime >= 0);
50    if (m_maxDelayTime < 0)
51        return;
52
53    m_buffer.allocate(bufferLengthForDelay(m_maxDelayTime, processor->sampleRate()));
54    m_buffer.zero();
55
56    m_smoothingRate = AudioUtilities::discreteTimeConstantForSampleRate(SmoothingTimeConstant, processor->sampleRate());
57}
58
59DelayDSPKernel::DelayDSPKernel(double maxDelayTime, float sampleRate)
60    : AudioDSPKernel(sampleRate)
61    , m_maxDelayTime(maxDelayTime)
62    , m_writeIndex(0)
63    , m_firstTime(true)
64{
65    ASSERT(maxDelayTime > 0.0);
66    if (maxDelayTime <= 0.0)
67        return;
68
69    size_t bufferLength = bufferLengthForDelay(maxDelayTime, sampleRate);
70    ASSERT(bufferLength);
71    if (!bufferLength)
72        return;
73
74    m_buffer.allocate(bufferLength);
75    m_buffer.zero();
76
77    m_smoothingRate = AudioUtilities::discreteTimeConstantForSampleRate(SmoothingTimeConstant, sampleRate);
78}
79
80size_t DelayDSPKernel::bufferLengthForDelay(double maxDelayTime, double sampleRate) const
81{
82    // Compute the length of the buffer needed to handle a max delay of |maxDelayTime|. One is
83    // added to handle the case where the actual delay equals the maximum delay.
84    return 1 + AudioUtilities::timeToSampleFrame(maxDelayTime, sampleRate);
85}
86
87void DelayDSPKernel::process(const float* source, float* destination, size_t framesToProcess)
88{
89    size_t bufferLength = m_buffer.size();
90    float* buffer = m_buffer.data();
91
92    ASSERT(bufferLength);
93    if (!bufferLength)
94        return;
95
96    ASSERT(source && destination);
97    if (!source || !destination)
98        return;
99
100    float sampleRate = this->sampleRate();
101    double delayTime = 0;
102    float* delayTimes = m_delayTimes.data();
103    double maxTime = maxDelayTime();
104
105    bool sampleAccurate = delayProcessor() && delayProcessor()->delayTime()->hasSampleAccurateValues();
106
107    if (sampleAccurate)
108        delayProcessor()->delayTime()->calculateSampleAccurateValues(delayTimes, framesToProcess);
109    else {
110        delayTime = delayProcessor() ? delayProcessor()->delayTime()->finalValue() : m_desiredDelayFrames / sampleRate;
111
112        // Make sure the delay time is in a valid range.
113        delayTime = std::min(maxTime, delayTime);
114        delayTime = std::max(0.0, delayTime);
115
116        if (m_firstTime) {
117            m_currentDelayTime = delayTime;
118            m_firstTime = false;
119        }
120    }
121
122    for (unsigned i = 0; i < framesToProcess; ++i) {
123        if (sampleAccurate) {
124            delayTime = delayTimes[i];
125            delayTime = std::min(maxTime, delayTime);
126            delayTime = std::max(0.0, delayTime);
127            m_currentDelayTime = delayTime;
128        } else {
129            // Approach desired delay time.
130            m_currentDelayTime += (delayTime - m_currentDelayTime) * m_smoothingRate;
131        }
132
133        double desiredDelayFrames = m_currentDelayTime * sampleRate;
134
135        double readPosition = m_writeIndex + bufferLength - desiredDelayFrames;
136        if (readPosition >= bufferLength)
137            readPosition -= bufferLength;
138
139        // Linearly interpolate in-between delay times.
140        int readIndex1 = static_cast<int>(readPosition);
141        int readIndex2 = (readIndex1 + 1) % bufferLength;
142        double interpolationFactor = readPosition - readIndex1;
143
144        double input = static_cast<float>(*source++);
145        buffer[m_writeIndex] = static_cast<float>(input);
146        m_writeIndex = (m_writeIndex + 1) % bufferLength;
147
148        double sample1 = buffer[readIndex1];
149        double sample2 = buffer[readIndex2];
150
151        double output = (1.0 - interpolationFactor) * sample1 + interpolationFactor * sample2;
152
153        *destination++ = static_cast<float>(output);
154    }
155}
156
157void DelayDSPKernel::reset()
158{
159    m_firstTime = true;
160    m_buffer.zero();
161}
162
163double DelayDSPKernel::tailTime() const
164{
165    return m_maxDelayTime;
166}
167
168double DelayDSPKernel::latencyTime() const
169{
170    return 0;
171}
172
173} // namespace WebCore
174
175#endif // ENABLE(WEB_AUDIO)
176