Bug 1492479 - Move MediaStreamError out of MediaManager. r=jya
authorJan-Ivar Bruaroey <jib@mozilla.com>
Fri, 30 Nov 2018 05:15:54 +0000
changeset 505359 99426a6a77bf8ddfb334ed052eb18e2a9bc48122
parent 505358 8a78c4c56019d4891f24998613f80de5f894f340
child 505360 1894e5ca0523dcf9b19985df4b8d1ad8659623ef
push id10290
push userffxbld-merge
push dateMon, 03 Dec 2018 16:23:23 +0000
treeherdermozilla-beta@700bed2445e6 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersjya
bugs1492479
milestone65.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1492479 - Move MediaStreamError out of MediaManager. r=jya Differential Revision: https://phabricator.services.mozilla.com/D13175
dom/base/Navigator.cpp
dom/media/MediaDevices.cpp
dom/media/MediaManager.cpp
dom/media/MediaManager.h
dom/media/MediaStreamError.h
dom/media/MediaStreamTrack.cpp
dom/media/MediaStreamTrack.h
dom/media/webspeech/recognition/SpeechRecognition.cpp
media/webrtc/signaling/src/peerconnection/RemoteTrackSource.h
--- a/dom/base/Navigator.cpp
+++ b/dom/base/Navigator.cpp
@@ -1223,23 +1223,24 @@ Navigator::MozGetUserMedia(const MediaSt
     [weakWindow, onsuccess = std::move(onsuccess)](const RefPtr<DOMMediaStream>& aStream) {
       nsCOMPtr<nsPIDOMWindowInner> window = do_QueryReferent(weakWindow);
       if (!window || !window->GetOuterWindow() ||
           window->GetOuterWindow()->GetCurrentInnerWindow() != window) {
         return; // Leave Promise pending after navigation by design.
       }
       MediaManager::CallOnSuccess(&onsuccess, *aStream);
     },
-    [weakWindow, onerror = std::move(onerror)](const RefPtr<dom::MediaStreamError>& aError) {
+    [weakWindow, onerror = std::move(onerror)](const RefPtr<MediaMgrError>& aError) {
       nsCOMPtr<nsPIDOMWindowInner> window = do_QueryReferent(weakWindow);
       if (!window || !window->GetOuterWindow() ||
           window->GetOuterWindow()->GetCurrentInnerWindow() != window) {
         return; // Leave Promise pending after navigation by design.
       }
-      MediaManager::CallOnError(&onerror, *aError);
+      auto error = MakeRefPtr<MediaStreamError>(window, *aError);
+      MediaManager::CallOnError(&onerror, *error);
     }
   );
 }
 
 void
 Navigator::MozGetUserMediaDevices(const MediaStreamConstraints& aConstraints,
                                   MozGetUserMediaDevicesSuccessCallback& aOnSuccess,
                                   NavigatorUserMediaErrorCallback& aOnError,
--- a/dom/media/MediaDevices.cpp
+++ b/dom/media/MediaDevices.cpp
@@ -62,26 +62,27 @@ already_AddRefed<Promise> MediaDevices::
   if (NS_WARN_IF(aRv.Failed())) {
     return nullptr;
   }
   RefPtr<MediaDevices> self(this);
   MediaManager::Get()
       ->GetUserMedia(GetOwner(), aConstraints, aCallerType)
       ->Then(GetCurrentThreadSerialEventTarget(), __func__,
              [this, self, p](RefPtr<DOMMediaStream>&& aStream) {
-               if (NS_FAILED(CheckInnerWindowCorrectness())) {
+               if (!GetWindowIfCurrent()) {
                  return;  // Leave Promise pending after navigation by design.
                }
                p->MaybeResolve(std::move(aStream));
              },
-             [this, self, p](const RefPtr<MediaStreamError>& error) {
-               if (NS_FAILED(CheckInnerWindowCorrectness())) {
+             [this, self, p](const RefPtr<MediaMgrError>& error) {
+               nsPIDOMWindowInner* window = GetWindowIfCurrent();
+               if (!window) {
                  return;  // Leave Promise pending after navigation by design.
                }
-               p->MaybeReject(error);
+               p->MaybeReject(MakeRefPtr<MediaStreamError>(window, *error));
              });
   return p.forget();
 }
 
 already_AddRefed<Promise> MediaDevices::EnumerateDevices(CallerType aCallerType,
                                                          ErrorResult& aRv) {
   MOZ_ASSERT(NS_IsMainThread());
   RefPtr<Promise> p = Promise::Create(GetParentObject(), aRv);
@@ -89,20 +90,21 @@ already_AddRefed<Promise> MediaDevices::
     return nullptr;
   }
   RefPtr<MediaDevices> self(this);
   MediaManager::Get()
       ->EnumerateDevices(GetOwner(), aCallerType)
       ->Then(GetCurrentThreadSerialEventTarget(), __func__,
              [this, self,
               p](RefPtr<MediaManager::MediaDeviceSetRefCnt>&& aDevices) {
-               if (NS_FAILED(CheckInnerWindowCorrectness())) {
+               nsPIDOMWindowInner* window = GetWindowIfCurrent();
+               if (!window) {
                  return;  // Leave Promise pending after navigation by design.
                }
-               auto windowId = GetOwner()->WindowID();
+               auto windowId = window->WindowID();
                nsTArray<RefPtr<MediaDeviceInfo>> infos;
                for (auto& device : *aDevices) {
                  MOZ_ASSERT(device->mKind == dom::MediaDeviceKind::Audioinput ||
                             device->mKind == dom::MediaDeviceKind::Videoinput ||
                             device->mKind == dom::MediaDeviceKind::Audiooutput);
                  // Include name only if page currently has a gUM stream active
                  // or persistent permissions (audio or video) have been granted
                  nsString label;
@@ -112,21 +114,22 @@ already_AddRefed<Promise> MediaDevices::
                                           false)) {
                    label = device->mName;
                  }
                  infos.AppendElement(MakeRefPtr<MediaDeviceInfo>(
                      device->mID, device->mKind, label));
                }
                p->MaybeResolve(std::move(infos));
              },
-             [this, self, p](const RefPtr<MediaStreamError>& error) {
-               if (NS_FAILED(CheckInnerWindowCorrectness())) {
+             [this, self, p](const RefPtr<MediaMgrError>& error) {
+               nsPIDOMWindowInner* window = GetWindowIfCurrent();
+               if (!window) {
                  return;  // Leave Promise pending after navigation by design.
                }
-               p->MaybeReject(error);
+               p->MaybeReject(MakeRefPtr<MediaStreamError>(window, *error));
              });
   return p.forget();
 }
 
 NS_IMPL_ADDREF_INHERITED(MediaDevices, DOMEventTargetHelper)
 NS_IMPL_RELEASE_INHERITED(MediaDevices, DOMEventTargetHelper)
 NS_INTERFACE_MAP_BEGIN(MediaDevices)
   NS_INTERFACE_MAP_ENTRY(MediaDevices)
--- a/dom/media/MediaManager.cpp
+++ b/dom/media/MediaManager.cpp
@@ -446,18 +446,17 @@ class SourceListener : public SupportsWe
 
   bool CapturingVideo() const;
 
   bool CapturingAudio() const;
 
   CaptureState CapturingSource(MediaSourceEnum aSource) const;
 
   RefPtr<SourceListenerPromise> ApplyConstraintsToTrack(
-      nsPIDOMWindowInner* aWindow, TrackID aTrackID,
-      const dom::MediaTrackConstraints& aConstraints,
+      TrackID aTrackID, const dom::MediaTrackConstraints& aConstraints,
       dom::CallerType aCallerType);
 
   PrincipalHandle GetPrincipalHandle() const;
 
  private:
   virtual ~SourceListener() = default;
 
   /**
@@ -1097,26 +1096,19 @@ class GetUserMediaStreamRunnable : publi
         mWindowID(aWindowID),
         mWindowListener(aWindowListener),
         mSourceListener(aSourceListener),
         mPrincipalInfo(aPrincipalInfo),
         mPeerIdentity(aPeerIdentity),
         mManager(MediaManager::GetInstance()) {}
 
   ~GetUserMediaStreamRunnable() {
-    if (!mHolder.IsEmpty()) {
-      nsGlobalWindowInner* globalWindow =
-          nsGlobalWindowInner::GetInnerWindowWithId(mWindowID);
-      nsPIDOMWindowInner* window =
-          globalWindow ? globalWindow->AsInner() : nullptr;
-
-      mHolder.Reject(MakeRefPtr<MediaStreamError>(
-                         window, MediaStreamError::Name::AbortError),
-                     __func__);
-    }
+    mHolder.RejectIfExists(
+        MakeRefPtr<MediaMgrError>(MediaMgrError::Name::AbortError),
+        __func__);
   }
 
   class TracksCreatedListener : public MediaStreamTrackListener {
    public:
     TracksCreatedListener(
         MediaManager* aManager,
         MozPromiseHolder<MediaManager::StreamPromise>&& aHolder,
         GetUserMediaWindowListener* aWindowListener, uint64_t aWindowID,
@@ -1127,26 +1119,19 @@ class GetUserMediaStreamRunnable : publi
           mWindowID(aWindowID),
           mGraph(aTrack->GraphImpl()),
           mStream(new nsMainThreadPtrHolder<DOMMediaStream>(
               "TracksCreatedListener::mStream", aStream)),
           mTrack(new nsMainThreadPtrHolder<MediaStreamTrack>(
               "TracksCreatedListener::mTrack", aTrack)) {}
 
     ~TracksCreatedListener() {
-      if (!mHolder.IsEmpty()) {
-        nsGlobalWindowInner* globalWindow =
-            nsGlobalWindowInner::GetInnerWindowWithId(mWindowID);
-        nsPIDOMWindowInner* window =
-            globalWindow ? globalWindow->AsInner() : nullptr;
-
-        mHolder.Reject(MakeRefPtr<MediaStreamError>(
-                           window, MediaMgrError::Name::AbortError),
-                       __func__);
-      }
+      mHolder.RejectIfExists(
+          MakeRefPtr<MediaMgrError>(MediaMgrError::Name::AbortError),
+          __func__);
     }
 
     void NotifyOutput(MediaStreamGraph* aGraph,
                       StreamTime aCurrentTrackTime) override {
       // It's enough to know that one of the tracks have output, as both tracks
       // are guaranteed to be created in the graph at this point.
 
       if (mDispatchedTracksCreated) {
@@ -1260,48 +1245,27 @@ class GetUserMediaStreamRunnable : publi
 
         MediaSourceEnum GetMediaSource() const override { return mSource; }
 
         const PeerIdentity* GetPeerIdentity() const override {
           return mPeerIdentity;
         }
 
         RefPtr<MediaStreamTrackSource::ApplyConstraintsPromise>
-        ApplyConstraints(nsPIDOMWindowInner* aWindow,
-                         const MediaTrackConstraints& aConstraints,
+        ApplyConstraints(const MediaTrackConstraints& aConstraints,
                          dom::CallerType aCallerType) override {
           MOZ_ASSERT(NS_IsMainThread());
           if (sHasShutdown || !mListener) {
             // Track has been stopped, or we are in shutdown. In either case
             // there's no observable outcome, so pretend we succeeded.
             return MediaStreamTrackSource::ApplyConstraintsPromise::
                 CreateAndResolve(false, __func__);
           }
-
-          return mListener
-              ->ApplyConstraintsToTrack(aWindow, mTrackID, aConstraints,
-                                        aCallerType)
-              ->Then(GetMainThreadSerialEventTarget(), __func__,
-                     [](bool) {
-                       return MediaStreamTrackSource::ApplyConstraintsPromise::
-                           CreateAndResolve(false, __func__);
-                     },
-                     [weakWindow = nsWeakPtr(do_GetWeakReference(aWindow))](
-                         RefPtr<MediaMgrError>&& aError)
-                         -> RefPtr<
-                             MediaStreamTrackSource::ApplyConstraintsPromise> {
-                       RefPtr<MediaStreamError> error;
-                       if (weakWindow->IsAlive()) {
-                         nsCOMPtr<nsPIDOMWindowInner> window =
-                             do_QueryReferent(weakWindow);
-                         error = new MediaStreamError(window, *aError);
-                       }
-                       return MediaStreamTrackSource::ApplyConstraintsPromise::
-                           CreateAndReject(error, __func__);
-                     });
+          return mListener->ApplyConstraintsToTrack(mTrackID, aConstraints,
+                                                    aCallerType);
         }
 
         void GetSettings(dom::MediaTrackSettings& aOutSettings) override {
           if (mListener) {
             mListener->GetSettingsFor(mTrackID, aOutSettings);
           }
         }
 
@@ -1378,24 +1342,21 @@ class GetUserMediaStreamRunnable : publi
             GetInvariant(mConstraints.mVideo));
         domStream->AddTrackInternal(track);
       }
     }
 
     if (!domStream || !stream || sHasShutdown) {
       LOG(("Returning error for getUserMedia() - no stream"));
 
-      if (auto* window = nsGlobalWindowInner::GetInnerWindowWithId(mWindowID)) {
-        mHolder.Reject(
-            MakeRefPtr<MediaStreamError>(
-                window->AsInner(), MediaStreamError::Name::AbortError,
-                sHasShutdown ? NS_LITERAL_STRING("In shutdown")
-                             : NS_LITERAL_STRING("No stream.")),
-            __func__);
-      }
+      mHolder.Reject(MakeRefPtr<MediaMgrError>(
+                         MediaMgrError::Name::AbortError,
+                         sHasShutdown ? NS_LITERAL_STRING("In shutdown")
+                                      : NS_LITERAL_STRING("No stream.")),
+                     __func__);
       return NS_OK;
     }
 
     // Activate our source listener. We'll call Start() on the source when we
     // get a callback that the MediaStream has started consuming. The listener
     // is freed when the page is invalidated (on navigation or close).
     mWindowListener->Activate(mSourceListener, stream, mAudioDevice,
                               mVideoDevice);
@@ -1419,36 +1380,31 @@ class GetUserMediaStreamRunnable : publi
           LOG(
               ("GetUserMediaStreamRunnable::Run: starting success callback "
                "following InitializeAsync()"));
           // Initiating and starting devices succeeded.
           track->AddListener(tracksCreatedListener);
           windowListener->ChromeAffectingStateChanged();
           manager->SendPendingGUMRequest();
         },
-        [manager = mManager, windowID = mWindowID, holder = std::move(mHolder)](
-            const RefPtr<MediaMgrError>& error) mutable {
+        [manager = mManager, windowID = mWindowID,
+         holder = std::move(mHolder)](RefPtr<MediaMgrError>&& aError) mutable {
           MOZ_ASSERT(NS_IsMainThread());
           LOG(
               ("GetUserMediaStreamRunnable::Run: starting failure callback "
                "following InitializeAsync()"));
           // Initiating and starting devices failed.
 
           // Only run if the window is still active for our window listener.
           if (!(manager->IsWindowStillActive(windowID))) {
             return;
           }
           // This is safe since we're on main-thread, and the windowlist can
           // only be invalidated from the main-thread (see OnNavigation)
-          if (auto* window =
-                  nsGlobalWindowInner::GetInnerWindowWithId(windowID)) {
-            holder.Reject(
-                MakeRefPtr<MediaStreamError>(window->AsInner(), *error),
-                __func__);
-          }
+          holder.Reject(std::move(aError), __func__);
         });
 
     if (!IsPincipalInfoPrivate(mPrincipalInfo)) {
       // Call GetPrincipalKey again, this time w/persist = true, to promote
       // deviceIds to persistent, in case they're not already. Fire'n'forget.
       media::GetPrincipalKey(mPrincipalInfo, true)
           ->Then(GetCurrentThreadSerialEventTarget(), __func__,
                  [](const PrincipalKeyPromise::ResolveOrRejectValue& aValue) {
@@ -1604,37 +1560,27 @@ class GetUserMediaTask : public Runnable
         mIsChrome(aIsChrome),
         mShouldFocusSource(aShouldFocusSource),
         mDeviceChosen(false),
         mMediaDeviceSet(aMediaDeviceSet),
         mManager(MediaManager::GetInstance()) {}
 
   ~GetUserMediaTask() {
     if (!mHolder.IsEmpty()) {
-      Fail(MediaStreamError::Name::NotAllowedError);
+      Fail(MediaMgrError::Name::NotAllowedError);
     }
   }
 
   void Fail(MediaMgrError::Name aName, const nsString& aMessage = EmptyString(),
             const nsString& aConstraint = EmptyString()) {
     NS_DispatchToMainThread(NS_NewRunnableFunction(
         "GetUserMediaTask::Fail",
-        [aName, aMessage, aConstraint, windowId = mWindowID,
-         windowListener = mWindowListener,
-         holder = std::move(mHolder)]() mutable {
-          auto* globalWindow =
-              nsGlobalWindowInner::GetInnerWindowWithId(windowId);
-          RefPtr<nsPIDOMWindowInner> window =
-              globalWindow ? globalWindow->AsInner() : nullptr;
-          RefPtr<MediaStreamError> error;
-          if (window) {
-            error = new MediaStreamError(window, aName, aMessage, aConstraint);
-          }
-          holder.Reject(error, __func__);
-          return;
+        [aName, aMessage, aConstraint, holder = std::move(mHolder)]() mutable {
+          holder.Reject(MakeRefPtr<MediaMgrError>(aName, aMessage, aConstraint),
+                        __func__);
         }));
     // Do after the above runs, as it checks active window list
     NS_DispatchToMainThread(NewRunnableMethod<RefPtr<SourceListener>>(
         "GetUserMediaWindowListener::Remove", mWindowListener,
         &GetUserMediaWindowListener::Remove, mSourceListener));
   }
 
   NS_IMETHOD
@@ -1722,28 +1668,23 @@ class GetUserMediaTask : public Runnable
     return NS_OK;
   }
 
   nsresult Denied(MediaMgrError::Name aName,
                   const nsString& aMessage = EmptyString()) {
     // We add a disabled listener to the StreamListeners array until accepted
     // If this was the only active MediaStream, remove the window from the list.
     if (NS_IsMainThread()) {
-      if (auto* window = nsGlobalWindowInner::GetInnerWindowWithId(mWindowID)) {
-        mHolder.Reject(
-            MakeRefPtr<MediaStreamError>(window->AsInner(), aName, aMessage),
-            __func__);
-      }
+      mHolder.Reject(MakeRefPtr<MediaMgrError>(aName, aMessage), __func__);
       // Should happen *after* error runs for consistency, but may not matter
       mWindowListener->Remove(mSourceListener);
     } else {
       // This will re-check the window being alive on main-thread
       Fail(aName, aMessage);
     }
-
     return NS_OK;
   }
 
   nsresult SetContraints(const MediaStreamConstraints& aConstraints) {
     mConstraints = aConstraints;
     return NS_OK;
   }
 
@@ -2226,77 +2167,77 @@ int MediaManager::AddDeviceChangeCallbac
       manager->GetBackend(0)->SetFakeDeviceChangeEvents();
   }));
 
   return DeviceChangeCallback::AddDeviceChangeCallback(aCallback);
 }
 
 void MediaManager::OnDeviceChange() {
   RefPtr<MediaManager> self(this);
-  NS_DispatchToMainThread(media::NewRunnableFrom([self]() mutable {
-    MOZ_ASSERT(NS_IsMainThread());
-    if (sHasShutdown) {
-      return NS_OK;
-    }
-    self->DeviceChangeCallback::OnDeviceChange();
-
-    // On some Windows machine, if we call EnumerateRawDevices immediately after
-    // receiving devicechange event, sometimes we would get outdated devices
-    // list.
-    PR_Sleep(PR_MillisecondsToInterval(100));
-    RefPtr<MediaDeviceSetPromise> p = self->EnumerateRawDevices(
-        0, MediaSourceEnum::Camera, MediaSourceEnum::Microphone,
-        MediaSinkEnum::Speaker);
-    p->Then(GetCurrentThreadSerialEventTarget(), __func__,
-            [self](RefPtr<MediaDeviceSetRefCnt>&& aDevices) mutable {
-              MediaManager* mgr = MediaManager::GetIfExists();
-              if (!mgr) {
-                return;
-              }
-
-              nsTArray<nsString> deviceIDs;
-
-              for (auto& device : *aDevices) {
-                nsString id;
-                device->GetId(id);
-                id.ReplaceSubstring(NS_LITERAL_STRING("default: "),
-                                    NS_LITERAL_STRING(""));
-                if (!deviceIDs.Contains(id)) {
-                  deviceIDs.AppendElement(id);
-                }
-              }
-
-              for (auto& id : self->mDeviceIDs) {
-                if (deviceIDs.Contains(id)) {
-                  continue;
-                }
-
-                // Stop the coresponding SourceListener
-                nsGlobalWindowInner::InnerWindowByIdTable* windowsById =
-                    nsGlobalWindowInner::GetWindowsTable();
-                if (!windowsById) {
-                  continue;
-                }
-
-                for (auto iter = windowsById->Iter(); !iter.Done();
-                     iter.Next()) {
-                  nsGlobalWindowInner* window = iter.Data();
-                  self->IterateWindowListeners(
-                      window->AsInner(),
-                      [&id](GetUserMediaWindowListener* aListener) {
-                        aListener->StopRawID(id);
-                      });
-                }
-              }
-
-              self->mDeviceIDs = deviceIDs;
-            },
-            [](RefPtr<MediaStreamError>&& reason) {});
-    return NS_OK;
-  }));
+  NS_DispatchToMainThread(
+      NS_NewRunnableFunction("MediaManager::OnDeviceChange", [self]() {
+        MOZ_ASSERT(NS_IsMainThread());
+        if (sHasShutdown) {
+          return;
+        }
+        self->DeviceChangeCallback::OnDeviceChange();
+
+        // On some Windows machine, if we call EnumerateRawDevices immediately
+        // after receiving devicechange event, sometimes we would get outdated
+        // devices list.
+        PR_Sleep(PR_MillisecondsToInterval(100));
+        self->EnumerateRawDevices(0, MediaSourceEnum::Camera,
+                                  MediaSourceEnum::Microphone,
+                                  MediaSinkEnum::Speaker)
+            ->Then(GetCurrentThreadSerialEventTarget(), __func__,
+                   [self](RefPtr<MediaDeviceSetRefCnt>&& aDevices) {
+                     MediaManager* mgr = MediaManager::GetIfExists();
+                     if (!mgr) {
+                       return;
+                     }
+
+                     nsTArray<nsString> deviceIDs;
+
+                     for (auto& device : *aDevices) {
+                       nsString id;
+                       device->GetId(id);
+                       id.ReplaceSubstring(NS_LITERAL_STRING("default: "),
+                                           NS_LITERAL_STRING(""));
+                       if (!deviceIDs.Contains(id)) {
+                         deviceIDs.AppendElement(id);
+                       }
+                     }
+
+                     for (auto& id : self->mDeviceIDs) {
+                       if (deviceIDs.Contains(id)) {
+                         continue;
+                       }
+
+                       // Stop the coresponding SourceListener
+                       nsGlobalWindowInner::InnerWindowByIdTable* windowsById =
+                           nsGlobalWindowInner::GetWindowsTable();
+                       if (!windowsById) {
+                         continue;
+                       }
+
+                       for (auto iter = windowsById->Iter(); !iter.Done();
+                            iter.Next()) {
+                         nsGlobalWindowInner* window = iter.Data();
+                         self->IterateWindowListeners(
+                             window->AsInner(),
+                             [&id](GetUserMediaWindowListener* aListener) {
+                               aListener->StopRawID(id);
+                             });
+                       }
+                     }
+
+                     self->mDeviceIDs = deviceIDs;
+                   },
+                   [](RefPtr<MediaMgrError>&& reason) {});
+      }));
 }
 
 nsresult MediaManager::GenerateUUID(nsAString& aResult) {
   nsresult rv;
   nsCOMPtr<nsIUUIDGenerator> uuidgen =
       do_GetService("@mozilla.org/uuid-generator;1", &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
@@ -2386,45 +2327,41 @@ RefPtr<MediaManager::StreamPromise> Medi
 
   MediaStreamConstraints c(aConstraintsPassedIn);  // use a modifiable copy
 
   // Do all the validation we can while we're sync (to return an
   // already-rejected promise on failure).
 
   if (!IsOn(c.mVideo) && !IsOn(c.mAudio)) {
     return StreamPromise::CreateAndReject(
-        MakeRefPtr<MediaStreamError>(
-            aWindow, MediaStreamError::Name::TypeError,
+        MakeRefPtr<MediaMgrError>(
+            MediaMgrError::Name::TypeError,
             NS_LITERAL_STRING("audio and/or video is required")),
         __func__);
   }
 
   if (!IsFullyActive(aWindow)) {
     return StreamPromise::CreateAndReject(
-        MakeRefPtr<MediaStreamError>(aWindow,
-                                     MediaStreamError::Name::InvalidStateError),
+        MakeRefPtr<MediaMgrError>(MediaMgrError::Name::InvalidStateError),
         __func__);
   }
 
   if (sHasShutdown) {
     return StreamPromise::CreateAndReject(
-        MakeRefPtr<MediaStreamError>(aWindow,
-                                     MediaStreamError::Name::AbortError,
-                                     NS_LITERAL_STRING("In shutdown")),
+        MakeRefPtr<MediaMgrError>(MediaMgrError::Name::AbortError,
+                                  NS_LITERAL_STRING("In shutdown")),
         __func__);
   }
 
   // Determine permissions early (while we still have a stack).
 
   nsIURI* docURI = aWindow->GetDocumentURI();
   if (!docURI) {
     return StreamPromise::CreateAndReject(
-        MakeRefPtr<MediaStreamError>(aWindow,
-                                     MediaStreamError::Name::AbortError),
-        __func__);
+        MakeRefPtr<MediaMgrError>(MediaMgrError::Name::AbortError), __func__);
   }
   bool isChrome = (aCallerType == dom::CallerType::System);
   bool privileged =
       isChrome ||
       Preferences::GetBool("media.navigator.permission.disabled", false);
   bool isHTTPS = false;
   bool isHandlingUserInput = EventStateManager::IsHandlingUserInput();
   ;
@@ -2464,37 +2401,34 @@ RefPtr<MediaManager::StreamPromise> Medi
     Telemetry::Accumulate(Telemetry::WEBRTC_GET_USER_MEDIA_SECURE_ORIGIN,
                           (uint32_t)GetUserMediaSecurityState::Other);
   }
 
   nsCOMPtr<nsIPrincipal> principal =
       nsGlobalWindowInner::Cast(aWindow)->GetPrincipal();
   if (NS_WARN_IF(!principal)) {
     return StreamPromise::CreateAndReject(
-        MakeRefPtr<MediaStreamError>(aWindow,
-                                     MediaStreamError::Name::SecurityError),
+        MakeRefPtr<MediaMgrError>(MediaMgrError::Name::SecurityError),
         __func__);
   }
 
   nsIDocument* doc = aWindow->GetExtantDoc();
   if (NS_WARN_IF(!doc)) {
     return StreamPromise::CreateAndReject(
-        MakeRefPtr<MediaStreamError>(aWindow,
-                                     MediaStreamError::Name::SecurityError),
+        MakeRefPtr<MediaMgrError>(MediaMgrError::Name::SecurityError),
         __func__);
   }
 
   // This principal needs to be sent to different threads and so via IPC.
   // For this reason it's better to convert it to PrincipalInfo right now.
   ipc::PrincipalInfo principalInfo;
   rv = PrincipalToPrincipalInfo(principal, &principalInfo);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return StreamPromise::CreateAndReject(
-        MakeRefPtr<MediaStreamError>(aWindow,
-                                     MediaStreamError::Name::SecurityError),
+        MakeRefPtr<MediaMgrError>(MediaMgrError::Name::SecurityError),
         __func__);
   }
 
   const bool resistFingerprinting =
       nsContentUtils::ResistFingerprinting(aCallerType);
 
   if (resistFingerprinting) {
     ReduceConstraint(c.mVideo);
@@ -2534,29 +2468,28 @@ RefPtr<MediaManager::StreamPromise> Medi
         // the requesting document is not from a host on the whitelist.
         if (!Preferences::GetBool(
                 ((videoType == MediaSourceEnum::Browser)
                      ? "media.getusermedia.browser.enabled"
                      : "media.getusermedia.screensharing.enabled"),
                 false) ||
             (!privileged && !aWindow->IsSecureContext())) {
           return StreamPromise::CreateAndReject(
-              MakeRefPtr<MediaStreamError>(
-                  aWindow, MediaStreamError::Name::NotAllowedError),
+              MakeRefPtr<MediaMgrError>(MediaMgrError::Name::NotAllowedError),
               __func__);
         }
         break;
 
       case MediaSourceEnum::Microphone:
       case MediaSourceEnum::Other:
       default: {
         return StreamPromise::CreateAndReject(
-            MakeRefPtr<MediaStreamError>(
-                aWindow, MediaStreamError::Name::OverconstrainedError,
-                NS_LITERAL_STRING(""), NS_LITERAL_STRING("mediaSource")),
+            MakeRefPtr<MediaMgrError>(MediaMgrError::Name::OverconstrainedError,
+                                      NS_LITERAL_STRING(""),
+                                      NS_LITERAL_STRING("mediaSource")),
             __func__);
       }
     }
 
     if (vc.mAdvanced.WasPassed() && videoType != MediaSourceEnum::Camera) {
       // iterate through advanced, forcing all unset mediaSources to match
       // "root"
       const char* unset = EnumToASCII(dom::MediaSourceEnumValues::strings,
@@ -2604,28 +2537,27 @@ RefPtr<MediaManager::StreamPromise> Medi
       case MediaSourceEnum::Microphone:
         break;
 
       case MediaSourceEnum::AudioCapture:
         // Only enable AudioCapture if the pref is enabled. If it's not, we can
         // deny right away.
         if (!Preferences::GetBool("media.getusermedia.audiocapture.enabled")) {
           return StreamPromise::CreateAndReject(
-              MakeRefPtr<MediaStreamError>(
-                  aWindow, MediaStreamError::Name::NotAllowedError),
+              MakeRefPtr<MediaMgrError>(MediaMgrError::Name::NotAllowedError),
               __func__);
         }
         break;
 
       case MediaSourceEnum::Other:
       default: {
         return StreamPromise::CreateAndReject(
-            MakeRefPtr<MediaStreamError>(
-                aWindow, MediaStreamError::Name::OverconstrainedError,
-                NS_LITERAL_STRING(""), NS_LITERAL_STRING("mediaSource")),
+            MakeRefPtr<MediaMgrError>(MediaMgrError::Name::OverconstrainedError,
+                                      NS_LITERAL_STRING(""),
+                                      NS_LITERAL_STRING("mediaSource")),
             __func__);
       }
     }
     if (ac.mAdvanced.WasPassed()) {
       // iterate through advanced, forcing all unset mediaSources to match
       // "root"
       const char* unset = EnumToASCII(dom::MediaSourceEnumValues::strings,
                                       MediaSourceEnum::Camera);
@@ -2701,18 +2633,17 @@ RefPtr<MediaManager::StreamPromise> Medi
       }
     }
 
     if ((!IsOn(c.mAudio) && !IsOn(c.mVideo)) ||
         (IsOn(c.mAudio) && audioPerm == nsIPermissionManager::DENY_ACTION) ||
         (IsOn(c.mVideo) && videoPerm == nsIPermissionManager::DENY_ACTION)) {
       windowListener->Remove(sourceListener);
       return StreamPromise::CreateAndReject(
-          MakeRefPtr<MediaStreamError>(aWindow,
-                                       MediaStreamError::Name::NotAllowedError),
+          MakeRefPtr<MediaMgrError>(MediaMgrError::Name::NotAllowedError),
           __func__);
     }
   }
 
   // Get list of all devices, with origin-specific device ids.
 
   MediaEnginePrefs prefs = mPrefs;
 
@@ -2790,18 +2721,17 @@ RefPtr<MediaManager::StreamPromise> Medi
                 nsGlobalWindowInner::GetInnerWindowWithId(windowID);
             RefPtr<nsPIDOMWindowInner> window =
                 globalWindow ? globalWindow->AsInner() : nullptr;
             if (!window || !self->IsWindowListenerStillActive(windowListener)) {
               LOG(("GetUserMedia: bad window (%" PRIu64 ") in post enumeration "
                    "success callback!",
                    windowID));
               return StreamPromise::CreateAndReject(
-                  MakeRefPtr<MediaStreamError>(
-                      window, MediaStreamError::Name::AbortError),
+                  MakeRefPtr<MediaMgrError>(MediaMgrError::Name::AbortError),
                   __func__);
             }
 
             // Apply any constraints. This modifies the passed-in list.
             return self->SelectSettings(c, isChrome, aDevices)
                 ->Then(
                     GetCurrentThreadSerialEventTarget(), __func__,
                     [self, windowID, c, windowListener, sourceListener,
@@ -2820,61 +2750,58 @@ RefPtr<MediaManager::StreamPromise> Medi
                           globalWindow ? globalWindow->AsInner() : nullptr;
                       if (!window ||
                           !self->IsWindowListenerStillActive(windowListener)) {
                         LOG(("GetUserMedia: bad window (%" PRIu64
                              ") in post enumeration "
                              "success callback 2!",
                              windowID));
                         return StreamPromise::CreateAndReject(
-                            MakeRefPtr<MediaStreamError>(
-                                window, MediaStreamError::Name::AbortError),
+                            MakeRefPtr<MediaMgrError>(
+                                MediaMgrError::Name::AbortError),
                             __func__);
                       }
 
                       if (badConstraint) {
                         LOG(
                             ("GetUserMedia: bad constraint found in post "
                              "enumeration promise2 "
                              "success callback! Calling error handler!"));
                         nsString constraint;
                         constraint.AssignASCII(badConstraint);
                         return StreamPromise::CreateAndReject(
-                            MakeRefPtr<MediaStreamError>(
-                                window,
-                                MediaStreamError::Name::OverconstrainedError,
+                            MakeRefPtr<MediaMgrError>(
+                                MediaMgrError::Name::OverconstrainedError,
                                 NS_LITERAL_STRING(""), constraint),
                             __func__);
                       }
                       if (!aDevices->Length()) {
                         LOG(
                             ("GetUserMedia: no devices found in post "
                              "enumeration promise2 "
                              "success callback! Calling error handler!"));
                         // When privacy.resistFingerprinting = true, no
                         // available device implies content script is requesting
                         // a fake device, so report NotAllowedError.
-                        auto error =
-                            resistFingerprinting
-                                ? MediaStreamError::Name::NotAllowedError
-                                : MediaStreamError::Name::NotFoundError;
+                        auto error = resistFingerprinting
+                                         ? MediaMgrError::Name::NotAllowedError
+                                         : MediaMgrError::Name::NotFoundError;
                         return StreamPromise::CreateAndReject(
-                            MakeRefPtr<MediaStreamError>(window, error),
-                            __func__);
+                            MakeRefPtr<MediaMgrError>(error), __func__);
                       }
 
                       // before we give up devices below
                       nsCOMPtr<nsIMutableArray> devicesCopy = nsArray::Create();
                       if (!askPermission) {
                         for (auto& device : *aDevices) {
                           nsresult rv = devicesCopy->AppendElement(device);
                           if (NS_WARN_IF(NS_FAILED(rv))) {
                             return StreamPromise::CreateAndReject(
-                                MakeRefPtr<MediaStreamError>(
-                                    window, MediaStreamError::Name::AbortError),
+                                MakeRefPtr<MediaMgrError>(
+                                    MediaMgrError::Name::AbortError),
                                 __func__);
                           }
                         }
                       }
 
                       bool focusSource = mozilla::Preferences::GetBool(
                           "media.getusermedia.window.focus_source.enabled",
                           true);
@@ -2927,41 +2854,31 @@ RefPtr<MediaManager::StreamPromise> Medi
                         }
                       }
 
 #ifdef MOZ_WEBRTC
                       EnableWebRtcLog();
 #endif
                       return p;
                     },
-                    // SelectSettings failure callback
-                    [windowID](nsresult rv) mutable {
+                    [](nsresult rv) {
                       LOG(
-                          ("GetUserMedia: post enumeration promise2 failure "
-                           "callback called!"));
-                      nsPIDOMWindowInner* window =
-                          nsGlobalWindowInner::GetInnerWindowWithId(windowID)
-                              ->AsInner();
+                          ("GetUserMedia: post enumeration SelectSettings "
+                           "failure callback called!"));
                       return StreamPromise::CreateAndReject(
-                          MakeRefPtr<MediaStreamError>(
-                              window, MediaStreamError::Name::AbortError),
+                          MakeRefPtr<MediaMgrError>(
+                              MediaMgrError::Name::AbortError),
                           __func__);
                     });
           },
-          // EnumerateDevicesImpl failure callback
-          [windowID](RefPtr<MediaStreamError>&& error) {
+          [](RefPtr<MediaMgrError>&& aError) {
             LOG(
-                ("GetUserMedia: post enumeration promise failure callback "
-                 "called!"));
-            nsPIDOMWindowInner* window =
-                nsGlobalWindowInner::GetInnerWindowWithId(windowID)->AsInner();
-            return StreamPromise::CreateAndReject(
-                MakeRefPtr<MediaStreamError>(
-                    window, MediaStreamError::Name::AbortError),
-                __func__);
+                ("GetUserMedia: post enumeration EnumerateDevicesImpl "
+                 "failure callback called!"));
+            return StreamPromise::CreateAndReject(std::move(aError), __func__);
           });
 }
 
 /* static */ void MediaManager::AnonymizeDevices(MediaDeviceSet& aDevices,
                                                  const nsACString& aOriginKey) {
   if (!aOriginKey.IsEmpty()) {
     for (RefPtr<MediaDevice>& device : aDevices) {
       nsString id;
@@ -3067,21 +2984,18 @@ RefPtr<MediaManager::MediaDeviceSetPromi
 
   nsCOMPtr<nsIPrincipal> principal =
       nsGlobalWindowInner::Cast(window)->GetPrincipal();
   MOZ_ASSERT(principal);
 
   ipc::PrincipalInfo principalInfo;
   nsresult rv = PrincipalToPrincipalInfo(principal, &principalInfo);
   if (NS_WARN_IF(NS_FAILED(rv))) {
-    nsPIDOMWindowInner* window =
-        nsGlobalWindowInner::GetInnerWindowWithId(aWindowId)->AsInner();
     return MediaDeviceSetPromise::CreateAndReject(
-        MakeRefPtr<MediaStreamError>(window,
-                                     MediaStreamError::Name::NotAllowedError),
+        MakeRefPtr<MediaMgrError>(MediaMgrError::Name::NotAllowedError),
         __func__);
   }
 
   bool persist = IsActivelyCapturingOrHasAPermission(aWindowId);
 
   // GetPrincipalKey is an async API that returns a promise. We use .Then() to
   // pass in a lambda to run back on this same thread later once
   // GetPrincipalKey resolves. Needed variables are "captured"
@@ -3091,44 +3005,37 @@ RefPtr<MediaManager::MediaDeviceSetPromi
           GetMainThreadSerialEventTarget(), __func__,
           [aWindowId, aVideoInputType, aAudioInputType, aVideoInputEnumType,
            aAudioInputEnumType, aAudioOutputType](
               const nsCString& aOriginKey) -> RefPtr<MediaDeviceSetPromise> {
             MOZ_ASSERT(NS_IsMainThread());
             MediaManager* mgr = MediaManager::GetIfExists();
             MOZ_ASSERT(mgr);
             if (!mgr->IsWindowStillActive(aWindowId)) {
-              nsPIDOMWindowInner* window =
-                  nsGlobalWindowInner::GetInnerWindowWithId(aWindowId)
-                      ->AsInner();
               return MediaDeviceSetPromise::CreateAndReject(
-                  MakeRefPtr<MediaStreamError>(
-                      window, MediaStreamError::Name::AbortError),
+                  MakeRefPtr<MediaMgrError>(MediaMgrError::Name::AbortError),
                   __func__);
             }
 
             return mgr
                 ->EnumerateRawDevices(aWindowId, aVideoInputType,
                                       aAudioInputType, aAudioOutputType,
                                       aVideoInputEnumType, aAudioInputEnumType)
                 ->Then(
                     GetMainThreadSerialEventTarget(), __func__,
                     [aWindowId, aOriginKey, aVideoInputEnumType,
                      aAudioInputEnumType, aVideoInputType,
                      aAudioInputType](RefPtr<MediaDeviceSetRefCnt>&& aDevices)
                         -> RefPtr<MediaDeviceSetPromise> {
                       // Only run if window is still on our active list.
                       MediaManager* mgr = MediaManager::GetIfExists();
                       if (!mgr || !mgr->IsWindowStillActive(aWindowId)) {
-                        nsPIDOMWindowInner* window =
-                            nsGlobalWindowInner::GetInnerWindowWithId(aWindowId)
-                                ->AsInner();
                         return MediaDeviceSetPromise::CreateAndReject(
-                            MakeRefPtr<MediaStreamError>(
-                                window, MediaStreamError::Name::AbortError),
+                            MakeRefPtr<MediaMgrError>(
+                                MediaMgrError::Name::AbortError),
                             __func__);
                       }
 
                       // If we fetched any real cameras or mics, remove the
                       // "default" part of their IDs.
                       if (aVideoInputType == MediaSourceEnum::Camera &&
                           aAudioInputType == MediaSourceEnum::Microphone &&
                           (aVideoInputEnumType != DeviceEnumerationType::Fake ||
@@ -3142,55 +3049,48 @@ RefPtr<MediaManager::MediaDeviceSetPromi
                                               NS_LITERAL_STRING(""));
                           if (!mgr->mDeviceIDs.Contains(id)) {
                             mgr->mDeviceIDs.AppendElement(id);
                           }
                         }
                       }
 
                       if (!mgr->IsWindowStillActive(aWindowId)) {
-                        nsPIDOMWindowInner* window =
-                            nsGlobalWindowInner::GetInnerWindowWithId(aWindowId)
-                                ->AsInner();
                         return MediaDeviceSetPromise::CreateAndReject(
-                            MakeRefPtr<MediaStreamError>(
-                                window, MediaStreamError::Name::AbortError),
+                            MakeRefPtr<MediaMgrError>(
+                                MediaMgrError::Name::AbortError),
                             __func__);
                       }
 
                       MediaManager::AnonymizeDevices(*aDevices, aOriginKey);
                       return MediaDeviceSetPromise::CreateAndResolve(
                           std::move(aDevices), __func__);
                     },
-                    [](RefPtr<MediaStreamError>&& reason) {
+                    [](RefPtr<MediaMgrError>&& aError) {
                       return MediaDeviceSetPromise::CreateAndReject(
-                          std::move(reason), __func__);
+                          std::move(aError), __func__);
                     });
           },
-          [aWindowId](nsresult rs) {
+          [](nsresult rs) {
             NS_WARNING(
                 "EnumerateDevicesImpl failed to get Principal Key. Enumeration "
                 "will not continue.");
-            nsPIDOMWindowInner* window =
-                nsGlobalWindowInner::GetInnerWindowWithId(aWindowId)->AsInner();
             return MediaDeviceSetPromise::CreateAndReject(
-                MakeRefPtr<MediaStreamError>(
-                    window, MediaStreamError::Name::AbortError),
+                MakeRefPtr<MediaMgrError>(MediaMgrError::Name::AbortError),
                 __func__);
           });
 }
 
 RefPtr<MediaManager::MediaDeviceSetPromise> MediaManager::EnumerateDevices(
     nsPIDOMWindowInner* aWindow, dom::CallerType aCallerType) {
   MOZ_ASSERT(NS_IsMainThread());
   if (sHasShutdown) {
     return MediaDeviceSetPromise::CreateAndReject(
-        MakeRefPtr<MediaStreamError>(aWindow,
-                                     MediaStreamError::Name::AbortError,
-                                     NS_LITERAL_STRING("In shutdown")),
+        MakeRefPtr<MediaMgrError>(MediaMgrError::Name::AbortError,
+                                  NS_LITERAL_STRING("In shutdown")),
         __func__);
   }
   uint64_t windowId = aWindow->WindowID();
 
   nsIPrincipal* principal = aWindow->GetExtantDoc()->NodePrincipal();
 
   RefPtr<GetUserMediaWindowListener> windowListener =
       GetWindowListener(windowId);
@@ -3241,33 +3141,33 @@ RefPtr<MediaManager::MediaDeviceSetPromi
 
   MediaSinkEnum audioOutputType = MediaSinkEnum::Other;
   if (Preferences::GetBool("media.setsinkid.enabled")) {
     audioOutputType = MediaSinkEnum::Speaker;
   }
   return EnumerateDevicesImpl(windowId, MediaSourceEnum::Camera,
                               MediaSourceEnum::Microphone, audioOutputType,
                               videoEnumerationType, audioEnumerationType)
-      ->Then(
-          GetCurrentThreadSerialEventTarget(), __func__,
-          [windowListener,
-           sourceListener](RefPtr<MediaDeviceSetRefCnt>&& aDevices) {
-            DebugOnly<bool> rv = windowListener->Remove(sourceListener);
-            MOZ_ASSERT(rv);
-            return MediaDeviceSetPromise::CreateAndResolve(std::move(aDevices),
-                                                           __func__);
-          },
-          [windowListener, sourceListener](RefPtr<MediaStreamError>&& error) {
-            // This may fail, if a new doc has been set the OnNavigation method
-            // should have removed all previous active listeners. Attempt to
-            // clean it here, just in case, but ignore the return value.
-            Unused << windowListener->Remove(sourceListener);
-            return MediaDeviceSetPromise::CreateAndReject(std::move(error),
-                                                          __func__);
-          });
+      ->Then(GetCurrentThreadSerialEventTarget(), __func__,
+             [windowListener,
+              sourceListener](RefPtr<MediaDeviceSetRefCnt>&& aDevices) {
+               DebugOnly<bool> rv = windowListener->Remove(sourceListener);
+               MOZ_ASSERT(rv);
+               return MediaDeviceSetPromise::CreateAndResolve(
+                   std::move(aDevices), __func__);
+             },
+             [windowListener, sourceListener](RefPtr<MediaMgrError>&& aError) {
+               // This may fail, if a new doc has been set the OnNavigation
+               // method should have removed all previous active listeners.
+               // Attempt to clean it here, just in case, but ignore the return
+               // value.
+               Unused << windowListener->Remove(sourceListener);
+               return MediaDeviceSetPromise::CreateAndReject(std::move(aError),
+                                                             __func__);
+             });
 }
 
 RefPtr<SinkInfoPromise> MediaManager::GetSinkDevice(nsPIDOMWindowInner* aWindow,
                                                     const nsString& aDeviceId) {
   MOZ_ASSERT(NS_IsMainThread());
   MOZ_ASSERT(aWindow);
 
   // We have to add the window id here because enumerate methods
@@ -3312,17 +3212,17 @@ RefPtr<SinkInfoPromise> MediaManager::Ge
                    }
                    return SinkInfoPromise::CreateAndReject(
                        NS_ERROR_DOM_MEDIA_NOT_ALLOWED_ERR, __func__);
                  }
                }
                return SinkInfoPromise::CreateAndReject(NS_ERROR_NOT_AVAILABLE,
                                                        __func__);
              },
-             [](RefPtr<MediaStreamError>&& reason) {
+             [](RefPtr<MediaMgrError>&& aError) {
                return SinkInfoPromise::CreateAndReject(NS_ERROR_NOT_AVAILABLE,
                                                        __func__);
              });
 }
 
 /*
  * GetUserMediaDevices - called by the UI-part of getUserMedia from chrome JS.
  */
