2 * Copyright (C) 2010, Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
25 #ifndef AudioContext_h
26 #define AudioContext_h
28 #include "ActiveDOMObject.h"
29 #include "AsyncAudioDecoder.h"
31 #include "AudioDestinationNode.h"
32 #include "EventListener.h"
33 #include "EventTarget.h"
34 #include "HRTFDatabaseLoader.h"
35 #include <wtf/HashSet.h>
36 #include <wtf/MainThread.h>
37 #include <wtf/OwnPtr.h>
38 #include <wtf/PassRefPtr.h>
39 #include <wtf/RefCounted.h>
40 #include <wtf/RefPtr.h>
41 #include <wtf/ThreadSafeRefCounted.h>
42 #include <wtf/Threading.h>
43 #include <wtf/Vector.h>
44 #include <wtf/text/AtomicStringHash.h>
50 class AudioBufferCallback;
51 class AudioBufferSourceNode;
52 class MediaElementAudioSourceNode;
53 class HTMLMediaElement;
54 class AudioChannelMerger;
55 class AudioChannelSplitter;
57 class AudioPannerNode;
59 class BiquadFilterNode;
62 class LowPass2FilterNode;
63 class HighPass2FilterNode;
65 class DynamicsCompressorNode;
66 class RealtimeAnalyserNode;
68 class JavaScriptAudioNode;
70 // AudioContext is the cornerstone of the web audio API and all AudioNodes are created from it.
71 // For thread safety between the audio thread and the main thread, it has a rendering graph locking mechanism.
73 class AudioContext : public ActiveDOMObject, public ThreadSafeRefCounted<AudioContext>, public EventTarget {
75 // Create an AudioContext for rendering to the audio hardware.
76 static PassRefPtr<AudioContext> create(Document*);
78 // Create an AudioContext for offline (non-realtime) rendering.
79 static PassRefPtr<AudioContext> createOfflineContext(Document*, unsigned numberOfChannels, size_t numberOfFrames, double sampleRate, ExceptionCode&);
81 virtual ~AudioContext();
83 bool isInitialized() const;
85 bool isOfflineContext() { return m_isOfflineContext; }
87 // Returns true when initialize() was called AND all asynchronous initialization has completed.
88 bool isRunnable() const;
90 // Document notification
93 Document* document() const; // ASSERTs if document no longer exists.
96 AudioDestinationNode* destination() { return m_destinationNode.get(); }
97 double currentTime() { return m_destinationNode->currentTime(); }
98 double sampleRate() { return m_destinationNode->sampleRate(); }
100 PassRefPtr<AudioBuffer> createBuffer(unsigned numberOfChannels, size_t numberOfFrames, double sampleRate);
101 PassRefPtr<AudioBuffer> createBuffer(ArrayBuffer* arrayBuffer, bool mixToMono);
103 // Asynchronous audio file data decoding.
104 void decodeAudioData(ArrayBuffer*, PassRefPtr<AudioBufferCallback>, PassRefPtr<AudioBufferCallback>, ExceptionCode& ec);
106 // Keep track of this buffer so we can release memory after the context is shut down...
107 void refBuffer(PassRefPtr<AudioBuffer> buffer);
109 AudioListener* listener() { return m_listener.get(); }
111 // The AudioNode create methods are called on the main thread (from JavaScript).
112 PassRefPtr<AudioBufferSourceNode> createBufferSource();
114 PassRefPtr<MediaElementAudioSourceNode> createMediaElementSource(HTMLMediaElement*, ExceptionCode&);
116 PassRefPtr<AudioGainNode> createGainNode();
117 PassRefPtr<BiquadFilterNode> createBiquadFilter();
118 PassRefPtr<WaveShaperNode> createWaveShaper();
119 PassRefPtr<DelayNode> createDelayNode();
120 PassRefPtr<LowPass2FilterNode> createLowPass2Filter();
121 PassRefPtr<HighPass2FilterNode> createHighPass2Filter();
122 PassRefPtr<AudioPannerNode> createPanner();
123 PassRefPtr<ConvolverNode> createConvolver();
124 PassRefPtr<DynamicsCompressorNode> createDynamicsCompressor();
125 PassRefPtr<RealtimeAnalyserNode> createAnalyser();
126 PassRefPtr<JavaScriptAudioNode> createJavaScriptNode(size_t bufferSize);
127 PassRefPtr<AudioChannelSplitter> createChannelSplitter();
128 PassRefPtr<AudioChannelMerger> createChannelMerger();
130 AudioBus* temporaryMonoBus() { return m_temporaryMonoBus.get(); }
131 AudioBus* temporaryStereoBus() { return m_temporaryStereoBus.get(); }
133 // When a source node has no more processing to do (has finished playing), then it tells the context to dereference it.
134 void notifyNodeFinishedProcessing(AudioNode*);
136 // Called at the start of each render quantum.
137 void handlePreRenderTasks();
139 // Called at the end of each render quantum.
140 void handlePostRenderTasks();
142 // Called periodically at the end of each render quantum to dereference finished source nodes.
143 void derefFinishedSourceNodes();
145 // We schedule deletion of all marked nodes at the end of each realtime render quantum.
146 void markForDeletion(AudioNode*);
147 void deleteMarkedNodes();
149 // Keeps track of the number of connections made.
150 void incrementConnectionCount()
152 ASSERT(isMainThread());
156 unsigned connectionCount() const { return m_connectionCount; }
159 // Thread Safety and Graph Locking:
162 void setAudioThread(ThreadIdentifier thread) { m_audioThread = thread; } // FIXME: check either not initialized or the same
163 ThreadIdentifier audioThread() const { return m_audioThread; }
164 bool isAudioThread() const;
166 // Returns true only after the audio thread has been started and then shutdown.
167 bool isAudioThreadFinished() { return m_isAudioThreadFinished; }
169 // mustReleaseLock is set to true if we acquired the lock in this method call and caller must unlock(), false if it was previously acquired.
170 void lock(bool& mustReleaseLock);
172 // Returns true if we own the lock.
173 // mustReleaseLock is set to true if we acquired the lock in this method call and caller must unlock(), false if it was previously acquired.
174 bool tryLock(bool& mustReleaseLock);
178 // Returns true if this thread owns the context's lock.
179 bool isGraphOwner() const;
183 AutoLocker(AudioContext* context)
187 context->lock(m_mustReleaseLock);
192 if (m_mustReleaseLock)
196 AudioContext* m_context;
197 bool m_mustReleaseLock;
200 // In AudioNode::deref() a tryLock() is used for calling finishDeref(), but if it fails keep track here.
201 void addDeferredFinishDeref(AudioNode*, AudioNode::RefType);
203 // In the audio thread at the start of each render cycle, we'll call handleDeferredFinishDerefs().
204 void handleDeferredFinishDerefs();
206 // Only accessed when the graph lock is held.
207 void markAudioNodeInputDirty(AudioNodeInput*);
208 void markAudioNodeOutputDirty(AudioNodeOutput*);
211 virtual ScriptExecutionContext* scriptExecutionContext() const;
212 virtual AudioContext* toAudioContext();
213 virtual EventTargetData* eventTargetData() { return &m_eventTargetData; }
214 virtual EventTargetData* ensureEventTargetData() { return &m_eventTargetData; }
216 DEFINE_ATTRIBUTE_EVENT_LISTENER(complete);
218 // Reconcile ref/deref which are defined both in ThreadSafeRefCounted and EventTarget.
219 using ThreadSafeRefCounted<AudioContext>::ref;
220 using ThreadSafeRefCounted<AudioContext>::deref;
222 void startRendering();
223 void fireCompletionEvent();
225 static unsigned s_hardwareContextCount;
228 AudioContext(Document*);
229 AudioContext(Document*, unsigned numberOfChannels, size_t numberOfFrames, double sampleRate);
230 void constructCommon();
232 void lazyInitialize();
234 static void uninitializeDispatch(void* userData);
236 void scheduleNodeDeletion();
237 static void deleteMarkedNodesDispatch(void* userData);
239 bool m_isInitialized;
240 bool m_isAudioThreadFinished;
241 bool m_isAudioThreadShutdown;
243 Document* m_document;
245 // The context itself keeps a reference to all source nodes. The source nodes, then reference all nodes they're connected to.
246 // In turn, these nodes reference all nodes they're connected to. All nodes are ultimately connected to the AudioDestinationNode.
247 // When the context dereferences a source node, it will be deactivated from the rendering graph along with all other nodes it is
248 // uniquely connected to. See the AudioNode::ref() and AudioNode::deref() methods for more details.
249 void refNode(AudioNode*);
250 void derefNode(AudioNode*);
252 // When the context goes away, there might still be some sources which haven't finished playing.
253 // Make sure to dereference them here.
254 void derefUnfinishedSourceNodes();
256 RefPtr<AudioDestinationNode> m_destinationNode;
257 RefPtr<AudioListener> m_listener;
259 // Only accessed in the main thread.
260 Vector<RefPtr<AudioBuffer> > m_allocatedBuffers;
262 // Only accessed in the audio thread.
263 Vector<AudioNode*> m_finishedNodes;
265 // We don't use RefPtr<AudioNode> here because AudioNode has a more complex ref() / deref() implementation
266 // with an optional argument for refType. We need to use the special refType: RefTypeConnection
267 // Either accessed when the graph lock is held, or on the main thread when the audio thread has finished.
268 Vector<AudioNode*> m_referencedNodes;
270 // Accumulate nodes which need to be deleted here.
271 // They will be scheduled for deletion (on the main thread) at the end of a render cycle (in realtime thread).
272 Vector<AudioNode*> m_nodesToDelete;
273 bool m_isDeletionScheduled;
275 // Only accessed when the graph lock is held.
276 HashSet<AudioNodeInput*> m_dirtyAudioNodeInputs;
277 HashSet<AudioNodeOutput*> m_dirtyAudioNodeOutputs;
278 void handleDirtyAudioNodeInputs();
279 void handleDirtyAudioNodeOutputs();
281 OwnPtr<AudioBus> m_temporaryMonoBus;
282 OwnPtr<AudioBus> m_temporaryStereoBus;
284 unsigned m_connectionCount;
287 Mutex m_contextGraphMutex;
288 volatile ThreadIdentifier m_audioThread;
289 volatile ThreadIdentifier m_graphOwnerThread; // if the lock is held then this is the thread which owns it, otherwise == UndefinedThreadIdentifier
291 // Deferred de-referencing.
293 RefInfo(AudioNode* node, AudioNode::RefType refType)
299 AudioNode::RefType m_refType;
302 // Only accessed in the audio thread.
303 Vector<RefInfo> m_deferredFinishDerefList;
305 // HRTF Database loader
306 RefPtr<HRTFDatabaseLoader> m_hrtfDatabaseLoader;
309 virtual void refEventTarget() { ref(); }
310 virtual void derefEventTarget() { deref(); }
311 EventTargetData m_eventTargetData;
313 RefPtr<AudioBuffer> m_renderTarget;
315 bool m_isOfflineContext;
317 AsyncAudioDecoder m_audioDecoder;
322 #endif // AudioContext_h