Bug 1772053 - Enable dynamic code disable mitigations only on Windows 10 1703+ r...
[gecko.git] / dom / media / MediaTrackGraph.cpp
blobf6af3c8861196e7baeef4fe283b4174518432173
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 #include "MediaTrackGraphImpl.h"
7 #include "mozilla/MathAlgorithms.h"
8 #include "mozilla/Unused.h"
10 #include "AudioSegment.h"
11 #include "CrossGraphPort.h"
12 #include "VideoSegment.h"
13 #include "nsContentUtils.h"
14 #include "nsPrintfCString.h"
15 #include "nsServiceManagerUtils.h"
16 #include "prerror.h"
17 #include "mozilla/Logging.h"
18 #include "mozilla/Attributes.h"
19 #include "ForwardedInputTrack.h"
20 #include "ImageContainer.h"
21 #include "AudioCaptureTrack.h"
22 #include "AudioNodeTrack.h"
23 #include "AudioNodeExternalInputTrack.h"
24 #if defined(MOZ_WEBRTC)
25 # include "MediaEngineWebRTCAudio.h"
26 #endif // MOZ_WEBRTC
27 #include "MediaTrackListener.h"
28 #include "mozilla/dom/BaseAudioContextBinding.h"
29 #include "mozilla/dom/WorkletThread.h"
30 #include "mozilla/media/MediaUtils.h"
31 #include <algorithm>
32 #include "GeckoProfiler.h"
33 #include "VideoFrameContainer.h"
34 #include "mozilla/AbstractThread.h"
35 #include "mozilla/StaticPrefs_dom.h"
36 #include "mozilla/StaticPrefs_media.h"
37 #include "transport/runnable_utils.h"
38 #include "VideoUtils.h"
39 #include "GraphRunner.h"
40 #include "Tracing.h"
41 #include "UnderrunHandler.h"
42 #include "mozilla/CycleCollectedJSRuntime.h"
43 #include "mozilla/Preferences.h"
45 #include "webaudio/blink/DenormalDisabler.h"
46 #include "webaudio/blink/HRTFDatabaseLoader.h"
48 using namespace mozilla::layers;
49 using namespace mozilla::dom;
50 using namespace mozilla::gfx;
51 using namespace mozilla::media;
53 namespace mozilla {
55 LazyLogModule gMediaTrackGraphLog("MediaTrackGraph");
56 #ifdef LOG
57 # undef LOG
58 #endif // LOG
59 #define LOG(type, msg) MOZ_LOG(gMediaTrackGraphLog, type, msg)
61 NativeInputTrack* DeviceInputTrackManager::GetNativeInputTrack() {
62 return mNativeInputTrack.get();
65 DeviceInputTrack* DeviceInputTrackManager::GetDeviceInputTrack(
66 CubebUtils::AudioDeviceID aID) {
67 if (mNativeInputTrack && mNativeInputTrack->mDeviceId == aID) {
68 return mNativeInputTrack.get();
70 for (const RefPtr<NonNativeInputTrack>& t : mNonNativeInputTracks) {
71 if (t->mDeviceId == aID) {
72 return t.get();
75 return nullptr;
78 NonNativeInputTrack* DeviceInputTrackManager::GetFirstNonNativeInputTrack() {
79 if (mNonNativeInputTracks.IsEmpty()) {
80 return nullptr;
82 return mNonNativeInputTracks[0].get();
85 void DeviceInputTrackManager::Add(DeviceInputTrack* aTrack) {
86 if (NativeInputTrack* native = aTrack->AsNativeInputTrack()) {
87 MOZ_ASSERT(!mNativeInputTrack);
88 mNativeInputTrack = native;
89 } else {
90 NonNativeInputTrack* nonNative = aTrack->AsNonNativeInputTrack();
91 MOZ_ASSERT(nonNative);
92 struct DeviceTrackComparator {
93 public:
94 bool Equals(const RefPtr<NonNativeInputTrack>& aTrack,
95 CubebUtils::AudioDeviceID aDeviceId) const {
96 return aTrack->mDeviceId == aDeviceId;
99 MOZ_ASSERT(!mNonNativeInputTracks.Contains(aTrack->mDeviceId,
100 DeviceTrackComparator()));
101 mNonNativeInputTracks.AppendElement(nonNative);
105 void DeviceInputTrackManager::Remove(DeviceInputTrack* aTrack) {
106 if (aTrack->AsNativeInputTrack()) {
107 MOZ_ASSERT(mNativeInputTrack);
108 MOZ_ASSERT(mNativeInputTrack.get() == aTrack->AsNativeInputTrack());
109 mNativeInputTrack = nullptr;
110 } else {
111 NonNativeInputTrack* nonNative = aTrack->AsNonNativeInputTrack();
112 MOZ_ASSERT(nonNative);
113 DebugOnly<bool> removed = mNonNativeInputTracks.RemoveElement(nonNative);
114 MOZ_ASSERT(removed);
118 namespace {
120 * A hash table containing the graph instances, one per Window ID,
121 * sample rate, and device ID combination.
123 class GraphKey final {
124 public:
125 GraphKey(uint64_t aWindowID, TrackRate aSampleRate,
126 CubebUtils::AudioDeviceID aOutputDeviceID)
127 : mWindowID(aWindowID),
128 mSampleRate(aSampleRate),
129 mOutputDeviceID(aOutputDeviceID) {}
130 GraphKey(const GraphKey&) = default;
131 ~GraphKey() = default;
132 bool operator==(const GraphKey& b) const {
133 return mWindowID == b.mWindowID && mSampleRate == b.mSampleRate &&
134 mOutputDeviceID == b.mOutputDeviceID;
136 PLDHashNumber Hash() const {
137 return HashGeneric(mWindowID, mSampleRate, mOutputDeviceID);
140 private:
141 uint64_t mWindowID;
142 TrackRate mSampleRate;
143 CubebUtils::AudioDeviceID mOutputDeviceID;
145 nsTHashMap<nsGenericHashKey<GraphKey>, MediaTrackGraphImpl*> gGraphs;
146 } // anonymous namespace
148 MediaTrackGraphImpl::~MediaTrackGraphImpl() {
149 MOZ_ASSERT(mTracks.IsEmpty() && mSuspendedTracks.IsEmpty(),
150 "All tracks should have been destroyed by messages from the main "
151 "thread");
152 LOG(LogLevel::Debug, ("MediaTrackGraph %p destroyed", this));
153 LOG(LogLevel::Debug, ("MediaTrackGraphImpl::~MediaTrackGraphImpl"));
156 void MediaTrackGraphImpl::AddTrackGraphThread(MediaTrack* aTrack) {
157 MOZ_ASSERT(OnGraphThreadOrNotRunning());
158 aTrack->mStartTime = mProcessedTime;
160 if (aTrack->IsSuspended()) {
161 mSuspendedTracks.AppendElement(aTrack);
162 LOG(LogLevel::Debug,
163 ("%p: Adding media track %p, in the suspended track array", this,
164 aTrack));
165 } else {
166 mTracks.AppendElement(aTrack);
167 LOG(LogLevel::Debug, ("%p: Adding media track %p, count %zu", this, aTrack,
168 mTracks.Length()));
171 SetTrackOrderDirty();
174 void MediaTrackGraphImpl::RemoveTrackGraphThread(MediaTrack* aTrack) {
175 MOZ_ASSERT(OnGraphThreadOrNotRunning());
176 // Remove references in mTrackUpdates before we allow aTrack to die.
177 // Pending updates are not needed (since the main thread has already given
178 // up the track) so we will just drop them.
180 MonitorAutoLock lock(mMonitor);
181 for (uint32_t i = 0; i < mTrackUpdates.Length(); ++i) {
182 if (mTrackUpdates[i].mTrack == aTrack) {
183 mTrackUpdates[i].mTrack = nullptr;
188 // Ensure that mFirstCycleBreaker is updated when necessary.
189 SetTrackOrderDirty();
191 UnregisterAllAudioOutputs(aTrack);
193 if (aTrack->IsSuspended()) {
194 mSuspendedTracks.RemoveElement(aTrack);
195 } else {
196 mTracks.RemoveElement(aTrack);
199 LOG(LogLevel::Debug, ("%p: Removed media track %p, count %zu", this, aTrack,
200 mTracks.Length()));
202 NS_RELEASE(aTrack); // probably destroying it
205 TrackTime MediaTrackGraphImpl::GraphTimeToTrackTimeWithBlocking(
206 const MediaTrack* aTrack, GraphTime aTime) const {
207 MOZ_ASSERT(
208 aTime <= mStateComputedTime,
209 "Don't ask about times where we haven't made blocking decisions yet");
210 return std::max<TrackTime>(
211 0, std::min(aTime, aTrack->mStartBlocking) - aTrack->mStartTime);
214 GraphTime MediaTrackGraphImpl::IterationEnd() const {
215 MOZ_ASSERT(OnGraphThread());
216 return mIterationEndTime;
219 void MediaTrackGraphImpl::UpdateCurrentTimeForTracks(
220 GraphTime aPrevCurrentTime) {
221 MOZ_ASSERT(OnGraphThread());
222 for (MediaTrack* track : AllTracks()) {
223 // Shouldn't have already notified of ended *and* have output!
224 MOZ_ASSERT_IF(track->mStartBlocking > aPrevCurrentTime,
225 !track->mNotifiedEnded);
227 // Calculate blocked time and fire Blocked/Unblocked events
228 GraphTime blockedTime = mStateComputedTime - track->mStartBlocking;
229 NS_ASSERTION(blockedTime >= 0, "Error in blocking time");
230 track->AdvanceTimeVaryingValuesToCurrentTime(mStateComputedTime,
231 blockedTime);
232 LOG(LogLevel::Verbose,
233 ("%p: MediaTrack %p bufferStartTime=%f blockedTime=%f", this, track,
234 MediaTimeToSeconds(track->mStartTime),
235 MediaTimeToSeconds(blockedTime)));
236 track->mStartBlocking = mStateComputedTime;
238 TrackTime trackCurrentTime =
239 track->GraphTimeToTrackTime(mStateComputedTime);
240 if (track->mEnded) {
241 MOZ_ASSERT(track->GetEnd() <= trackCurrentTime);
242 if (!track->mNotifiedEnded) {
243 // Playout of this track ended and listeners have not been notified.
244 track->mNotifiedEnded = true;
245 SetTrackOrderDirty();
246 for (const auto& listener : track->mTrackListeners) {
247 listener->NotifyOutput(this, track->GetEnd());
248 listener->NotifyEnded(this);
251 } else {
252 for (const auto& listener : track->mTrackListeners) {
253 listener->NotifyOutput(this, trackCurrentTime);
259 template <typename C, typename Chunk>
260 void MediaTrackGraphImpl::ProcessChunkMetadataForInterval(MediaTrack* aTrack,
261 C& aSegment,
262 TrackTime aStart,
263 TrackTime aEnd) {
264 MOZ_ASSERT(OnGraphThreadOrNotRunning());
265 MOZ_ASSERT(aTrack);
267 TrackTime offset = 0;
268 for (typename C::ConstChunkIterator chunk(aSegment); !chunk.IsEnded();
269 chunk.Next()) {
270 if (offset >= aEnd) {
271 break;
273 offset += chunk->GetDuration();
274 if (chunk->IsNull() || offset < aStart) {
275 continue;
277 const PrincipalHandle& principalHandle = chunk->GetPrincipalHandle();
278 if (principalHandle != aSegment.GetLastPrincipalHandle()) {
279 aSegment.SetLastPrincipalHandle(principalHandle);
280 LOG(LogLevel::Debug,
281 ("%p: MediaTrack %p, principalHandle "
282 "changed in %sChunk with duration %lld",
283 this, aTrack,
284 aSegment.GetType() == MediaSegment::AUDIO ? "Audio" : "Video",
285 (long long)chunk->GetDuration()));
286 for (const auto& listener : aTrack->mTrackListeners) {
287 listener->NotifyPrincipalHandleChanged(this, principalHandle);
293 void MediaTrackGraphImpl::ProcessChunkMetadata(GraphTime aPrevCurrentTime) {
294 MOZ_ASSERT(OnGraphThreadOrNotRunning());
295 for (MediaTrack* track : AllTracks()) {
296 TrackTime iterationStart = track->GraphTimeToTrackTime(aPrevCurrentTime);
297 TrackTime iterationEnd = track->GraphTimeToTrackTime(mProcessedTime);
298 if (!track->mSegment) {
299 continue;
301 if (track->mType == MediaSegment::AUDIO) {
302 ProcessChunkMetadataForInterval<AudioSegment, AudioChunk>(
303 track, *track->GetData<AudioSegment>(), iterationStart, iterationEnd);
304 } else if (track->mType == MediaSegment::VIDEO) {
305 ProcessChunkMetadataForInterval<VideoSegment, VideoChunk>(
306 track, *track->GetData<VideoSegment>(), iterationStart, iterationEnd);
307 } else {
308 MOZ_CRASH("Unknown track type");
313 GraphTime MediaTrackGraphImpl::WillUnderrun(MediaTrack* aTrack,
314 GraphTime aEndBlockingDecisions) {
315 // Ended tracks can't underrun. ProcessedMediaTracks also can't cause
316 // underrun currently, since we'll always be able to produce data for them
317 // unless they block on some other track.
318 if (aTrack->mEnded || aTrack->AsProcessedTrack()) {
319 return aEndBlockingDecisions;
321 // This track isn't ended or suspended. We don't need to call
322 // TrackTimeToGraphTime since an underrun is the only thing that can block
323 // it.
324 GraphTime bufferEnd = aTrack->GetEnd() + aTrack->mStartTime;
325 #ifdef DEBUG
326 if (bufferEnd < mProcessedTime) {
327 LOG(LogLevel::Error, ("%p: MediaTrack %p underrun, "
328 "bufferEnd %f < mProcessedTime %f (%" PRId64
329 " < %" PRId64 "), TrackTime %" PRId64,
330 this, aTrack, MediaTimeToSeconds(bufferEnd),
331 MediaTimeToSeconds(mProcessedTime), bufferEnd,
332 mProcessedTime, aTrack->GetEnd()));
333 NS_ASSERTION(bufferEnd >= mProcessedTime, "Buffer underran");
335 #endif
336 return std::min(bufferEnd, aEndBlockingDecisions);
339 namespace {
340 // Value of mCycleMarker for unvisited tracks in cycle detection.
341 const uint32_t NOT_VISITED = UINT32_MAX;
342 // Value of mCycleMarker for ordered tracks in muted cycles.
343 const uint32_t IN_MUTED_CYCLE = 1;
344 } // namespace
346 bool MediaTrackGraphImpl::AudioTrackPresent() {
347 MOZ_ASSERT(OnGraphThreadOrNotRunning());
349 bool audioTrackPresent = false;
350 for (MediaTrack* track : mTracks) {
351 if (track->AsAudioNodeTrack()) {
352 audioTrackPresent = true;
353 break;
356 if (track->mType == MediaSegment::AUDIO && !track->mNotifiedEnded) {
357 audioTrackPresent = true;
358 break;
362 // We may not have audio input device when we only have AudioNodeTracks. But
363 // if audioTrackPresent is false, we must have no input device.
364 MOZ_DIAGNOSTIC_ASSERT_IF(
365 !audioTrackPresent,
366 !mDeviceInputTrackManagerGraphThread.GetNativeInputTrack());
368 return audioTrackPresent;
371 void MediaTrackGraphImpl::CheckDriver() {
372 MOZ_ASSERT(OnGraphThread());
373 // An offline graph has only one driver.
374 // Otherwise, if a switch is already pending, let that happen.
375 if (!mRealtime || Switching()) {
376 return;
379 AudioCallbackDriver* audioCallbackDriver =
380 CurrentDriver()->AsAudioCallbackDriver();
381 if (audioCallbackDriver && !audioCallbackDriver->OnFallback()) {
382 for (PendingResumeOperation& op : mPendingResumeOperations) {
383 op.Apply(this);
385 mPendingResumeOperations.Clear();
388 // Note that this looks for any audio tracks, input or output, and switches
389 // to a SystemClockDriver if there are none active or no resume operations
390 // to make any active.
391 bool needAudioCallbackDriver =
392 !mPendingResumeOperations.IsEmpty() || AudioTrackPresent();
393 if (!needAudioCallbackDriver) {
394 if (audioCallbackDriver && audioCallbackDriver->IsStarted()) {
395 SwitchAtNextIteration(
396 new SystemClockDriver(this, CurrentDriver(), mSampleRate));
398 return;
401 NativeInputTrack* native =
402 mDeviceInputTrackManagerGraphThread.GetNativeInputTrack();
403 CubebUtils::AudioDeviceID inputDevice = native ? native->mDeviceId : nullptr;
404 uint32_t inputChannelCount =
405 native ? AudioInputChannelCount(native->mDeviceId) : 0;
406 AudioInputType inputPreference =
407 native ? AudioInputDevicePreference(native->mDeviceId)
408 : AudioInputType::Unknown;
410 uint32_t graphOutputChannelCount = AudioOutputChannelCount();
411 if (!audioCallbackDriver) {
412 if (graphOutputChannelCount > 0) {
413 AudioCallbackDriver* driver = new AudioCallbackDriver(
414 this, CurrentDriver(), mSampleRate, graphOutputChannelCount,
415 inputChannelCount, mOutputDeviceID, inputDevice, inputPreference);
416 SwitchAtNextIteration(driver);
418 return;
421 // Check if this graph should switch to a different number of output channels.
422 // Generally, a driver switch is explicitly made by an event (e.g., setting
423 // the AudioDestinationNode channelCount), but if an HTMLMediaElement is
424 // directly playing back via another HTMLMediaElement, the number of channels
425 // of the media determines how many channels to output, and it can change
426 // dynamically.
427 if (graphOutputChannelCount != audioCallbackDriver->OutputChannelCount()) {
428 AudioCallbackDriver* driver = new AudioCallbackDriver(
429 this, CurrentDriver(), mSampleRate, graphOutputChannelCount,
430 inputChannelCount, mOutputDeviceID, inputDevice, inputPreference);
431 SwitchAtNextIteration(driver);
435 void MediaTrackGraphImpl::UpdateTrackOrder() {
436 if (!mTrackOrderDirty) {
437 return;
440 mTrackOrderDirty = false;
442 // The algorithm for finding cycles is based on Tim Leslie's iterative
443 // implementation [1][2] of Pearce's variant [3] of Tarjan's strongly
444 // connected components (SCC) algorithm. There are variations (a) to
445 // distinguish whether tracks in SCCs of size 1 are in a cycle and (b) to
446 // re-run the algorithm over SCCs with breaks at DelayNodes.
448 // [1] http://www.timl.id.au/?p=327
449 // [2]
450 // https://github.com/scipy/scipy/blob/e2c502fca/scipy/sparse/csgraph/_traversal.pyx#L582
451 // [3] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.102.1707
453 // There are two stacks. One for the depth-first search (DFS),
454 mozilla::LinkedList<MediaTrack> dfsStack;
455 // and another for tracks popped from the DFS stack, but still being
456 // considered as part of SCCs involving tracks on the stack.
457 mozilla::LinkedList<MediaTrack> sccStack;
459 // An index into mTracks for the next track found with no unsatisfied
460 // upstream dependencies.
461 uint32_t orderedTrackCount = 0;
463 for (uint32_t i = 0; i < mTracks.Length(); ++i) {
464 MediaTrack* t = mTracks[i];
465 ProcessedMediaTrack* pt = t->AsProcessedTrack();
466 if (pt) {
467 // The dfsStack initially contains a list of all processed tracks in
468 // unchanged order.
469 dfsStack.insertBack(t);
470 pt->mCycleMarker = NOT_VISITED;
471 } else {
472 // SourceMediaTracks have no inputs and so can be ordered now.
473 mTracks[orderedTrackCount] = t;
474 ++orderedTrackCount;
478 // mNextStackMarker corresponds to "index" in Tarjan's algorithm. It is a
479 // counter to label mCycleMarker on the next visited track in the DFS
480 // uniquely in the set of visited tracks that are still being considered.
482 // In this implementation, the counter descends so that the values are
483 // strictly greater than the values that mCycleMarker takes when the track
484 // has been ordered (0 or IN_MUTED_CYCLE).
486 // Each new track labelled, as the DFS searches upstream, receives a value
487 // less than those used for all other tracks being considered.
488 uint32_t nextStackMarker = NOT_VISITED - 1;
489 // Reset list of DelayNodes in cycles stored at the tail of mTracks.
490 mFirstCycleBreaker = mTracks.Length();
492 // Rearrange dfsStack order as required to DFS upstream and pop tracks
493 // in processing order to place in mTracks.
494 while (auto pt = static_cast<ProcessedMediaTrack*>(dfsStack.getFirst())) {
495 const auto& inputs = pt->mInputs;
496 MOZ_ASSERT(pt->AsProcessedTrack());
497 if (pt->mCycleMarker == NOT_VISITED) {
498 // Record the position on the visited stack, so that any searches
499 // finding this track again know how much of the stack is in the cycle.
500 pt->mCycleMarker = nextStackMarker;
501 --nextStackMarker;
502 // Not-visited input tracks should be processed first.
503 // SourceMediaTracks have already been ordered.
504 for (uint32_t i = inputs.Length(); i--;) {
505 if (inputs[i]->GetSource()->IsSuspended()) {
506 continue;
508 auto input = inputs[i]->GetSource()->AsProcessedTrack();
509 if (input && input->mCycleMarker == NOT_VISITED) {
510 // It can be that this track has an input which is from a suspended
511 // AudioContext.
512 if (input->isInList()) {
513 input->remove();
514 dfsStack.insertFront(input);
518 continue;
521 // Returning from DFS. Pop from dfsStack.
522 pt->remove();
524 // cycleStackMarker keeps track of the highest marker value on any
525 // upstream track, if any, found receiving input, directly or indirectly,
526 // from the visited stack (and so from |ps|, making a cycle). In a
527 // variation from Tarjan's SCC algorithm, this does not include |ps|
528 // unless it is part of the cycle.
529 uint32_t cycleStackMarker = 0;
530 for (uint32_t i = inputs.Length(); i--;) {
531 if (inputs[i]->GetSource()->IsSuspended()) {
532 continue;
534 auto input = inputs[i]->GetSource()->AsProcessedTrack();
535 if (input) {
536 cycleStackMarker = std::max(cycleStackMarker, input->mCycleMarker);
540 if (cycleStackMarker <= IN_MUTED_CYCLE) {
541 // All inputs have been ordered and their stack markers have been removed.
542 // This track is not part of a cycle. It can be processed next.
543 pt->mCycleMarker = 0;
544 mTracks[orderedTrackCount] = pt;
545 ++orderedTrackCount;
546 continue;
549 // A cycle has been found. Record this track for ordering when all
550 // tracks in this SCC have been popped from the DFS stack.
551 sccStack.insertFront(pt);
553 if (cycleStackMarker > pt->mCycleMarker) {
554 // Cycles have been found that involve tracks that remain on the stack.
555 // Leave mCycleMarker indicating the most downstream (last) track on
556 // the stack known to be part of this SCC. In this way, any searches on
557 // other paths that find |ps| will know (without having to traverse from
558 // this track again) that they are part of this SCC (i.e. part of an
559 // intersecting cycle).
560 pt->mCycleMarker = cycleStackMarker;
561 continue;
564 // |pit| is the root of an SCC involving no other tracks on dfsStack, the
565 // complete SCC has been recorded, and tracks in this SCC are part of at
566 // least one cycle.
567 MOZ_ASSERT(cycleStackMarker == pt->mCycleMarker);
568 // If there are DelayNodes in this SCC, then they may break the cycles.
569 bool haveDelayNode = false;
570 auto next = sccStack.getFirst();
571 // Tracks in this SCC are identified by mCycleMarker <= cycleStackMarker.
572 // (There may be other tracks later in sccStack from other incompletely
573 // searched SCCs, involving tracks still on dfsStack.)
575 // DelayNodes in cycles must behave differently from those not in cycles,
576 // so all DelayNodes in the SCC must be identified.
577 while (next && static_cast<ProcessedMediaTrack*>(next)->mCycleMarker <=
578 cycleStackMarker) {
579 auto nt = next->AsAudioNodeTrack();
580 // Get next before perhaps removing from list below.
581 next = next->getNext();
582 if (nt && nt->Engine()->AsDelayNodeEngine()) {
583 haveDelayNode = true;
584 // DelayNodes break cycles by producing their output in a
585 // preprocessing phase; they do not need to be ordered before their
586 // consumers. Order them at the tail of mTracks so that they can be
587 // handled specially. Do so now, so that DFS ignores them.
588 nt->remove();
589 nt->mCycleMarker = 0;
590 --mFirstCycleBreaker;
591 mTracks[mFirstCycleBreaker] = nt;
594 auto after_scc = next;
595 while ((next = sccStack.getFirst()) != after_scc) {
596 next->remove();
597 auto removed = static_cast<ProcessedMediaTrack*>(next);
598 if (haveDelayNode) {
599 // Return tracks to the DFS stack again (to order and detect cycles
600 // without delayNodes). Any of these tracks that are still inputs
601 // for tracks on the visited stack must be returned to the front of
602 // the stack to be ordered before their dependents. We know that none
603 // of these tracks need input from tracks on the visited stack, so
604 // they can all be searched and ordered before the current stack head
605 // is popped.
606 removed->mCycleMarker = NOT_VISITED;
607 dfsStack.insertFront(removed);
608 } else {
609 // Tracks in cycles without any DelayNodes must be muted, and so do
610 // not need input and can be ordered now. They must be ordered before
611 // their consumers so that their muted output is available.
612 removed->mCycleMarker = IN_MUTED_CYCLE;
613 mTracks[orderedTrackCount] = removed;
614 ++orderedTrackCount;
619 MOZ_ASSERT(orderedTrackCount == mFirstCycleBreaker);
622 TrackTime MediaTrackGraphImpl::PlayAudio(AudioMixer* aMixer,
623 const TrackKeyAndVolume& aTkv,
624 GraphTime aPlayedTime) {
625 MOZ_ASSERT(OnGraphThread());
626 MOZ_ASSERT(mRealtime, "Should only attempt to play audio in realtime mode");
627 MOZ_ASSERT(aMixer, "Can only play audio if there's a mixer");
629 TrackTime ticksWritten = 0;
631 ticksWritten = 0;
632 MediaTrack* track = aTkv.mTrack;
633 AudioSegment* audio = track->GetData<AudioSegment>();
634 AudioSegment output;
636 TrackTime offset = track->GraphTimeToTrackTime(aPlayedTime);
638 // We don't update Track->mTracksStartTime here to account for time spent
639 // blocked. Instead, we'll update it in UpdateCurrentTimeForTracks after
640 // the blocked period has completed. But we do need to make sure we play
641 // from the right offsets in the track buffer, even if we've already
642 // written silence for some amount of blocked time after the current time.
643 GraphTime t = aPlayedTime;
644 while (t < mStateComputedTime) {
645 bool blocked = t >= track->mStartBlocking;
646 GraphTime end = blocked ? mStateComputedTime : track->mStartBlocking;
647 NS_ASSERTION(end <= mStateComputedTime, "mStartBlocking is wrong!");
649 // Check how many ticks of sound we can provide if we are blocked some
650 // time in the middle of this cycle.
651 TrackTime toWrite = end - t;
653 if (blocked) {
654 output.InsertNullDataAtStart(toWrite);
655 ticksWritten += toWrite;
656 LOG(LogLevel::Verbose,
657 ("%p: MediaTrack %p writing %" PRId64 " blocking-silence samples for "
658 "%f to %f (%" PRId64 " to %" PRId64 ")",
659 this, track, toWrite, MediaTimeToSeconds(t), MediaTimeToSeconds(end),
660 offset, offset + toWrite));
661 } else {
662 TrackTime endTicksNeeded = offset + toWrite;
663 TrackTime endTicksAvailable = audio->GetDuration();
665 if (endTicksNeeded <= endTicksAvailable) {
666 LOG(LogLevel::Verbose,
667 ("%p: MediaTrack %p writing %" PRId64 " samples for %f to %f "
668 "(samples %" PRId64 " to %" PRId64 ")",
669 this, track, toWrite, MediaTimeToSeconds(t),
670 MediaTimeToSeconds(end), offset, endTicksNeeded));
671 output.AppendSlice(*audio, offset, endTicksNeeded);
672 ticksWritten += toWrite;
673 offset = endTicksNeeded;
674 } else {
675 // MOZ_ASSERT(track->IsEnded(), "Not enough data, and track not
676 // ended."); If we are at the end of the track, maybe write the
677 // remaining samples, and pad with/output silence.
678 if (endTicksNeeded > endTicksAvailable && offset < endTicksAvailable) {
679 output.AppendSlice(*audio, offset, endTicksAvailable);
681 LOG(LogLevel::Verbose,
682 ("%p: MediaTrack %p writing %" PRId64 " samples for %f to %f "
683 "(samples %" PRId64 " to %" PRId64 ")",
684 this, track, toWrite, MediaTimeToSeconds(t),
685 MediaTimeToSeconds(end), offset, endTicksNeeded));
686 uint32_t available = endTicksAvailable - offset;
687 ticksWritten += available;
688 toWrite -= available;
689 offset = endTicksAvailable;
691 output.AppendNullData(toWrite);
692 LOG(LogLevel::Verbose,
693 ("%p MediaTrack %p writing %" PRId64 " padding slsamples for %f to "
694 "%f (samples %" PRId64 " to %" PRId64 ")",
695 this, track, toWrite, MediaTimeToSeconds(t),
696 MediaTimeToSeconds(end), offset, endTicksNeeded));
697 ticksWritten += toWrite;
699 output.ApplyVolume(mGlobalVolume * aTkv.mVolume);
701 t = end;
703 uint32_t outputChannels;
704 // Use the number of channel the driver expects: this is the number of
705 // channel that can be output by the underlying system level audio stream.
706 // Fall back to something sensible if this graph is being driven by a normal
707 // thread (this can happen when there are no output devices, etc.).
708 if (CurrentDriver()->AsAudioCallbackDriver()) {
709 outputChannels =
710 CurrentDriver()->AsAudioCallbackDriver()->OutputChannelCount();
711 } else {
712 outputChannels = AudioOutputChannelCount();
714 output.WriteTo(*aMixer, outputChannels, mSampleRate);
716 return ticksWritten;
719 DeviceInputTrack* MediaTrackGraphImpl::GetDeviceInputTrackMainThread(
720 CubebUtils::AudioDeviceID aID) {
721 MOZ_ASSERT(NS_IsMainThread());
722 return mDeviceInputTrackManagerMainThread.GetDeviceInputTrack(aID);
725 NativeInputTrack* MediaTrackGraphImpl::GetNativeInputTrackMainThread() {
726 MOZ_ASSERT(NS_IsMainThread());
727 return mDeviceInputTrackManagerMainThread.GetNativeInputTrack();
730 void MediaTrackGraphImpl::OpenAudioInputImpl(DeviceInputTrack* aTrack) {
731 MOZ_ASSERT(OnGraphThread());
732 LOG(LogLevel::Debug,
733 ("%p OpenAudioInputImpl: device %p", this, aTrack->mDeviceId));
735 mDeviceInputTrackManagerGraphThread.Add(aTrack);
737 if (aTrack->AsNativeInputTrack()) {
738 // Switch Drivers since we're adding input (to input-only or full-duplex)
739 AudioCallbackDriver* driver = new AudioCallbackDriver(
740 this, CurrentDriver(), mSampleRate, AudioOutputChannelCount(),
741 AudioInputChannelCount(aTrack->mDeviceId), mOutputDeviceID,
742 aTrack->mDeviceId, AudioInputDevicePreference(aTrack->mDeviceId));
743 LOG(LogLevel::Debug,
744 ("%p OpenAudioInputImpl: starting new AudioCallbackDriver(input) %p",
745 this, driver));
746 SwitchAtNextIteration(driver);
747 } else {
748 NonNativeInputTrack* nonNative = aTrack->AsNonNativeInputTrack();
749 MOZ_ASSERT(nonNative);
750 // Start non-native input right away.
751 nonNative->StartAudio(MakeRefPtr<AudioInputSource>(
752 MakeRefPtr<AudioInputSourceListener>(nonNative),
753 nonNative->GenerateSourceId(), nonNative->mDeviceId,
754 AudioInputChannelCount(nonNative->mDeviceId),
755 AudioInputDevicePreference(nonNative->mDeviceId) ==
756 AudioInputType::Voice,
757 nonNative->mPrincipalHandle, nonNative->mSampleRate, GraphRate(),
758 StaticPrefs::media_clockdrift_buffering()));
762 void MediaTrackGraphImpl::OpenAudioInput(DeviceInputTrack* aTrack) {
763 MOZ_ASSERT(NS_IsMainThread());
764 MOZ_ASSERT(aTrack);
766 LOG(LogLevel::Debug, ("%p OpenInput: DeviceInputTrack %p for device %p", this,
767 aTrack, aTrack->mDeviceId));
769 class Message : public ControlMessage {
770 public:
771 Message(MediaTrackGraphImpl* aGraph, DeviceInputTrack* aInputTrack)
772 : ControlMessage(nullptr), mGraph(aGraph), mInputTrack(aInputTrack) {}
773 void Run() override {
774 TRACE("MTG::OpenAudioInputImpl ControlMessage");
775 mGraph->OpenAudioInputImpl(mInputTrack);
777 MediaTrackGraphImpl* mGraph;
778 DeviceInputTrack* mInputTrack;
781 mDeviceInputTrackManagerMainThread.Add(aTrack);
783 this->AppendMessage(MakeUnique<Message>(this, aTrack));
786 void MediaTrackGraphImpl::CloseAudioInputImpl(DeviceInputTrack* aTrack) {
787 MOZ_ASSERT(OnGraphThread());
789 LOG(LogLevel::Debug,
790 ("%p CloseAudioInputImpl: device %p", this, aTrack->mDeviceId));
792 if (NonNativeInputTrack* nonNative = aTrack->AsNonNativeInputTrack()) {
793 nonNative->StopAudio();
794 mDeviceInputTrackManagerGraphThread.Remove(aTrack);
795 return;
798 MOZ_ASSERT(aTrack->AsNativeInputTrack());
800 mDeviceInputTrackManagerGraphThread.Remove(aTrack);
802 // Switch Drivers since we're adding or removing an input (to nothing/system
803 // or output only)
804 bool audioTrackPresent = AudioTrackPresent();
806 GraphDriver* driver;
807 if (audioTrackPresent) {
808 // We still have audio output
809 LOG(LogLevel::Debug,
810 ("%p: CloseInput: output present (AudioCallback)", this));
812 driver = new AudioCallbackDriver(
813 this, CurrentDriver(), mSampleRate, AudioOutputChannelCount(),
814 AudioInputChannelCount(aTrack->mDeviceId), mOutputDeviceID, nullptr,
815 AudioInputDevicePreference(aTrack->mDeviceId));
816 SwitchAtNextIteration(driver);
817 } else if (CurrentDriver()->AsAudioCallbackDriver()) {
818 LOG(LogLevel::Debug,
819 ("%p: CloseInput: no output present (SystemClockCallback)", this));
821 driver = new SystemClockDriver(this, CurrentDriver(), mSampleRate);
822 SwitchAtNextIteration(driver);
823 } // else SystemClockDriver->SystemClockDriver, no switch
826 void MediaTrackGraphImpl::RegisterAudioOutput(MediaTrack* aTrack, void* aKey) {
827 MOZ_ASSERT(OnGraphThread());
829 TrackKeyAndVolume* tkv = mAudioOutputs.AppendElement();
830 tkv->mTrack = aTrack;
831 tkv->mKey = aKey;
832 tkv->mVolume = 1.0;
834 if (!CurrentDriver()->AsAudioCallbackDriver() && !Switching()) {
835 NativeInputTrack* native =
836 mDeviceInputTrackManagerGraphThread.GetNativeInputTrack();
837 CubebUtils::AudioDeviceID inputDevice =
838 native ? native->mDeviceId : nullptr;
839 uint32_t inputChannelCount =
840 native ? AudioInputChannelCount(native->mDeviceId) : 0;
841 AudioInputType inputPreference =
842 native ? AudioInputDevicePreference(native->mDeviceId)
843 : AudioInputType::Unknown;
845 AudioCallbackDriver* driver = new AudioCallbackDriver(
846 this, CurrentDriver(), mSampleRate, AudioOutputChannelCount(),
847 inputChannelCount, mOutputDeviceID, inputDevice, inputPreference);
848 SwitchAtNextIteration(driver);
852 void MediaTrackGraphImpl::UnregisterAllAudioOutputs(MediaTrack* aTrack) {
853 MOZ_ASSERT(OnGraphThreadOrNotRunning());
855 mAudioOutputs.RemoveElementsBy([aTrack](const TrackKeyAndVolume& aTkv) {
856 return aTkv.mTrack == aTrack;
860 void MediaTrackGraphImpl::UnregisterAudioOutput(MediaTrack* aTrack,
861 void* aKey) {
862 MOZ_ASSERT(OnGraphThreadOrNotRunning());
864 mAudioOutputs.RemoveElementsBy(
865 [&aKey, &aTrack](const TrackKeyAndVolume& aTkv) {
866 return aTkv.mKey == aKey && aTkv.mTrack == aTrack;
870 void MediaTrackGraphImpl::CloseAudioInput(DeviceInputTrack* aTrack) {
871 MOZ_ASSERT(NS_IsMainThread());
872 MOZ_ASSERT(aTrack);
874 LOG(LogLevel::Debug, ("%p CloseInput: DeviceInputTrack %p for device %p",
875 this, aTrack, aTrack->mDeviceId));
877 class Message : public ControlMessage {
878 public:
879 Message(MediaTrackGraphImpl* aGraph, DeviceInputTrack* aInputTrack)
880 : ControlMessage(nullptr), mGraph(aGraph), mInputTrack(aInputTrack) {}
881 void Run() override {
882 TRACE("MTG::CloseAudioInputImpl ControlMessage");
883 mGraph->CloseAudioInputImpl(mInputTrack);
885 MediaTrackGraphImpl* mGraph;
886 DeviceInputTrack* mInputTrack;
889 // DeviceInputTrack is still alive (in mTracks) even we remove it here, since
890 // aTrack->Destroy() is called after this. See DeviceInputTrack::CloseAudio
891 // for more details.
892 mDeviceInputTrackManagerMainThread.Remove(aTrack);
894 this->AppendMessage(MakeUnique<Message>(this, aTrack));
896 if (aTrack->AsNativeInputTrack()) {
897 LOG(LogLevel::Debug,
898 ("%p Native input device %p is closed!", this, aTrack->mDeviceId));
899 SetNewNativeInput();
903 // All AudioInput listeners get the same speaker data (at least for now).
904 void MediaTrackGraphImpl::NotifyOutputData(AudioDataValue* aBuffer,
905 size_t aFrames, TrackRate aRate,
906 uint32_t aChannels) {
907 if (!mDeviceInputTrackManagerGraphThread.GetNativeInputTrack()) {
908 return;
911 #if defined(MOZ_WEBRTC)
912 for (const auto& track : mTracks) {
913 if (const auto& t = track->AsAudioProcessingTrack()) {
914 t->NotifyOutputData(this, aBuffer, aFrames, aRate, aChannels);
917 #endif
920 void MediaTrackGraphImpl::NotifyInputStopped() {
921 NativeInputTrack* native =
922 mDeviceInputTrackManagerGraphThread.GetNativeInputTrack();
923 if (!native) {
924 return;
926 native->NotifyInputStopped(this);
929 void MediaTrackGraphImpl::NotifyInputData(const AudioDataValue* aBuffer,
930 size_t aFrames, TrackRate aRate,
931 uint32_t aChannels,
932 uint32_t aAlreadyBuffered) {
933 // Either we have an audio input device, or we just removed the audio input
934 // this iteration, and we're switching back to an output-only driver next
935 // iteration.
936 NativeInputTrack* native =
937 mDeviceInputTrackManagerGraphThread.GetNativeInputTrack();
938 MOZ_ASSERT(native || Switching());
939 if (!native) {
940 return;
942 native->NotifyInputData(this, aBuffer, aFrames, aRate, aChannels,
943 aAlreadyBuffered);
946 void MediaTrackGraphImpl::DeviceChangedImpl() {
947 MOZ_ASSERT(OnGraphThread());
948 NativeInputTrack* native =
949 mDeviceInputTrackManagerGraphThread.GetNativeInputTrack();
950 if (!native) {
951 return;
953 native->DeviceChanged(this);
956 void MediaTrackGraphImpl::SetMaxOutputChannelCount(uint32_t aMaxChannelCount) {
957 MOZ_ASSERT(OnGraphThread());
958 mMaxOutputChannelCount = aMaxChannelCount;
961 void MediaTrackGraphImpl::DeviceChanged() {
962 // This is safe to be called from any thread: this message comes from an
963 // underlying platform API, and we don't have much guarantees. If it is not
964 // called from the main thread (and it probably will rarely be), it will post
965 // itself to the main thread, and the actual device change message will be ran
966 // and acted upon on the graph thread.
967 if (!NS_IsMainThread()) {
968 RefPtr<nsIRunnable> runnable = WrapRunnable(
969 RefPtr<MediaTrackGraphImpl>(this), &MediaTrackGraphImpl::DeviceChanged);
970 mMainThread->Dispatch(runnable.forget());
971 return;
974 class Message : public ControlMessage {
975 public:
976 explicit Message(MediaTrackGraph* aGraph)
977 : ControlMessage(nullptr),
978 mGraphImpl(static_cast<MediaTrackGraphImpl*>(aGraph)) {}
979 void Run() override {
980 TRACE("MTG::DeviceChangeImpl ControlMessage");
981 mGraphImpl->DeviceChangedImpl();
983 // We know that this is valid, because the graph can't shutdown if it has
984 // messages.
985 MediaTrackGraphImpl* mGraphImpl;
988 if (mMainThreadTrackCount == 0 && mMainThreadPortCount == 0) {
989 // This is a special case where the origin of this event cannot control the
990 // lifetime of the graph, because the graph is controling the lifetime of
991 // the AudioCallbackDriver where the event originated.
992 // We know the graph is soon going away, so there's no need to notify about
993 // this device change.
994 return;
997 // Reset the latency, it will get fetched again next time it's queried.
998 MOZ_ASSERT(NS_IsMainThread());
999 mAudioOutputLatency = 0.0;
1001 // Dispatch to the bg thread to do the (potentially expensive) query of the
1002 // maximum channel count, and then dispatch back to the main thread, then to
1003 // the graph, with the new info.
1004 RefPtr<MediaTrackGraphImpl> self = this;
1005 NS_DispatchBackgroundTask(NS_NewRunnableFunction(
1006 "MaxChannelCountUpdateOnBgThread", [self{std::move(self)}]() {
1007 uint32_t maxChannelCount = CubebUtils::MaxNumberOfChannels();
1008 self->Dispatch(NS_NewRunnableFunction(
1009 "MaxChannelCountUpdateToMainThread",
1010 [self{self}, maxChannelCount]() {
1011 class MessageToGraph : public ControlMessage {
1012 public:
1013 explicit MessageToGraph(MediaTrackGraph* aGraph,
1014 uint32_t aMaxChannelCount)
1015 : ControlMessage(nullptr),
1016 mGraphImpl(static_cast<MediaTrackGraphImpl*>(aGraph)),
1017 mMaxChannelCount(aMaxChannelCount) {}
1018 void Run() override {
1019 TRACE("MTG::SetMaxOutputChannelCount ControlMessage")
1020 mGraphImpl->SetMaxOutputChannelCount(mMaxChannelCount);
1022 MediaTrackGraphImpl* mGraphImpl;
1023 uint32_t mMaxChannelCount;
1025 self->AppendMessage(
1026 MakeUnique<MessageToGraph>(self, maxChannelCount));
1027 }));
1028 }));
1030 AppendMessage(MakeUnique<Message>(this));
1033 static const char* GetAudioInputTypeString(const AudioInputType& aType) {
1034 return aType == AudioInputType::Voice ? "Voice" : "Unknown";
1037 void MediaTrackGraphImpl::ReevaluateInputDevice(CubebUtils::AudioDeviceID aID) {
1038 MOZ_ASSERT(OnGraphThread());
1040 LOG(LogLevel::Debug, ("%p: ReevaluateInputDevice: device %p", this, aID));
1042 DeviceInputTrack* track =
1043 mDeviceInputTrackManagerGraphThread.GetDeviceInputTrack(aID);
1044 if (!track) {
1045 LOG(LogLevel::Debug,
1046 ("%p: No DeviceInputTrack for this device. Ignore", this));
1047 return;
1050 bool needToSwitch = false;
1052 if (NonNativeInputTrack* nonNative = track->AsNonNativeInputTrack()) {
1053 if (nonNative->NumberOfChannels() != AudioInputChannelCount(aID)) {
1054 LOG(LogLevel::Debug,
1055 ("%p: %u-channel non-native input device %p (track %p) is "
1056 "re-configured to %d-channel",
1057 this, nonNative->NumberOfChannels(), aID, track,
1058 AudioInputChannelCount(aID)));
1059 needToSwitch = true;
1061 if (nonNative->DevicePreference() != AudioInputDevicePreference(aID)) {
1062 LOG(LogLevel::Debug,
1063 ("%p: %s-type non-native input device %p (track %p) is re-configured "
1064 "to %s-type",
1065 this, GetAudioInputTypeString(nonNative->DevicePreference()), aID,
1066 track, GetAudioInputTypeString(AudioInputDevicePreference(aID))));
1067 needToSwitch = true;
1070 if (needToSwitch) {
1071 nonNative->StopAudio();
1072 nonNative->StartAudio(MakeRefPtr<AudioInputSource>(
1073 MakeRefPtr<AudioInputSourceListener>(nonNative),
1074 nonNative->GenerateSourceId(), aID, AudioInputChannelCount(aID),
1075 AudioInputDevicePreference(aID) == AudioInputType::Voice,
1076 nonNative->mPrincipalHandle, nonNative->mSampleRate, GraphRate(),
1077 StaticPrefs::media_clockdrift_buffering()));
1080 return;
1083 MOZ_ASSERT(track->AsNativeInputTrack());
1085 if (AudioCallbackDriver* audioCallbackDriver =
1086 CurrentDriver()->AsAudioCallbackDriver()) {
1087 if (audioCallbackDriver->InputChannelCount() !=
1088 AudioInputChannelCount(aID)) {
1089 LOG(LogLevel::Debug,
1090 ("%p: ReevaluateInputDevice: %u-channel AudioCallbackDriver %p is "
1091 "re-configured to %d-channel",
1092 this, audioCallbackDriver->InputChannelCount(), audioCallbackDriver,
1093 AudioInputChannelCount(aID)));
1094 needToSwitch = true;
1096 if (audioCallbackDriver->InputDevicePreference() !=
1097 AudioInputDevicePreference(aID)) {
1098 LOG(LogLevel::Debug,
1099 ("%p: ReevaluateInputDevice: %s-type AudioCallbackDriver %p is "
1100 "re-configured to %s-type",
1101 this,
1102 GetAudioInputTypeString(
1103 audioCallbackDriver->InputDevicePreference()),
1104 audioCallbackDriver,
1105 GetAudioInputTypeString(AudioInputDevicePreference(aID))));
1106 needToSwitch = true;
1108 } else if (Switching() && NextDriver()->AsAudioCallbackDriver()) {
1109 // We're already in the process of switching to a audio callback driver,
1110 // which will happen at the next iteration.
1111 // However, maybe it's not the correct number of channels. Re-query the
1112 // correct channel amount at this time.
1113 needToSwitch = true;
1116 if (needToSwitch) {
1117 AudioCallbackDriver* newDriver = new AudioCallbackDriver(
1118 this, CurrentDriver(), mSampleRate, AudioOutputChannelCount(),
1119 AudioInputChannelCount(aID), mOutputDeviceID, aID,
1120 AudioInputDevicePreference(aID));
1121 SwitchAtNextIteration(newDriver);
1125 bool MediaTrackGraphImpl::OnGraphThreadOrNotRunning() const {
1126 // either we're on the right thread (and calling CurrentDriver() is safe),
1127 // or we're going to fail the assert anyway, so don't cross-check
1128 // via CurrentDriver().
1129 return mGraphDriverRunning ? OnGraphThread() : NS_IsMainThread();
1132 bool MediaTrackGraphImpl::OnGraphThread() const {
1133 // we're on the right thread (and calling mDriver is safe),
1134 MOZ_ASSERT(mDriver);
1135 if (mGraphRunner && mGraphRunner->OnThread()) {
1136 return true;
1138 return mDriver->OnThread();
1141 bool MediaTrackGraphImpl::Destroyed() const {
1142 MOZ_ASSERT(NS_IsMainThread());
1143 return !mSelfRef;
1146 bool MediaTrackGraphImpl::ShouldUpdateMainThread() {
1147 MOZ_ASSERT(OnGraphThreadOrNotRunning());
1148 if (mRealtime) {
1149 return true;
1152 TimeStamp now = TimeStamp::Now();
1153 // For offline graphs, update now if it has been long enough since the last
1154 // update, or if it has reached the end.
1155 if ((now - mLastMainThreadUpdate).ToMilliseconds() >
1156 CurrentDriver()->IterationDuration() ||
1157 mStateComputedTime >= mEndTime) {
1158 mLastMainThreadUpdate = now;
1159 return true;
1161 return false;
1164 void MediaTrackGraphImpl::PrepareUpdatesToMainThreadState(bool aFinalUpdate) {
1165 MOZ_ASSERT(OnGraphThreadOrNotRunning());
1166 mMonitor.AssertCurrentThreadOwns();
1168 // We don't want to frequently update the main thread about timing update
1169 // when we are not running in realtime.
1170 if (aFinalUpdate || ShouldUpdateMainThread()) {
1171 // Strip updates that will be obsoleted below, so as to keep the length of
1172 // mTrackUpdates sane.
1173 size_t keptUpdateCount = 0;
1174 for (size_t i = 0; i < mTrackUpdates.Length(); ++i) {
1175 MediaTrack* track = mTrackUpdates[i].mTrack;
1176 // RemoveTrackGraphThread() clears mTrack in updates for
1177 // tracks that are removed from the graph.
1178 MOZ_ASSERT(!track || track->GraphImpl() == this);
1179 if (!track || track->MainThreadNeedsUpdates()) {
1180 // Discard this update as it has either been cleared when the track
1181 // was destroyed or there will be a newer update below.
1182 continue;
1184 if (keptUpdateCount != i) {
1185 mTrackUpdates[keptUpdateCount] = std::move(mTrackUpdates[i]);
1186 MOZ_ASSERT(!mTrackUpdates[i].mTrack);
1188 ++keptUpdateCount;
1190 mTrackUpdates.TruncateLength(keptUpdateCount);
1192 mTrackUpdates.SetCapacity(mTrackUpdates.Length() + mTracks.Length() +
1193 mSuspendedTracks.Length());
1194 for (MediaTrack* track : AllTracks()) {
1195 if (!track->MainThreadNeedsUpdates()) {
1196 continue;
1198 TrackUpdate* update = mTrackUpdates.AppendElement();
1199 update->mTrack = track;
1200 // No blocking to worry about here, since we've passed
1201 // UpdateCurrentTimeForTracks.
1202 update->mNextMainThreadCurrentTime =
1203 track->GraphTimeToTrackTime(mProcessedTime);
1204 update->mNextMainThreadEnded = track->mNotifiedEnded;
1206 mNextMainThreadGraphTime = mProcessedTime;
1207 if (!mPendingUpdateRunnables.IsEmpty()) {
1208 mUpdateRunnables.AppendElements(std::move(mPendingUpdateRunnables));
1212 // If this is the final update, then a stable state event will soon be
1213 // posted just before this thread finishes, and so there is no need to also
1214 // post here.
1215 if (!aFinalUpdate &&
1216 // Don't send the message to the main thread if it's not going to have
1217 // any work to do.
1218 !(mUpdateRunnables.IsEmpty() && mTrackUpdates.IsEmpty())) {
1219 EnsureStableStateEventPosted();
1223 GraphTime MediaTrackGraphImpl::RoundUpToEndOfAudioBlock(GraphTime aTime) {
1224 if (aTime % WEBAUDIO_BLOCK_SIZE == 0) {
1225 return aTime;
1227 return RoundUpToNextAudioBlock(aTime);
1230 GraphTime MediaTrackGraphImpl::RoundUpToNextAudioBlock(GraphTime aTime) {
1231 uint64_t block = aTime >> WEBAUDIO_BLOCK_SIZE_BITS;
1232 uint64_t nextBlock = block + 1;
1233 GraphTime nextTime = nextBlock << WEBAUDIO_BLOCK_SIZE_BITS;
1234 return nextTime;
1237 void MediaTrackGraphImpl::ProduceDataForTracksBlockByBlock(
1238 uint32_t aTrackIndex, TrackRate aSampleRate) {
1239 MOZ_ASSERT(OnGraphThread());
1240 MOZ_ASSERT(aTrackIndex <= mFirstCycleBreaker,
1241 "Cycle breaker is not AudioNodeTrack?");
1243 while (mProcessedTime < mStateComputedTime) {
1244 // Microtask checkpoints are in between render quanta.
1245 nsAutoMicroTask mt;
1247 GraphTime next = RoundUpToNextAudioBlock(mProcessedTime);
1248 for (uint32_t i = mFirstCycleBreaker; i < mTracks.Length(); ++i) {
1249 auto nt = static_cast<AudioNodeTrack*>(mTracks[i]);
1250 MOZ_ASSERT(nt->AsAudioNodeTrack());
1251 nt->ProduceOutputBeforeInput(mProcessedTime);
1253 for (uint32_t i = aTrackIndex; i < mTracks.Length(); ++i) {
1254 ProcessedMediaTrack* pt = mTracks[i]->AsProcessedTrack();
1255 if (pt) {
1256 pt->ProcessInput(
1257 mProcessedTime, next,
1258 (next == mStateComputedTime) ? ProcessedMediaTrack::ALLOW_END : 0);
1261 mProcessedTime = next;
1263 NS_ASSERTION(mProcessedTime == mStateComputedTime,
1264 "Something went wrong with rounding to block boundaries");
1267 void MediaTrackGraphImpl::RunMessageAfterProcessing(
1268 UniquePtr<ControlMessage> aMessage) {
1269 MOZ_ASSERT(OnGraphThread());
1271 if (mFrontMessageQueue.IsEmpty()) {
1272 mFrontMessageQueue.AppendElement();
1275 // Only one block is used for messages from the graph thread.
1276 MOZ_ASSERT(mFrontMessageQueue.Length() == 1);
1277 mFrontMessageQueue[0].mMessages.AppendElement(std::move(aMessage));
1280 void MediaTrackGraphImpl::RunMessagesInQueue() {
1281 TRACE("MTG::RunMessagesInQueue");
1282 MOZ_ASSERT(OnGraphThread());
1283 // Calculate independent action times for each batch of messages (each
1284 // batch corresponding to an event loop task). This isolates the performance
1285 // of different scripts to some extent.
1286 for (uint32_t i = 0; i < mFrontMessageQueue.Length(); ++i) {
1287 nsTArray<UniquePtr<ControlMessage>>& messages =
1288 mFrontMessageQueue[i].mMessages;
1290 for (uint32_t j = 0; j < messages.Length(); ++j) {
1291 TRACE("ControlMessage::Run");
1292 messages[j]->Run();
1295 mFrontMessageQueue.Clear();
1298 void MediaTrackGraphImpl::UpdateGraph(GraphTime aEndBlockingDecisions) {
1299 TRACE("MTG::UpdateGraph");
1300 MOZ_ASSERT(OnGraphThread());
1301 MOZ_ASSERT(aEndBlockingDecisions >= mProcessedTime);
1302 // The next state computed time can be the same as the previous: it
1303 // means the driver would have been blocking indefinitly, but the graph has
1304 // been woken up right after having been to sleep.
1305 MOZ_ASSERT(aEndBlockingDecisions >= mStateComputedTime);
1307 CheckDriver();
1308 UpdateTrackOrder();
1310 // Always do another iteration if there are tracks waiting to resume.
1311 bool ensureNextIteration = !mPendingResumeOperations.IsEmpty();
1313 for (MediaTrack* track : mTracks) {
1314 if (SourceMediaTrack* is = track->AsSourceTrack()) {
1315 ensureNextIteration |= is->PullNewData(aEndBlockingDecisions);
1316 is->ExtractPendingInput(mStateComputedTime, aEndBlockingDecisions);
1318 if (track->mEnded) {
1319 // The track's not suspended, and since it's ended, underruns won't
1320 // stop it playing out. So there's no blocking other than what we impose
1321 // here.
1322 GraphTime endTime = track->GetEnd() + track->mStartTime;
1323 if (endTime <= mStateComputedTime) {
1324 LOG(LogLevel::Verbose,
1325 ("%p: MediaTrack %p is blocked due to being ended", this, track));
1326 track->mStartBlocking = mStateComputedTime;
1327 } else {
1328 LOG(LogLevel::Verbose,
1329 ("%p: MediaTrack %p has ended, but is not blocked yet (current "
1330 "time %f, end at %f)",
1331 this, track, MediaTimeToSeconds(mStateComputedTime),
1332 MediaTimeToSeconds(endTime)));
1333 // Data can't be added to a ended track, so underruns are irrelevant.
1334 MOZ_ASSERT(endTime <= aEndBlockingDecisions);
1335 track->mStartBlocking = endTime;
1337 } else {
1338 track->mStartBlocking = WillUnderrun(track, aEndBlockingDecisions);
1340 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
1341 if (SourceMediaTrack* s = track->AsSourceTrack()) {
1342 if (s->Ended()) {
1343 continue;
1346 MutexAutoLock lock(s->mMutex);
1347 if (!s->mUpdateTrack->mPullingEnabled) {
1348 // The invariant that data must be provided is only enforced when
1349 // pulling.
1350 continue;
1353 if (track->GetEnd() <
1354 track->GraphTimeToTrackTime(aEndBlockingDecisions)) {
1355 LOG(LogLevel::Error,
1356 ("%p: SourceMediaTrack %p (%s) is live and pulled, "
1357 "but wasn't fed "
1358 "enough data. TrackListeners=%zu. Track-end=%f, "
1359 "Iteration-end=%f",
1360 this, track,
1361 (track->mType == MediaSegment::AUDIO ? "audio" : "video"),
1362 track->mTrackListeners.Length(),
1363 MediaTimeToSeconds(track->GetEnd()),
1364 MediaTimeToSeconds(
1365 track->GraphTimeToTrackTime(aEndBlockingDecisions))));
1366 MOZ_DIAGNOSTIC_ASSERT(false,
1367 "A non-ended SourceMediaTrack wasn't fed "
1368 "enough data by NotifyPull");
1371 #endif /* MOZ_DIAGNOSTIC_ASSERT_ENABLED */
1375 for (MediaTrack* track : mSuspendedTracks) {
1376 track->mStartBlocking = mStateComputedTime;
1379 // If the loop is woken up so soon that IterationEnd() barely advances or
1380 // if an offline graph is not currently rendering, we end up having
1381 // aEndBlockingDecisions == mStateComputedTime.
1382 // Since the process interval [mStateComputedTime, aEndBlockingDecision) is
1383 // empty, Process() will not find any unblocked track and so will not
1384 // ensure another iteration. If the graph should be rendering, then ensure
1385 // another iteration to render.
1386 if (ensureNextIteration || (aEndBlockingDecisions == mStateComputedTime &&
1387 mStateComputedTime < mEndTime)) {
1388 EnsureNextIteration();
1392 void MediaTrackGraphImpl::Process(AudioMixer* aMixer) {
1393 TRACE("MTG::Process");
1394 MOZ_ASSERT(OnGraphThread());
1395 // Play track contents.
1396 bool allBlockedForever = true;
1397 // True when we've done ProcessInput for all processed tracks.
1398 bool doneAllProducing = false;
1399 const GraphTime oldProcessedTime = mProcessedTime;
1401 // Figure out what each track wants to do
1402 for (uint32_t i = 0; i < mTracks.Length(); ++i) {
1403 MediaTrack* track = mTracks[i];
1404 if (!doneAllProducing) {
1405 ProcessedMediaTrack* pt = track->AsProcessedTrack();
1406 if (pt) {
1407 AudioNodeTrack* n = track->AsAudioNodeTrack();
1408 if (n) {
1409 #ifdef DEBUG
1410 // Verify that the sampling rate for all of the following tracks is
1411 // the same
1412 for (uint32_t j = i + 1; j < mTracks.Length(); ++j) {
1413 AudioNodeTrack* nextTrack = mTracks[j]->AsAudioNodeTrack();
1414 if (nextTrack) {
1415 MOZ_ASSERT(n->mSampleRate == nextTrack->mSampleRate,
1416 "All AudioNodeTracks in the graph must have the same "
1417 "sampling rate");
1420 #endif
1421 // Since an AudioNodeTrack is present, go ahead and
1422 // produce audio block by block for all the rest of the tracks.
1423 ProduceDataForTracksBlockByBlock(i, n->mSampleRate);
1424 doneAllProducing = true;
1425 } else {
1426 pt->ProcessInput(mProcessedTime, mStateComputedTime,
1427 ProcessedMediaTrack::ALLOW_END);
1428 // Assert that a live track produced enough data
1429 MOZ_ASSERT_IF(!track->mEnded,
1430 track->GetEnd() >= GraphTimeToTrackTimeWithBlocking(
1431 track, mStateComputedTime));
1435 if (track->mStartBlocking > oldProcessedTime) {
1436 allBlockedForever = false;
1439 mProcessedTime = mStateComputedTime;
1441 if (aMixer) {
1442 MOZ_ASSERT(mRealtime, "If there's a mixer, this graph must be realtime");
1443 aMixer->StartMixing();
1444 // This is the number of frames that are written to the output buffer, for
1445 // this iteration.
1446 TrackTime ticksPlayed = 0;
1447 for (auto& t : mAudioOutputs) {
1448 TrackTime ticksPlayedForThisTrack =
1449 PlayAudio(aMixer, t, oldProcessedTime);
1450 if (ticksPlayed == 0) {
1451 ticksPlayed = ticksPlayedForThisTrack;
1452 } else {
1453 MOZ_ASSERT(
1454 !ticksPlayedForThisTrack || ticksPlayedForThisTrack == ticksPlayed,
1455 "Each track should have the same number of frames.");
1459 if (ticksPlayed == 0) {
1460 // Nothing was played, so the mixer doesn't know how many frames were
1461 // processed. We still tell it so AudioCallbackDriver knows how much has
1462 // been processed. (bug 1406027)
1463 aMixer->Mix(
1464 nullptr,
1465 CurrentDriver()->AsAudioCallbackDriver()->OutputChannelCount(),
1466 mStateComputedTime - oldProcessedTime, mSampleRate);
1468 aMixer->FinishMixing();
1471 if (!allBlockedForever) {
1472 EnsureNextIteration();
1476 bool MediaTrackGraphImpl::UpdateMainThreadState() {
1477 MOZ_ASSERT(OnGraphThread());
1478 if (mForceShutDownReceived) {
1479 for (MediaTrack* track : AllTracks()) {
1480 track->OnGraphThreadDone();
1484 MonitorAutoLock lock(mMonitor);
1485 bool finalUpdate =
1486 mForceShutDownReceived || (IsEmpty() && mBackMessageQueue.IsEmpty());
1487 PrepareUpdatesToMainThreadState(finalUpdate);
1488 if (!finalUpdate) {
1489 SwapMessageQueues();
1490 return true;
1492 // The JSContext will not be used again.
1493 // Clear main thread access while under monitor.
1494 mJSContext = nullptr;
1496 dom::WorkletThread::DeleteCycleCollectedJSContext();
1497 // Enter shutdown mode when this iteration is completed.
1498 // No need to Destroy tracks here. The main-thread owner of each
1499 // track is responsible for calling Destroy on them.
1500 return false;
1503 auto MediaTrackGraphImpl::OneIteration(GraphTime aStateTime,
1504 GraphTime aIterationEnd,
1505 AudioMixer* aMixer) -> IterationResult {
1506 if (mGraphRunner) {
1507 return mGraphRunner->OneIteration(aStateTime, aIterationEnd, aMixer);
1510 return OneIterationImpl(aStateTime, aIterationEnd, aMixer);
1513 auto MediaTrackGraphImpl::OneIterationImpl(GraphTime aStateTime,
1514 GraphTime aIterationEnd,
1515 AudioMixer* aMixer)
1516 -> IterationResult {
1517 TRACE("MTG::OneIterationImpl");
1519 mIterationEndTime = aIterationEnd;
1521 if (SoftRealTimeLimitReached()) {
1522 TRACE("MTG::Demoting real-time thread!");
1523 DemoteThreadFromRealTime();
1526 // Changes to LIFECYCLE_RUNNING occur before starting or reviving the graph
1527 // thread, and so the monitor need not be held to check mLifecycleState.
1528 // LIFECYCLE_THREAD_NOT_STARTED is possible when shutting down offline
1529 // graphs that have not started.
1531 // While changes occur on mainthread, this assert confirms that
1532 // this code shouldn't run if mainthread might be changing the state (to
1533 // > LIFECYCLE_RUNNING)
1535 // Ignore mutex warning: static during execution of the graph
1536 PUSH_IGNORE_THREAD_SAFETY
1537 MOZ_DIAGNOSTIC_ASSERT(mLifecycleState <= LIFECYCLE_RUNNING);
1538 POP_THREAD_SAFETY
1540 MOZ_ASSERT(OnGraphThread());
1542 WebCore::DenormalDisabler disabler;
1544 // Process graph message from the main thread for this iteration.
1545 RunMessagesInQueue();
1547 // Process MessagePort events.
1548 // These require a single thread, which has an nsThread with an event queue.
1549 if (mGraphRunner || !mRealtime) {
1550 TRACE("MTG::MessagePort events");
1551 NS_ProcessPendingEvents(nullptr);
1554 GraphTime stateTime = std::min(aStateTime, GraphTime(mEndTime));
1555 UpdateGraph(stateTime);
1557 mStateComputedTime = stateTime;
1559 GraphTime oldProcessedTime = mProcessedTime;
1560 Process(aMixer);
1561 MOZ_ASSERT(mProcessedTime == stateTime);
1563 UpdateCurrentTimeForTracks(oldProcessedTime);
1565 ProcessChunkMetadata(oldProcessedTime);
1567 // Process graph messages queued from RunMessageAfterProcessing() on this
1568 // thread during the iteration.
1569 RunMessagesInQueue();
1571 if (!UpdateMainThreadState()) {
1572 if (Switching()) {
1573 // We'll never get to do this switch. Clear mNextDriver to break the
1574 // ref-cycle graph->nextDriver->currentDriver->graph.
1575 SwitchAtNextIteration(nullptr);
1577 return IterationResult::CreateStop(
1578 NewRunnableMethod("MediaTrackGraphImpl::SignalMainThreadCleanup", this,
1579 &MediaTrackGraphImpl::SignalMainThreadCleanup));
1582 if (Switching()) {
1583 RefPtr<GraphDriver> nextDriver = std::move(mNextDriver);
1584 return IterationResult::CreateSwitchDriver(
1585 nextDriver, NewRunnableMethod<StoreRefPtrPassByPtr<GraphDriver>>(
1586 "MediaTrackGraphImpl::SetCurrentDriver", this,
1587 &MediaTrackGraphImpl::SetCurrentDriver, nextDriver));
1590 return IterationResult::CreateStillProcessing();
1593 void MediaTrackGraphImpl::ApplyTrackUpdate(TrackUpdate* aUpdate) {
1594 MOZ_ASSERT(NS_IsMainThread());
1595 mMonitor.AssertCurrentThreadOwns();
1597 MediaTrack* track = aUpdate->mTrack;
1598 if (!track) return;
1599 track->mMainThreadCurrentTime = aUpdate->mNextMainThreadCurrentTime;
1600 track->mMainThreadEnded = aUpdate->mNextMainThreadEnded;
1602 if (track->ShouldNotifyTrackEnded()) {
1603 track->NotifyMainThreadListeners();
1607 void MediaTrackGraphImpl::ForceShutDown() {
1608 MOZ_ASSERT(NS_IsMainThread(), "Must be called on main thread");
1609 LOG(LogLevel::Debug, ("%p: MediaTrackGraph::ForceShutdown", this));
1611 if (mShutdownBlocker) {
1612 // Avoid waiting forever for a graph to shut down
1613 // synchronously. Reports are that some 3rd-party audio drivers
1614 // occasionally hang in shutdown (both for us and Chrome).
1615 NS_NewTimerWithCallback(
1616 getter_AddRefs(mShutdownTimer), this,
1617 MediaTrackGraph::AUDIO_CALLBACK_DRIVER_SHUTDOWN_TIMEOUT,
1618 nsITimer::TYPE_ONE_SHOT);
1621 class Message final : public ControlMessage {
1622 public:
1623 explicit Message(MediaTrackGraphImpl* aGraph)
1624 : ControlMessage(nullptr), mGraph(aGraph) {}
1625 void Run() override {
1626 TRACE("MTG::ForceShutdown ControlMessage");
1627 mGraph->mForceShutDownReceived = true;
1629 // The graph owns this message.
1630 MediaTrackGraphImpl* MOZ_NON_OWNING_REF mGraph;
1633 if (mMainThreadTrackCount > 0 || mMainThreadPortCount > 0) {
1634 // If both the track and port counts are zero, the regular shutdown
1635 // sequence will progress shortly to shutdown threads and destroy the graph.
1636 AppendMessage(MakeUnique<Message>(this));
1637 InterruptJS();
1641 NS_IMETHODIMP
1642 MediaTrackGraphImpl::Notify(nsITimer* aTimer) {
1643 MOZ_ASSERT(NS_IsMainThread());
1644 NS_ASSERTION(!mShutdownBlocker,
1645 "MediaTrackGraph took too long to shut down!");
1646 // Sigh, graph took too long to shut down. Stop blocking system
1647 // shutdown and hope all is well.
1648 RemoveShutdownBlocker();
1649 return NS_OK;
1652 bool MediaTrackGraphImpl::AddShutdownBlocker() {
1653 MOZ_ASSERT(NS_IsMainThread());
1654 MOZ_ASSERT(!mShutdownBlocker);
1656 class Blocker : public media::ShutdownBlocker {
1657 const RefPtr<MediaTrackGraphImpl> mGraph;
1659 public:
1660 Blocker(MediaTrackGraphImpl* aGraph, const nsString& aName)
1661 : media::ShutdownBlocker(aName), mGraph(aGraph) {}
1663 NS_IMETHOD
1664 BlockShutdown(nsIAsyncShutdownClient* aProfileBeforeChange) override {
1665 mGraph->ForceShutDown();
1666 return NS_OK;
1670 nsCOMPtr<nsIAsyncShutdownClient> barrier = media::GetShutdownBarrier();
1671 if (!barrier) {
1672 // We're already shutting down, we won't be able to add a blocker, bail.
1673 LOG(LogLevel::Error,
1674 ("%p: Couldn't get shutdown barrier, won't add shutdown blocker",
1675 this));
1676 return false;
1679 // Blocker names must be distinct.
1680 nsString blockerName;
1681 blockerName.AppendPrintf("MediaTrackGraph %p shutdown", this);
1682 mShutdownBlocker = MakeAndAddRef<Blocker>(this, blockerName);
1683 nsresult rv = barrier->AddBlocker(mShutdownBlocker,
1684 NS_LITERAL_STRING_FROM_CSTRING(__FILE__),
1685 __LINE__, u"MediaTrackGraph shutdown"_ns);
1686 MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv));
1687 return true;
1690 void MediaTrackGraphImpl::RemoveShutdownBlocker() {
1691 if (!mShutdownBlocker) {
1692 return;
1694 media::MustGetShutdownBarrier()->RemoveBlocker(mShutdownBlocker);
1695 mShutdownBlocker = nullptr;
1698 NS_IMETHODIMP
1699 MediaTrackGraphImpl::GetName(nsACString& aName) {
1700 aName.AssignLiteral("MediaTrackGraphImpl");
1701 return NS_OK;
1704 namespace {
1706 class MediaTrackGraphShutDownRunnable : public Runnable {
1707 public:
1708 explicit MediaTrackGraphShutDownRunnable(MediaTrackGraphImpl* aGraph)
1709 : Runnable("MediaTrackGraphShutDownRunnable"), mGraph(aGraph) {}
1710 // MOZ_CAN_RUN_SCRIPT_BOUNDARY until Runnable::Run is MOZ_CAN_RUN_SCRIPT.
1711 // See bug 1535398.
1712 MOZ_CAN_RUN_SCRIPT_BOUNDARY NS_IMETHOD Run() override {
1713 TRACE("MTG::MediaTrackGraphShutDownRunnable runnable");
1714 MOZ_ASSERT(NS_IsMainThread());
1715 MOZ_ASSERT(!mGraph->mGraphDriverRunning && mGraph->mDriver,
1716 "We should know the graph thread control loop isn't running!");
1718 LOG(LogLevel::Debug, ("%p: Shutting down graph", mGraph.get()));
1720 // We've asserted the graph isn't running. Use mDriver instead of
1721 // CurrentDriver to avoid thread-safety checks
1722 #if 0 // AudioCallbackDrivers are released asynchronously anyways
1723 // XXX a better test would be have setting mGraphDriverRunning make sure
1724 // any current callback has finished and block future ones -- or just
1725 // handle it all in Shutdown()!
1726 if (mGraph->mDriver->AsAudioCallbackDriver()) {
1727 MOZ_ASSERT(!mGraph->mDriver->AsAudioCallbackDriver()->InCallback());
1729 #endif
1731 for (MediaTrackGraphImpl::PendingResumeOperation& op :
1732 mGraph->mPendingResumeOperations) {
1733 op.Abort();
1736 if (mGraph->mGraphRunner) {
1737 RefPtr<GraphRunner>(mGraph->mGraphRunner)->Shutdown();
1740 // This will wait until it's shutdown since
1741 // we'll start tearing down the graph after this
1742 RefPtr<GraphDriver>(mGraph->mDriver)->Shutdown();
1744 // Release the driver now so that an AudioCallbackDriver will release its
1745 // SharedThreadPool reference. Each SharedThreadPool reference must be
1746 // released before SharedThreadPool::SpinUntilEmpty() runs on
1747 // xpcom-shutdown-threads. Don't wait for GC/CC to release references to
1748 // objects owning tracks, or for expiration of mGraph->mShutdownTimer,
1749 // which won't otherwise release its reference on the graph until
1750 // nsTimerImpl::Shutdown(), which runs after xpcom-shutdown-threads.
1751 mGraph->SetCurrentDriver(nullptr);
1753 // Safe to access these without the monitor since the graph isn't running.
1754 // We may be one of several graphs. Drop ticket to eventually unblock
1755 // shutdown.
1756 if (mGraph->mShutdownTimer && !mGraph->mShutdownBlocker) {
1757 MOZ_ASSERT(
1758 false,
1759 "AudioCallbackDriver took too long to shut down and we let shutdown"
1760 " continue - freezing and leaking");
1762 // The timer fired, so we may be deeper in shutdown now. Block any
1763 // further teardown and just leak, for safety.
1764 return NS_OK;
1767 // mGraph's thread is not running so it's OK to do whatever here
1768 for (MediaTrack* track : mGraph->AllTracks()) {
1769 // Clean up all MediaSegments since we cannot release Images too
1770 // late during shutdown. Also notify listeners that they were removed
1771 // so they can clean up any gfx resources.
1772 track->RemoveAllResourcesAndListenersImpl();
1775 #ifdef DEBUG
1777 MonitorAutoLock lock(mGraph->mMonitor);
1778 MOZ_ASSERT(mGraph->mUpdateRunnables.IsEmpty());
1780 #endif
1781 mGraph->mPendingUpdateRunnables.Clear();
1783 mGraph->RemoveShutdownBlocker();
1785 // We can't block past the final LIFECYCLE_WAITING_FOR_TRACK_DESTRUCTION
1786 // stage, since completion of that stage requires all tracks to be freed,
1787 // which requires shutdown to proceed.
1789 if (mGraph->IsEmpty()) {
1790 // mGraph is no longer needed, so delete it.
1791 mGraph->Destroy();
1792 } else {
1793 // The graph is not empty. We must be in a forced shutdown.
1794 // Some later AppendMessage will detect that the graph has
1795 // been emptied, and delete it.
1796 NS_ASSERTION(mGraph->mForceShutDownReceived, "Not in forced shutdown?");
1797 mGraph->LifecycleStateRef() =
1798 MediaTrackGraphImpl::LIFECYCLE_WAITING_FOR_TRACK_DESTRUCTION;
1800 return NS_OK;
1803 private:
1804 RefPtr<MediaTrackGraphImpl> mGraph;
1807 class MediaTrackGraphStableStateRunnable : public Runnable {
1808 public:
1809 explicit MediaTrackGraphStableStateRunnable(MediaTrackGraphImpl* aGraph,
1810 bool aSourceIsMTG)
1811 : Runnable("MediaTrackGraphStableStateRunnable"),
1812 mGraph(aGraph),
1813 mSourceIsMTG(aSourceIsMTG) {}
1814 NS_IMETHOD Run() override {
1815 TRACE("MTG::MediaTrackGraphStableStateRunnable ControlMessage");
1816 if (mGraph) {
1817 mGraph->RunInStableState(mSourceIsMTG);
1819 return NS_OK;
1822 private:
1823 RefPtr<MediaTrackGraphImpl> mGraph;
1824 bool mSourceIsMTG;
1828 * Control messages forwarded from main thread to graph manager thread
1830 class CreateMessage : public ControlMessage {
1831 public:
1832 explicit CreateMessage(MediaTrack* aTrack) : ControlMessage(aTrack) {}
1833 void Run() override {
1834 TRACE("MTG::AddTrackGraphThread ControlMessage");
1835 mTrack->GraphImpl()->AddTrackGraphThread(mTrack);
1837 void RunDuringShutdown() override {
1838 // Make sure to run this message during shutdown too, to make sure
1839 // that we balance the number of tracks registered with the graph
1840 // as they're destroyed during shutdown.
1841 Run();
1845 } // namespace
1847 void MediaTrackGraphImpl::RunInStableState(bool aSourceIsMTG) {
1848 MOZ_ASSERT(NS_IsMainThread(), "Must be called on main thread");
1850 nsTArray<nsCOMPtr<nsIRunnable>> runnables;
1851 // When we're doing a forced shutdown, pending control messages may be
1852 // run on the main thread via RunDuringShutdown. Those messages must
1853 // run without the graph monitor being held. So, we collect them here.
1854 nsTArray<UniquePtr<ControlMessage>> controlMessagesToRunDuringShutdown;
1857 MonitorAutoLock lock(mMonitor);
1858 if (aSourceIsMTG) {
1859 MOZ_ASSERT(mPostedRunInStableStateEvent);
1860 mPostedRunInStableStateEvent = false;
1863 // This should be kept in sync with the LifecycleState enum in
1864 // MediaTrackGraphImpl.h
1865 const char* LifecycleState_str[] = {
1866 "LIFECYCLE_THREAD_NOT_STARTED", "LIFECYCLE_RUNNING",
1867 "LIFECYCLE_WAITING_FOR_MAIN_THREAD_CLEANUP",
1868 "LIFECYCLE_WAITING_FOR_THREAD_SHUTDOWN",
1869 "LIFECYCLE_WAITING_FOR_TRACK_DESTRUCTION"};
1871 if (LifecycleStateRef() != LIFECYCLE_RUNNING) {
1872 LOG(LogLevel::Debug,
1873 ("%p: Running stable state callback. Current state: %s", this,
1874 LifecycleState_str[LifecycleStateRef()]));
1877 runnables = std::move(mUpdateRunnables);
1878 for (uint32_t i = 0; i < mTrackUpdates.Length(); ++i) {
1879 TrackUpdate* update = &mTrackUpdates[i];
1880 if (update->mTrack) {
1881 ApplyTrackUpdate(update);
1884 mTrackUpdates.Clear();
1886 mMainThreadGraphTime = mNextMainThreadGraphTime;
1888 if (mCurrentTaskMessageQueue.IsEmpty()) {
1889 if (LifecycleStateRef() == LIFECYCLE_WAITING_FOR_MAIN_THREAD_CLEANUP &&
1890 IsEmpty()) {
1891 // Complete shutdown. First, ensure that this graph is no longer used.
1892 // A new graph graph will be created if one is needed.
1893 // Asynchronously clean up old graph. We don't want to do this
1894 // synchronously because it spins the event loop waiting for threads
1895 // to shut down, and we don't want to do that in a stable state handler.
1896 LifecycleStateRef() = LIFECYCLE_WAITING_FOR_THREAD_SHUTDOWN;
1897 LOG(LogLevel::Debug,
1898 ("%p: Sending MediaTrackGraphShutDownRunnable", this));
1899 nsCOMPtr<nsIRunnable> event = new MediaTrackGraphShutDownRunnable(this);
1900 mMainThread->Dispatch(event.forget());
1902 } else {
1903 if (LifecycleStateRef() <= LIFECYCLE_WAITING_FOR_MAIN_THREAD_CLEANUP) {
1904 MessageBlock* block = mBackMessageQueue.AppendElement();
1905 block->mMessages = std::move(mCurrentTaskMessageQueue);
1906 EnsureNextIteration();
1909 // If this MediaTrackGraph has entered regular (non-forced) shutdown it
1910 // is not able to process any more messages. Those messages being added to
1911 // the graph in the first place is an error.
1912 MOZ_DIAGNOSTIC_ASSERT(LifecycleStateRef() <
1913 LIFECYCLE_WAITING_FOR_MAIN_THREAD_CLEANUP ||
1914 mForceShutDownReceived);
1917 if (LifecycleStateRef() == LIFECYCLE_THREAD_NOT_STARTED) {
1918 // Start the driver now. We couldn't start it earlier because the graph
1919 // might exit immediately on finding it has no tracks. The first message
1920 // for a new graph must create a track. Ensure that his message runs on
1921 // the first iteration.
1922 MOZ_ASSERT(MessagesQueued());
1923 SwapMessageQueues();
1925 LOG(LogLevel::Debug,
1926 ("%p: Starting a graph with a %s", this,
1927 CurrentDriver()->AsAudioCallbackDriver() ? "AudioCallbackDriver"
1928 : "SystemClockDriver"));
1929 LifecycleStateRef() = LIFECYCLE_RUNNING;
1930 mGraphDriverRunning = true;
1931 RefPtr<GraphDriver> driver = CurrentDriver();
1932 driver->Start();
1933 // It's not safe to Shutdown() a thread from StableState, and
1934 // releasing this may shutdown a SystemClockDriver thread.
1935 // Proxy the release to outside of StableState.
1936 NS_ReleaseOnMainThread("MediaTrackGraphImpl::CurrentDriver",
1937 driver.forget(),
1938 true); // always proxy
1941 if (LifecycleStateRef() == LIFECYCLE_WAITING_FOR_MAIN_THREAD_CLEANUP &&
1942 mForceShutDownReceived) {
1943 // Defer calls to RunDuringShutdown() to happen while mMonitor is not
1944 // held.
1945 for (uint32_t i = 0; i < mBackMessageQueue.Length(); ++i) {
1946 MessageBlock& mb = mBackMessageQueue[i];
1947 controlMessagesToRunDuringShutdown.AppendElements(
1948 std::move(mb.mMessages));
1950 mBackMessageQueue.Clear();
1951 MOZ_ASSERT(mCurrentTaskMessageQueue.IsEmpty());
1952 // Stop MediaTrackGraph threads.
1953 LifecycleStateRef() = LIFECYCLE_WAITING_FOR_THREAD_SHUTDOWN;
1954 nsCOMPtr<nsIRunnable> event = new MediaTrackGraphShutDownRunnable(this);
1955 mMainThread->Dispatch(event.forget());
1958 mGraphDriverRunning = LifecycleStateRef() == LIFECYCLE_RUNNING;
1961 // Make sure we get a new current time in the next event loop task
1962 if (!aSourceIsMTG) {
1963 MOZ_ASSERT(mPostedRunInStableState);
1964 mPostedRunInStableState = false;
1967 for (uint32_t i = 0; i < controlMessagesToRunDuringShutdown.Length(); ++i) {
1968 controlMessagesToRunDuringShutdown[i]->RunDuringShutdown();
1971 #ifdef DEBUG
1972 mCanRunMessagesSynchronously =
1973 !mGraphDriverRunning &&
1974 LifecycleStateRef() >= LIFECYCLE_WAITING_FOR_THREAD_SHUTDOWN;
1975 #endif
1977 for (uint32_t i = 0; i < runnables.Length(); ++i) {
1978 runnables[i]->Run();
1982 void MediaTrackGraphImpl::EnsureRunInStableState() {
1983 MOZ_ASSERT(NS_IsMainThread(), "main thread only");
1985 if (mPostedRunInStableState) return;
1986 mPostedRunInStableState = true;
1987 nsCOMPtr<nsIRunnable> event =
1988 new MediaTrackGraphStableStateRunnable(this, false);
1989 nsContentUtils::RunInStableState(event.forget());
1992 void MediaTrackGraphImpl::EnsureStableStateEventPosted() {
1993 MOZ_ASSERT(OnGraphThread());
1994 mMonitor.AssertCurrentThreadOwns();
1996 if (mPostedRunInStableStateEvent) return;
1997 mPostedRunInStableStateEvent = true;
1998 nsCOMPtr<nsIRunnable> event =
1999 new MediaTrackGraphStableStateRunnable(this, true);
2000 mMainThread->Dispatch(event.forget());
2003 void MediaTrackGraphImpl::SignalMainThreadCleanup() {
2004 MOZ_ASSERT(mDriver->OnThread());
2006 MonitorAutoLock lock(mMonitor);
2007 // LIFECYCLE_THREAD_NOT_STARTED is possible when shutting down offline
2008 // graphs that have not started.
2009 MOZ_DIAGNOSTIC_ASSERT(mLifecycleState <= LIFECYCLE_RUNNING);
2010 LOG(LogLevel::Debug,
2011 ("%p: MediaTrackGraph waiting for main thread cleanup", this));
2012 LifecycleStateRef() =
2013 MediaTrackGraphImpl::LIFECYCLE_WAITING_FOR_MAIN_THREAD_CLEANUP;
2014 EnsureStableStateEventPosted();
2017 void MediaTrackGraphImpl::AppendMessage(UniquePtr<ControlMessage> aMessage) {
2018 MOZ_ASSERT(NS_IsMainThread(), "main thread only");
2019 MOZ_RELEASE_ASSERT(!aMessage->GetTrack() ||
2020 !aMessage->GetTrack()->IsDestroyed());
2021 MOZ_DIAGNOSTIC_ASSERT(mMainThreadTrackCount > 0 || mMainThreadPortCount > 0);
2023 if (!mGraphDriverRunning &&
2024 LifecycleStateRef() > LIFECYCLE_WAITING_FOR_MAIN_THREAD_CLEANUP) {
2025 // The graph control loop is not running and main thread cleanup has
2026 // happened. From now on we can't append messages to
2027 // mCurrentTaskMessageQueue, because that will never be processed again, so
2028 // just RunDuringShutdown this message. This should only happen during
2029 // forced shutdown, or after a non-realtime graph has finished processing.
2030 #ifdef DEBUG
2031 MOZ_ASSERT(mCanRunMessagesSynchronously);
2032 mCanRunMessagesSynchronously = false;
2033 #endif
2034 aMessage->RunDuringShutdown();
2035 #ifdef DEBUG
2036 mCanRunMessagesSynchronously = true;
2037 #endif
2038 if (IsEmpty() &&
2039 LifecycleStateRef() >= LIFECYCLE_WAITING_FOR_TRACK_DESTRUCTION) {
2040 Destroy();
2042 return;
2045 mCurrentTaskMessageQueue.AppendElement(std::move(aMessage));
2046 EnsureRunInStableState();
2049 void MediaTrackGraphImpl::Dispatch(already_AddRefed<nsIRunnable>&& aRunnable) {
2050 mMainThread->Dispatch(std::move(aRunnable));
2053 MediaTrack::MediaTrack(TrackRate aSampleRate, MediaSegment::Type aType,
2054 MediaSegment* aSegment)
2055 : mSampleRate(aSampleRate),
2056 mType(aType),
2057 mSegment(aSegment),
2058 mStartTime(0),
2059 mForgottenTime(0),
2060 mEnded(false),
2061 mNotifiedEnded(false),
2062 mDisabledMode(DisabledTrackMode::ENABLED),
2063 mStartBlocking(GRAPH_TIME_MAX),
2064 mSuspendedCount(0),
2065 mMainThreadCurrentTime(0),
2066 mMainThreadEnded(false),
2067 mEndedNotificationSent(false),
2068 mMainThreadDestroyed(false),
2069 mGraph(nullptr) {
2070 MOZ_COUNT_CTOR(MediaTrack);
2071 MOZ_ASSERT_IF(mSegment, mSegment->GetType() == aType);
2074 MediaTrack::~MediaTrack() {
2075 MOZ_COUNT_DTOR(MediaTrack);
2076 NS_ASSERTION(mMainThreadDestroyed, "Should have been destroyed already");
2077 NS_ASSERTION(mMainThreadListeners.IsEmpty(),
2078 "All main thread listeners should have been removed");
2081 size_t MediaTrack::SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
2082 size_t amount = 0;
2084 // Not owned:
2085 // - mGraph - Not reported here
2086 // - mConsumers - elements
2087 // Future:
2088 // - mLastPlayedVideoFrame
2089 // - mTrackListeners - elements
2091 amount += mTrackListeners.ShallowSizeOfExcludingThis(aMallocSizeOf);
2092 amount += mMainThreadListeners.ShallowSizeOfExcludingThis(aMallocSizeOf);
2093 amount += mConsumers.ShallowSizeOfExcludingThis(aMallocSizeOf);
2095 return amount;
2098 size_t MediaTrack::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const {
2099 return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf);
2102 void MediaTrack::IncrementSuspendCount() {
2103 ++mSuspendedCount;
2104 if (mSuspendedCount != 1 || !mGraph) {
2105 MOZ_ASSERT(mGraph || mConsumers.IsEmpty());
2106 return;
2108 MOZ_ASSERT(mGraph->OnGraphThreadOrNotRunning());
2109 for (uint32_t i = 0; i < mConsumers.Length(); ++i) {
2110 mConsumers[i]->Suspended();
2112 MOZ_ASSERT(mGraph->mTracks.Contains(this));
2113 mGraph->mTracks.RemoveElement(this);
2114 mGraph->mSuspendedTracks.AppendElement(this);
2115 mGraph->SetTrackOrderDirty();
2118 void MediaTrack::DecrementSuspendCount() {
2119 MOZ_ASSERT(mSuspendedCount > 0, "Suspend count underrun");
2120 --mSuspendedCount;
2121 if (mSuspendedCount != 0 || !mGraph) {
2122 MOZ_ASSERT(mGraph || mConsumers.IsEmpty());
2123 return;
2125 MOZ_ASSERT(mGraph->OnGraphThreadOrNotRunning());
2126 for (uint32_t i = 0; i < mConsumers.Length(); ++i) {
2127 mConsumers[i]->Resumed();
2129 MOZ_ASSERT(mGraph->mSuspendedTracks.Contains(this));
2130 mGraph->mSuspendedTracks.RemoveElement(this);
2131 mGraph->mTracks.AppendElement(this);
2132 mGraph->SetTrackOrderDirty();
2135 void ProcessedMediaTrack::DecrementSuspendCount() {
2136 mCycleMarker = NOT_VISITED;
2137 MediaTrack::DecrementSuspendCount();
2140 MediaTrackGraphImpl* MediaTrack::GraphImpl() { return mGraph; }
2142 const MediaTrackGraphImpl* MediaTrack::GraphImpl() const { return mGraph; }
2144 MediaTrackGraph* MediaTrack::Graph() { return mGraph; }
2146 const MediaTrackGraph* MediaTrack::Graph() const { return mGraph; }
2148 void MediaTrack::SetGraphImpl(MediaTrackGraphImpl* aGraph) {
2149 MOZ_ASSERT(!mGraph, "Should only be called once");
2150 MOZ_ASSERT(mSampleRate == aGraph->GraphRate());
2151 mGraph = aGraph;
2154 void MediaTrack::SetGraphImpl(MediaTrackGraph* aGraph) {
2155 MediaTrackGraphImpl* graph = static_cast<MediaTrackGraphImpl*>(aGraph);
2156 SetGraphImpl(graph);
2159 TrackTime MediaTrack::GraphTimeToTrackTime(GraphTime aTime) const {
2160 NS_ASSERTION(mStartBlocking == GraphImpl()->mStateComputedTime ||
2161 aTime <= mStartBlocking,
2162 "Incorrectly ignoring blocking!");
2163 return aTime - mStartTime;
2166 GraphTime MediaTrack::TrackTimeToGraphTime(TrackTime aTime) const {
2167 NS_ASSERTION(mStartBlocking == GraphImpl()->mStateComputedTime ||
2168 aTime + mStartTime <= mStartBlocking,
2169 "Incorrectly ignoring blocking!");
2170 return aTime + mStartTime;
2173 TrackTime MediaTrack::GraphTimeToTrackTimeWithBlocking(GraphTime aTime) const {
2174 return GraphImpl()->GraphTimeToTrackTimeWithBlocking(this, aTime);
2177 void MediaTrack::RemoveAllResourcesAndListenersImpl() {
2178 GraphImpl()->AssertOnGraphThreadOrNotRunning();
2180 for (auto& l : mTrackListeners.Clone()) {
2181 l->NotifyRemoved(Graph());
2183 mTrackListeners.Clear();
2185 RemoveAllDirectListenersImpl();
2187 if (mSegment) {
2188 mSegment->Clear();
2192 void MediaTrack::DestroyImpl() {
2193 for (int32_t i = mConsumers.Length() - 1; i >= 0; --i) {
2194 mConsumers[i]->Disconnect();
2196 if (mSegment) {
2197 mSegment->Clear();
2199 mGraph = nullptr;
2202 void MediaTrack::Destroy() {
2203 // Keep this track alive until we leave this method
2204 RefPtr<MediaTrack> kungFuDeathGrip = this;
2206 class Message : public ControlMessage {
2207 public:
2208 explicit Message(MediaTrack* aTrack) : ControlMessage(aTrack) {}
2209 void RunDuringShutdown() override {
2210 TRACE("MediaTrack::Destroy ControlMessage");
2211 mTrack->RemoveAllResourcesAndListenersImpl();
2212 auto graph = mTrack->GraphImpl();
2213 mTrack->DestroyImpl();
2214 graph->RemoveTrackGraphThread(mTrack);
2216 void Run() override {
2217 mTrack->OnGraphThreadDone();
2218 RunDuringShutdown();
2221 // Keep a reference to the graph, since Message might RunDuringShutdown()
2222 // synchronously and make GraphImpl() invalid.
2223 RefPtr<MediaTrackGraphImpl> graph = GraphImpl();
2224 graph->AppendMessage(MakeUnique<Message>(this));
2225 graph->RemoveTrack(this);
2226 // Message::RunDuringShutdown may have removed this track from the graph,
2227 // but our kungFuDeathGrip above will have kept this track alive if
2228 // necessary.
2229 mMainThreadDestroyed = true;
2232 TrackTime MediaTrack::GetEnd() const {
2233 return mSegment ? mSegment->GetDuration() : 0;
2236 void MediaTrack::AddAudioOutput(void* aKey) {
2237 class Message : public ControlMessage {
2238 public:
2239 Message(MediaTrack* aTrack, void* aKey)
2240 : ControlMessage(aTrack), mKey(aKey) {}
2241 void Run() override {
2242 TRACE("MediaTrack::AddAudioOutputImpl ControlMessage");
2243 mTrack->AddAudioOutputImpl(mKey);
2245 void* mKey;
2247 if (mMainThreadDestroyed) {
2248 return;
2250 GraphImpl()->AppendMessage(MakeUnique<Message>(this, aKey));
2253 void MediaTrackGraphImpl::SetAudioOutputVolume(MediaTrack* aTrack, void* aKey,
2254 float aVolume) {
2255 for (auto& tkv : mAudioOutputs) {
2256 if (tkv.mKey == aKey && aTrack == tkv.mTrack) {
2257 tkv.mVolume = aVolume;
2258 return;
2261 MOZ_CRASH("Audio stream key not found when setting the volume.");
2264 void MediaTrack::SetAudioOutputVolumeImpl(void* aKey, float aVolume) {
2265 MOZ_ASSERT(GraphImpl()->OnGraphThread());
2266 GraphImpl()->SetAudioOutputVolume(this, aKey, aVolume);
2269 void MediaTrack::SetAudioOutputVolume(void* aKey, float aVolume) {
2270 class Message : public ControlMessage {
2271 public:
2272 Message(MediaTrack* aTrack, void* aKey, float aVolume)
2273 : ControlMessage(aTrack), mKey(aKey), mVolume(aVolume) {}
2274 void Run() override {
2275 TRACE("MediaTrack::SetAudioOutputVolumeImpl ControlMessage");
2276 mTrack->SetAudioOutputVolumeImpl(mKey, mVolume);
2278 void* mKey;
2279 float mVolume;
2281 if (mMainThreadDestroyed) {
2282 return;
2284 GraphImpl()->AppendMessage(MakeUnique<Message>(this, aKey, aVolume));
2287 void MediaTrack::AddAudioOutputImpl(void* aKey) {
2288 LOG(LogLevel::Info, ("MediaTrack %p adding AudioOutput", this));
2289 GraphImpl()->RegisterAudioOutput(this, aKey);
2292 void MediaTrack::RemoveAudioOutputImpl(void* aKey) {
2293 LOG(LogLevel::Info, ("MediaTrack %p removing AudioOutput", this));
2294 GraphImpl()->UnregisterAudioOutput(this, aKey);
2297 void MediaTrack::RemoveAudioOutput(void* aKey) {
2298 class Message : public ControlMessage {
2299 public:
2300 explicit Message(MediaTrack* aTrack, void* aKey)
2301 : ControlMessage(aTrack), mKey(aKey) {}
2302 void Run() override {
2303 TRACE("MediaTrack::RemoveAudioOutputImpl ControlMessage");
2304 mTrack->RemoveAudioOutputImpl(mKey);
2306 void* mKey;
2308 if (mMainThreadDestroyed) {
2309 return;
2311 GraphImpl()->AppendMessage(MakeUnique<Message>(this, aKey));
2314 void MediaTrack::Suspend() {
2315 class Message : public ControlMessage {
2316 public:
2317 explicit Message(MediaTrack* aTrack) : ControlMessage(aTrack) {}
2318 void Run() override {
2319 TRACE("MediaTrack::IncrementSuspendCount ControlMessage");
2320 mTrack->IncrementSuspendCount();
2324 // This can happen if this method has been called asynchronously, and the
2325 // track has been destroyed since then.
2326 if (mMainThreadDestroyed) {
2327 return;
2329 GraphImpl()->AppendMessage(MakeUnique<Message>(this));
2332 void MediaTrack::Resume() {
2333 class Message : public ControlMessage {
2334 public:
2335 explicit Message(MediaTrack* aTrack) : ControlMessage(aTrack) {}
2336 void Run() override {
2337 TRACE("MediaTrack::DecrementSuspendCount ControlMessage");
2338 mTrack->DecrementSuspendCount();
2342 // This can happen if this method has been called asynchronously, and the
2343 // track has been destroyed since then.
2344 if (mMainThreadDestroyed) {
2345 return;
2347 GraphImpl()->AppendMessage(MakeUnique<Message>(this));
2350 void MediaTrack::AddListenerImpl(
2351 already_AddRefed<MediaTrackListener> aListener) {
2352 RefPtr<MediaTrackListener> l(aListener);
2353 mTrackListeners.AppendElement(std::move(l));
2355 PrincipalHandle lastPrincipalHandle = mSegment->GetLastPrincipalHandle();
2356 mTrackListeners.LastElement()->NotifyPrincipalHandleChanged(
2357 Graph(), lastPrincipalHandle);
2358 if (mNotifiedEnded) {
2359 mTrackListeners.LastElement()->NotifyEnded(Graph());
2361 if (CombinedDisabledMode() == DisabledTrackMode::SILENCE_BLACK) {
2362 mTrackListeners.LastElement()->NotifyEnabledStateChanged(Graph(), false);
2366 void MediaTrack::AddListener(MediaTrackListener* aListener) {
2367 class Message : public ControlMessage {
2368 public:
2369 Message(MediaTrack* aTrack, MediaTrackListener* aListener)
2370 : ControlMessage(aTrack), mListener(aListener) {}
2371 void Run() override {
2372 TRACE("MediaTrack::AddListenerImpl ControlMessage");
2373 mTrack->AddListenerImpl(mListener.forget());
2375 RefPtr<MediaTrackListener> mListener;
2377 MOZ_ASSERT(mSegment, "Segment-less tracks do not support listeners");
2378 if (mMainThreadDestroyed) {
2379 return;
2381 GraphImpl()->AppendMessage(MakeUnique<Message>(this, aListener));
2384 void MediaTrack::RemoveListenerImpl(MediaTrackListener* aListener) {
2385 for (size_t i = 0; i < mTrackListeners.Length(); ++i) {
2386 if (mTrackListeners[i] == aListener) {
2387 mTrackListeners[i]->NotifyRemoved(Graph());
2388 mTrackListeners.RemoveElementAt(i);
2389 return;
2394 RefPtr<GenericPromise> MediaTrack::RemoveListener(
2395 MediaTrackListener* aListener) {
2396 class Message : public ControlMessage {
2397 public:
2398 Message(MediaTrack* aTrack, MediaTrackListener* aListener)
2399 : ControlMessage(aTrack), mListener(aListener) {}
2400 void Run() override {
2401 TRACE("MediaTrack::RemoveListenerImpl ControlMessage");
2402 mTrack->RemoveListenerImpl(mListener);
2403 mRemovedPromise.Resolve(true, __func__);
2405 void RunDuringShutdown() override {
2406 // During shutdown we still want the listener's NotifyRemoved to be
2407 // called, since not doing that might block shutdown of other modules.
2408 Run();
2410 RefPtr<MediaTrackListener> mListener;
2411 MozPromiseHolder<GenericPromise> mRemovedPromise;
2414 UniquePtr<Message> message = MakeUnique<Message>(this, aListener);
2415 RefPtr<GenericPromise> p = message->mRemovedPromise.Ensure(__func__);
2416 if (mMainThreadDestroyed) {
2417 message->mRemovedPromise.Reject(NS_ERROR_FAILURE, __func__);
2418 return p;
2420 GraphImpl()->AppendMessage(std::move(message));
2421 return p;
2424 void MediaTrack::AddDirectListenerImpl(
2425 already_AddRefed<DirectMediaTrackListener> aListener) {
2426 // Base implementation, for tracks that don't support direct track listeners.
2427 RefPtr<DirectMediaTrackListener> listener = aListener;
2428 listener->NotifyDirectListenerInstalled(
2429 DirectMediaTrackListener::InstallationResult::TRACK_NOT_SUPPORTED);
2432 void MediaTrack::AddDirectListener(DirectMediaTrackListener* aListener) {
2433 class Message : public ControlMessage {
2434 public:
2435 Message(MediaTrack* aTrack, DirectMediaTrackListener* aListener)
2436 : ControlMessage(aTrack), mListener(aListener) {}
2437 void Run() override {
2438 TRACE("MediaTrack::AddDirectListenerImpl ControlMessage");
2439 mTrack->AddDirectListenerImpl(mListener.forget());
2441 RefPtr<DirectMediaTrackListener> mListener;
2443 if (mMainThreadDestroyed) {
2444 return;
2446 GraphImpl()->AppendMessage(MakeUnique<Message>(this, aListener));
2449 void MediaTrack::RemoveDirectListenerImpl(DirectMediaTrackListener* aListener) {
2450 // Base implementation, the listener was never added so nothing to do.
2453 void MediaTrack::RemoveDirectListener(DirectMediaTrackListener* aListener) {
2454 class Message : public ControlMessage {
2455 public:
2456 Message(MediaTrack* aTrack, DirectMediaTrackListener* aListener)
2457 : ControlMessage(aTrack), mListener(aListener) {}
2458 void Run() override {
2459 TRACE("MediaTrack::RemoveDirectListenerImpl ControlMessage");
2460 mTrack->RemoveDirectListenerImpl(mListener);
2462 void RunDuringShutdown() override {
2463 // During shutdown we still want the listener's
2464 // NotifyDirectListenerUninstalled to be called, since not doing that
2465 // might block shutdown of other modules.
2466 Run();
2468 RefPtr<DirectMediaTrackListener> mListener;
2470 if (mMainThreadDestroyed) {
2471 return;
2473 GraphImpl()->AppendMessage(MakeUnique<Message>(this, aListener));
2476 void MediaTrack::RunAfterPendingUpdates(
2477 already_AddRefed<nsIRunnable> aRunnable) {
2478 MOZ_ASSERT(NS_IsMainThread());
2479 MediaTrackGraphImpl* graph = GraphImpl();
2480 nsCOMPtr<nsIRunnable> runnable(aRunnable);
2482 class Message : public ControlMessage {
2483 public:
2484 Message(MediaTrack* aTrack, already_AddRefed<nsIRunnable> aRunnable)
2485 : ControlMessage(aTrack), mRunnable(aRunnable) {}
2486 void Run() override {
2487 TRACE("MediaTrack::DispatchToMainThreadStableState ControlMessage");
2488 mTrack->Graph()->DispatchToMainThreadStableState(mRunnable.forget());
2490 void RunDuringShutdown() override {
2491 // Don't run mRunnable now as it may call AppendMessage() which would
2492 // assume that there are no remaining controlMessagesToRunDuringShutdown.
2493 MOZ_ASSERT(NS_IsMainThread());
2494 mTrack->GraphImpl()->Dispatch(mRunnable.forget());
2497 private:
2498 nsCOMPtr<nsIRunnable> mRunnable;
2501 if (mMainThreadDestroyed) {
2502 return;
2504 graph->AppendMessage(MakeUnique<Message>(this, runnable.forget()));
2507 void MediaTrack::SetDisabledTrackModeImpl(DisabledTrackMode aMode) {
2508 MOZ_DIAGNOSTIC_ASSERT(
2509 aMode == DisabledTrackMode::ENABLED ||
2510 mDisabledMode == DisabledTrackMode::ENABLED,
2511 "Changing disabled track mode for a track is not allowed");
2512 DisabledTrackMode oldMode = CombinedDisabledMode();
2513 mDisabledMode = aMode;
2514 NotifyIfDisabledModeChangedFrom(oldMode);
2517 void MediaTrack::SetDisabledTrackMode(DisabledTrackMode aMode) {
2518 class Message : public ControlMessage {
2519 public:
2520 Message(MediaTrack* aTrack, DisabledTrackMode aMode)
2521 : ControlMessage(aTrack), mMode(aMode) {}
2522 void Run() override {
2523 TRACE("MediaTrack::SetDisabledTrackModeImpl ControlMessage");
2524 mTrack->SetDisabledTrackModeImpl(mMode);
2526 DisabledTrackMode mMode;
2528 if (mMainThreadDestroyed) {
2529 return;
2531 GraphImpl()->AppendMessage(MakeUnique<Message>(this, aMode));
2534 void MediaTrack::ApplyTrackDisabling(MediaSegment* aSegment,
2535 MediaSegment* aRawSegment) {
2536 if (mDisabledMode == DisabledTrackMode::ENABLED) {
2537 return;
2539 if (mDisabledMode == DisabledTrackMode::SILENCE_BLACK) {
2540 aSegment->ReplaceWithDisabled();
2541 if (aRawSegment) {
2542 aRawSegment->ReplaceWithDisabled();
2544 } else if (mDisabledMode == DisabledTrackMode::SILENCE_FREEZE) {
2545 aSegment->ReplaceWithNull();
2546 if (aRawSegment) {
2547 aRawSegment->ReplaceWithNull();
2549 } else {
2550 MOZ_CRASH("Unsupported mode");
2554 void MediaTrack::AddMainThreadListener(
2555 MainThreadMediaTrackListener* aListener) {
2556 MOZ_ASSERT(NS_IsMainThread());
2557 MOZ_ASSERT(aListener);
2558 MOZ_ASSERT(!mMainThreadListeners.Contains(aListener));
2560 mMainThreadListeners.AppendElement(aListener);
2562 // If it is not yet time to send the notification, then exit here.
2563 if (!mEndedNotificationSent) {
2564 return;
2567 class NotifyRunnable final : public Runnable {
2568 public:
2569 explicit NotifyRunnable(MediaTrack* aTrack)
2570 : Runnable("MediaTrack::NotifyRunnable"), mTrack(aTrack) {}
2572 NS_IMETHOD Run() override {
2573 TRACE("MediaTrack::NotifyMainThreadListeners Runnable");
2574 MOZ_ASSERT(NS_IsMainThread());
2575 mTrack->NotifyMainThreadListeners();
2576 return NS_OK;
2579 private:
2580 ~NotifyRunnable() = default;
2582 RefPtr<MediaTrack> mTrack;
2585 nsCOMPtr<nsIRunnable> runnable = new NotifyRunnable(this);
2586 GraphImpl()->Dispatch(runnable.forget());
2589 void MediaTrack::AdvanceTimeVaryingValuesToCurrentTime(GraphTime aCurrentTime,
2590 GraphTime aBlockedTime) {
2591 mStartTime += aBlockedTime;
2593 if (!mSegment) {
2594 // No data to be forgotten.
2595 return;
2598 TrackTime time = aCurrentTime - mStartTime;
2599 // Only prune if there is a reasonable chunk (50ms) to forget, so we don't
2600 // spend too much time pruning segments.
2601 const TrackTime minChunkSize = mSampleRate * 50 / 1000;
2602 if (time < mForgottenTime + minChunkSize) {
2603 return;
2606 mForgottenTime = std::min(GetEnd() - 1, time);
2607 mSegment->ForgetUpTo(mForgottenTime);
2610 void MediaTrack::NotifyIfDisabledModeChangedFrom(DisabledTrackMode aOldMode) {
2611 DisabledTrackMode mode = CombinedDisabledMode();
2612 if (aOldMode == mode) {
2613 return;
2616 for (const auto& listener : mTrackListeners) {
2617 listener->NotifyEnabledStateChanged(
2618 Graph(), mode != DisabledTrackMode::SILENCE_BLACK);
2621 for (const auto& c : mConsumers) {
2622 if (c->GetDestination()) {
2623 c->GetDestination()->OnInputDisabledModeChanged(mode);
2628 SourceMediaTrack::SourceMediaTrack(MediaSegment::Type aType,
2629 TrackRate aSampleRate)
2630 : MediaTrack(aSampleRate, aType,
2631 aType == MediaSegment::AUDIO
2632 ? static_cast<MediaSegment*>(new AudioSegment())
2633 : static_cast<MediaSegment*>(new VideoSegment())),
2634 mMutex("mozilla::media::SourceMediaTrack") {
2635 mUpdateTrack = MakeUnique<TrackData>();
2636 mUpdateTrack->mInputRate = aSampleRate;
2637 mUpdateTrack->mResamplerChannelCount = 0;
2638 mUpdateTrack->mData = UniquePtr<MediaSegment>(mSegment->CreateEmptyClone());
2639 mUpdateTrack->mEnded = false;
2640 mUpdateTrack->mPullingEnabled = false;
2641 mUpdateTrack->mGraphThreadDone = false;
2644 void SourceMediaTrack::DestroyImpl() {
2645 GraphImpl()->AssertOnGraphThreadOrNotRunning();
2646 for (int32_t i = mConsumers.Length() - 1; i >= 0; --i) {
2647 // Disconnect before we come under mMutex's lock since it can call back
2648 // through RemoveDirectListenerImpl() and deadlock.
2649 mConsumers[i]->Disconnect();
2652 // Hold mMutex while mGraph is reset so that other threads holding mMutex
2653 // can null-check know that the graph will not destroyed.
2654 MutexAutoLock lock(mMutex);
2655 mUpdateTrack = nullptr;
2656 MediaTrack::DestroyImpl();
2659 void SourceMediaTrack::SetPullingEnabled(bool aEnabled) {
2660 class Message : public ControlMessage {
2661 public:
2662 Message(SourceMediaTrack* aTrack, bool aEnabled)
2663 : ControlMessage(nullptr), mTrack(aTrack), mEnabled(aEnabled) {}
2664 void Run() override {
2665 TRACE("SourceMediaTrack::SetPullingEnabled ControlMessage");
2666 MutexAutoLock lock(mTrack->mMutex);
2667 if (!mTrack->mUpdateTrack) {
2668 // We can't enable pulling for a track that has ended. We ignore
2669 // this if we're disabling pulling, since shutdown sequences are
2670 // complex. If there's truly an issue we'll have issues enabling anyway.
2671 MOZ_ASSERT_IF(mEnabled, mTrack->mEnded);
2672 return;
2674 MOZ_ASSERT(mTrack->mType == MediaSegment::AUDIO,
2675 "Pulling is not allowed for video");
2676 mTrack->mUpdateTrack->mPullingEnabled = mEnabled;
2678 SourceMediaTrack* mTrack;
2679 bool mEnabled;
2681 GraphImpl()->AppendMessage(MakeUnique<Message>(this, aEnabled));
2684 bool SourceMediaTrack::PullNewData(GraphTime aDesiredUpToTime) {
2685 TRACE_COMMENT("SourceMediaTrack::PullNewData", "%p", this);
2686 TrackTime t;
2687 TrackTime current;
2689 if (mEnded) {
2690 return false;
2692 MutexAutoLock lock(mMutex);
2693 if (mUpdateTrack->mEnded) {
2694 return false;
2696 if (!mUpdateTrack->mPullingEnabled) {
2697 return false;
2699 // Compute how much track time we'll need assuming we don't block
2700 // the track at all.
2701 t = GraphTimeToTrackTime(aDesiredUpToTime);
2702 current = GetEnd() + mUpdateTrack->mData->GetDuration();
2704 if (t <= current) {
2705 return false;
2707 LOG(LogLevel::Verbose, ("%p: Calling NotifyPull track=%p t=%f current end=%f",
2708 GraphImpl(), this, GraphImpl()->MediaTimeToSeconds(t),
2709 GraphImpl()->MediaTimeToSeconds(current)));
2710 for (auto& l : mTrackListeners) {
2711 l->NotifyPull(Graph(), current, t);
2713 return true;
2717 * This moves chunks from aIn to aOut. For audio this is simple. For video
2718 * we carry durations over if present, or extend up to aDesiredUpToTime if not.
2720 * We also handle "resetters" from captured media elements. This type of source
2721 * pushes future frames into the track, and should it need to remove some, e.g.,
2722 * because of a seek or pause, it tells us by letting time go backwards. Without
2723 * this, tracks would be live for too long after a seek or pause.
2725 static void MoveToSegment(SourceMediaTrack* aTrack, MediaSegment* aIn,
2726 MediaSegment* aOut, TrackTime aCurrentTime,
2727 TrackTime aDesiredUpToTime)
2728 REQUIRES(aTrack->GetMutex()) {
2729 MOZ_ASSERT(aIn->GetType() == aOut->GetType());
2730 MOZ_ASSERT(aOut->GetDuration() >= aCurrentTime);
2731 MOZ_ASSERT(aDesiredUpToTime >= aCurrentTime);
2732 if (aIn->GetType() == MediaSegment::AUDIO) {
2733 AudioSegment* in = static_cast<AudioSegment*>(aIn);
2734 AudioSegment* out = static_cast<AudioSegment*>(aOut);
2735 TrackTime desiredDurationToMove = aDesiredUpToTime - aCurrentTime;
2736 TrackTime end = std::min(in->GetDuration(), desiredDurationToMove);
2738 out->AppendSlice(*in, 0, end);
2739 in->RemoveLeading(end);
2741 aTrack->GetMutex().AssertCurrentThreadOwns();
2742 out->ApplyVolume(aTrack->GetVolumeLocked());
2743 } else {
2744 VideoSegment* in = static_cast<VideoSegment*>(aIn);
2745 VideoSegment* out = static_cast<VideoSegment*>(aOut);
2746 for (VideoSegment::ConstChunkIterator c(*in); !c.IsEnded(); c.Next()) {
2747 MOZ_ASSERT(!c->mTimeStamp.IsNull());
2748 VideoChunk* last = out->GetLastChunk();
2749 if (!last || last->mTimeStamp.IsNull()) {
2750 // This is the first frame, or the last frame pushed to `out` has been
2751 // all consumed. Just append and we deal with its duration later.
2752 out->AppendFrame(do_AddRef(c->mFrame.GetImage()),
2753 c->mFrame.GetIntrinsicSize(),
2754 c->mFrame.GetPrincipalHandle(),
2755 c->mFrame.GetForceBlack(), c->mTimeStamp);
2756 if (c->GetDuration() > 0) {
2757 out->ExtendLastFrameBy(c->GetDuration());
2759 continue;
2762 // We now know when this frame starts, aka when the last frame ends.
2764 if (c->mTimeStamp < last->mTimeStamp) {
2765 // Time is going backwards. This is a resetting frame from
2766 // DecodedStream. Clear everything up to currentTime.
2767 out->Clear();
2768 out->AppendNullData(aCurrentTime);
2771 // Append the current frame (will have duration 0).
2772 out->AppendFrame(do_AddRef(c->mFrame.GetImage()),
2773 c->mFrame.GetIntrinsicSize(),
2774 c->mFrame.GetPrincipalHandle(),
2775 c->mFrame.GetForceBlack(), c->mTimeStamp);
2776 if (c->GetDuration() > 0) {
2777 out->ExtendLastFrameBy(c->GetDuration());
2780 if (out->GetDuration() < aDesiredUpToTime) {
2781 out->ExtendLastFrameBy(aDesiredUpToTime - out->GetDuration());
2783 in->Clear();
2784 MOZ_ASSERT(aIn->GetDuration() == 0, "aIn must be consumed");
2788 void SourceMediaTrack::ExtractPendingInput(GraphTime aCurrentTime,
2789 GraphTime aDesiredUpToTime) {
2790 MutexAutoLock lock(mMutex);
2792 if (!mUpdateTrack) {
2793 MOZ_ASSERT(mEnded);
2794 return;
2797 TrackTime trackCurrentTime = GraphTimeToTrackTime(aCurrentTime);
2799 ApplyTrackDisabling(mUpdateTrack->mData.get());
2801 if (!mUpdateTrack->mData->IsEmpty()) {
2802 for (const auto& l : mTrackListeners) {
2803 l->NotifyQueuedChanges(GraphImpl(), GetEnd(), *mUpdateTrack->mData);
2806 TrackTime trackDesiredUpToTime = GraphTimeToTrackTime(aDesiredUpToTime);
2807 TrackTime endTime = trackDesiredUpToTime;
2808 if (mUpdateTrack->mEnded) {
2809 endTime = std::min(trackDesiredUpToTime,
2810 GetEnd() + mUpdateTrack->mData->GetDuration());
2812 LOG(LogLevel::Verbose,
2813 ("%p: SourceMediaTrack %p advancing end from %" PRId64 " to %" PRId64,
2814 GraphImpl(), this, int64_t(trackCurrentTime), int64_t(endTime)));
2815 MoveToSegment(this, mUpdateTrack->mData.get(), mSegment.get(),
2816 trackCurrentTime, endTime);
2817 if (mUpdateTrack->mEnded && GetEnd() < trackDesiredUpToTime) {
2818 mEnded = true;
2819 mUpdateTrack = nullptr;
2823 void SourceMediaTrack::ResampleAudioToGraphSampleRate(MediaSegment* aSegment) {
2824 mMutex.AssertCurrentThreadOwns();
2825 if (aSegment->GetType() != MediaSegment::AUDIO ||
2826 mUpdateTrack->mInputRate == GraphImpl()->GraphRate()) {
2827 return;
2829 AudioSegment* segment = static_cast<AudioSegment*>(aSegment);
2830 segment->ResampleChunks(mUpdateTrack->mResampler,
2831 &mUpdateTrack->mResamplerChannelCount,
2832 mUpdateTrack->mInputRate, GraphImpl()->GraphRate());
2835 void SourceMediaTrack::AdvanceTimeVaryingValuesToCurrentTime(
2836 GraphTime aCurrentTime, GraphTime aBlockedTime) {
2837 MutexAutoLock lock(mMutex);
2838 MediaTrack::AdvanceTimeVaryingValuesToCurrentTime(aCurrentTime, aBlockedTime);
2841 void SourceMediaTrack::SetAppendDataSourceRate(TrackRate aRate) {
2842 MutexAutoLock lock(mMutex);
2843 if (!mUpdateTrack) {
2844 return;
2846 MOZ_DIAGNOSTIC_ASSERT(mSegment->GetType() == MediaSegment::AUDIO);
2847 // Set the new input rate and reset the resampler.
2848 mUpdateTrack->mInputRate = aRate;
2849 mUpdateTrack->mResampler.own(nullptr);
2850 mUpdateTrack->mResamplerChannelCount = 0;
2853 TrackTime SourceMediaTrack::AppendData(MediaSegment* aSegment,
2854 MediaSegment* aRawSegment) {
2855 MutexAutoLock lock(mMutex);
2856 MOZ_DIAGNOSTIC_ASSERT(aSegment->GetType() == mType);
2857 TrackTime appended = 0;
2858 if (!mUpdateTrack || mUpdateTrack->mEnded || mUpdateTrack->mGraphThreadDone) {
2859 aSegment->Clear();
2860 return appended;
2863 // Data goes into mData, and on the next iteration of the MTG moves
2864 // into the track's segment after NotifyQueuedTrackChanges(). This adds
2865 // 0-10ms of delay before data gets to direct listeners.
2866 // Indirect listeners (via subsequent TrackUnion nodes) are synced to
2867 // playout time, and so can be delayed by buffering.
2869 // Apply track disabling before notifying any consumers directly
2870 // or inserting into the graph
2871 ApplyTrackDisabling(aSegment, aRawSegment);
2873 ResampleAudioToGraphSampleRate(aSegment);
2875 // Must notify first, since AppendFrom() will empty out aSegment
2876 NotifyDirectConsumers(aRawSegment ? aRawSegment : aSegment);
2877 appended = aSegment->GetDuration();
2878 mUpdateTrack->mData->AppendFrom(aSegment); // note: aSegment is now dead
2880 auto graph = GraphImpl();
2881 MonitorAutoLock lock(graph->GetMonitor());
2882 if (graph->CurrentDriver()) { // graph has not completed forced shutdown
2883 graph->EnsureNextIteration();
2887 return appended;
2890 TrackTime SourceMediaTrack::ClearFutureData() {
2891 MutexAutoLock lock(mMutex);
2892 auto graph = GraphImpl();
2893 if (!mUpdateTrack || !graph) {
2894 return 0;
2897 TrackTime duration = mUpdateTrack->mData->GetDuration();
2898 mUpdateTrack->mData->Clear();
2899 return duration;
2902 void SourceMediaTrack::NotifyDirectConsumers(MediaSegment* aSegment) {
2903 mMutex.AssertCurrentThreadOwns();
2905 for (const auto& l : mDirectTrackListeners) {
2906 TrackTime offset = 0; // FIX! need a separate TrackTime.... or the end of
2907 // the internal buffer
2908 l->NotifyRealtimeTrackDataAndApplyTrackDisabling(Graph(), offset,
2909 *aSegment);
2913 void SourceMediaTrack::AddDirectListenerImpl(
2914 already_AddRefed<DirectMediaTrackListener> aListener) {
2915 MutexAutoLock lock(mMutex);
2917 RefPtr<DirectMediaTrackListener> listener = aListener;
2918 LOG(LogLevel::Debug,
2919 ("%p: Adding direct track listener %p to source track %p", GraphImpl(),
2920 listener.get(), this));
2922 MOZ_ASSERT(mType == MediaSegment::VIDEO);
2923 for (const auto& l : mDirectTrackListeners) {
2924 if (l == listener) {
2925 listener->NotifyDirectListenerInstalled(
2926 DirectMediaTrackListener::InstallationResult::ALREADY_EXISTS);
2927 return;
2931 mDirectTrackListeners.AppendElement(listener);
2933 LOG(LogLevel::Debug,
2934 ("%p: Added direct track listener %p", GraphImpl(), listener.get()));
2935 listener->NotifyDirectListenerInstalled(
2936 DirectMediaTrackListener::InstallationResult::SUCCESS);
2938 if (mDisabledMode != DisabledTrackMode::ENABLED) {
2939 listener->IncreaseDisabled(mDisabledMode);
2942 if (mEnded) {
2943 return;
2946 // Pass buffered data to the listener
2947 VideoSegment bufferedData;
2948 size_t videoFrames = 0;
2949 VideoSegment& segment = *GetData<VideoSegment>();
2950 for (VideoSegment::ConstChunkIterator iter(segment); !iter.IsEnded();
2951 iter.Next()) {
2952 if (iter->mTimeStamp.IsNull()) {
2953 // No timestamp means this is only for the graph's internal book-keeping,
2954 // denoting a late start of the track.
2955 continue;
2957 ++videoFrames;
2958 bufferedData.AppendFrame(do_AddRef(iter->mFrame.GetImage()),
2959 iter->mFrame.GetIntrinsicSize(),
2960 iter->mFrame.GetPrincipalHandle(),
2961 iter->mFrame.GetForceBlack(), iter->mTimeStamp);
2964 VideoSegment& video = static_cast<VideoSegment&>(*mUpdateTrack->mData);
2965 for (VideoSegment::ConstChunkIterator iter(video); !iter.IsEnded();
2966 iter.Next()) {
2967 ++videoFrames;
2968 MOZ_ASSERT(!iter->mTimeStamp.IsNull());
2969 bufferedData.AppendFrame(do_AddRef(iter->mFrame.GetImage()),
2970 iter->mFrame.GetIntrinsicSize(),
2971 iter->mFrame.GetPrincipalHandle(),
2972 iter->mFrame.GetForceBlack(), iter->mTimeStamp);
2975 LOG(LogLevel::Info,
2976 ("%p: Notifying direct listener %p of %zu video frames and duration "
2977 "%" PRId64,
2978 GraphImpl(), listener.get(), videoFrames, bufferedData.GetDuration()));
2979 listener->NotifyRealtimeTrackData(Graph(), 0, bufferedData);
2982 void SourceMediaTrack::RemoveDirectListenerImpl(
2983 DirectMediaTrackListener* aListener) {
2984 MutexAutoLock lock(mMutex);
2985 for (int32_t i = mDirectTrackListeners.Length() - 1; i >= 0; --i) {
2986 const RefPtr<DirectMediaTrackListener>& l = mDirectTrackListeners[i];
2987 if (l == aListener) {
2988 if (mDisabledMode != DisabledTrackMode::ENABLED) {
2989 aListener->DecreaseDisabled(mDisabledMode);
2991 aListener->NotifyDirectListenerUninstalled();
2992 mDirectTrackListeners.RemoveElementAt(i);
2997 void SourceMediaTrack::End() {
2998 MutexAutoLock lock(mMutex);
2999 if (!mUpdateTrack) {
3000 // Already ended
3001 return;
3003 mUpdateTrack->mEnded = true;
3004 if (auto graph = GraphImpl()) {
3005 MonitorAutoLock lock(graph->GetMonitor());
3006 if (graph->CurrentDriver()) { // graph has not completed forced shutdown
3007 graph->EnsureNextIteration();
3012 void SourceMediaTrack::SetDisabledTrackModeImpl(DisabledTrackMode aMode) {
3014 MutexAutoLock lock(mMutex);
3015 for (const auto& l : mDirectTrackListeners) {
3016 DisabledTrackMode oldMode = mDisabledMode;
3017 bool oldEnabled = oldMode == DisabledTrackMode::ENABLED;
3018 if (!oldEnabled && aMode == DisabledTrackMode::ENABLED) {
3019 LOG(LogLevel::Debug, ("%p: SourceMediaTrack %p setting "
3020 "direct listener enabled",
3021 GraphImpl(), this));
3022 l->DecreaseDisabled(oldMode);
3023 } else if (oldEnabled && aMode != DisabledTrackMode::ENABLED) {
3024 LOG(LogLevel::Debug, ("%p: SourceMediaTrack %p setting "
3025 "direct listener disabled",
3026 GraphImpl(), this));
3027 l->IncreaseDisabled(aMode);
3031 MediaTrack::SetDisabledTrackModeImpl(aMode);
3034 uint32_t SourceMediaTrack::NumberOfChannels() const {
3035 AudioSegment* audio = GetData<AudioSegment>();
3036 MOZ_DIAGNOSTIC_ASSERT(audio);
3037 if (!audio) {
3038 return 0;
3040 return audio->MaxChannelCount();
3043 void SourceMediaTrack::RemoveAllDirectListenersImpl() {
3044 GraphImpl()->AssertOnGraphThreadOrNotRunning();
3045 MutexAutoLock lock(mMutex);
3047 for (auto& l : mDirectTrackListeners.Clone()) {
3048 l->NotifyDirectListenerUninstalled();
3050 mDirectTrackListeners.Clear();
3053 void SourceMediaTrack::SetVolume(float aVolume) {
3054 MutexAutoLock lock(mMutex);
3055 mVolume = aVolume;
3058 float SourceMediaTrack::GetVolumeLocked() {
3059 mMutex.AssertCurrentThreadOwns();
3060 return mVolume;
3063 SourceMediaTrack::~SourceMediaTrack() = default;
3065 void MediaInputPort::Init() {
3066 mGraph->AssertOnGraphThreadOrNotRunning();
3067 LOG(LogLevel::Debug, ("%p: Adding MediaInputPort %p (from %p to %p)",
3068 mSource->GraphImpl(), this, mSource, mDest));
3069 // Only connect the port if it wasn't disconnected on allocation.
3070 if (mSource) {
3071 mSource->AddConsumer(this);
3072 mDest->AddInput(this);
3074 // mPortCount decremented via MediaInputPort::Destroy's message
3075 ++mGraph->mPortCount;
3078 void MediaInputPort::Disconnect() {
3079 mGraph->AssertOnGraphThreadOrNotRunning();
3080 NS_ASSERTION(!mSource == !mDest,
3081 "mSource and mDest must either both be null or both non-null");
3083 if (!mSource) {
3084 return;
3087 mSource->RemoveConsumer(this);
3088 mDest->RemoveInput(this);
3089 mSource = nullptr;
3090 mDest = nullptr;
3092 mGraph->SetTrackOrderDirty();
3095 MediaTrack* MediaInputPort::GetSource() const {
3096 mGraph->AssertOnGraphThreadOrNotRunning();
3097 return mSource;
3100 ProcessedMediaTrack* MediaInputPort::GetDestination() const {
3101 mGraph->AssertOnGraphThreadOrNotRunning();
3102 return mDest;
3105 MediaInputPort::InputInterval MediaInputPort::GetNextInputInterval(
3106 MediaInputPort const* aPort, GraphTime aTime) {
3107 InputInterval result = {GRAPH_TIME_MAX, GRAPH_TIME_MAX, false};
3108 if (!aPort) {
3109 result.mStart = aTime;
3110 result.mInputIsBlocked = true;
3111 return result;
3113 aPort->mGraph->AssertOnGraphThreadOrNotRunning();
3114 if (aTime >= aPort->mDest->mStartBlocking) {
3115 return result;
3117 result.mStart = aTime;
3118 result.mEnd = aPort->mDest->mStartBlocking;
3119 result.mInputIsBlocked = aTime >= aPort->mSource->mStartBlocking;
3120 if (!result.mInputIsBlocked) {
3121 result.mEnd = std::min(result.mEnd, aPort->mSource->mStartBlocking);
3123 return result;
3126 void MediaInputPort::Suspended() {
3127 mGraph->AssertOnGraphThreadOrNotRunning();
3128 mDest->InputSuspended(this);
3131 void MediaInputPort::Resumed() {
3132 mGraph->AssertOnGraphThreadOrNotRunning();
3133 mDest->InputResumed(this);
3136 void MediaInputPort::Destroy() {
3137 class Message : public ControlMessage {
3138 public:
3139 explicit Message(MediaInputPort* aPort)
3140 : ControlMessage(nullptr), mPort(aPort) {}
3141 void Run() override {
3142 TRACE("MediaInputPort::Destroy ControlMessage");
3143 mPort->Disconnect();
3144 --mPort->GraphImpl()->mPortCount;
3145 mPort->SetGraphImpl(nullptr);
3146 NS_RELEASE(mPort);
3148 void RunDuringShutdown() override { Run(); }
3149 MediaInputPort* mPort;
3151 // Keep a reference to the graph, since Message might RunDuringShutdown()
3152 // synchronously and make GraphImpl() invalid.
3153 RefPtr<MediaTrackGraphImpl> graph = mGraph;
3154 graph->AppendMessage(MakeUnique<Message>(this));
3155 --graph->mMainThreadPortCount;
3158 MediaTrackGraphImpl* MediaInputPort::GraphImpl() const {
3159 mGraph->AssertOnGraphThreadOrNotRunning();
3160 return mGraph;
3163 MediaTrackGraph* MediaInputPort::Graph() const {
3164 mGraph->AssertOnGraphThreadOrNotRunning();
3165 return mGraph;
3168 void MediaInputPort::SetGraphImpl(MediaTrackGraphImpl* aGraph) {
3169 MOZ_ASSERT(!mGraph || !aGraph, "Should only be set once");
3170 DebugOnly<MediaTrackGraphImpl*> graph = mGraph ? mGraph : aGraph;
3171 MOZ_ASSERT(graph->OnGraphThreadOrNotRunning());
3172 mGraph = aGraph;
3175 already_AddRefed<MediaInputPort> ProcessedMediaTrack::AllocateInputPort(
3176 MediaTrack* aTrack, uint16_t aInputNumber, uint16_t aOutputNumber) {
3177 // This method creates two references to the MediaInputPort: one for
3178 // the main thread, and one for the MediaTrackGraph.
3179 class Message : public ControlMessage {
3180 public:
3181 explicit Message(MediaInputPort* aPort)
3182 : ControlMessage(aPort->mDest), mPort(aPort) {}
3183 void Run() override {
3184 TRACE("ProcessedMediaTrack::AllocateInputPort ControlMessage");
3185 mPort->Init();
3186 // The graph holds its reference implicitly
3187 mPort->GraphImpl()->SetTrackOrderDirty();
3188 Unused << mPort.forget();
3190 void RunDuringShutdown() override { Run(); }
3191 RefPtr<MediaInputPort> mPort;
3194 MOZ_DIAGNOSTIC_ASSERT(aTrack->mType == mType);
3195 RefPtr<MediaInputPort> port;
3196 if (aTrack->IsDestroyed()) {
3197 // Create a port that's disconnected, which is what it'd be after its source
3198 // track is Destroy()ed normally. Disconnect() is idempotent so destroying
3199 // this later is fine.
3200 port = new MediaInputPort(GraphImpl(), nullptr, nullptr, aInputNumber,
3201 aOutputNumber);
3202 } else {
3203 MOZ_ASSERT(aTrack->GraphImpl() == GraphImpl());
3204 port = new MediaInputPort(GraphImpl(), aTrack, this, aInputNumber,
3205 aOutputNumber);
3207 ++GraphImpl()->mMainThreadPortCount;
3208 GraphImpl()->AppendMessage(MakeUnique<Message>(port));
3209 return port.forget();
3212 void ProcessedMediaTrack::QueueSetAutoend(bool aAutoend) {
3213 class Message : public ControlMessage {
3214 public:
3215 Message(ProcessedMediaTrack* aTrack, bool aAutoend)
3216 : ControlMessage(aTrack), mAutoend(aAutoend) {}
3217 void Run() override {
3218 TRACE("ProcessedMediaTrack::SetAutoendImpl ControlMessage");
3219 static_cast<ProcessedMediaTrack*>(mTrack)->SetAutoendImpl(mAutoend);
3221 bool mAutoend;
3223 if (mMainThreadDestroyed) {
3224 return;
3226 GraphImpl()->AppendMessage(MakeUnique<Message>(this, aAutoend));
3229 void ProcessedMediaTrack::DestroyImpl() {
3230 for (int32_t i = mInputs.Length() - 1; i >= 0; --i) {
3231 mInputs[i]->Disconnect();
3234 for (int32_t i = mSuspendedInputs.Length() - 1; i >= 0; --i) {
3235 mSuspendedInputs[i]->Disconnect();
3238 MediaTrack::DestroyImpl();
3239 // The track order is only important if there are connections, in which
3240 // case MediaInputPort::Disconnect() called SetTrackOrderDirty().
3241 // MediaTrackGraphImpl::RemoveTrackGraphThread() will also call
3242 // SetTrackOrderDirty(), for other reasons.
3245 MediaTrackGraphImpl::MediaTrackGraphImpl(
3246 GraphDriverType aDriverRequested, GraphRunType aRunTypeRequested,
3247 TrackRate aSampleRate, uint32_t aChannelCount,
3248 CubebUtils::AudioDeviceID aOutputDeviceID,
3249 nsISerialEventTarget* aMainThread)
3250 : MediaTrackGraph(aSampleRate),
3251 mGraphRunner(aRunTypeRequested == SINGLE_THREAD
3252 ? GraphRunner::Create(this)
3253 : already_AddRefed<GraphRunner>(nullptr)),
3254 mFirstCycleBreaker(0)
3255 // An offline graph is not initially processing.
3257 mEndTime(aDriverRequested == OFFLINE_THREAD_DRIVER ? 0 : GRAPH_TIME_MAX),
3258 mPortCount(0),
3259 mOutputDeviceID(aOutputDeviceID),
3260 mMonitor("MediaTrackGraphImpl"),
3261 mLifecycleState(LIFECYCLE_THREAD_NOT_STARTED),
3262 mPostedRunInStableStateEvent(false),
3263 mGraphDriverRunning(false),
3264 mPostedRunInStableState(false),
3265 mRealtime(aDriverRequested != OFFLINE_THREAD_DRIVER),
3266 mTrackOrderDirty(false),
3267 mMainThread(aMainThread),
3268 mSelfRef(this),
3269 mGlobalVolume(CubebUtils::GetVolumeScale())
3270 #ifdef DEBUG
3272 mCanRunMessagesSynchronously(false)
3273 #endif
3275 mMainThreadGraphTime(0, "MediaTrackGraphImpl::mMainThreadGraphTime"),
3276 mAudioOutputLatency(0.0),
3277 mMaxOutputChannelCount(std::min(8u, CubebUtils::MaxNumberOfChannels())) {
3278 bool failedToGetShutdownBlocker = false;
3279 if (!IsNonRealtime()) {
3280 failedToGetShutdownBlocker = !AddShutdownBlocker();
3283 if ((aRunTypeRequested == SINGLE_THREAD && !mGraphRunner) ||
3284 failedToGetShutdownBlocker) {
3285 // At least one of the following happened
3286 // - Failed to create thread.
3287 // - Failed to install a shutdown blocker when one is needed.
3288 // Because we have a fail state, jump to last phase of the lifecycle.
3289 mLifecycleState = LIFECYCLE_WAITING_FOR_TRACK_DESTRUCTION;
3290 RemoveShutdownBlocker(); // No-op if blocker wasn't added.
3291 #ifdef DEBUG
3292 mCanRunMessagesSynchronously = true;
3293 #endif
3294 return;
3296 if (mRealtime) {
3297 if (aDriverRequested == AUDIO_THREAD_DRIVER) {
3298 // Always start with zero input channels, and no particular preferences
3299 // for the input channel.
3300 mDriver = new AudioCallbackDriver(this, nullptr, mSampleRate,
3301 aChannelCount, 0, mOutputDeviceID,
3302 nullptr, AudioInputType::Unknown);
3303 } else {
3304 mDriver = new SystemClockDriver(this, nullptr, mSampleRate);
3306 } else {
3307 mDriver =
3308 new OfflineClockDriver(this, mSampleRate, MEDIA_GRAPH_TARGET_PERIOD_MS);
3311 mLastMainThreadUpdate = TimeStamp::Now();
3313 RegisterWeakAsyncMemoryReporter(this);
3316 #ifdef DEBUG
3317 bool MediaTrackGraphImpl::InDriverIteration(const GraphDriver* aDriver) const {
3318 return aDriver->OnThread() ||
3319 (mGraphRunner && mGraphRunner->InDriverIteration(aDriver));
3321 #endif
3323 void MediaTrackGraphImpl::Destroy() {
3324 // First unregister from memory reporting.
3325 UnregisterWeakMemoryReporter(this);
3327 // Clear the self reference which will destroy this instance if all
3328 // associated GraphDrivers are destroyed.
3329 mSelfRef = nullptr;
3332 // Internal method has a Window ID parameter so that TestAudioTrackGraph
3333 // GTests can create a graph without a window.
3334 /* static */
3335 MediaTrackGraphImpl* MediaTrackGraphImpl::GetInstanceIfExists(
3336 uint64_t aWindowID, TrackRate aSampleRate,
3337 CubebUtils::AudioDeviceID aOutputDeviceID) {
3338 MOZ_ASSERT(NS_IsMainThread(), "Main thread only");
3340 TrackRate sampleRate =
3341 aSampleRate ? aSampleRate : CubebUtils::PreferredSampleRate();
3342 GraphKey key(aWindowID, sampleRate, aOutputDeviceID);
3344 return gGraphs.Get(key);
3347 // Public method has an nsPIDOMWindowInner* parameter to ensure that the
3348 // window is a real inner Window, not a WindowProxy.
3349 /* static */
3350 MediaTrackGraph* MediaTrackGraph::GetInstanceIfExists(
3351 nsPIDOMWindowInner* aWindow, TrackRate aSampleRate,
3352 CubebUtils::AudioDeviceID aOutputDeviceID) {
3353 return MediaTrackGraphImpl::GetInstanceIfExists(aWindow->WindowID(),
3354 aSampleRate, aOutputDeviceID);
3357 /* static */
3358 MediaTrackGraphImpl* MediaTrackGraphImpl::GetInstance(
3359 GraphDriverType aGraphDriverRequested, uint64_t aWindowID,
3360 TrackRate aSampleRate, CubebUtils::AudioDeviceID aOutputDeviceID,
3361 nsISerialEventTarget* aMainThread) {
3362 MOZ_ASSERT(NS_IsMainThread(), "Main thread only");
3364 TrackRate sampleRate =
3365 aSampleRate ? aSampleRate : CubebUtils::PreferredSampleRate();
3366 MediaTrackGraphImpl* graph =
3367 GetInstanceIfExists(aWindowID, sampleRate, aOutputDeviceID);
3369 if (!graph) {
3370 GraphRunType runType = DIRECT_DRIVER;
3371 if (aGraphDriverRequested != OFFLINE_THREAD_DRIVER &&
3372 (StaticPrefs::dom_audioworklet_enabled() ||
3373 Preferences::GetBool("media.audiograph.single_thread.enabled",
3374 false))) {
3375 runType = SINGLE_THREAD;
3378 // In a real time graph, the number of output channels is determined by
3379 // the underlying number of channel of the default audio output device, and
3380 // capped to 8.
3381 uint32_t channelCount =
3382 std::min<uint32_t>(8, CubebUtils::MaxNumberOfChannels());
3383 graph = new MediaTrackGraphImpl(aGraphDriverRequested, runType, sampleRate,
3384 channelCount, aOutputDeviceID, aMainThread);
3385 GraphKey key(aWindowID, sampleRate, aOutputDeviceID);
3386 gGraphs.InsertOrUpdate(key, graph);
3388 LOG(LogLevel::Debug,
3389 ("Starting up MediaTrackGraph %p for window 0x%" PRIx64, graph,
3390 aWindowID));
3393 return graph;
3396 /* static */
3397 MediaTrackGraph* MediaTrackGraph::GetInstance(
3398 GraphDriverType aGraphDriverRequested, nsPIDOMWindowInner* aWindow,
3399 TrackRate aSampleRate, CubebUtils::AudioDeviceID aOutputDeviceID) {
3400 return MediaTrackGraphImpl::GetInstance(
3401 aGraphDriverRequested, aWindow->WindowID(), aSampleRate, aOutputDeviceID,
3402 aWindow->EventTargetFor(TaskCategory::Other));
3405 MediaTrackGraph* MediaTrackGraph::CreateNonRealtimeInstance(
3406 TrackRate aSampleRate, nsPIDOMWindowInner* aWindow) {
3407 MOZ_ASSERT(NS_IsMainThread(), "Main thread only");
3409 nsISerialEventTarget* mainThread = GetMainThreadSerialEventTarget();
3410 // aWindow can be null when the document is being unlinked, so this works when
3411 // with a generic main thread if that's the case.
3412 if (aWindow) {
3413 mainThread =
3414 aWindow->AsGlobal()->AbstractMainThreadFor(TaskCategory::Other);
3417 // Offline graphs have 0 output channel count: they write the output to a
3418 // buffer, not an audio output track.
3419 MediaTrackGraphImpl* graph =
3420 new MediaTrackGraphImpl(OFFLINE_THREAD_DRIVER, DIRECT_DRIVER, aSampleRate,
3421 0, DEFAULT_OUTPUT_DEVICE, mainThread);
3423 LOG(LogLevel::Debug, ("Starting up Offline MediaTrackGraph %p", graph));
3425 return graph;
3428 void MediaTrackGraph::ForceShutDown() {
3429 MOZ_ASSERT(NS_IsMainThread(), "Main thread only");
3431 MediaTrackGraphImpl* graph = static_cast<MediaTrackGraphImpl*>(this);
3433 graph->ForceShutDown();
3436 NS_IMPL_ISUPPORTS(MediaTrackGraphImpl, nsIMemoryReporter, nsIThreadObserver,
3437 nsITimerCallback, nsINamed)
3439 NS_IMETHODIMP
3440 MediaTrackGraphImpl::CollectReports(nsIHandleReportCallback* aHandleReport,
3441 nsISupports* aData, bool aAnonymize) {
3442 MOZ_ASSERT(NS_IsMainThread());
3443 if (mMainThreadTrackCount == 0) {
3444 // No tracks to report.
3445 FinishCollectReports(aHandleReport, aData, nsTArray<AudioNodeSizes>());
3446 return NS_OK;
3449 class Message final : public ControlMessage {
3450 public:
3451 Message(MediaTrackGraphImpl* aGraph, nsIHandleReportCallback* aHandleReport,
3452 nsISupports* aHandlerData)
3453 : ControlMessage(nullptr),
3454 mGraph(aGraph),
3455 mHandleReport(aHandleReport),
3456 mHandlerData(aHandlerData) {}
3457 void Run() override {
3458 TRACE("MTG::CollectSizesForMemoryReport ControlMessage");
3459 mGraph->CollectSizesForMemoryReport(mHandleReport.forget(),
3460 mHandlerData.forget());
3462 void RunDuringShutdown() override {
3463 // Run this message during shutdown too, so that endReports is called.
3464 Run();
3466 MediaTrackGraphImpl* mGraph;
3467 // nsMemoryReporterManager keeps the callback and data alive only if it
3468 // does not time out.
3469 nsCOMPtr<nsIHandleReportCallback> mHandleReport;
3470 nsCOMPtr<nsISupports> mHandlerData;
3473 AppendMessage(MakeUnique<Message>(this, aHandleReport, aData));
3475 return NS_OK;
3478 void MediaTrackGraphImpl::CollectSizesForMemoryReport(
3479 already_AddRefed<nsIHandleReportCallback> aHandleReport,
3480 already_AddRefed<nsISupports> aHandlerData) {
3481 class FinishCollectRunnable final : public Runnable {
3482 public:
3483 explicit FinishCollectRunnable(
3484 already_AddRefed<nsIHandleReportCallback> aHandleReport,
3485 already_AddRefed<nsISupports> aHandlerData)
3486 : mozilla::Runnable("FinishCollectRunnable"),
3487 mHandleReport(aHandleReport),
3488 mHandlerData(aHandlerData) {}
3490 NS_IMETHOD Run() override {
3491 TRACE("MTG::FinishCollectReports ControlMessage");
3492 MediaTrackGraphImpl::FinishCollectReports(mHandleReport, mHandlerData,
3493 std::move(mAudioTrackSizes));
3494 return NS_OK;
3497 nsTArray<AudioNodeSizes> mAudioTrackSizes;
3499 private:
3500 ~FinishCollectRunnable() = default;
3502 // Avoiding nsCOMPtr because NSCAP_ASSERT_NO_QUERY_NEEDED in its
3503 // constructor modifies the ref-count, which cannot be done off main
3504 // thread.
3505 RefPtr<nsIHandleReportCallback> mHandleReport;
3506 RefPtr<nsISupports> mHandlerData;
3509 RefPtr<FinishCollectRunnable> runnable = new FinishCollectRunnable(
3510 std::move(aHandleReport), std::move(aHandlerData));
3512 auto audioTrackSizes = &runnable->mAudioTrackSizes;
3514 for (MediaTrack* t : AllTracks()) {
3515 AudioNodeTrack* track = t->AsAudioNodeTrack();
3516 if (track) {
3517 AudioNodeSizes* usage = audioTrackSizes->AppendElement();
3518 track->SizeOfAudioNodesIncludingThis(MallocSizeOf, *usage);
3522 mMainThread->Dispatch(runnable.forget());
3525 void MediaTrackGraphImpl::FinishCollectReports(
3526 nsIHandleReportCallback* aHandleReport, nsISupports* aData,
3527 const nsTArray<AudioNodeSizes>& aAudioTrackSizes) {
3528 MOZ_ASSERT(NS_IsMainThread());
3530 nsCOMPtr<nsIMemoryReporterManager> manager =
3531 do_GetService("@mozilla.org/memory-reporter-manager;1");
3533 if (!manager) return;
3535 #define REPORT(_path, _amount, _desc) \
3536 aHandleReport->Callback(""_ns, _path, KIND_HEAP, UNITS_BYTES, _amount, \
3537 nsLiteralCString(_desc), aData);
3539 for (size_t i = 0; i < aAudioTrackSizes.Length(); i++) {
3540 const AudioNodeSizes& usage = aAudioTrackSizes[i];
3541 const char* const nodeType =
3542 usage.mNodeType ? usage.mNodeType : "<unknown>";
3544 nsPrintfCString enginePath("explicit/webaudio/audio-node/%s/engine-objects",
3545 nodeType);
3546 REPORT(enginePath, usage.mEngine,
3547 "Memory used by AudioNode engine objects (Web Audio).");
3549 nsPrintfCString trackPath("explicit/webaudio/audio-node/%s/track-objects",
3550 nodeType);
3551 REPORT(trackPath, usage.mTrack,
3552 "Memory used by AudioNode track objects (Web Audio).");
3555 size_t hrtfLoaders = WebCore::HRTFDatabaseLoader::sizeOfLoaders(MallocSizeOf);
3556 if (hrtfLoaders) {
3557 REPORT(nsLiteralCString(
3558 "explicit/webaudio/audio-node/PannerNode/hrtf-databases"),
3559 hrtfLoaders, "Memory used by PannerNode databases (Web Audio).");
3562 #undef REPORT
3564 manager->EndReport();
3567 SourceMediaTrack* MediaTrackGraph::CreateSourceTrack(MediaSegment::Type aType) {
3568 SourceMediaTrack* track = new SourceMediaTrack(aType, GraphRate());
3569 AddTrack(track);
3570 return track;
3573 ProcessedMediaTrack* MediaTrackGraph::CreateForwardedInputTrack(
3574 MediaSegment::Type aType) {
3575 ForwardedInputTrack* track = new ForwardedInputTrack(GraphRate(), aType);
3576 AddTrack(track);
3577 return track;
3580 AudioCaptureTrack* MediaTrackGraph::CreateAudioCaptureTrack() {
3581 AudioCaptureTrack* track = new AudioCaptureTrack(GraphRate());
3582 AddTrack(track);
3583 return track;
3586 CrossGraphTransmitter* MediaTrackGraph::CreateCrossGraphTransmitter(
3587 CrossGraphReceiver* aReceiver) {
3588 CrossGraphTransmitter* track =
3589 new CrossGraphTransmitter(GraphRate(), aReceiver);
3590 AddTrack(track);
3591 return track;
3594 CrossGraphReceiver* MediaTrackGraph::CreateCrossGraphReceiver(
3595 TrackRate aTransmitterRate) {
3596 CrossGraphReceiver* track =
3597 new CrossGraphReceiver(GraphRate(), aTransmitterRate);
3598 AddTrack(track);
3599 return track;
3602 void MediaTrackGraph::AddTrack(MediaTrack* aTrack) {
3603 MediaTrackGraphImpl* graph = static_cast<MediaTrackGraphImpl*>(this);
3604 #ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
3605 if (graph->mRealtime) {
3606 bool found = false;
3607 for (const auto& currentGraph : gGraphs.Values()) {
3608 if (currentGraph == graph) {
3609 found = true;
3610 break;
3613 MOZ_DIAGNOSTIC_ASSERT(found, "Graph must not be shutting down");
3615 #endif
3616 NS_ADDREF(aTrack);
3617 aTrack->SetGraphImpl(graph);
3618 ++graph->mMainThreadTrackCount;
3619 graph->AppendMessage(MakeUnique<CreateMessage>(aTrack));
3622 void MediaTrackGraphImpl::RemoveTrack(MediaTrack* aTrack) {
3623 MOZ_ASSERT(NS_IsMainThread());
3624 MOZ_DIAGNOSTIC_ASSERT(mMainThreadTrackCount > 0);
3625 if (--mMainThreadTrackCount == 0) {
3626 LOG(LogLevel::Info, ("MediaTrackGraph %p, last track %p removed from "
3627 "main thread. Graph will shut down.",
3628 this, aTrack));
3629 // Find the graph in the hash table and remove it.
3630 for (auto iter = gGraphs.Iter(); !iter.Done(); iter.Next()) {
3631 if (iter.UserData() == this) {
3632 iter.Remove();
3633 break;
3636 // The graph thread will shut itself down soon, but won't be able to do
3637 // that if JS continues to run.
3638 InterruptJS();
3642 auto MediaTrackGraph::NotifyWhenDeviceStarted(MediaTrack* aTrack)
3643 -> RefPtr<GraphStartedPromise> {
3644 MOZ_ASSERT(NS_IsMainThread());
3645 MozPromiseHolder<GraphStartedPromise> h;
3646 RefPtr<GraphStartedPromise> p = h.Ensure(__func__);
3647 aTrack->GraphImpl()->NotifyWhenGraphStarted(aTrack, std::move(h));
3648 return p;
3651 void MediaTrackGraphImpl::NotifyWhenGraphStarted(
3652 RefPtr<MediaTrack> aTrack,
3653 MozPromiseHolder<GraphStartedPromise>&& aHolder) {
3654 class GraphStartedNotificationControlMessage : public ControlMessage {
3655 RefPtr<MediaTrack> mMediaTrack;
3656 MozPromiseHolder<GraphStartedPromise> mHolder;
3658 public:
3659 GraphStartedNotificationControlMessage(
3660 RefPtr<MediaTrack> aTrack,
3661 MozPromiseHolder<GraphStartedPromise>&& aHolder)
3662 : ControlMessage(nullptr),
3663 mMediaTrack(std::move(aTrack)),
3664 mHolder(std::move(aHolder)) {}
3665 void Run() override {
3666 TRACE("MTG::GraphStartedNotificationControlMessage ControlMessage");
3667 // This runs on the graph thread, so when this runs, and the current
3668 // driver is an AudioCallbackDriver, we know the audio hardware is
3669 // started. If not, we are going to switch soon, keep reposting this
3670 // ControlMessage.
3671 MediaTrackGraphImpl* graphImpl = mMediaTrack->GraphImpl();
3672 if (graphImpl->CurrentDriver()->AsAudioCallbackDriver() &&
3673 graphImpl->CurrentDriver()->ThreadRunning() &&
3674 !graphImpl->CurrentDriver()->AsAudioCallbackDriver()->OnFallback()) {
3675 // Avoid Resolve's locking on the graph thread by doing it on main.
3676 graphImpl->Dispatch(NS_NewRunnableFunction(
3677 "MediaTrackGraphImpl::NotifyWhenGraphStarted::Resolver",
3678 [holder = std::move(mHolder)]() mutable {
3679 holder.Resolve(true, __func__);
3680 }));
3681 } else {
3682 graphImpl->DispatchToMainThreadStableState(
3683 NewRunnableMethod<
3684 StoreCopyPassByRRef<RefPtr<MediaTrack>>,
3685 StoreCopyPassByRRef<MozPromiseHolder<GraphStartedPromise>>>(
3686 "MediaTrackGraphImpl::NotifyWhenGraphStarted", graphImpl,
3687 &MediaTrackGraphImpl::NotifyWhenGraphStarted,
3688 std::move(mMediaTrack), std::move(mHolder)));
3691 void RunDuringShutdown() override {
3692 mHolder.Reject(NS_ERROR_ILLEGAL_DURING_SHUTDOWN, __func__);
3696 if (aTrack->IsDestroyed()) {
3697 aHolder.Reject(NS_ERROR_NOT_AVAILABLE, __func__);
3698 return;
3701 MediaTrackGraphImpl* graph = aTrack->GraphImpl();
3702 graph->AppendMessage(MakeUnique<GraphStartedNotificationControlMessage>(
3703 std::move(aTrack), std::move(aHolder)));
3706 class AudioContextOperationControlMessage : public ControlMessage {
3707 using AudioContextOperationPromise =
3708 MediaTrackGraph::AudioContextOperationPromise;
3710 public:
3711 AudioContextOperationControlMessage(
3712 MediaTrack* aDestinationTrack, nsTArray<RefPtr<MediaTrack>> aTracks,
3713 AudioContextOperation aOperation,
3714 MozPromiseHolder<AudioContextOperationPromise>&& aHolder)
3715 : ControlMessage(aDestinationTrack),
3716 mTracks(std::move(aTracks)),
3717 mAudioContextOperation(aOperation),
3718 mHolder(std::move(aHolder)) {}
3719 void Run() override {
3720 TRACE_COMMENT("MTG::ApplyAudioContextOperationImpl ControlMessage",
3721 kAudioContextOptionsStrings[static_cast<uint8_t>(
3722 mAudioContextOperation)]);
3723 mTrack->GraphImpl()->ApplyAudioContextOperationImpl(this);
3725 void RunDuringShutdown() override {
3726 MOZ_ASSERT(mAudioContextOperation == AudioContextOperation::Close,
3727 "We should be reviving the graph?");
3728 mHolder.Reject(false, __func__);
3731 nsTArray<RefPtr<MediaTrack>> mTracks;
3732 AudioContextOperation mAudioContextOperation;
3733 MozPromiseHolder<AudioContextOperationPromise> mHolder;
3736 void MediaTrackGraphImpl::ApplyAudioContextOperationImpl(
3737 AudioContextOperationControlMessage* aMessage) {
3738 MOZ_ASSERT(OnGraphThread());
3739 AudioContextState state;
3740 switch (aMessage->mAudioContextOperation) {
3741 // Suspend and Close operations may be performed immediately because no
3742 // specific kind of GraphDriver is required. CheckDriver() will schedule
3743 // a change to a SystemCallbackDriver if all tracks are suspended.
3744 case AudioContextOperation::Suspend:
3745 state = AudioContextState::Suspended;
3746 break;
3747 case AudioContextOperation::Close:
3748 state = AudioContextState::Closed;
3749 break;
3750 case AudioContextOperation::Resume:
3751 // Resume operations require an AudioCallbackDriver. CheckDriver() will
3752 // schedule an AudioCallbackDriver if necessary and process pending
3753 // operations if and when an AudioCallbackDriver is running.
3754 mPendingResumeOperations.EmplaceBack(aMessage);
3755 return;
3757 // First resolve any pending Resume promises for the same AudioContext so as
3758 // to resolve its associated promises in the same order as they were
3759 // created. These Resume operations are considered complete and immediately
3760 // canceled by the Suspend or Close.
3761 MediaTrack* destinationTrack = aMessage->GetTrack();
3762 bool shrinking = false;
3763 auto moveDest = mPendingResumeOperations.begin();
3764 for (PendingResumeOperation& op : mPendingResumeOperations) {
3765 if (op.DestinationTrack() == destinationTrack) {
3766 op.Apply(this);
3767 shrinking = true;
3768 continue;
3770 if (shrinking) { // Fill-in gaps in the array.
3771 *moveDest = std::move(op);
3773 ++moveDest;
3775 mPendingResumeOperations.TruncateLength(moveDest -
3776 mPendingResumeOperations.begin());
3778 for (MediaTrack* track : aMessage->mTracks) {
3779 track->IncrementSuspendCount();
3781 // Resolve after main thread state is up to date with completed processing.
3782 DispatchToMainThreadStableState(NS_NewRunnableFunction(
3783 "MediaTrackGraphImpl::ApplyAudioContextOperationImpl",
3784 [holder = std::move(aMessage->mHolder), state]() mutable {
3785 holder.Resolve(state, __func__);
3786 }));
3789 MediaTrackGraphImpl::PendingResumeOperation::PendingResumeOperation(
3790 AudioContextOperationControlMessage* aMessage)
3791 : mDestinationTrack(aMessage->GetTrack()),
3792 mTracks(std::move(aMessage->mTracks)),
3793 mHolder(std::move(aMessage->mHolder)) {
3794 MOZ_ASSERT(aMessage->mAudioContextOperation == AudioContextOperation::Resume);
3797 void MediaTrackGraphImpl::PendingResumeOperation::Apply(
3798 MediaTrackGraphImpl* aGraph) {
3799 MOZ_ASSERT(aGraph->OnGraphThread());
3800 for (MediaTrack* track : mTracks) {
3801 track->DecrementSuspendCount();
3803 // The graph is provided through the parameter so that it is available even
3804 // when the track is destroyed.
3805 aGraph->DispatchToMainThreadStableState(NS_NewRunnableFunction(
3806 "PendingResumeOperation::Apply", [holder = std::move(mHolder)]() mutable {
3807 holder.Resolve(AudioContextState::Running, __func__);
3808 }));
3811 void MediaTrackGraphImpl::PendingResumeOperation::Abort() {
3812 // The graph is shutting down before the operation completed.
3813 MOZ_ASSERT(!mDestinationTrack->GraphImpl() ||
3814 mDestinationTrack->GraphImpl()->LifecycleStateRef() ==
3815 MediaTrackGraphImpl::LIFECYCLE_WAITING_FOR_THREAD_SHUTDOWN);
3816 mHolder.Reject(false, __func__);
3819 auto MediaTrackGraph::ApplyAudioContextOperation(
3820 MediaTrack* aDestinationTrack, nsTArray<RefPtr<MediaTrack>> aTracks,
3821 AudioContextOperation aOperation) -> RefPtr<AudioContextOperationPromise> {
3822 MozPromiseHolder<AudioContextOperationPromise> holder;
3823 RefPtr<AudioContextOperationPromise> p = holder.Ensure(__func__);
3824 MediaTrackGraphImpl* graphImpl = static_cast<MediaTrackGraphImpl*>(this);
3825 graphImpl->AppendMessage(MakeUnique<AudioContextOperationControlMessage>(
3826 aDestinationTrack, std::move(aTracks), aOperation, std::move(holder)));
3827 return p;
3830 uint32_t MediaTrackGraphImpl::AudioOutputChannelCount() const {
3831 MOZ_ASSERT(OnGraphThread());
3832 // The audio output channel count for a graph is the maximum of the output
3833 // channel count of all the tracks that are in mAudioOutputs, or the max audio
3834 // output channel count the machine can do, whichever is smaller.
3835 uint32_t channelCount = 0;
3836 for (auto& tkv : mAudioOutputs) {
3837 channelCount = std::max(channelCount, tkv.mTrack->NumberOfChannels());
3839 channelCount = std::min(channelCount, mMaxOutputChannelCount);
3840 if (channelCount) {
3841 return channelCount;
3842 } else {
3843 if (CurrentDriver()->AsAudioCallbackDriver()) {
3844 return CurrentDriver()->AsAudioCallbackDriver()->OutputChannelCount();
3846 return 2;
3850 double MediaTrackGraph::AudioOutputLatency() {
3851 return static_cast<MediaTrackGraphImpl*>(this)->AudioOutputLatency();
3854 double MediaTrackGraphImpl::AudioOutputLatency() {
3855 MOZ_ASSERT(NS_IsMainThread());
3856 if (mAudioOutputLatency != 0.0) {
3857 return mAudioOutputLatency;
3859 MonitorAutoLock lock(mMonitor);
3860 if (CurrentDriver()->AsAudioCallbackDriver()) {
3861 mAudioOutputLatency = CurrentDriver()
3862 ->AsAudioCallbackDriver()
3863 ->AudioOutputLatency()
3864 .ToSeconds();
3865 } else {
3866 // Failure mode: return 0.0 if running on a normal thread.
3867 mAudioOutputLatency = 0.0;
3870 return mAudioOutputLatency;
3873 bool MediaTrackGraph::IsNonRealtime() const {
3874 return !static_cast<const MediaTrackGraphImpl*>(this)->mRealtime;
3877 void MediaTrackGraph::StartNonRealtimeProcessing(uint32_t aTicksToProcess) {
3878 MOZ_ASSERT(NS_IsMainThread(), "main thread only");
3880 MediaTrackGraphImpl* graph = static_cast<MediaTrackGraphImpl*>(this);
3881 NS_ASSERTION(!graph->mRealtime, "non-realtime only");
3883 class Message : public ControlMessage {
3884 public:
3885 explicit Message(MediaTrackGraphImpl* aGraph, uint32_t aTicksToProcess)
3886 : ControlMessage(nullptr),
3887 mGraph(aGraph),
3888 mTicksToProcess(aTicksToProcess) {}
3889 void Run() override {
3890 TRACE("MTG::StartNonRealtimeProcessing ControlMessage");
3891 MOZ_ASSERT(mGraph->mEndTime == 0,
3892 "StartNonRealtimeProcessing should be called only once");
3893 mGraph->mEndTime = mGraph->RoundUpToEndOfAudioBlock(
3894 mGraph->mStateComputedTime + mTicksToProcess);
3896 // The graph owns this message.
3897 MediaTrackGraphImpl* MOZ_NON_OWNING_REF mGraph;
3898 uint32_t mTicksToProcess;
3901 graph->AppendMessage(MakeUnique<Message>(graph, aTicksToProcess));
3904 void MediaTrackGraphImpl::InterruptJS() {
3905 MonitorAutoLock lock(mMonitor);
3906 mInterruptJSCalled = true;
3907 if (mJSContext) {
3908 JS_RequestInterruptCallback(mJSContext);
3912 static bool InterruptCallback(JSContext* aCx) {
3913 // Interrupt future calls also.
3914 JS_RequestInterruptCallback(aCx);
3915 // Stop execution.
3916 return false;
3919 void MediaTrackGraph::NotifyJSContext(JSContext* aCx) {
3920 MOZ_ASSERT(OnGraphThread());
3921 MOZ_ASSERT(aCx);
3923 auto* impl = static_cast<MediaTrackGraphImpl*>(this);
3924 MonitorAutoLock lock(impl->mMonitor);
3925 if (impl->mJSContext) {
3926 MOZ_ASSERT(impl->mJSContext == aCx);
3927 return;
3929 JS_AddInterruptCallback(aCx, InterruptCallback);
3930 impl->mJSContext = aCx;
3931 if (impl->mInterruptJSCalled) {
3932 JS_RequestInterruptCallback(aCx);
3936 void ProcessedMediaTrack::AddInput(MediaInputPort* aPort) {
3937 MediaTrack* t = aPort->GetSource();
3938 if (!t->IsSuspended()) {
3939 mInputs.AppendElement(aPort);
3940 } else {
3941 mSuspendedInputs.AppendElement(aPort);
3943 GraphImpl()->SetTrackOrderDirty();
3946 void ProcessedMediaTrack::InputSuspended(MediaInputPort* aPort) {
3947 GraphImpl()->AssertOnGraphThreadOrNotRunning();
3948 mInputs.RemoveElement(aPort);
3949 mSuspendedInputs.AppendElement(aPort);
3950 GraphImpl()->SetTrackOrderDirty();
3953 void ProcessedMediaTrack::InputResumed(MediaInputPort* aPort) {
3954 GraphImpl()->AssertOnGraphThreadOrNotRunning();
3955 mSuspendedInputs.RemoveElement(aPort);
3956 mInputs.AppendElement(aPort);
3957 GraphImpl()->SetTrackOrderDirty();
3960 void MediaTrackGraphImpl::SwitchAtNextIteration(GraphDriver* aNextDriver) {
3961 MOZ_ASSERT(OnGraphThread());
3962 LOG(LogLevel::Debug, ("%p: Switching to new driver: %p", this, aNextDriver));
3963 if (GraphDriver* nextDriver = NextDriver()) {
3964 if (nextDriver != CurrentDriver()) {
3965 LOG(LogLevel::Debug,
3966 ("%p: Discarding previous next driver: %p", this, nextDriver));
3969 mNextDriver = aNextDriver;
3972 void MediaTrackGraph::RegisterCaptureTrackForWindow(
3973 uint64_t aWindowId, ProcessedMediaTrack* aCaptureTrack) {
3974 MOZ_ASSERT(NS_IsMainThread());
3975 MediaTrackGraphImpl* graphImpl = static_cast<MediaTrackGraphImpl*>(this);
3976 graphImpl->RegisterCaptureTrackForWindow(aWindowId, aCaptureTrack);
3979 void MediaTrackGraphImpl::RegisterCaptureTrackForWindow(
3980 uint64_t aWindowId, ProcessedMediaTrack* aCaptureTrack) {
3981 MOZ_ASSERT(NS_IsMainThread());
3982 WindowAndTrack winAndTrack;
3983 winAndTrack.mWindowId = aWindowId;
3984 winAndTrack.mCaptureTrackSink = aCaptureTrack;
3985 mWindowCaptureTracks.AppendElement(winAndTrack);
3988 void MediaTrackGraph::UnregisterCaptureTrackForWindow(uint64_t aWindowId) {
3989 MOZ_ASSERT(NS_IsMainThread());
3990 MediaTrackGraphImpl* graphImpl = static_cast<MediaTrackGraphImpl*>(this);
3991 graphImpl->UnregisterCaptureTrackForWindow(aWindowId);
3994 void MediaTrackGraphImpl::UnregisterCaptureTrackForWindow(uint64_t aWindowId) {
3995 MOZ_ASSERT(NS_IsMainThread());
3996 mWindowCaptureTracks.RemoveElementsBy(
3997 [aWindowId](const auto& track) { return track.mWindowId == aWindowId; });
4000 already_AddRefed<MediaInputPort> MediaTrackGraph::ConnectToCaptureTrack(
4001 uint64_t aWindowId, MediaTrack* aMediaTrack) {
4002 return aMediaTrack->GraphImpl()->ConnectToCaptureTrack(aWindowId,
4003 aMediaTrack);
4006 already_AddRefed<MediaInputPort> MediaTrackGraphImpl::ConnectToCaptureTrack(
4007 uint64_t aWindowId, MediaTrack* aMediaTrack) {
4008 MOZ_ASSERT(NS_IsMainThread());
4009 for (uint32_t i = 0; i < mWindowCaptureTracks.Length(); i++) {
4010 if (mWindowCaptureTracks[i].mWindowId == aWindowId) {
4011 ProcessedMediaTrack* sink = mWindowCaptureTracks[i].mCaptureTrackSink;
4012 return sink->AllocateInputPort(aMediaTrack);
4015 return nullptr;
4018 void MediaTrackGraph::DispatchToMainThreadStableState(
4019 already_AddRefed<nsIRunnable> aRunnable) {
4020 AssertOnGraphThreadOrNotRunning();
4021 static_cast<MediaTrackGraphImpl*>(this)
4022 ->mPendingUpdateRunnables.AppendElement(std::move(aRunnable));
4025 Watchable<mozilla::GraphTime>& MediaTrackGraphImpl::CurrentTime() {
4026 MOZ_ASSERT(NS_IsMainThread());
4027 return mMainThreadGraphTime;
4030 GraphTime MediaTrackGraph::ProcessedTime() const {
4031 AssertOnGraphThreadOrNotRunning();
4032 return static_cast<const MediaTrackGraphImpl*>(this)->mProcessedTime;
4035 uint32_t MediaTrackGraphImpl::AudioInputChannelCount(
4036 CubebUtils::AudioDeviceID aID) {
4037 MOZ_ASSERT(OnGraphThreadOrNotRunning());
4038 DeviceInputTrack* t =
4039 mDeviceInputTrackManagerGraphThread.GetDeviceInputTrack(aID);
4040 return t ? t->MaxRequestedInputChannels() : 0;
4043 AudioInputType MediaTrackGraphImpl::AudioInputDevicePreference(
4044 CubebUtils::AudioDeviceID aID) {
4045 MOZ_ASSERT(OnGraphThreadOrNotRunning());
4046 DeviceInputTrack* t =
4047 mDeviceInputTrackManagerGraphThread.GetDeviceInputTrack(aID);
4048 return t && t->HasVoiceInput() ? AudioInputType::Voice
4049 : AudioInputType::Unknown;
4052 void MediaTrackGraphImpl::SetNewNativeInput() {
4053 MOZ_ASSERT(NS_IsMainThread());
4054 MOZ_ASSERT(!mDeviceInputTrackManagerMainThread.GetNativeInputTrack());
4056 LOG(LogLevel::Debug, ("%p SetNewNativeInput", this));
4058 NonNativeInputTrack* track =
4059 mDeviceInputTrackManagerMainThread.GetFirstNonNativeInputTrack();
4060 if (!track) {
4061 LOG(LogLevel::Debug, ("%p No other devices opened. Do nothing", this));
4062 return;
4065 const CubebUtils::AudioDeviceID deviceId = track->mDeviceId;
4066 const PrincipalHandle principal = track->mPrincipalHandle;
4068 LOG(LogLevel::Debug,
4069 ("%p Select device %p as the new native input device", this, deviceId));
4071 struct TrackListener {
4072 DeviceInputConsumerTrack* track;
4073 // Keep its reference so it won't be dropped when after
4074 // DisconnectDeviceInput().
4075 RefPtr<AudioDataListener> listener;
4077 nsTArray<TrackListener> pairs;
4079 for (const auto& t : track->GetConsumerTracks()) {
4080 pairs.AppendElement(
4081 TrackListener{t.get(), t->GetAudioDataListener().get()});
4084 for (TrackListener& pair : pairs) {
4085 pair.track->DisconnectDeviceInput();
4088 for (TrackListener& pair : pairs) {
4089 pair.track->ConnectDeviceInput(deviceId, pair.listener.get(), principal);
4090 LOG(LogLevel::Debug,
4091 ("%p: Reinitialize AudioProcessingTrack %p for device %p", this,
4092 pair.track, deviceId));
4095 LOG(LogLevel::Debug,
4096 ("%p Native input device is set to device %p now", this, deviceId));
4098 MOZ_ASSERT(mDeviceInputTrackManagerMainThread.GetNativeInputTrack());
4101 // nsIThreadObserver methods
4103 NS_IMETHODIMP
4104 MediaTrackGraphImpl::OnDispatchedEvent() {
4105 MonitorAutoLock lock(mMonitor);
4106 EnsureNextIteration();
4107 return NS_OK;
4110 NS_IMETHODIMP
4111 MediaTrackGraphImpl::OnProcessNextEvent(nsIThreadInternal*, bool) {
4112 return NS_OK;
4115 NS_IMETHODIMP
4116 MediaTrackGraphImpl::AfterProcessNextEvent(nsIThreadInternal*, bool) {
4117 return NS_OK;
4119 } // namespace mozilla