@@ -4643,18 +4543,18 @@ CaptureState SourceListener::CapturingSo
     return CaptureState::Enabled;
   }
 
   return CaptureState::Disabled;
 }
 
 RefPtr<SourceListener::SourceListenerPromise>
 SourceListener::ApplyConstraintsToTrack(
-    nsPIDOMWindowInner* aWindow, TrackID aTrackID,
-    const MediaTrackConstraints& aConstraints, dom::CallerType aCallerType) {
+    TrackID aTrackID, const MediaTrackConstraints& aConstraints,
+    dom::CallerType aCallerType) {
   MOZ_ASSERT(NS_IsMainThread());
   DeviceState& state = GetDeviceStateFor(aTrackID);
 
   if (mStopped || state.mStopped) {
     LOG(("gUM %s track %d applyConstraints, but source is stopped",
          aTrackID == kAudioTrack ? "audio" : "video", aTrackID));
     return SourceListenerPromise::CreateAndResolve(false, __func__);
   }
--- a/dom/media/MediaManager.h
+++ b/dom/media/MediaManager.h
@@ -210,21 +210,19 @@ class MediaManager final : public nsIMed
   static void CallOnError(const GetUserMediaErrorCallback* aCallback,
                           dom::MediaStreamError& aError);
   static void CallOnSuccess(const GetUserMediaSuccessCallback* aCallback,
                             DOMMediaStream& aStream);
 
   typedef nsTArray<RefPtr<MediaDevice>> MediaDeviceSet;
   typedef media::Refcountable<MediaDeviceSet> MediaDeviceSetRefCnt;
 
-  typedef MozPromise<RefPtr<DOMMediaStream>, RefPtr<dom::MediaStreamError>,
-                     true>
+  typedef MozPromise<RefPtr<DOMMediaStream>, RefPtr<MediaMgrError>, true>
       StreamPromise;
-  typedef MozPromise<RefPtr<MediaDeviceSetRefCnt>,
-                     RefPtr<dom::MediaStreamError>, true>
+  typedef MozPromise<RefPtr<MediaDeviceSetRefCnt>, RefPtr<MediaMgrError>, true>
       MediaDeviceSetPromise;
   typedef MozPromise<const char*, nsresult, false> BadConstraintsPromise;
 
   RefPtr<StreamPromise> GetUserMedia(
       nsPIDOMWindowInner* aWindow,
       const dom::MediaStreamConstraints& aConstraints,
       dom::CallerType aCallerType);
 
--- a/dom/media/MediaStreamError.h
+++ b/dom/media/MediaStreamError.h
@@ -46,21 +46,21 @@ class BaseMediaMgrError {
     OverconstrainedError,
     SecurityError,
     TypeError,
   };
 
  protected:
   BaseMediaMgrError(Name aName, const nsAString& aMessage,
                     const nsAString& aConstraint);
+
+ public:
   nsString mNameString;
   nsString mMessage;
   const nsString mConstraint;
-
- private:
   const Name mName;
 };
 
 class MediaMgrError final : public nsISupports, public BaseMediaMgrError {
  public:
   explicit MediaMgrError(Name aName, const nsAString& aMessage = EmptyString(),
                          const nsAString& aConstraint = EmptyString())
       : BaseMediaMgrError(aName, aMessage, aConstraint) {}
--- a/dom/media/MediaStreamTrack.cpp
+++ b/dom/media/MediaStreamTrack.cpp
@@ -40,22 +40,21 @@ NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(Me
   NS_IMPL_CYCLE_COLLECTION_UNLINK(mPrincipal)
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(MediaStreamTrackSource)
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPrincipal)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 auto MediaStreamTrackSource::ApplyConstraints(
-    nsPIDOMWindowInner* aWindow, const dom::MediaTrackConstraints& aConstraints,
-    CallerType aCallerType) -> RefPtr<ApplyConstraintsPromise> {
+    const dom::MediaTrackConstraints& aConstraints, CallerType aCallerType)
+    -> RefPtr<ApplyConstraintsPromise> {
   return ApplyConstraintsPromise::CreateAndReject(
-      MakeRefPtr<MediaStreamError>(aWindow,
-                                   MediaStreamError::Name::OverconstrainedError,
-                                   NS_LITERAL_STRING("")),
+      MakeRefPtr<MediaMgrError>(MediaMgrError::Name::OverconstrainedError,
+                                NS_LITERAL_STRING("")),
       __func__);
 }
 
 /**
  * MSGListener monitors state changes of the media flowing through the
  * MediaStreamGraph.
  *
  *
@@ -358,31 +357,34 @@ already_AddRefed<Promise> MediaStreamTra
   //
   // After GetSource().ApplyConstraints succeeds (after it's been to
   // media-thread and back), and no sooner, do we set mConstraints to the newly
   // applied values.
 
   // Keep a reference to this, to make sure it's still here when we get back.
   RefPtr<MediaStreamTrack> self(this);
   GetSource()
-      .ApplyConstraints(window, aConstraints, aCallerType)
-      ->Then(GetCurrentThreadSerialEventTarget(), __func__,
-             [this, self, promise, aConstraints](bool aDummy) {
-               if (NS_FAILED(CheckInnerWindowCorrectness())) {
-                 return;  // Leave Promise pending after navigation by design.
-               }
-               mConstraints = aConstraints;
-               promise->MaybeResolve(false);
-             },
-             [this, self, promise](const RefPtr<MediaStreamError>& reason) {
-               if (NS_FAILED(CheckInnerWindowCorrectness())) {
-                 return;  // Leave Promise pending after navigation by design.
-               }
-               promise->MaybeReject(reason);
-             });
+      .ApplyConstraints(aConstraints, aCallerType)
+      ->Then(
+          GetCurrentThreadSerialEventTarget(), __func__,
+          [this, self, promise, aConstraints](bool aDummy) {
+            nsPIDOMWindowInner* window = mOwningStream->GetParentObject();
+            if (!window || !window->IsCurrentInnerWindow()) {
+               return;  // Leave Promise pending after navigation by design.
+            }
+            mConstraints = aConstraints;
+            promise->MaybeResolve(false);
+          },
+          [this, self, promise](const RefPtr<MediaMgrError>& aError) {
+            nsPIDOMWindowInner* window = mOwningStream->GetParentObject();
+            if (!window || !window->IsCurrentInnerWindow()) {
+               return;  // Leave Promise pending after navigation by design.
+            }
+            promise->MaybeReject(MakeRefPtr<MediaStreamError>(window, *aError));
+          });
   return promise.forget();
 }
 
 MediaStreamGraph* MediaStreamTrack::Graph() {
   return GetOwnedStream()->Graph();
 }
 
 MediaStreamGraphImpl* MediaStreamTrack::GraphImpl() {
--- a/dom/media/MediaStreamTrack.h
+++ b/dom/media/MediaStreamTrack.h
@@ -30,22 +30,22 @@ class MediaStreamGraphImpl;
 class MediaStreamTrackListener;
 class DirectMediaStreamTrackListener;
 class PeerConnectionImpl;
 class PeerConnectionMedia;
 class PeerIdentity;
 class ProcessedMediaStream;
 class RemoteSourceStreamInfo;
 class SourceStreamInfo;
+class MediaMgrError;
 
 namespace dom {
 
 class AudioStreamTrack;
 class VideoStreamTrack;
-class MediaStreamError;
 class TrackSink;
 enum class CallerType : uint32_t;
 
 /**
  * Common interface through which a MediaStreamTrack can communicate with its
  * producer on the main thread.
  *
  * Kept alive by a strong ref in all MediaStreamTracks (original and clones)
@@ -150,25 +150,24 @@ class MediaStreamTrackSource : public ns
    * Forwards a photo request to backends that support it. Other backends return
    * NS_ERROR_NOT_IMPLEMENTED to indicate that a MediaStreamGraph-based fallback
    * should be used.
    */
   virtual nsresult TakePhoto(MediaEnginePhotoCallback*) const {
     return NS_ERROR_NOT_IMPLEMENTED;
   }
 
-  typedef MozPromise<bool /* aIgnored */, RefPtr<dom::MediaStreamError>, true>
+  typedef MozPromise<bool /* aIgnored */, RefPtr<MediaMgrError>, true>
       ApplyConstraintsPromise;
 
   /**
    * We provide a fallback solution to ApplyConstraints() here.
    * Sources that support ApplyConstraints() will have to override it.
    */
   virtual RefPtr<ApplyConstraintsPromise> ApplyConstraints(
-      nsPIDOMWindowInner* aWindow,
       const dom::MediaTrackConstraints& aConstraints, CallerType aCallerType);
 
   /**
    * Same for GetSettings (no-op).
    */
   virtual void GetSettings(dom::MediaTrackSettings& aResult){};
 
   /**
--- a/dom/media/webspeech/recognition/SpeechRecognition.cpp
+++ b/dom/media/webspeech/recognition/SpeechRecognition.cpp
@@ -686,31 +686,26 @@ void SpeechRecognition::Start(const Opti
                  nsTArray<RefPtr<AudioStreamTrack>> tracks;
                  mStream->GetAudioTracks(tracks);
                  for (const RefPtr<AudioStreamTrack>& track : tracks) {
                    if (!track->Ended()) {
                      NotifyTrackAdded(track);
                    }
                  }
                },
-               [this, self](RefPtr<MediaStreamError>&& error) {
+               [this, self](RefPtr<MediaMgrError>&& error) {
                  SpeechRecognitionErrorCode errorCode;
 
-                 nsAutoString name;
-                 error->GetName(name);
-                 if (name.EqualsLiteral("NotAllowedError")) {
+                 if (error->mName == MediaMgrError::Name::NotAllowedError) {
                    errorCode = SpeechRecognitionErrorCode::Not_allowed;
                  } else {
                    errorCode = SpeechRecognitionErrorCode::Audio_capture;
                  }
-
-                 nsAutoString message;
-                 error->GetMessage(message);
                  DispatchError(SpeechRecognition::EVENT_AUDIO_ERROR, errorCode,
-                               message);
+                               error->mMessage);
                });
   }
 
   RefPtr<SpeechEvent> event = new SpeechEvent(this, EVENT_START);
   NS_DispatchToMainThread(event);
 }
 
 bool SpeechRecognition::SetRecognitionService(ErrorResult& aRv) {
--- a/media/webrtc/signaling/src/peerconnection/RemoteTrackSource.h
+++ b/media/webrtc/signaling/src/peerconnection/RemoteTrackSource.h
@@ -17,25 +17,22 @@ public:
     : dom::MediaStreamTrackSource(aPrincipal, aLabel) {}
 
   dom::MediaSourceEnum GetMediaSource() const override
   {
     return dom::MediaSourceEnum::Other;
   }
 
   RefPtr<ApplyConstraintsPromise>
-  ApplyConstraints(nsPIDOMWindowInner* aWindow,
-                   const dom::MediaTrackConstraints& aConstraints,
+  ApplyConstraints(const dom::MediaTrackConstraints& aConstraints,
                    dom::CallerType aCallerType) override
   {
     return ApplyConstraintsPromise::CreateAndReject(
-        MakeRefPtr<MediaStreamError>(aWindow,
-                                     MediaStreamError::Name::OverconstrainedError,
-                                     NS_LITERAL_STRING("")),
-        __func__);
+        MakeRefPtr<MediaMgrError>(MediaStreamError::Name::OverconstrainedError,
+                                  NS_LITERAL_STRING("")), __func__);
   }
 
   void Stop() override
   {
     // XXX (Bug 1314270): Implement rejection logic if necessary when we have
     //                    clarity in the spec.
   }