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