initial import
[vuplus_webkit] / Source / WebCore / webaudio / AudioContext.h
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 #ifndef AudioContext_h
26 #define AudioContext_h
27
28 #include "ActiveDOMObject.h"
29 #include "AsyncAudioDecoder.h"
30 #include "AudioBus.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>
45
46 namespace WebCore {
47
48 class ArrayBuffer;
49 class AudioBuffer;
50 class AudioBufferCallback;
51 class AudioBufferSourceNode;
52 class MediaElementAudioSourceNode;
53 class HTMLMediaElement;
54 class AudioChannelMerger;
55 class AudioChannelSplitter;
56 class AudioGainNode;
57 class AudioPannerNode;
58 class AudioListener;
59 class BiquadFilterNode;
60 class DelayNode;
61 class Document;
62 class LowPass2FilterNode;
63 class HighPass2FilterNode;
64 class ConvolverNode;
65 class DynamicsCompressorNode;
66 class RealtimeAnalyserNode;
67 class WaveShaperNode;
68 class JavaScriptAudioNode;
69
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. 
72
73 class AudioContext : public ActiveDOMObject, public ThreadSafeRefCounted<AudioContext>, public EventTarget {
74 public:
75     // Create an AudioContext for rendering to the audio hardware.
76     static PassRefPtr<AudioContext> create(Document*);
77
78     // Create an AudioContext for offline (non-realtime) rendering.
79     static PassRefPtr<AudioContext> createOfflineContext(Document*, unsigned numberOfChannels, size_t numberOfFrames, double sampleRate, ExceptionCode&);
80
81     virtual ~AudioContext();
82
83     bool isInitialized() const;
84     
85     bool isOfflineContext() { return m_isOfflineContext; }
86
87     // Returns true when initialize() was called AND all asynchronous initialization has completed.
88     bool isRunnable() const;
89
90     // Document notification
91     virtual void stop();
92
93     Document* document() const; // ASSERTs if document no longer exists.
94     bool hasDocument();
95
96     AudioDestinationNode* destination() { return m_destinationNode.get(); }
97     double currentTime() { return m_destinationNode->currentTime(); }
98     double sampleRate() { return m_destinationNode->sampleRate(); }
99
100     PassRefPtr<AudioBuffer> createBuffer(unsigned numberOfChannels, size_t numberOfFrames, double sampleRate);
101     PassRefPtr<AudioBuffer> createBuffer(ArrayBuffer* arrayBuffer, bool mixToMono);
102
103     // Asynchronous audio file data decoding.
104     void decodeAudioData(ArrayBuffer*, PassRefPtr<AudioBufferCallback>, PassRefPtr<AudioBufferCallback>, ExceptionCode& ec);
105
106     // Keep track of this buffer so we can release memory after the context is shut down...
107     void refBuffer(PassRefPtr<AudioBuffer> buffer);
108
109     AudioListener* listener() { return m_listener.get(); }
110
111     // The AudioNode create methods are called on the main thread (from JavaScript).
112     PassRefPtr<AudioBufferSourceNode> createBufferSource();
113 #if ENABLE(VIDEO)
114     PassRefPtr<MediaElementAudioSourceNode> createMediaElementSource(HTMLMediaElement*, ExceptionCode&);
115 #endif
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();
129
130     AudioBus* temporaryMonoBus() { return m_temporaryMonoBus.get(); }
131     AudioBus* temporaryStereoBus() { return m_temporaryStereoBus.get(); }
132
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*);
135
136     // Called at the start of each render quantum.
137     void handlePreRenderTasks();
138
139     // Called at the end of each render quantum.
140     void handlePostRenderTasks();
141
142     // Called periodically at the end of each render quantum to dereference finished source nodes.
143     void derefFinishedSourceNodes();
144
145     // We schedule deletion of all marked nodes at the end of each realtime render quantum.
146     void markForDeletion(AudioNode*);
147     void deleteMarkedNodes();
148     
149     // Keeps track of the number of connections made.
150     void incrementConnectionCount()
151     {
152         ASSERT(isMainThread());
153         m_connectionCount++;
154     }
155
156     unsigned connectionCount() const { return m_connectionCount; }
157
158     //
159     // Thread Safety and Graph Locking:
160     //
161     
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;
165
166     // Returns true only after the audio thread has been started and then shutdown.
167     bool isAudioThreadFinished() { return m_isAudioThreadFinished; }
168     
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);
171
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);
175
176     void unlock();
177
178     // Returns true if this thread owns the context's lock.
179     bool isGraphOwner() const;
180
181     class AutoLocker {
182     public:
183         AutoLocker(AudioContext* context)
184             : m_context(context)
185         {
186             ASSERT(context);
187             context->lock(m_mustReleaseLock);
188         }
189         
190         ~AutoLocker()
191         {
192             if (m_mustReleaseLock)
193                 m_context->unlock();
194         }
195     private:
196         AudioContext* m_context;
197         bool m_mustReleaseLock;
198     };
199     
200     // In AudioNode::deref() a tryLock() is used for calling finishDeref(), but if it fails keep track here.
201     void addDeferredFinishDeref(AudioNode*, AudioNode::RefType);
202
203     // In the audio thread at the start of each render cycle, we'll call handleDeferredFinishDerefs().
204     void handleDeferredFinishDerefs();
205
206     // Only accessed when the graph lock is held.
207     void markAudioNodeInputDirty(AudioNodeInput*);
208     void markAudioNodeOutputDirty(AudioNodeOutput*);
209
210     // EventTarget
211     virtual ScriptExecutionContext* scriptExecutionContext() const;
212     virtual AudioContext* toAudioContext();
213     virtual EventTargetData* eventTargetData() { return &m_eventTargetData; }
214     virtual EventTargetData* ensureEventTargetData() { return &m_eventTargetData; }
215
216     DEFINE_ATTRIBUTE_EVENT_LISTENER(complete);
217
218     // Reconcile ref/deref which are defined both in ThreadSafeRefCounted and EventTarget.
219     using ThreadSafeRefCounted<AudioContext>::ref;
220     using ThreadSafeRefCounted<AudioContext>::deref;
221
222     void startRendering();
223     void fireCompletionEvent();
224     
225     static unsigned s_hardwareContextCount;
226     
227 private:
228     AudioContext(Document*);
229     AudioContext(Document*, unsigned numberOfChannels, size_t numberOfFrames, double sampleRate);
230     void constructCommon();
231
232     void lazyInitialize();
233     void uninitialize();
234     static void uninitializeDispatch(void* userData);
235
236     void scheduleNodeDeletion();
237     static void deleteMarkedNodesDispatch(void* userData);
238     
239     bool m_isInitialized;
240     bool m_isAudioThreadFinished;
241     bool m_isAudioThreadShutdown;
242
243     Document* m_document;
244
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*);
251
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();
255
256     RefPtr<AudioDestinationNode> m_destinationNode;
257     RefPtr<AudioListener> m_listener;
258
259     // Only accessed in the main thread.
260     Vector<RefPtr<AudioBuffer> > m_allocatedBuffers;
261
262     // Only accessed in the audio thread.
263     Vector<AudioNode*> m_finishedNodes;
264
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;
269
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;
274
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();
280
281     OwnPtr<AudioBus> m_temporaryMonoBus;
282     OwnPtr<AudioBus> m_temporaryStereoBus;
283
284     unsigned m_connectionCount;
285
286     // Graph locking.
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
290     
291     // Deferred de-referencing.
292     struct RefInfo {
293         RefInfo(AudioNode* node, AudioNode::RefType refType)
294             : m_node(node)
295             , m_refType(refType)
296         {
297         }
298         AudioNode* m_node;
299         AudioNode::RefType m_refType;
300     };    
301
302     // Only accessed in the audio thread.
303     Vector<RefInfo> m_deferredFinishDerefList;
304     
305     // HRTF Database loader
306     RefPtr<HRTFDatabaseLoader> m_hrtfDatabaseLoader;
307
308     // EventTarget
309     virtual void refEventTarget() { ref(); }
310     virtual void derefEventTarget() { deref(); }
311     EventTargetData m_eventTargetData;
312
313     RefPtr<AudioBuffer> m_renderTarget;
314     
315     bool m_isOfflineContext;
316
317     AsyncAudioDecoder m_audioDecoder;
318 };
319
320 } // WebCore
321
322 #endif // AudioContext_h