Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / modules / webaudio / AudioScheduledSourceNode.cpp
1 /*
2  * Copyright (C) 2012, 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 "modules/webaudio/AudioScheduledSourceNode.h"
30
31 #include "bindings/v8/ExceptionState.h"
32 #include "core/dom/ExceptionCode.h"
33 #include "core/events/Event.h"
34 #include "platform/audio/AudioUtilities.h"
35 #include "modules/webaudio/AudioContext.h"
36 #include <algorithm>
37 #include "wtf/MathExtras.h"
38
39 using namespace std;
40
41 namespace WebCore {
42
43 const double AudioScheduledSourceNode::UnknownTime = -1;
44
45 AudioScheduledSourceNode::AudioScheduledSourceNode(AudioContext* context, float sampleRate)
46     : AudioSourceNode(context, sampleRate)
47     , m_playbackState(UNSCHEDULED_STATE)
48     , m_startTime(0)
49     , m_endTime(UnknownTime)
50     , m_hasEndedListener(false)
51 {
52 }
53
54 void AudioScheduledSourceNode::updateSchedulingInfo(size_t quantumFrameSize,
55                                                     AudioBus* outputBus,
56                                                     size_t& quantumFrameOffset,
57                                                     size_t& nonSilentFramesToProcess)
58 {
59     ASSERT(outputBus);
60     if (!outputBus)
61         return;
62
63     ASSERT(quantumFrameSize == AudioNode::ProcessingSizeInFrames);
64     if (quantumFrameSize != AudioNode::ProcessingSizeInFrames)
65         return;
66
67     double sampleRate = this->sampleRate();
68
69     // quantumStartFrame     : Start frame of the current time quantum.
70     // quantumEndFrame       : End frame of the current time quantum.
71     // startFrame            : Start frame for this source.
72     // endFrame              : End frame for this source.
73     size_t quantumStartFrame = context()->currentSampleFrame();
74     size_t quantumEndFrame = quantumStartFrame + quantumFrameSize;
75     size_t startFrame = AudioUtilities::timeToSampleFrame(m_startTime, sampleRate);
76     size_t endFrame = m_endTime == UnknownTime ? 0 : AudioUtilities::timeToSampleFrame(m_endTime, sampleRate);
77
78     // If we know the end time and it's already passed, then don't bother doing any more rendering this cycle.
79     if (m_endTime != UnknownTime && endFrame <= quantumStartFrame)
80         finish();
81
82     if (m_playbackState == UNSCHEDULED_STATE || m_playbackState == FINISHED_STATE || startFrame >= quantumEndFrame) {
83         // Output silence.
84         outputBus->zero();
85         nonSilentFramesToProcess = 0;
86         return;
87     }
88
89     // Check if it's time to start playing.
90     if (m_playbackState == SCHEDULED_STATE) {
91         // Increment the active source count only if we're transitioning from SCHEDULED_STATE to PLAYING_STATE.
92         m_playbackState = PLAYING_STATE;
93         context()->incrementActiveSourceCount();
94     }
95
96     quantumFrameOffset = startFrame > quantumStartFrame ? startFrame - quantumStartFrame : 0;
97     quantumFrameOffset = min(quantumFrameOffset, quantumFrameSize); // clamp to valid range
98     nonSilentFramesToProcess = quantumFrameSize - quantumFrameOffset;
99
100     if (!nonSilentFramesToProcess) {
101         // Output silence.
102         outputBus->zero();
103         return;
104     }
105
106     // Handle silence before we start playing.
107     // Zero any initial frames representing silence leading up to a rendering start time in the middle of the quantum.
108     if (quantumFrameOffset) {
109         for (unsigned i = 0; i < outputBus->numberOfChannels(); ++i)
110             memset(outputBus->channel(i)->mutableData(), 0, sizeof(float) * quantumFrameOffset);
111     }
112
113     // Handle silence after we're done playing.
114     // If the end time is somewhere in the middle of this time quantum, then zero out the
115     // frames from the end time to the very end of the quantum.
116     if (m_endTime != UnknownTime && endFrame >= quantumStartFrame && endFrame < quantumEndFrame) {
117         size_t zeroStartFrame = endFrame - quantumStartFrame;
118         size_t framesToZero = quantumFrameSize - zeroStartFrame;
119
120         bool isSafe = zeroStartFrame < quantumFrameSize && framesToZero <= quantumFrameSize && zeroStartFrame + framesToZero <= quantumFrameSize;
121         ASSERT(isSafe);
122
123         if (isSafe) {
124             if (framesToZero > nonSilentFramesToProcess)
125                 nonSilentFramesToProcess = 0;
126             else
127                 nonSilentFramesToProcess -= framesToZero;
128
129             for (unsigned i = 0; i < outputBus->numberOfChannels(); ++i)
130                 memset(outputBus->channel(i)->mutableData() + zeroStartFrame, 0, sizeof(float) * framesToZero);
131         }
132
133         finish();
134     }
135
136     return;
137 }
138
139
140 void AudioScheduledSourceNode::start(double when, ExceptionState& exceptionState)
141 {
142     ASSERT(isMainThread());
143
144     if (m_playbackState != UNSCHEDULED_STATE) {
145         exceptionState.throwDOMException(
146             InvalidStateError,
147             "cannot call start more than once.");
148         return;
149     }
150
151     m_startTime = when;
152     m_playbackState = SCHEDULED_STATE;
153 }
154
155 void AudioScheduledSourceNode::stop(double when, ExceptionState& exceptionState)
156 {
157     ASSERT(isMainThread());
158
159     if (m_playbackState == UNSCHEDULED_STATE) {
160         exceptionState.throwDOMException(
161             InvalidStateError,
162             "cannot call stop without calling start first.");
163     } else {
164         // stop() can be called more than once, with the last call to stop taking effect, unless the
165         // source has already stopped due to earlier calls to stop. No exceptions are thrown in any
166         // case.
167         when = max(0.0, when);
168         m_endTime = when;
169     }
170 }
171
172 void AudioScheduledSourceNode::setOnended(PassRefPtr<EventListener> listener)
173 {
174     m_hasEndedListener = listener;
175     setAttributeEventListener(EventTypeNames::ended, listener);
176 }
177
178 void AudioScheduledSourceNode::finish()
179 {
180     if (m_playbackState != FINISHED_STATE) {
181         // Let the context dereference this AudioNode.
182         context()->notifyNodeFinishedProcessing(this);
183         m_playbackState = FINISHED_STATE;
184         context()->decrementActiveSourceCount();
185     }
186
187     if (m_hasEndedListener) {
188         // |task| will keep the AudioScheduledSourceNode alive until the listener has been handled.
189         OwnPtr<NotifyEndedTask> task = adoptPtr(new NotifyEndedTask(this));
190         callOnMainThread(&AudioScheduledSourceNode::notifyEndedDispatch, task.leakPtr());
191     }
192 }
193
194 void AudioScheduledSourceNode::notifyEndedDispatch(void* userData)
195 {
196     OwnPtr<NotifyEndedTask> task = adoptPtr(static_cast<NotifyEndedTask*>(userData));
197
198     task->notifyEnded();
199 }
200
201 AudioScheduledSourceNode::NotifyEndedTask::NotifyEndedTask(PassRefPtr<AudioScheduledSourceNode> sourceNode)
202     : m_scheduledNode(sourceNode)
203 {
204 }
205
206 void AudioScheduledSourceNode::NotifyEndedTask::notifyEnded()
207 {
208     RefPtr<Event> event = Event::create(EventTypeNames::ended);
209     event->setTarget(m_scheduledNode);
210     m_scheduledNode->dispatchEvent(event.get());
211 }
212
213 } // namespace WebCore
214
215 #endif // ENABLE(WEB_AUDIO)