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 "AudioScheduledSourceNode.h"
30
31#include "AudioContext.h"
32#include "AudioUtilities.h"
33#include "Event.h"
34#include "EventNames.h"
35#include "ScriptController.h"
36#include "ScriptExecutionContext.h"
37#include <algorithm>
38#include <wtf/IsoMallocInlines.h>
39#include <wtf/MathExtras.h>
40
41#if PLATFORM(IOS_FAMILY)
42#include "ScriptController.h"
43#endif
44
45namespace WebCore {
46
47WTF_MAKE_ISO_ALLOCATED_IMPL(AudioScheduledSourceNode);
48
49const double AudioScheduledSourceNode::UnknownTime = -1;
50
51AudioScheduledSourceNode::AudioScheduledSourceNode(AudioContext& context, float sampleRate)
52 : AudioNode(context, sampleRate)
53 , m_endTime(UnknownTime)
54{
55}
56
57void AudioScheduledSourceNode::updateSchedulingInfo(size_t quantumFrameSize, AudioBus& outputBus, size_t& quantumFrameOffset, size_t& nonSilentFramesToProcess)
58{
59 nonSilentFramesToProcess = 0;
60 quantumFrameOffset = 0;
61
62 ASSERT(quantumFrameSize == AudioNode::ProcessingSizeInFrames);
63 if (quantumFrameSize != AudioNode::ProcessingSizeInFrames)
64 return;
65
66 double sampleRate = this->sampleRate();
67
68 // quantumStartFrame : Start frame of the current time quantum.
69 // quantumEndFrame : End frame of the current time quantum.
70 // startFrame : Start frame for this source.
71 // endFrame : End frame for this source.
72 size_t quantumStartFrame = context().currentSampleFrame();
73 size_t quantumEndFrame = quantumStartFrame + quantumFrameSize;
74 size_t startFrame = AudioUtilities::timeToSampleFrame(m_startTime, sampleRate);
75 size_t endFrame = m_endTime == UnknownTime ? 0 : AudioUtilities::timeToSampleFrame(m_endTime, sampleRate);
76
77 // If we know the end time and it's already passed, then don't bother doing any more rendering this cycle.
78 if (m_endTime != UnknownTime && endFrame <= quantumStartFrame)
79 finish();
80
81 if (m_playbackState == UNSCHEDULED_STATE || m_playbackState == FINISHED_STATE || startFrame >= quantumEndFrame) {
82 // Output silence.
83 outputBus.zero();
84 return;
85 }
86
87 // Check if it's time to start playing.
88 if (m_playbackState == SCHEDULED_STATE) {
89 // Increment the active source count only if we're transitioning from SCHEDULED_STATE to PLAYING_STATE.
90 m_playbackState = PLAYING_STATE;
91 context().incrementActiveSourceCount();
92 }
93
94 quantumFrameOffset = startFrame > quantumStartFrame ? startFrame - quantumStartFrame : 0;
95 quantumFrameOffset = std::min(quantumFrameOffset, quantumFrameSize); // clamp to valid range
96 nonSilentFramesToProcess = quantumFrameSize - quantumFrameOffset;
97
98 if (!nonSilentFramesToProcess) {
99 // Output silence.
100 outputBus.zero();
101 return;
102 }
103
104 // Handle silence before we start playing.
105 // Zero any initial frames representing silence leading up to a rendering start time in the middle of the quantum.
106 if (quantumFrameOffset) {
107 for (unsigned i = 0; i < outputBus.numberOfChannels(); ++i)
108 memset(outputBus.channel(i)->mutableData(), 0, sizeof(float) * quantumFrameOffset);
109 }
110
111 // Handle silence after we're done playing.
112 // If the end time is somewhere in the middle of this time quantum, then zero out the
113 // frames from the end time to the very end of the quantum.
114 if (m_endTime != UnknownTime && endFrame >= quantumStartFrame && endFrame < quantumEndFrame) {
115 size_t zeroStartFrame = endFrame - quantumStartFrame;
116 size_t framesToZero = quantumFrameSize - zeroStartFrame;
117
118 bool isSafe = zeroStartFrame < quantumFrameSize && framesToZero <= quantumFrameSize && zeroStartFrame + framesToZero <= quantumFrameSize;
119 ASSERT(isSafe);
120
121 if (isSafe) {
122 if (framesToZero > nonSilentFramesToProcess)
123 nonSilentFramesToProcess = 0;
124 else
125 nonSilentFramesToProcess -= framesToZero;
126
127 for (unsigned i = 0; i < outputBus.numberOfChannels(); ++i)
128 memset(outputBus.channel(i)->mutableData() + zeroStartFrame, 0, sizeof(float) * framesToZero);
129 }
130
131 finish();
132 }
133}
134
135ExceptionOr<void> AudioScheduledSourceNode::start(double when)
136{
137 ASSERT(isMainThread());
138 ALWAYS_LOG(LOGIDENTIFIER, when);
139
140 context().nodeWillBeginPlayback();
141
142 if (m_playbackState != UNSCHEDULED_STATE)
143 return Exception { InvalidStateError };
144 if (!std::isfinite(when) || when < 0)
145 return Exception { InvalidStateError };
146
147 m_startTime = when;
148 m_playbackState = SCHEDULED_STATE;
149
150 return { };
151}
152
153ExceptionOr<void> AudioScheduledSourceNode::stop(double when)
154{
155 ASSERT(isMainThread());
156 ALWAYS_LOG(LOGIDENTIFIER, when);
157
158 if (m_playbackState == UNSCHEDULED_STATE || m_endTime != UnknownTime)
159 return Exception { InvalidStateError };
160 if (!std::isfinite(when) || when < 0)
161 return Exception { InvalidStateError };
162
163 m_endTime = when;
164
165 return { };
166}
167
168void AudioScheduledSourceNode::finish()
169{
170 if (m_playbackState != FINISHED_STATE) {
171 // Let the context dereference this AudioNode.
172 context().notifyNodeFinishedProcessing(this);
173 m_playbackState = FINISHED_STATE;
174 context().decrementActiveSourceCount();
175 }
176
177 if (!m_hasEndedListener)
178 return;
179
180 context().postTask([this, protectedThis = makeRef(*this)] {
181 if (context().isStopped())
182 return;
183 this->dispatchEvent(Event::create(eventNames().endedEvent, Event::CanBubble::No, Event::IsCancelable::No));
184 });
185}
186
187bool AudioScheduledSourceNode::addEventListener(const AtomString& eventType, Ref<EventListener>&& listener, const AddEventListenerOptions& options)
188{
189 bool success = AudioNode::addEventListener(eventType, WTFMove(listener), options);
190 if (success && eventType == eventNames().endedEvent)
191 m_hasEndedListener = hasEventListeners(eventNames().endedEvent);
192 return success;
193}
194
195bool AudioScheduledSourceNode::removeEventListener(const AtomString& eventType, EventListener& listener, const ListenerOptions& options)
196{
197 bool success = AudioNode::removeEventListener(eventType, listener, options);
198 if (success && eventType == eventNames().endedEvent)
199 m_hasEndedListener = hasEventListeners(eventNames().endedEvent);
200 return success;
201}
202
203void AudioScheduledSourceNode::removeAllEventListeners()
204{
205 m_hasEndedListener = false;
206 AudioNode::removeAllEventListeners();
207}
208
209} // namespace WebCore
210
211#endif // ENABLE(WEB_AUDIO)
212