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