1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-*/
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
4 * You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #ifndef MOZILLA_MEDIATRACKGRAPHIMPL_H_
7 #define MOZILLA_MEDIATRACKGRAPHIMPL_H_
9 #include "MediaTrackGraph.h"
11 #include "AudioMixer.h"
12 #include "GraphDriver.h"
13 #include "DeviceInputTrack.h"
14 #include "mozilla/Atomics.h"
15 #include "mozilla/Maybe.h"
16 #include "mozilla/Monitor.h"
17 #include "mozilla/TimeStamp.h"
18 #include "mozilla/UniquePtr.h"
19 #include "mozilla/WeakPtr.h"
20 #include "nsClassHashtable.h"
21 #include "nsIMemoryReporter.h"
23 #include "nsIRunnable.h"
24 #include "nsIThreadInternal.h"
26 #include "AsyncLogger.h"
31 class ShutdownBlocker
;
34 class AudioContextOperationControlMessage
;
39 class DeviceInputTrackManager
{
41 DeviceInputTrackManager() = default;
43 // Returns the current NativeInputTrack.
44 NativeInputTrack
* GetNativeInputTrack();
45 // Returns the DeviceInputTrack paired with the device of aID if it exists.
46 // Otherwise, returns nullptr.
47 DeviceInputTrack
* GetDeviceInputTrack(CubebUtils::AudioDeviceID aID
);
48 // Returns the first added NonNativeInputTrack if any. Otherwise, returns
50 NonNativeInputTrack
* GetFirstNonNativeInputTrack();
51 // Adds DeviceInputTrack to the managing list.
52 void Add(DeviceInputTrack
* aTrack
);
53 // Removes DeviceInputTrack from the managing list.
54 void Remove(DeviceInputTrack
* aTrack
);
57 RefPtr
<NativeInputTrack
> mNativeInputTrack
;
58 nsTArray
<RefPtr
<NonNativeInputTrack
>> mNonNativeInputTracks
;
62 * A per-track update message passed from the media graph thread to the
66 RefPtr
<MediaTrack
> mTrack
;
67 TrackTime mNextMainThreadCurrentTime
;
68 bool mNextMainThreadEnded
;
72 * This represents a message run on the graph thread to modify track or graph
73 * state. These are passed from main thread to graph thread through
74 * AppendMessage(). A ControlMessage often has a weak reference to a
75 * particular affected track.
77 class ControlMessage
: public MediaTrack::ControlMessageInterface
{
79 explicit ControlMessage(MediaTrack
* aTrack
) : mTrack(aTrack
) {
80 MOZ_ASSERT(NS_IsMainThread());
81 MOZ_RELEASE_ASSERT(!aTrack
|| !aTrack
->IsDestroyed());
84 MediaTrack
* GetTrack() { return mTrack
; }
87 // We do not hold a reference to mTrack. The graph will be holding a reference
88 // to the track until the Destroy message is processed. The last message
89 // referencing a track is the Destroy message for that track.
90 MediaTrack
* const mTrack
;
95 nsTArray
<UniquePtr
<MediaTrack::ControlMessageInterface
>> mMessages
;
99 * The implementation of a media track graph. This class is private to this
100 * file. It's not in the anonymous namespace because MediaTrack needs to
101 * be able to friend it.
103 * There can be multiple MediaTrackGraph per process: one per document.
104 * Additionaly, each OfflineAudioContext object creates its own MediaTrackGraph
107 class MediaTrackGraphImpl
: public MediaTrackGraph
,
108 public GraphInterface
,
109 public nsIMemoryReporter
,
111 public nsIThreadObserver
,
112 public nsITimerCallback
,
115 using ControlMessageInterface
= MediaTrack::ControlMessageInterface
;
117 NS_DECL_THREADSAFE_ISUPPORTS
118 NS_DECL_NSIMEMORYREPORTER
120 NS_DECL_NSITHREADOBSERVER
121 NS_DECL_NSITIMERCALLBACK
125 * Use aGraphDriverRequested with SYSTEM_THREAD_DRIVER or AUDIO_THREAD_DRIVER
126 * to create a MediaTrackGraph which provides support for real-time audio
127 * and/or video. Set it to OFFLINE_THREAD_DRIVER in order to create a
128 * non-realtime instance which just churns through its inputs and produces
129 * output. Those objects currently only support audio, and are used to
130 * implement OfflineAudioContext. They do not support MediaTrack inputs.
132 explicit MediaTrackGraphImpl(uint64_t aWindowID
, TrackRate aSampleRate
,
133 CubebUtils::AudioDeviceID aOutputDeviceID
,
134 nsISerialEventTarget
* aMainThread
);
136 static MediaTrackGraphImpl
* GetInstance(
137 GraphDriverType aGraphDriverRequested
, uint64_t aWindowID
,
138 TrackRate aSampleRate
, CubebUtils::AudioDeviceID aPrimaryOutputDeviceID
,
139 nsISerialEventTarget
* aMainThread
);
140 static MediaTrackGraphImpl
* GetInstanceIfExists(
141 uint64_t aWindowID
, TrackRate aSampleRate
,
142 CubebUtils::AudioDeviceID aPrimaryOutputDeviceID
);
143 static MediaTrackGraph
* CreateNonRealtimeInstance(TrackRate aSampleRate
);
146 operator Lookup() const;
148 // Intended only for assertions, either on graph thread or not running (in
149 // which case we must be on the main thread).
150 bool OnGraphThreadOrNotRunning() const override
;
151 bool OnGraphThread() const override
;
153 bool Destroyed() const override
;
157 * True if we're on aDriver's thread, or if we're on mGraphRunner's thread
158 * and mGraphRunner is currently run by aDriver.
160 bool InDriverIteration(const GraphDriver
* aDriver
) const override
;
164 * Unregisters memory reporting and deletes this instance. This should be
165 * called instead of calling the destructor directly.
171 * This runs every time we need to sync state from the media graph thread
172 * to the main thread while the main thread is not in the middle
173 * of a script. It runs during a "stable state" (per HTML5) or during
174 * an event posted to the main thread.
175 * The boolean affects which boolean controlling runnable dispatch is cleared
177 void RunInStableState(bool aSourceIsMTG
);
179 * Ensure a runnable to run RunInStableState is posted to the appshell to
180 * run at the next stable state (per HTML5).
181 * See EnsureStableStateEventPosted.
183 void EnsureRunInStableState();
185 * Called to apply a TrackUpdate to its track.
187 void ApplyTrackUpdate(TrackUpdate
* aUpdate
) MOZ_REQUIRES(mMonitor
);
189 * Append a control message to the message queue. This queue is drained
190 * during RunInStableState; the messages will run on the graph thread.
192 virtual void AppendMessage(UniquePtr
<ControlMessageInterface
> aMessage
);
194 * Append to the message queue a control message to execute a given lambda
195 * function with no parameters. The lambda will be executed on the graph
196 * thread. The lambda will not be executed if the graph has been forced to
199 template <typename Function
>
200 void QueueControlMessageWithNoShutdown(Function
&& aFunction
) {
201 AppendMessage(WrapUnique(new MediaTrack::ControlMessageWithNoShutdown(
202 std::forward
<Function
>(aFunction
))));
205 * Append to the message queue a control message to execute a given lambda
206 * function with a single IsInShutdown parameter. A No argument indicates
207 * execution on the thread of a graph that is still running. A Yes argument
208 * indicates execution on the main thread when the graph has been forced to
211 template <typename Function
>
212 void QueueControlOrShutdownMessage(Function
&& aFunction
) {
213 AppendMessage(WrapUnique(new MediaTrack::ControlOrShutdownMessage(
214 std::forward
<Function
>(aFunction
))));
216 /* Add or remove an audio output for this track. At most one output may be
217 * registered per key. aPreferredSampleRate is the rate preferred by the
218 * output device; it may be zero to indicate the preferred rate for the
219 * default device; it is unused when aDeviceID is the graph's primary output.
221 void RegisterAudioOutput(MediaTrack
* aTrack
, void* aKey
,
222 CubebUtils::AudioDeviceID aDeviceID
,
223 TrackRate aPreferredSampleRate
);
224 void UnregisterAudioOutput(MediaTrack
* aTrack
, void* aKey
);
226 void SetAudioOutputVolume(MediaTrack
* aTrack
, void* aKey
, float aVolume
);
227 /* Manage the creation and destruction of CrossGraphReceivers.
228 * aPreferredSampleRate is the rate preferred by the output device. */
229 void IncrementOutputDeviceRefCnt(CubebUtils::AudioDeviceID aDeviceID
,
230 TrackRate aPreferredSampleRate
);
231 void DecrementOutputDeviceRefCnt(CubebUtils::AudioDeviceID aDeviceID
);
232 /* Send a control message to update mOutputDevices for main thread changes to
233 * mAudioOutputParams. */
234 void UpdateAudioOutput(MediaTrack
* aTrack
,
235 CubebUtils::AudioDeviceID aDeviceID
);
237 * Dispatches a runnable from any thread to the correct main thread for this
240 void Dispatch(already_AddRefed
<nsIRunnable
>&& aRunnable
);
243 * Make this MediaTrackGraph enter forced-shutdown state. This state
244 * will be noticed by the media graph thread, which will shut down all tracks
245 * and other state controlled by the media graph thread.
246 * This is called during application shutdown, and on document unload if an
247 * AudioContext is using the graph.
249 void ForceShutDown();
252 * Sets mShutdownBlocker and makes it block shutdown.
253 * Main thread only. Not idempotent. Returns true if a blocker was added,
254 * false if this failed.
256 bool AddShutdownBlocker();
259 * Removes mShutdownBlocker and unblocks shutdown.
260 * Main thread only. Idempotent.
262 void RemoveShutdownBlocker();
265 * Called before the thread runs.
267 void Init(GraphDriverType aDriverRequested
, GraphRunType aRunTypeRequested
,
268 uint32_t aChannelCount
);
271 * Respond to CollectReports with sizes collected on the graph thread.
273 static void FinishCollectReports(
274 nsIHandleReportCallback
* aHandleReport
, nsISupports
* aData
,
275 const nsTArray
<AudioNodeSizes
>& aAudioTrackSizes
);
277 // The following methods run on the graph thread (or possibly the main thread
278 // if mLifecycleState > LIFECYCLE_RUNNING)
279 void CollectSizesForMemoryReport(
280 already_AddRefed
<nsIHandleReportCallback
> aHandleReport
,
281 already_AddRefed
<nsISupports
> aHandlerData
);
284 * Returns true if this MediaTrackGraph should keep running
286 bool UpdateMainThreadState();
289 * Proxy method called by GraphDriver to iterate the graph.
290 * If this graph was created with GraphRunType SINGLE_THREAD, mGraphRunner
291 * will take care of calling OneIterationImpl from its thread. Otherwise,
292 * OneIterationImpl is called directly. Mixed audio output from the graph is
293 * passed into aMixerReceiver, if it is non-null.
295 IterationResult
OneIteration(GraphTime aStateTime
, GraphTime aIterationEnd
,
296 MixerCallbackReceiver
* aMixerReceiver
) override
;
299 * Returns true if this MediaTrackGraph should keep running
301 IterationResult
OneIterationImpl(GraphTime aStateTime
,
302 GraphTime aIterationEnd
,
303 MixerCallbackReceiver
* aMixerReceiver
);
306 * Called from the driver, when the graph thread is about to stop, to tell
307 * the main thread to attempt to begin cleanup. The main thread may either
308 * shutdown or revive the graph depending on whether it receives new
311 void SignalMainThreadCleanup();
313 /* This is the end of the current iteration, that is, the current time of the
315 GraphTime
IterationEnd() const;
318 * Ensure there is an event posted to the main thread to run RunInStableState.
319 * mMonitor must be held.
320 * See EnsureRunInStableState
322 void EnsureStableStateEventPosted() MOZ_REQUIRES(mMonitor
);
324 * Generate messages to the main thread to update it for all state changes.
325 * mMonitor must be held.
327 void PrepareUpdatesToMainThreadState(bool aFinalUpdate
)
328 MOZ_REQUIRES(mMonitor
);
330 * If we are rendering in non-realtime mode, we don't want to send messages to
331 * the main thread at each iteration for performance reasons. We instead
332 * notify the main thread at the same rate
334 bool ShouldUpdateMainThread();
335 // The following methods are the various stages of RunThread processing.
337 * Advance all track state to mStateComputedTime.
339 void UpdateCurrentTimeForTracks(GraphTime aPrevCurrentTime
);
341 * Process chunks for all tracks and raise events for properties that have
342 * changed, such as principalId.
344 void ProcessChunkMetadata(GraphTime aPrevCurrentTime
);
346 * Process chunks for the given track and interval, and raise events for
347 * properties that have changed, such as principalHandle.
349 template <typename C
, typename Chunk
>
350 void ProcessChunkMetadataForInterval(MediaTrack
* aTrack
, C
& aSegment
,
351 TrackTime aStart
, TrackTime aEnd
);
353 * Process graph messages in mFrontMessageQueue.
355 void RunMessagesInQueue();
357 * Update track processing order and recompute track blocking until
358 * aEndBlockingDecisions.
360 void UpdateGraph(GraphTime aEndBlockingDecisions
);
362 void SwapMessageQueues() MOZ_REQUIRES(mMonitor
) {
363 MOZ_ASSERT(OnGraphThreadOrNotRunning());
364 mMonitor
.AssertCurrentThreadOwns();
365 MOZ_ASSERT(mFrontMessageQueue
.IsEmpty());
366 mFrontMessageQueue
.SwapElements(mBackMessageQueue
);
367 if (!mFrontMessageQueue
.IsEmpty()) {
368 EnsureNextIteration();
372 * Do all the processing and play the audio and video, from
373 * mProcessedTime to mStateComputedTime.
375 void Process(MixerCallbackReceiver
* aMixerReceiver
);
378 * For use during ProcessedMediaTrack::ProcessInput() or
379 * MediaTrackListener callbacks, when graph state cannot be changed.
380 * Schedules |aMessage| to run after processing, at a time when graph state
381 * can be changed. Graph thread.
383 void RunMessageAfterProcessing(UniquePtr
<ControlMessageInterface
> aMessage
);
385 /* From the main thread, ask the MTG to resolve the returned promise when
386 * the device specified has started.
387 * A null aDeviceID indicates the default audio output device.
388 * The promise is rejected with NS_ERROR_INVALID_ARG if aSink does not
389 * correspond to any output devices used by the graph, or
390 * NS_ERROR_NOT_AVAILABLE if outputs to the device are removed or
391 * NS_ERROR_ILLEGAL_DURING_SHUTDOWN if the graph is force shut down
392 * before the promise could be resolved.
394 using GraphStartedPromise
= GenericPromise
;
395 RefPtr
<GraphStartedPromise
> NotifyWhenDeviceStarted(
396 CubebUtils::AudioDeviceID aDeviceID
) override
;
399 * Resolve the GraphStartedPromise when the driver has started processing on
400 * the audio thread after the device has started.
401 * (Audio is initially processed in the FallbackDriver's thread while the
402 * device is starting up.)
404 void NotifyWhenPrimaryDeviceStarted(
405 MozPromiseHolder
<GraphStartedPromise
>&& aHolder
);
408 * Apply an AudioContext operation (suspend/resume/close), on the graph
411 void ApplyAudioContextOperationImpl(
412 AudioContextOperationControlMessage
* aMessage
);
415 * Determine if we have any audio tracks, or are about to add any audiotracks.
417 bool AudioTrackPresent();
420 * Schedules a replacement GraphDriver in mNextDriver, if necessary.
425 * Sort mTracks so that every track not in a cycle is after any tracks
426 * it depends on, and every track in a cycle is marked as being in a cycle.
428 void UpdateTrackOrder();
431 * Returns smallest value of t such that t is a multiple of
432 * WEBAUDIO_BLOCK_SIZE and t >= aTime.
434 static GraphTime
RoundUpToEndOfAudioBlock(GraphTime aTime
);
436 * Returns smallest value of t such that t is a multiple of
437 * WEBAUDIO_BLOCK_SIZE and t > aTime.
439 static GraphTime
RoundUpToNextAudioBlock(GraphTime aTime
);
441 * Produce data for all tracks >= aTrackIndex for the current time interval.
442 * Advances block by block, each iteration producing data for all tracks
443 * for a single block.
444 * This is called whenever we have an AudioNodeTrack in the graph.
446 void ProduceDataForTracksBlockByBlock(uint32_t aTrackIndex
,
447 TrackRate aSampleRate
);
449 * If aTrack will underrun between aTime, and aEndBlockingDecisions, returns
450 * the time at which the underrun will start. Otherwise return
451 * aEndBlockingDecisions.
453 GraphTime
WillUnderrun(MediaTrack
* aTrack
, GraphTime aEndBlockingDecisions
);
456 * Given a graph time aTime, convert it to a track time taking into
457 * account the time during which aTrack is scheduled to be blocked.
459 TrackTime
GraphTimeToTrackTimeWithBlocking(const MediaTrack
* aTrack
,
460 GraphTime aTime
) const;
464 * Set mOutputDeviceForAEC to indicate the audio output to be passed as the
465 * reverse stream for audio echo cancellation. Graph thread.
467 void SelectOutputDeviceForAEC();
469 * Queue audio (mix of track audio and silence for blocked intervals)
470 * to the audio output track. Returns the number of frames played.
472 struct TrackAndVolume
;
473 TrackTime
PlayAudio(const TrackAndVolume
& aOutput
, GraphTime aPlayedTime
,
474 uint32_t aOutputChannelCount
);
477 /* Runs off a message on the graph thread when something requests audio from
478 * an input audio device of ID aID, and delivers the input audio frames to
480 void OpenAudioInputImpl(DeviceInputTrack
* aTrack
);
481 /* Called on the main thread when something requests audio from an input
482 * audio device aID. */
483 virtual void OpenAudioInput(DeviceInputTrack
* aTrack
) override
;
485 /* Runs off a message on the graph when input audio from aID is not needed
486 * anymore, for a particular track. It can be that other tracks still need
487 * audio from this audio input device. */
488 void CloseAudioInputImpl(DeviceInputTrack
* aTrack
);
489 /* Called on the main thread when input audio from aID is not needed
490 * anymore, for a particular track. It can be that other tracks still need
491 * audio from this audio input device. */
492 virtual void CloseAudioInput(DeviceInputTrack
* aTrack
) override
;
494 void UnregisterAllAudioOutputs(MediaTrack
* aTrack
);
496 /* Called on the graph thread when the input device settings should be
497 * reevaluated, for example, if the channel count of the input track should
499 void ReevaluateInputDevice(CubebUtils::AudioDeviceID aID
);
501 /* Called on the graph thread when there is new output data for listeners.
502 * This is the mixed audio output of this MediaTrackGraph. */
503 void NotifyOutputData(const AudioChunk
& aChunk
);
504 /* Called on the graph thread after an AudioCallbackDriver with an input
505 * stream has stopped. */
506 void NotifyInputStopped() override
;
507 /* Called on the graph thread when there is new input data for listeners. This
508 * is the raw audio input for this MediaTrackGraph. */
509 void NotifyInputData(const AudioDataValue
* aBuffer
, size_t aFrames
,
510 TrackRate aRate
, uint32_t aChannels
,
511 uint32_t aAlreadyBuffered
) override
;
512 /* Called on the main thread after an AudioCallbackDriver has attempted an
513 * operation to set aRequestedParams on the cubeb stream. */
514 void NotifySetRequestedInputProcessingParamsResult(
515 AudioCallbackDriver
* aDriver
, int aGeneration
,
516 Result
<cubeb_input_processing_params
, int>&& aResult
) override
;
517 /* Called every time there are changes to input/output audio devices like
518 * plug/unplug etc. This can be called on any thread, and posts a message to
519 * the main thread so that it can post a message to the graph thread. */
520 void DeviceChanged() override
;
521 /* Called every time there are changes to input/output audio devices. This is
522 * called on the graph thread. */
523 void DeviceChangedImpl();
526 * Compute how much track data we would like to buffer for aTrack.
528 TrackTime
GetDesiredBufferEnd(MediaTrack
* aTrack
);
530 * Returns true when there are no active tracks.
532 bool IsEmpty() const {
534 OnGraphThreadOrNotRunning() ||
535 (NS_IsMainThread() &&
536 LifecycleStateRef() >= LIFECYCLE_WAITING_FOR_MAIN_THREAD_CLEANUP
));
537 return mTracks
.IsEmpty() && mSuspendedTracks
.IsEmpty() && mPortCount
== 0;
541 * Add aTrack to the graph and initializes its graph-specific state.
543 void AddTrackGraphThread(MediaTrack
* aTrack
);
545 * Remove aTrack from the graph. Ensures that pending messages about the
546 * track back to the main thread are flushed.
548 void RemoveTrackGraphThread(MediaTrack
* aTrack
);
550 * Remove a track from the graph. Main thread.
552 void RemoveTrack(MediaTrack
* aTrack
);
554 * Remove aPort from the graph and release it.
556 void DestroyPort(MediaInputPort
* aPort
);
558 * Mark the media track order as dirty.
560 void SetTrackOrderDirty() {
561 MOZ_ASSERT(OnGraphThreadOrNotRunning());
562 mTrackOrderDirty
= true;
566 // Get the current maximum channel count required for a device.
567 // aDevice is an element of mOutputDevices. Graph thread only.
568 struct OutputDeviceEntry
;
569 uint32_t AudioOutputChannelCount(const OutputDeviceEntry
& aDevice
) const;
570 // Get the current maximum channel count for audio output through an
571 // AudioCallbackDriver. Graph thread only.
572 uint32_t PrimaryOutputChannelCount() const;
575 // Set a new maximum channel count. Graph thread only.
576 void SetMaxOutputChannelCount(uint32_t aMaxChannelCount
);
578 double AudioOutputLatency();
579 /* Return whether the clock for the audio output device used for the AEC
580 * reverse stream might drift from the clock for this MediaTrackGraph. */
581 bool OutputForAECMightDrift() {
582 AssertOnGraphThread();
583 return mOutputDeviceForAEC
!= PrimaryOutputDeviceID();
586 * The audio input channel count for a MediaTrackGraph is the max of all the
587 * channel counts requested by the listeners. The max channel count is
588 * delivered to the listeners themselves, and they take care of downmixing.
590 uint32_t AudioInputChannelCount(CubebUtils::AudioDeviceID aID
);
592 AudioInputType
AudioInputDevicePreference(CubebUtils::AudioDeviceID aID
);
594 double MediaTimeToSeconds(GraphTime aTime
) const {
595 NS_ASSERTION(aTime
> -TRACK_TIME_MAX
&& aTime
<= TRACK_TIME_MAX
,
597 return static_cast<double>(aTime
) / GraphRate();
601 * Signal to the graph that the thread has paused indefinitly,
604 void PausedIndefinitly();
605 void ResumedFromPaused();
608 * Not safe to call off the MediaTrackGraph thread unless monitor is held!
610 GraphDriver
* CurrentDriver() const MOZ_NO_THREAD_SAFETY_ANALYSIS
{
612 if (!OnGraphThreadOrNotRunning()) {
613 mMonitor
.AssertCurrentThreadOwns();
620 * Effectively set the new driver, while we are switching.
621 * It is only safe to call this at the very end of an iteration, when there
622 * has been a SwitchAtNextIteration call during the iteration. The driver
623 * should return and pass the control to the new driver shortly after.
624 * Monitor must be held.
626 void SetCurrentDriver(GraphDriver
* aDriver
) {
627 MOZ_ASSERT_IF(mGraphDriverRunning
, InDriverIteration(mDriver
));
628 MOZ_ASSERT_IF(!mGraphDriverRunning
, NS_IsMainThread());
629 MonitorAutoLock
lock(GetMonitor());
633 GraphDriver
* NextDriver() const {
634 MOZ_ASSERT(OnGraphThread());
638 bool Switching() const { return NextDriver(); }
640 void SwitchAtNextIteration(GraphDriver
* aNextDriver
);
642 Monitor
& GetMonitor() { return mMonitor
; }
644 void EnsureNextIteration() { CurrentDriver()->EnsureNextIteration(); }
646 // Capture API. This allows to get a mixed-down output for a window.
647 void RegisterCaptureTrackForWindow(uint64_t aWindowId
,
648 ProcessedMediaTrack
* aCaptureTrack
);
649 void UnregisterCaptureTrackForWindow(uint64_t aWindowId
);
650 already_AddRefed
<MediaInputPort
> ConnectToCaptureTrack(
651 uint64_t aWindowId
, MediaTrack
* aMediaTrack
);
653 Watchable
<GraphTime
>& CurrentTime() override
;
656 * Interrupt any JS running on the graph thread.
657 * Called on the main thread when shutting down the graph.
665 explicit iterator(MediaTrackGraphImpl
& aGraph
)
666 : mGraph(&aGraph
), mArrayNum(-1), mArrayIndex(0) {
669 iterator() : mGraph(nullptr), mArrayNum(2), mArrayIndex(0) {}
670 MediaTrack
* operator*() { return Array()->ElementAt(mArrayIndex
); }
671 iterator
operator++() {
673 while (mArrayNum
< 2 &&
674 (mArrayNum
< 0 || mArrayIndex
>= Array()->Length())) {
680 bool operator==(const iterator
& aOther
) const {
681 return mArrayNum
== aOther
.mArrayNum
&&
682 mArrayIndex
== aOther
.mArrayIndex
;
684 bool operator!=(const iterator
& aOther
) const {
685 return !(*this == aOther
);
689 nsTArray
<MediaTrack
*>* Array() {
690 return mArrayNum
== 0 ? &mGraph
->mTracks
: &mGraph
->mSuspendedTracks
;
692 MediaTrackGraphImpl
* mGraph
;
694 uint32_t mArrayIndex
;
697 explicit TrackSet(MediaTrackGraphImpl
& aGraph
) : mGraph(aGraph
) {}
698 iterator
begin() { return iterator(mGraph
); }
699 iterator
end() { return iterator(); }
702 MediaTrackGraphImpl
& mGraph
;
704 TrackSet
AllTracks() { return TrackSet(*this); }
709 * The ID of the inner Window which uses this graph, or zero for offline
712 const uint64_t mWindowID
;
714 * If set, the GraphRunner class handles handing over data from audio
715 * callbacks to a common single thread, shared across GraphDrivers.
717 RefPtr
<GraphRunner
> mGraphRunner
;
720 * Main-thread view of the number of tracks in this graph, for lifetime
723 * When this becomes zero, the graph is marked as forbidden to add more
724 * tracks to. It will be shut down shortly after.
726 size_t mMainThreadTrackCount
= 0;
729 * Main-thread view of the number of ports in this graph, to catch bugs.
731 * When this becomes zero, and mMainThreadTrackCount is 0, the graph is
732 * marked as forbidden to add more control messages to. It will be shut down
735 size_t mMainThreadPortCount
= 0;
738 * Graphs own owning references to their driver, until shutdown. When a driver
739 * switch occur, previous driver is either deleted, or it's ownership is
740 * passed to a event that will take care of the asynchronous cleanup, as
741 * audio track can take some time to shut down.
742 * Accessed on both the main thread and the graph thread; both read and write.
743 * Must hold monitor to access it.
745 RefPtr
<GraphDriver
> mDriver
;
747 // Set during an iteration to switch driver after the iteration has finished.
748 // Should the current iteration be the last iteration, the next driver will be
749 // discarded. Access through SwitchAtNextIteration()/NextDriver(). Graph
751 RefPtr
<GraphDriver
> mNextDriver
;
753 // The following state is managed on the graph thread only, unless
754 // mLifecycleState > LIFECYCLE_RUNNING in which case the graph thread
755 // is not running and this state can be used from the main thread.
758 * The graph keeps a reference to each track.
759 * References are maintained manually to simplify reordering without
760 * unnecessary thread-safe refcount changes.
761 * Must satisfy OnGraphThreadOrNotRunning().
763 nsTArray
<MediaTrack
*> mTracks
;
765 * This stores MediaTracks that are part of suspended AudioContexts.
766 * mTracks and mSuspendTracks are disjoint sets: a track is either suspended
767 * or not suspended. Suspended tracks are not ordered in UpdateTrackOrder,
768 * and are therefore not doing any processing.
769 * Must satisfy OnGraphThreadOrNotRunning().
771 nsTArray
<MediaTrack
*> mSuspendedTracks
;
773 * Tracks from mFirstCycleBreaker to the end of mTracks produce output before
774 * they receive input. They correspond to DelayNodes that are in cycles.
776 uint32_t mFirstCycleBreaker
;
778 * Blocking decisions have been computed up to this time.
779 * Between each iteration, this is the same as mProcessedTime.
781 GraphTime mStateComputedTime
= 0;
783 * All track contents have been computed up to this time.
784 * The next batch of updates from the main thread will be processed
785 * at this time. This is behind mStateComputedTime during processing.
787 GraphTime mProcessedTime
= 0;
789 * The graph should stop processing at this time.
793 * Date of the last time we updated the main thread with the graph state.
795 TimeStamp mLastMainThreadUpdate
;
797 * Number of active MediaInputPorts
801 * Runnables to run after the next update to main thread state, but that are
802 * still waiting for the next iteration to finish.
804 nsTArray
<nsCOMPtr
<nsIRunnable
>> mPendingUpdateRunnables
;
807 * List of resume operations waiting for a switch to an AudioCallbackDriver.
809 class PendingResumeOperation
{
811 explicit PendingResumeOperation(
812 AudioContextOperationControlMessage
* aMessage
);
813 void Apply(MediaTrackGraphImpl
* aGraph
);
815 MediaTrack
* DestinationTrack() const { return mDestinationTrack
; }
818 RefPtr
<MediaTrack
> mDestinationTrack
;
819 nsTArray
<RefPtr
<MediaTrack
>> mTracks
;
820 MozPromiseHolder
<AudioContextOperationPromise
> mHolder
;
822 AutoTArray
<PendingResumeOperation
, 1> mPendingResumeOperations
;
824 // mMonitor guards the data below.
825 // MediaTrackGraph normally does its work without holding mMonitor, so it is
826 // not safe to just grab mMonitor from some thread and start monkeying with
827 // the graph. Instead, communicate with the graph thread using provided
828 // mechanisms such as the control message queue.
831 // Data guarded by mMonitor (must always be accessed with mMonitor held,
832 // regardless of the value of mLifecycleState).
835 * State to copy to main thread
837 nsTArray
<TrackUpdate
> mTrackUpdates
MOZ_GUARDED_BY(mMonitor
);
839 * Runnables to run after the next update to main thread state.
841 nsTArray
<nsCOMPtr
<nsIRunnable
>> mUpdateRunnables
MOZ_GUARDED_BY(mMonitor
);
843 * A list of batches of messages to process. Each batch is processed
847 * Message queue processed by the MTG thread during an iteration.
848 * Accessed on graph thread only.
850 nsTArray
<MessageBlock
> mFrontMessageQueue
;
852 * Message queue in which the main thread appends messages.
853 * Access guarded by mMonitor.
855 nsTArray
<MessageBlock
> mBackMessageQueue
MOZ_GUARDED_BY(mMonitor
);
857 /* True if there will messages to process if we swap the message queues. */
858 bool MessagesQueued() const MOZ_REQUIRES(mMonitor
) {
859 mMonitor
.AssertCurrentThreadOwns();
860 return !mBackMessageQueue
.IsEmpty();
863 * This enum specifies where this graph is in its lifecycle. This is used
864 * to control shutdown.
865 * Shutdown is tricky because it can happen in two different ways:
866 * 1) Shutdown due to inactivity. RunThread() detects that it has no
867 * pending messages and no tracks, and exits. The next RunInStableState()
868 * checks if there are new pending messages from the main thread (true only
869 * if new track creation raced with shutdown); if there are, it revives
870 * RunThread(), otherwise it commits to shutting down the graph. New track
871 * creation after this point will create a new graph. An async event is
872 * dispatched to Shutdown() the graph's threads and then delete the graph
874 * 2) Forced shutdown at application shutdown, completion of a non-realtime
875 * graph, or document unload. A flag is set, RunThread() detects the flag
876 * and exits, the next RunInStableState() detects the flag, and dispatches
877 * the async event to Shutdown() the graph's threads. However the graph
878 * object is not deleted. New messages for the graph are processed
879 * synchronously on the main thread if necessary. When the last track is
880 * destroyed, the graph object is deleted.
882 * This should be kept in sync with the LifecycleState_str array in
883 * MediaTrackGraph.cpp
885 enum LifecycleState
{
886 // The graph thread hasn't started yet.
887 LIFECYCLE_THREAD_NOT_STARTED
,
888 // RunThread() is running normally.
890 // In the following states, the graph thread is not running so
891 // all "graph thread only" state in this class can be used safely
892 // on the main thread.
893 // RunThread() has exited and we're waiting for the next
894 // RunInStableState(), at which point we can clean up the main-thread
895 // side of the graph.
896 LIFECYCLE_WAITING_FOR_MAIN_THREAD_CLEANUP
,
897 // RunInStableState() posted a ShutdownRunnable, and we're waiting for it
898 // to shut down the graph thread(s).
899 LIFECYCLE_WAITING_FOR_THREAD_SHUTDOWN
,
900 // Graph threads have shut down but we're waiting for remaining tracks
901 // to be destroyed. Only happens during application shutdown and on
902 // completed non-realtime graphs, since normally we'd only shut down a
903 // realtime graph when it has no tracks.
904 LIFECYCLE_WAITING_FOR_TRACK_DESTRUCTION
908 * Modified only in mMonitor. Transitions to
909 * LIFECYCLE_WAITING_FOR_MAIN_THREAD_CLEANUP occur on the graph thread at
910 * the end of an iteration. All other transitions occur on the main thread.
912 LifecycleState mLifecycleState
MOZ_GUARDED_BY(mMonitor
);
913 LifecycleState
& LifecycleStateRef() MOZ_NO_THREAD_SAFETY_ANALYSIS
{
915 if (mGraphDriverRunning
) {
916 mMonitor
.AssertCurrentThreadOwns();
918 MOZ_ASSERT(NS_IsMainThread());
921 return mLifecycleState
;
923 const LifecycleState
& LifecycleStateRef() const
924 MOZ_NO_THREAD_SAFETY_ANALYSIS
{
926 if (mGraphDriverRunning
) {
927 mMonitor
.AssertCurrentThreadOwns();
929 MOZ_ASSERT(NS_IsMainThread());
932 return mLifecycleState
;
936 * True once the graph thread has received the message from ForceShutDown().
937 * This is checked in the decision to shut down the
938 * graph thread so that control messages dispatched before forced shutdown
939 * are processed on the graph thread.
940 * Only set on the graph thread.
941 * Can be read safely on the thread currently owning the graph, as indicated
942 * by mLifecycleState.
944 bool mForceShutDownReceived
= false;
946 * true when InterruptJS() has been called, because shutdown (normal or
947 * forced) has commenced. Set on the main thread under mMonitor and read on
948 * the graph thread under mMonitor.
950 bool mInterruptJSCalled
MOZ_GUARDED_BY(mMonitor
) = false;
953 * Remove this blocker to unblock shutdown.
954 * Only accessed on the main thread.
956 RefPtr
<media::ShutdownBlocker
> mShutdownBlocker
;
959 * True when we have posted an event to the main thread to run
960 * RunInStableState() and the event hasn't run yet.
961 * Accessed on both main and MTG thread, mMonitor must be held.
963 bool mPostedRunInStableStateEvent
MOZ_GUARDED_BY(mMonitor
);
966 * The JSContext of the graph thread. Set under mMonitor on only the graph
967 * or GraphRunner thread. Once set this does not change until reset when
968 * the thread is about to exit. Read under mMonitor on the main thread to
969 * interrupt running JS for forced shutdown.
971 JSContext
* mJSContext
MOZ_GUARDED_BY(mMonitor
) = nullptr;
976 * Messages posted by the current event loop task. These are forwarded to
977 * the media graph thread during RunInStableState. We can't forward them
978 * immediately because we want all messages between stable states to be
979 * processed as an atomic batch.
981 nsTArray
<UniquePtr
<ControlMessageInterface
>> mCurrentTaskMessageQueue
;
983 * True from when RunInStableState sets mLifecycleState to LIFECYCLE_RUNNING,
984 * until RunInStableState has determined that mLifecycleState is >
987 Atomic
<bool> mGraphDriverRunning
;
989 * True when a stable state runner has been posted to the appshell to run
990 * RunInStableState at the next stable state.
991 * Only accessed on the main thread.
993 bool mPostedRunInStableState
;
995 * True when processing real-time audio/video. False when processing
996 * non-realtime audio.
1000 * True when a change has happened which requires us to recompute the track
1003 bool mTrackOrderDirty
;
1004 const RefPtr
<nsISerialEventTarget
> mMainThread
;
1006 // used to limit graph shutdown time
1007 // Only accessed on the main thread.
1008 nsCOMPtr
<nsITimer
> mShutdownTimer
;
1011 virtual ~MediaTrackGraphImpl();
1014 MOZ_DEFINE_MALLOC_SIZE_OF(MallocSizeOf
)
1016 // Set a new native iput device when the current native input device is close.
1017 // Main thread only.
1018 void SetNewNativeInput();
1021 * This class uses manual memory management, and all pointers to it are raw
1022 * pointers. However, in order for it to implement nsIMemoryReporter, it needs
1023 * to implement nsISupports and so be ref-counted. So it maintains a single
1024 * nsRefPtr to itself, giving it a ref-count of 1 during its entire lifetime,
1025 * and Destroy() nulls this self-reference in order to trigger self-deletion.
1027 RefPtr
<MediaTrackGraphImpl
> mSelfRef
;
1029 struct WindowAndTrack
{
1031 RefPtr
<ProcessedMediaTrack
> mCaptureTrackSink
;
1034 * Track for window audio capture.
1036 nsTArray
<WindowAndTrack
> mWindowCaptureTracks
;
1039 * Main thread unordered record of audio outputs, keyed by Track and output
1040 * key. Used to determine when an output device is no longer in use and to
1041 * record the volumes corresponding to each key. An array is used as a
1042 * simple hash table, on the assumption that the number of outputs is small.
1044 struct TrackAndKey
{
1045 MOZ_UNSAFE_REF("struct exists only if track exists") MediaTrack
* mTrack
;
1048 struct TrackKeyDeviceAndVolume
{
1049 MOZ_UNSAFE_REF("struct exists only if track exists")
1050 MediaTrack
* const mTrack
;
1052 const CubebUtils::AudioDeviceID mDeviceID
;
1055 bool operator==(const TrackAndKey
& aTrackAndKey
) const {
1056 return mTrack
== aTrackAndKey
.mTrack
&& mKey
== aTrackAndKey
.mKey
;
1059 nsTArray
<TrackKeyDeviceAndVolume
> mAudioOutputParams
;
1061 * Main thread record of which audio output devices are active, keyed by
1062 * AudioDeviceID, and their CrossGraphReceivers if any.
1063 * mOutputDeviceRefCnts[0] always exists and corresponds to the primary
1064 * audio output device, which an AudioCallbackDriver will use if active.
1065 * mCount may be zero for the first entry only. */
1066 struct DeviceReceiverAndCount
{
1067 const CubebUtils::AudioDeviceID mDeviceID
;
1068 // For secondary devices, mReceiver receives audio output.
1069 // Null for the primary output device, fed by an AudioCallbackDriver.
1070 const RefPtr
<CrossGraphReceiver
> mReceiver
;
1071 size_t mRefCnt
; // number of mAudioOutputParams entries with this device
1073 bool operator==(CubebUtils::AudioDeviceID aDeviceID
) const {
1074 return mDeviceID
== aDeviceID
;
1077 nsTArray
<DeviceReceiverAndCount
> mOutputDeviceRefCnts
;
1079 * Graph thread record of devices to which audio outputs are mixed, keyed by
1080 * AudioDeviceID. All tracks that have an audio output to each device are
1081 * grouped for mixing their outputs to a single stream.
1082 * mOutputDevices[0] always exists and corresponds to the primary audio
1083 * output device, which an AudioCallbackDriver will use if active.
1084 * An AudioCallbackDriver may be active when no audio outputs have audio
1087 struct TrackAndVolume
{
1088 MOZ_UNSAFE_REF("struct exists only if track exists")
1089 MediaTrack
* const mTrack
;
1092 bool operator==(const MediaTrack
* aTrack
) const { return mTrack
== aTrack
; }
1094 struct OutputDeviceEntry
{
1095 const CubebUtils::AudioDeviceID mDeviceID
;
1096 // For secondary devices, mReceiver receives audio output.
1097 // Null for the primary output device, fed by an AudioCallbackDriver.
1098 const RefPtr
<CrossGraphReceiver
> mReceiver
;
1100 * Mapping from MediaTrack to volume for all tracks that have their audio
1101 * output mixed and written to this output device.
1103 nsTArray
<TrackAndVolume
> mTrackOutputs
;
1105 bool operator==(CubebUtils::AudioDeviceID aDeviceID
) const {
1106 return mDeviceID
== aDeviceID
;
1109 nsTArray
<OutputDeviceEntry
> mOutputDevices
;
1111 * mOutputDeviceForAEC identifies the audio output to be passed as the
1112 * reverse stream for audio echo cancellation. Used only if a microphone is
1113 * active. Graph thread.
1115 CubebUtils::AudioDeviceID mOutputDeviceForAEC
= nullptr;
1118 * Global volume scale. Used when running tests so that the output is not too
1121 const float mGlobalVolume
;
1126 * Used to assert when AppendMessage() runs control messages synchronously.
1128 bool mCanRunMessagesSynchronously
;
1133 * The graph's main-thread observable graph time.
1134 * Updated by the stable state runnable after each iteration.
1136 Watchable
<GraphTime
> mMainThreadGraphTime
;
1139 * Set based on mProcessedTime at end of iteration.
1140 * Read by stable state runnable on main thread. Protected by mMonitor.
1142 GraphTime mNextMainThreadGraphTime
MOZ_GUARDED_BY(mMonitor
) = 0;
1145 * Cached audio output latency, in seconds. Main thread only. This is reset
1146 * whenever the audio device running this MediaTrackGraph changes.
1148 double mAudioOutputLatency
;
1151 * The max audio output channel count the default audio output device
1152 * supports. This is cached here because it can be expensive to query. The
1153 * cache is invalidated when the device is changed. This is initialized in the
1154 * ctor, and the read/write only on the graph thread.
1156 uint32_t mMaxOutputChannelCount
;
1160 * Manage the native or non-native input device in graph. Main thread only.
1162 DeviceInputTrackManager mDeviceInputTrackManagerMainThread
;
1166 * Manage the native or non-native input device in graph. Graph thread only.
1168 DeviceInputTrackManager mDeviceInputTrackManagerGraphThread
;
1170 * The mixer that the graph mixes into during an iteration. This is here
1171 * rather than on the stack so that its buffer is not allocated each
1172 * iteration. Graph thread only.
1177 } // namespace mozilla
1179 #endif /* MEDIATRACKGRAPHIMPL_H_ */