Bug 906986 - Fixing review issues. draft
authorMichael Froman <mfroman@mozilla.com>
Wed, 23 Mar 2016 11:53:29 -0500
changeset 345976 5c4919e83307e739f1d76f8849cbf9435f94380f
parent 343675 52925fd21f38b677d4abfde5fdbcbcad28802d02
child 346086 99316c069863bff12b926bd2d3c3565bd5270482
push id14204
push usermfroman@nostrum.com
push dateWed, 30 Mar 2016 17:53:18 +0000
bugs906986
milestone47.0a1
Bug 906986 - Fixing review issues. MozReview-Commit-ID: JgaZY4WfA8s
dom/media/tests/mochitest/mochitest.ini
dom/media/tests/mochitest/pc.js
dom/media/tests/mochitest/test_peerConnection_restartIce.html
dom/media/tests/mochitest/test_peerConnection_restartIceLocalAndRemoteRollback.html
dom/media/tests/mochitest/test_peerConnection_restartIceLocalRollback.html
dom/media/tests/mochitest/test_peerConnection_restartIceNoBundle.html
dom/media/tests/mochitest/test_peerConnection_restartIceNoRtcpMux.html
media/mtransport/nricectx.cpp
media/mtransport/nricectx.h
media/mtransport/nricectxhandler.cpp
media/mtransport/nricectxhandler.h
media/mtransport/test/ice_unittest.cpp
media/mtransport/third_party/nICEr/src/ice/ice_ctx.c
media/mtransport/transportlayerice.cpp
media/mtransport/transportlayerice.h
media/webrtc/signaling/src/jsep/JsepSession.h
media/webrtc/signaling/src/jsep/JsepSessionImpl.cpp
media/webrtc/signaling/src/jsep/JsepSessionImpl.h
media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp
media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.h
media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.cpp
media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.h
media/webrtc/signaling/src/sdp/SdpHelper.cpp
media/webrtc/signaling/src/sdp/SdpHelper.h
--- a/dom/media/tests/mochitest/mochitest.ini
+++ b/dom/media/tests/mochitest/mochitest.ini
@@ -133,16 +133,26 @@ skip-if = toolkit == 'gonk' # B2G emulat
 skip-if = toolkit == 'gonk' # B2G emulator is too slow to handle a two-way audio call reliably
 [test_peerConnection_offerRequiresReceiveAudio.html]
 [test_peerConnection_offerRequiresReceiveVideo.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' # b2g(Bug 960442, video support for WebRTC is disabled on b2g)
 [test_peerConnection_offerRequiresReceiveVideoAudio.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' || (android_version == '18' && debug) # b2g(Bug 960442, video support for WebRTC is disabled on b2g), android(Bug 1189784, timeouts on 4.3 emulator)
 [test_peerConnection_promiseSendOnly.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' || (android_version == '18' && debug) # b2g(Bug 960442, video support for WebRTC is disabled on b2g), android(Bug 1189784, timeouts on 4.3 emulator)
+[test_peerConnection_restartIce.html]
+skip-if = toolkit == 'gonk' || buildapp == 'mulet' # b2g (Bug 1059867)
+[test_peerConnection_restartIceNoBundle.html]
+skip-if = toolkit == 'gonk' || buildapp == 'mulet' # b2g (Bug 1059867)
+[test_peerConnection_restartIceNoRtcpMux.html]
+skip-if = toolkit == 'gonk' || buildapp == 'mulet' # b2g (Bug 1059867)
+[test_peerConnection_restartIceLocalRollback.html]
+skip-if = toolkit == 'gonk' || buildapp == 'mulet' # b2g (Bug 1059867)
+[test_peerConnection_restartIceLocalAndRemoteRollback.html]
+skip-if = toolkit == 'gonk' || buildapp == 'mulet' # b2g (Bug 1059867)
 [test_peerConnection_simulcastOffer.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' || android_version  || (os == 'linux' && debug) # b2g(Bug 960442, video support for WebRTC is disabled on b2g), no simulcast support on android, linux (bug 1242058)
 #[test_peerConnection_relayOnly.html]
 #skip-if = toolkit == 'gonk' || buildapp == 'mulet' # b2g(Bug 960442, video support for WebRTC is disabled on b2g)
 [test_peerConnection_callbacks.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' || (android_version == '18' && debug) # b2g(Bug 960442, video support for WebRTC is disabled on b2g), android(Bug 1189784, timeouts on 4.3 emulator)
 [test_peerConnection_replaceTrack.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' || android_version == '18' # b2g(Bug 960442, video support for WebRTC is disabled on b2g), android(Bug 1189784, timeouts on 4.3 emulator)
@@ -228,12 +238,8 @@ skip-if = toolkit == 'gonk' || buildapp 
 skip-if = toolkit == 'gonk' || (android_version == '18' && debug) # b2g (Bug 1059867), android(Bug 1189784, timeouts on 4.3 emulator)
 [test_peerConnection_remoteReofferRollback.html]
 skip-if = toolkit == 'gonk' || buildapp == 'mulet' # b2g (Bug 1059867)
 [test_selftest.html]
 # Bug 1227781: Crash with bogus TURN server.
 [test_peerConnection_bug1227781.html]
 # Bug 950317: Hack for making a cleanup hook after finishing all WebRTC cases
 [test_zmedia_cleanup.html]
-[test_peerConnection_restartIceNoBundle.html]
-[test_peerConnection_restartIce.html]
-[test_peerConnection_restartIceLocalRollback.html]
-[test_peerConnection_restartIceLocalAndRemoteRollback.html]
--- a/dom/media/tests/mochitest/pc.js
+++ b/dom/media/tests/mochitest/pc.js
@@ -724,16 +724,17 @@ function PeerConnectionWrapper(label, co
 
   this.expectedLocalTrackInfoById = {};
   this.expectedRemoteTrackInfoById = {};
   this.observedRemoteTrackInfoById = {};
 
   this.disableRtpCountChecking = false;
 
   this.iceCheckingRestartExpected = false;
+  this.iceCheckingIceRollbackExpected = false;
 
   info("Creating " + this);
   this._pc = new RTCPeerConnection(this.configuration);
 
   /**
    * Setup callback handlers
    */
   // This allows test to register their own callbacks for ICE connection state changes
@@ -1209,16 +1210,21 @@ PeerConnectionWrapper.prototype = {
       var newstate = this._pc.iceConnectionState;
       var oldstate = this.iceConnectionLog[this.iceConnectionLog.length - 1]
       if (Object.keys(iceStateTransitions).indexOf(oldstate) != -1) {
         if (this.iceCheckingRestartExpected) {
           is(newstate, "checking",
              "iceconnectionstate event \'" + newstate +
              "\' matches expected state \'checking\'");
           this.iceCheckingRestartExpected = false;
+        } else if (this.iceCheckingIceRollbackExpected) {
+          is(newstate, "connected",
+             "iceconnectionstate event \'" + newstate +
+             "\' matches expected state \'connected\'");
+          this.iceCheckingIceRollbackExpected = false;
         } else {
           ok(iceStateTransitions[oldstate].indexOf(newstate) != -1, this + ": legal ICE state transition from " + oldstate + " to " + newstate);
         }
       } else {
         ok(false, this + ": old ICE state " + oldstate + " missing in ICE transition array");
       }
       this.iceConnectionLog.push(newstate);
     };
--- a/dom/media/tests/mochitest/test_peerConnection_restartIce.html
+++ b/dom/media/tests/mochitest/test_peerConnection_restartIce.html
@@ -11,28 +11,29 @@
     title: "Renegotiation: restart ice"
   });
 
   var test;
   runNetworkTest(function (options) {
     test = new PeerConnectionTest(options);
 
     addRenegotiation(test.chain,
-                      [
-                        function PC_SET_OFFER_OPTION(test) {
-                          test.setOfferOptions({ iceRestart: true });
-                        },
-                        function PC_LOCAL_EXPECT_ICE_CHECKING(test) {
-                          test.pcLocal.iceCheckingRestartExpected = true;
-                        },
-                        function PC_REMOTE_EXPECT_ICE_CHECKING(test) {
-                          test.pcRemote.iceCheckingRestartExpected = true;
-                        }
-                      ]
-                    );
+      [
+        // causes a full, normal ice restart
+        function PC_LOCAL_SET_OFFER_OPTION(test) {
+          test.setOfferOptions({ iceRestart: true });
+        },
+        function PC_LOCAL_EXPECT_ICE_CHECKING(test) {
+          test.pcLocal.iceCheckingRestartExpected = true;
+        },
+        function PC_REMOTE_EXPECT_ICE_CHECKING(test) {
+          test.pcRemote.iceCheckingRestartExpected = true;
+        }
+      ]
+    );
 
     test.setMediaConstraints([{audio: true}, {video: true}],
                              [{audio: true}, {video: true}]);
     test.run();
   });
 
 </script>
 </pre>
--- a/dom/media/tests/mochitest/test_peerConnection_restartIceLocalAndRemoteRollback.html
+++ b/dom/media/tests/mochitest/test_peerConnection_restartIceLocalAndRemoteRollback.html
@@ -12,40 +12,49 @@
   });
 
   var test;
   runNetworkTest(function (options) {
     test = new PeerConnectionTest(options);
     var firstNegotiationSize = test.chain.commands.length;
 
     addRenegotiation(test.chain,
-                      [
-                        // causes a full, normal ice restart
-                        function PC_SET_OFFER_OPTION(test) {
-                          test.setOfferOptions({ iceRestart: true });
-                        },
-                        function PC_LOCAL_EXPECT_ICE_CHECKING(test) {
-                          test.pcLocal.iceCheckingRestartExpected = true;
-                        },
-                        function PC_REMOTE_EXPECT_ICE_CHECKING(test) {
-                          test.pcRemote.iceCheckingRestartExpected = true;
-                        },
-                      ]
-                    );
+      [
+        // causes a full, normal ice restart
+        function PC_LOCAL_SET_OFFER_OPTION(test) {
+          test.setOfferOptions({ iceRestart: true });
+        }
+      ]
+    );
 
     test.chain.replaceAfter('PC_REMOTE_CREATE_ANSWER',
       [
         function PC_LOCAL_SETUP_ICE_HANDLER(test) {
           test.pcLocal.setupIceCandidateHandler(test);
           if (test.testOptions.steeplechase) {
             test.pcLocal.endOfTrickleIce.then(() => {
               send_message({"type": "end_of_trickle_ice"});
             });
           }
         },
+        function PC_REMOTE_SETUP_ICE_HANDLER(test) {
+          test.pcRemote.setupIceCandidateHandler(test);
+          if (test.testOptions.steeplechase) {
+            test.pcRemote.endOfTrickleIce.then(() => {
+              send_message({"type": "end_of_trickle_ice"});
+            });
+          }
+        },
+
+        function PC_LOCAL_EXPECT_ICE_CONNECTED(test) {
+          test.pcLocal.iceCheckingIceRollbackExpected = true;
+        },
+        function PC_REMOTE_EXPECT_ICE_CONNECTED(test) {
+          test.pcRemote.iceCheckingIceRollbackExpected = true;
+        },
 
         function PC_REMOTE_ROLLBACK(test) {
           return test.setRemoteDescription(
               test.pcRemote,
               new RTCSessionDescription({ type: "rollback" }),
               STABLE);
         },
 
@@ -57,23 +66,33 @@
               new RTCSessionDescription({ type: "rollback", sdp: ""}),
               STABLE);
         },
 
         // Rolling back should shut down gathering
         function PC_LOCAL_WAIT_FOR_END_OF_TRICKLE(test) {
           return test.pcLocal.endOfTrickleIce;
         },
+        function PC_REMOTE_WAIT_FOR_END_OF_TRICKLE(test) {
+          return test.pcRemote.endOfTrickleIce;
+        },
+
+        function PC_LOCAL_EXPECT_ICE_CHECKING(test) {
+          test.pcLocal.iceCheckingRestartExpected = true;
+        },
+        function PC_REMOTE_EXPECT_ICE_CHECKING(test) {
+          test.pcRemote.iceCheckingRestartExpected = true;
+        }
       ],
-      firstNegotiationSize // Second PC_REMOTE_SET_REMOTE_DESCRIPTION
+      firstNegotiationSize // Replaces after second PC_REMOTE_CREATE_ANSWER
     );
     test.chain.append(commandsPeerConnectionOfferAnswer);
 
     // for now, only use one stream, because rollback doesn't seem to
-    // like multiple streams
+    // like multiple streams.  See bug 1259465.
     test.setMediaConstraints([{audio: true}],
                              [{audio: true}]);
     test.run();
   });
 
 </script>
 </pre>
 </body>
--- a/dom/media/tests/mochitest/test_peerConnection_restartIceLocalRollback.html
+++ b/dom/media/tests/mochitest/test_peerConnection_restartIceLocalRollback.html
@@ -11,61 +11,63 @@
     title: "Renegotiation: restart ice, local rollback"
   });
 
   var test;
   runNetworkTest(function (options) {
     test = new PeerConnectionTest(options);
 
     addRenegotiation(test.chain,
-                      [
-                        // causes a full, normal ice restart
-                        function PC_SET_OFFER_OPTION(test) {
-                          test.setOfferOptions({ iceRestart: true });
-                        },
-                        function PC_LOCAL_EXPECT_ICE_CHECKING(test) {
-                          test.pcLocal.iceCheckingRestartExpected = true;
-                        },
-                        function PC_REMOTE_EXPECT_ICE_CHECKING(test) {
-                          test.pcRemote.iceCheckingRestartExpected = true;
-                        },
-
-                        // causes an ice restart and then rolls it back
-                        // (does not result in sending and offer)
-                        function PC_LOCAL_SETUP_ICE_HANDLER(test) {
-                          test.pcLocal.setupIceCandidateHandler(test);
-                          if (test.testOptions.steeplechase) {
-                            test.pcLocal.endOfTrickleIce.then(() => {
-                              send_message({"type": "end_of_trickle_ice"});
-                            });
-                          }
-                        },
-                        function PC_LOCAL_CREATE_AND_SET_OFFER(test) {
-                          return test.createOffer(test.pcLocal).then(offer => {
-                            return test.setLocalDescription(test.pcLocal, 
-                                                            offer, 
-                                                            HAVE_LOCAL_OFFER);
-                          });
-                        },
-                        function PC_LOCAL_ROLLBACK(test) {
-                          return test.setLocalDescription(
-                              test.pcLocal,
-                              new RTCSessionDescription({ type: "rollback", 
-                                                          sdp: ""}),
-                              STABLE);
-                        },
-                        // Rolling back should shut down gathering
-                        function PC_LOCAL_WAIT_FOR_END_OF_TRICKLE(test) {
-                          return test.pcLocal.endOfTrickleIce;
-                        }
-                      ]
-                    );
+      [
+        // causes a full, normal ice restart
+        function PC_LOCAL_SET_OFFER_OPTION(test) {
+          test.setOfferOptions({ iceRestart: true });
+        },
+        // causes an ice restart and then rolls it back
+        // (does not result in sending an offer)
+        function PC_LOCAL_SETUP_ICE_HANDLER(test) {
+          test.pcLocal.setupIceCandidateHandler(test);
+          if (test.testOptions.steeplechase) {
+            test.pcLocal.endOfTrickleIce.then(() => {
+              send_message({"type": "end_of_trickle_ice"});
+            });
+          }
+        },
+        function PC_LOCAL_CREATE_AND_SET_OFFER(test) {
+          return test.createOffer(test.pcLocal).then(offer => {
+            return test.setLocalDescription(test.pcLocal,
+                                            offer,
+                                            HAVE_LOCAL_OFFER);
+          });
+        },
+        function PC_LOCAL_EXPECT_ICE_CONNECTED(test) {
+          test.pcLocal.iceCheckingIceRollbackExpected = true;
+        },
+        function PC_LOCAL_ROLLBACK(test) {
+          return test.setLocalDescription(
+              test.pcLocal,
+              new RTCSessionDescription({ type: "rollback",
+                                          sdp: ""}),
+              STABLE);
+        },
+        // Rolling back should shut down gathering
+        function PC_LOCAL_WAIT_FOR_END_OF_TRICKLE(test) {
+          return test.pcLocal.endOfTrickleIce;
+        },
+        function PC_LOCAL_EXPECT_ICE_CHECKING(test) {
+          test.pcLocal.iceCheckingRestartExpected = true;
+        },
+        function PC_REMOTE_EXPECT_ICE_CHECKING(test) {
+          test.pcRemote.iceCheckingRestartExpected = true;
+        }
+      ]
+    );
 
     // for now, only use one stream, because rollback doesn't seem to
-    // like multiple streams
+    // like multiple streams.  See bug 1259465.
     test.setMediaConstraints([{audio: true}],
                              [{audio: true}]);
     test.run();
   });
 
 </script>
 </pre>
 </body>
--- a/dom/media/tests/mochitest/test_peerConnection_restartIceNoBundle.html
+++ b/dom/media/tests/mochitest/test_peerConnection_restartIceNoBundle.html
@@ -13,28 +13,29 @@
 
   var test;
   runNetworkTest(function (options) {
     options = options || { };
     options.bundle = false;
     test = new PeerConnectionTest(options);
 
     addRenegotiation(test.chain,
-                      [
-                        function PC_SET_OFFER_OPTION(test) {
-                          test.setOfferOptions({ iceRestart: true });
-                        },
-                        function PC_LOCAL_EXPECT_ICE_CHECKING(test) {
-                          test.pcLocal.iceCheckingRestartExpected = true;
-                        },
-                        function PC_REMOTE_EXPECT_ICE_CHECKING(test) {
-                          test.pcRemote.iceCheckingRestartExpected = true;
-                        }
-                      ]
-                    );
+      [
+        // causes a full, normal ice restart
+        function PC_LOCAL_SET_OFFER_OPTION(test) {
+          test.setOfferOptions({ iceRestart: true });
+        },
+        function PC_LOCAL_EXPECT_ICE_CHECKING(test) {
+          test.pcLocal.iceCheckingRestartExpected = true;
+        },
+        function PC_REMOTE_EXPECT_ICE_CHECKING(test) {
+          test.pcRemote.iceCheckingRestartExpected = true;
+        }
+      ]
+    );
 
     test.setMediaConstraints([{audio: true}, {video: true}],
                              [{audio: true}, {video: true}]);
     test.run();
   });
 
 </script>
 </pre>
new file mode 100644
--- /dev/null
+++ b/dom/media/tests/mochitest/test_peerConnection_restartIceNoRtcpMux.html
@@ -0,0 +1,43 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <script type="application/javascript" src="pc.js"></script>
+</head>
+<body>
+<pre id="test">
+<script type="application/javascript">
+  createHTML({
+    bug: "906986",
+    title: "Renegotiation: restart ice, with disabled RTCP-Mux"
+  });
+
+  var test;
+  runNetworkTest(function (options) {
+    options = options || { };
+    options.rtcpmux = false;
+    test = new PeerConnectionTest(options);
+
+    addRenegotiation(test.chain,
+      [
+        // causes a full, normal ice restart
+        function PC_LOCAL_SET_OFFER_OPTION(test) {
+          test.setOfferOptions({ iceRestart: true });
+        },
+        function PC_LOCAL_EXPECT_ICE_CHECKING(test) {
+          test.pcLocal.iceCheckingRestartExpected = true;
+        },
+        function PC_REMOTE_EXPECT_ICE_CHECKING(test) {
+          test.pcRemote.iceCheckingRestartExpected = true;
+        }
+      ]
+    );
+
+    test.setMediaConstraints([{audio: true}, {video: true}],
+                             [{audio: true}, {video: true}]);
+    test.run();
+  });
+
+</script>
+</pre>
+</body>
+</html>
--- a/media/mtransport/nricectx.cpp
+++ b/media/mtransport/nricectx.cpp
@@ -373,19 +373,19 @@ void NrIceCtx::trickle_cb(void *arg, nr_
   MOZ_MTLOG(ML_INFO, "NrIceCtx(" << ctx->name_ << "): trickling candidate "
             << candidate_str);
 
   s->SignalCandidate(s, candidate_str);
 }
 
 
 void
-NrIceCtx::InitializeCryptoAndLogging(bool allow_loopback,
-                                     bool tcp_enabled,
-                                     bool allow_link_local) {
+NrIceCtx::InitializeGlobals(bool allow_loopback,
+                            bool tcp_enabled,
+                            bool allow_link_local) {
   // Initialize the crypto callbacks and logging stuff
   if (!initialized) {
     NR_reg_init(NR_REG_MODE_LOCAL);
     RLogRingBuffer::CreateInstance();
     nr_crypto_vtbl = &nr_ice_crypto_nss_vtbl;
     initialized = true;
 
     // Set the priorites for candidate type preferences.
@@ -457,131 +457,138 @@ NrIceCtx::InitializeCryptoAndLogging(boo
 }
 
 std::string
 NrIceCtx::GetNewUfrag()
 {
   char* ufrag;
   int r;
 
-  if ((r=nr_ice_get_new_ice_ufrag(&ufrag)))
+  if ((r=nr_ice_get_new_ice_ufrag(&ufrag))) {
+    MOZ_CRASH("Unable to get new ice ufrag");
     return "";
+  }
 
   std::string ufragStr = ufrag;
   RFREE(ufrag);
 
   return ufragStr;
 }
 
 std::string
 NrIceCtx::GetNewPwd()
 {
   char* pwd;
   int r;
 
-  if ((r=nr_ice_get_new_ice_pwd(&pwd)))
+  if ((r=nr_ice_get_new_ice_pwd(&pwd))) {
+    MOZ_CRASH("Unable to get new ice pwd");
     return "";
+  }
 
   std::string pwdStr = pwd;
   RFREE(pwd);
 
   return pwdStr;
 }
 
 bool
-NrIceCtx::Initialize(NrIceCtx* ctx,
-                     bool hide_non_default)
+NrIceCtx::Initialize(bool hide_non_default)
 {
   std::string ufrag = GetNewUfrag();
   std::string pwd = GetNewPwd();
 
-  return Initialize(ctx,
-                    hide_non_default,
+  return Initialize(hide_non_default,
                     ufrag,
                     pwd);
 }
 
 bool
-NrIceCtx::Initialize(NrIceCtx* ctx,
-                     bool hide_non_default,
+NrIceCtx::Initialize(bool hide_non_default,
                      const std::string& ufrag,
                      const std::string& pwd)
 {
+  MOZ_ASSERT(!ufrag.empty());
+  MOZ_ASSERT(!pwd.empty());
+  if (ufrag.empty() || pwd.empty()) {
+    return false;
+  }
+
   // Create the ICE context
   int r;
 
-  UINT4 flags = ctx->offerer_ ? NR_ICE_CTX_FLAGS_OFFERER:
+  UINT4 flags = offerer_ ? NR_ICE_CTX_FLAGS_OFFERER:
       NR_ICE_CTX_FLAGS_ANSWERER;
   flags |= NR_ICE_CTX_FLAGS_AGGRESSIVE_NOMINATION;
-  if (ctx->policy_ == ICE_POLICY_RELAY) {
+  if (policy_ == ICE_POLICY_RELAY) {
     flags |= NR_ICE_CTX_FLAGS_RELAY_ONLY;
   }
 
   if (hide_non_default)
     flags |= NR_ICE_CTX_FLAGS_ONLY_DEFAULT_ADDRS;
 
-  r = nr_ice_ctx_create_with_credentials(const_cast<char *>(ctx->name_.c_str()),
-                        flags,
-                        const_cast<char *>(ufrag.c_str()),
-                        const_cast<char *>(pwd.c_str()),
-                        &ctx->ctx_);
-  MOZ_ASSERT(ufrag == ctx->ctx_->ufrag);
-  MOZ_ASSERT(pwd == ctx->ctx_->pwd);
+  r = nr_ice_ctx_create_with_credentials(const_cast<char *>(name_.c_str()),
+                                         flags,
+                                         const_cast<char *>(ufrag.c_str()),
+                                         const_cast<char *>(pwd.c_str()),
+                                         &ctx_);
+  MOZ_ASSERT(ufrag == ctx_->ufrag);
+  MOZ_ASSERT(pwd == ctx_->pwd);
 
   if (r) {
-    MOZ_MTLOG(ML_ERROR, "Couldn't create ICE ctx for '" << ctx->name_ << "'");
+    MOZ_MTLOG(ML_ERROR, "Couldn't create ICE ctx for '" << name_ << "'");
     return false;
   }
 
   nr_interface_prioritizer *prioritizer = CreateInterfacePrioritizer();
   if (!prioritizer) {
     MOZ_MTLOG(LogLevel::Error, "Couldn't create interface prioritizer.");
     return false;
   }
 
-  r = nr_ice_ctx_set_interface_prioritizer(ctx->ctx_, prioritizer);
+  r = nr_ice_ctx_set_interface_prioritizer(ctx_, prioritizer);
   if (r) {
     MOZ_MTLOG(LogLevel::Error, "Couldn't set interface prioritizer.");
     return false;
   }
 
-  if (ctx->generating_trickle()) {
-    r = nr_ice_ctx_set_trickle_cb(ctx->ctx_, &NrIceCtx::trickle_cb, ctx);
+  if (generating_trickle()) {
+    r = nr_ice_ctx_set_trickle_cb(ctx_, &NrIceCtx::trickle_cb, this);
     if (r) {
-      MOZ_MTLOG(ML_ERROR, "Couldn't set trickle cb for '" << ctx->name_ << "'");
+      MOZ_MTLOG(ML_ERROR, "Couldn't set trickle cb for '" << name_ << "'");
       return false;
     }
   }
 
   // Create the handler objects
-  ctx->ice_handler_vtbl_ = new nr_ice_handler_vtbl();
-  ctx->ice_handler_vtbl_->select_pair = &NrIceCtx::select_pair;
-  ctx->ice_handler_vtbl_->stream_ready = &NrIceCtx::stream_ready;
-  ctx->ice_handler_vtbl_->stream_failed = &NrIceCtx::stream_failed;
-  ctx->ice_handler_vtbl_->ice_completed = &NrIceCtx::ice_completed;
-  ctx->ice_handler_vtbl_->msg_recvd = &NrIceCtx::msg_recvd;
-  ctx->ice_handler_vtbl_->ice_checking = &NrIceCtx::ice_checking;
+  ice_handler_vtbl_ = new nr_ice_handler_vtbl();
+  ice_handler_vtbl_->select_pair = &NrIceCtx::select_pair;
+  ice_handler_vtbl_->stream_ready = &NrIceCtx::stream_ready;
+  ice_handler_vtbl_->stream_failed = &NrIceCtx::stream_failed;
+  ice_handler_vtbl_->ice_completed = &NrIceCtx::ice_completed;
+  ice_handler_vtbl_->msg_recvd = &NrIceCtx::msg_recvd;
+  ice_handler_vtbl_->ice_checking = &NrIceCtx::ice_checking;
 
-  ctx->ice_handler_ = new nr_ice_handler();
-  ctx->ice_handler_->vtbl = ctx->ice_handler_vtbl_;
-  ctx->ice_handler_->obj = ctx;
+  ice_handler_ = new nr_ice_handler();
+  ice_handler_->vtbl = ice_handler_vtbl_;
+  ice_handler_->obj = this;
 
   // Create the peer ctx. Because we do not support parallel forking, we
   // only have one peer ctx.
-  std::string peer_name = ctx->name_ + ":default";
-  r = nr_ice_peer_ctx_create(ctx->ctx_, ctx->ice_handler_,
+  std::string peer_name = name_ + ":default";
+  r = nr_ice_peer_ctx_create(ctx_, ice_handler_,
                              const_cast<char *>(peer_name.c_str()),
-                             &ctx->peer_);
+                             &peer_);
   if (r) {
-    MOZ_MTLOG(ML_ERROR, "Couldn't create ICE peer ctx for '" << ctx->name_ << "'");
+    MOZ_MTLOG(ML_ERROR, "Couldn't create ICE peer ctx for '" << name_ << "'");
     return false;
   }
 
   nsresult rv;
-  ctx->sts_target_ = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
+  sts_target_ = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
 
   if (!NS_SUCCEEDED(rv))
     return false;
 
   return true;
 }
 
 // ONLY USE THIS FOR TESTING. Will cause totally unpredictable and possibly very
--- a/media/mtransport/nricectx.h
+++ b/media/mtransport/nricectx.h
@@ -210,28 +210,27 @@ class NrIceCtx {
                      ICE_CONTROLLED
   };
 
   enum Policy { ICE_POLICY_NONE,
                 ICE_POLICY_RELAY,
                 ICE_POLICY_ALL
   };
 
-  static void InitializeCryptoAndLogging(bool allow_loopback,
-                                         bool tcp_enabled,
-                                         bool allow_link_local);
-
-  static bool Initialize(NrIceCtx* ice_ctx,
-                         bool hide_non_default);
+  // initialize ICE globals, crypto, and logging
+  static void InitializeGlobals(bool allow_loopback,
+                                bool tcp_enabled,
+                                bool allow_link_local);
   static std::string GetNewUfrag();
   static std::string GetNewPwd();
-  static bool Initialize(NrIceCtx* ice_ctx,
-                         bool hide_non_default,
-                         const std::string& ufrag,
-                         const std::string& pwd);
+
+  bool Initialize(bool hide_non_default);
+  bool Initialize(bool hide_non_default,
+                  const std::string& ufrag,
+                  const std::string& pwd);
 
   // Deinitialize all ICE global state. Used only for testing.
   static void internal_DeinitializeGlobal();
 
 
   nr_ice_ctx *ctx() { return ctx_; }
   nr_ice_peer_ctx *peer() { return peer_; }
 
@@ -250,17 +249,16 @@ class NrIceCtx {
   // Some might be null
   size_t GetStreamCount() const
   {
     return streams_.size();
   }
 
   // The name of the ctx
   const std::string& name() const { return name_; }
-  bool offerer() const { return offerer_; }
 
   // Get ufrag and password.
   std::string ufrag() const;
   std::string pwd() const;
 
   // Current state
   ConnectionState connection_state() const {
     return connection_state_;
--- a/media/mtransport/nricectxhandler.cpp
+++ b/media/mtransport/nricectxhandler.cpp
@@ -1,49 +1,52 @@
 #include <sstream>
 
+#include "logging.h"
+
 // nICEr includes
 extern "C" {
 #include "nr_api.h"
 #include "ice_ctx.h"
 }
 
 // Local includes
 #include "nricectxhandler.h"
 #include "nricemediastream.h"
 
 namespace mozilla {
 
+MOZ_MTLOG_MODULE("mtransport")
+
 NrIceCtxHandler::NrIceCtxHandler(const std::string& name,
-                  bool offerer,
-                  NrIceCtx::Policy policy)
+                                 bool offerer,
+                                 NrIceCtx::Policy policy)
   : current_ctx(new NrIceCtx(name, offerer, policy)),
-    restart_ctx(nullptr),
+    old_ctx(nullptr),
     restart_count(0)
 {
 }
 
 RefPtr<NrIceCtxHandler>
 NrIceCtxHandler::Create(const std::string& name,
                         bool offerer,
                         bool allow_loopback,
                         bool tcp_enabled,
                         bool allow_link_local,
                         bool hide_non_default,
                         NrIceCtx::Policy policy)
 {
-  // InitializeCryptoAndLogging only executes once
-  NrIceCtx::InitializeCryptoAndLogging(allow_loopback,
-                                       tcp_enabled,
-                                       allow_link_local);
+  // InitializeGlobals only executes once
+  NrIceCtx::InitializeGlobals(allow_loopback, tcp_enabled, allow_link_local);
 
   RefPtr<NrIceCtxHandler> ctx = new NrIceCtxHandler(name, offerer, policy);
 
-  if (!NrIceCtx::Initialize(ctx->current_ctx,
-                            hide_non_default)) {
+  if (ctx == nullptr ||
+      ctx->current_ctx == nullptr ||
+      !ctx->current_ctx->Initialize(hide_non_default)) {
     return nullptr;
   }
 
   return ctx;
 }
 
 
 RefPtr<NrIceMediaStream>
@@ -52,61 +55,69 @@ NrIceCtxHandler::CreateStream(const std:
   // To make tracking NrIceMediaStreams easier during ICE restart
   // prepend an int to the name that increments with each ICE restart
   std::ostringstream os;
   os << restart_count << "-" << name;
   return NrIceMediaStream::Create(this->current_ctx, os.str(), components);
 }
 
 
-void
+bool
 NrIceCtxHandler::BeginIceRestart()
 {
   std::string ufrag = NrIceCtx::GetNewUfrag();
   std::string pwd = NrIceCtx::GetNewPwd();
-  BeginIceRestart(ufrag, pwd);
+  return BeginIceRestart(ufrag, pwd);
 }
 
 
-void
+bool
 NrIceCtxHandler::BeginIceRestart(const std::string& ufrag,
                                  const std::string& pwd)
 {
-  MOZ_ASSERT(!restart_ctx, "existing ice restart in progress");
+  MOZ_ASSERT(!old_ctx, "existing ice restart in progress");
+  if (old_ctx) {
+    MOZ_MTLOG(ML_ERROR, "Existing ice restart in progress");
+    return false; // ice restart already in progress
+  }
+
   RefPtr<NrIceCtx> new_ctx = new NrIceCtx(this->current_ctx->name(),
-                                          this->current_ctx->offerer(),
+                                          true, // offerer
                                           this->current_ctx->policy());
+  if (new_ctx == nullptr) {
+    return false;
+  }
 
   // reconstitute the hide_non_default bool based on the flags stored in the
   // original ctx flags
   bool hide_non_default = current_ctx->ctx()->flags & NR_ICE_CTX_FLAGS_ONLY_DEFAULT_ADDRS;
 
-  NrIceCtx::Initialize(new_ctx,
-                       hide_non_default,
-                       ufrag,
-                       pwd);
+  if (!new_ctx->Initialize(hide_non_default, ufrag, pwd)) {
+    return false;
+  }
 
   ++restart_count;
-  restart_ctx = current_ctx;
+  old_ctx = current_ctx;
   current_ctx = new_ctx;
+  return true;
 }
 
 
 void
 NrIceCtxHandler::FinalizeIceRestart()
 {
   // no harm calling this even if we're not in the middle of restarting
-  restart_ctx = nullptr;
+  old_ctx = nullptr;
 }
 
 
 void
 NrIceCtxHandler::RollbackIceRestart()
 {
-  if (restart_ctx == nullptr) {
+  if (old_ctx == nullptr) {
     return;
   }
-  current_ctx = restart_ctx;
-  restart_ctx = nullptr;
+  current_ctx = old_ctx;
+  old_ctx = nullptr;
 }
 
 
 } // close namespace
--- a/media/mtransport/nricectxhandler.h
+++ b/media/mtransport/nricectxhandler.h
@@ -9,41 +9,42 @@ class NrIceCtxHandler {
 public:
   // TODO(ekr@rtfm.com): Too many bools here. Bug 1193437.
   static RefPtr<NrIceCtxHandler> Create(const std::string& name,
                                  bool offerer,
                                  bool allow_loopback = false,
                                  bool tcp_enabled = true,
                                  bool allow_link_local = false,
                                  bool hide_non_default = false,
-                                 NrIceCtx::Policy policy = NrIceCtx::ICE_POLICY_ALL);
+                                 NrIceCtx::Policy policy = 
+                                   NrIceCtx::ICE_POLICY_ALL);
 
   RefPtr<NrIceMediaStream> CreateStream(const std::string& name,
                                         int components);
 
   RefPtr<NrIceCtx> ctx() { return current_ctx; }
 
-  void BeginIceRestart(); // used in testing
-  void BeginIceRestart(const std::string& ufrag,
+  bool BeginIceRestart(); // used in testing
+  bool BeginIceRestart(const std::string& ufrag,
                        const std::string& pwd);
-  bool IsRestarting() { return (restart_ctx != nullptr); }
+  bool IsRestarting() const { return (old_ctx != nullptr); }
   void FinalizeIceRestart();
   void RollbackIceRestart();
 
 
   NS_INLINE_DECL_THREADSAFE_REFCOUNTING(NrIceCtxHandler)
 
 private:
   NrIceCtxHandler(const std::string& name,
                   bool offerer,
                   NrIceCtx::Policy policy);
-  NrIceCtxHandler(); // disable
+  NrIceCtxHandler() = delete;
   ~NrIceCtxHandler() {}
   DISALLOW_COPY_ASSIGN(NrIceCtxHandler);
 
   RefPtr<NrIceCtx> current_ctx;
-  RefPtr<NrIceCtx> restart_ctx; // for while restart is in progress
+  RefPtr<NrIceCtx> old_ctx; // for while restart is in progress
   int restart_count; // used to differentiate streams between restarted ctx
 };
 
 } // close namespace
 
 #endif // nricectxhandler_h__
--- a/media/mtransport/test/ice_unittest.cpp
+++ b/media/mtransport/test/ice_unittest.cpp
@@ -284,17 +284,18 @@ class IceTestPeer : public sigslot::has_
  public:
   // TODO(ekr@rtfm.com): Convert to flags when NrIceCtx::Create() does.
   // Bug 1193437.
   IceTestPeer(const std::string& name, bool offerer,
               bool allow_loopback = false, bool enable_tcp = true,
               bool allow_link_local = false, bool hide_non_default = false) :
       name_(name),
       ice_ctx_(NrIceCtxHandler::Create(name, offerer, allow_loopback,
-                                       enable_tcp, allow_link_local, hide_non_default)),
+                                       enable_tcp, allow_link_local, 
+                                       hide_non_default)),
       candidates_(),
       gathering_complete_(false),
       ready_ct_(0),
       ice_complete_(false),
       ice_reached_checking_(false),
       received_(0),
       sent_(0),
       fake_resolver_(),
@@ -498,17 +499,18 @@ class IceTestPeer : public sigslot::has_
     }
 
     std::vector<std::string> candidates_in =
       ice_ctx_->ctx()->GetStream(stream)->GetCandidates();
 
     for (size_t i=0; i < candidates_in.size(); i++) {
       std::string candidate(FilterCandidate(candidates_in[i]));
       if (!candidate.empty()) {
-        std::cerr << name_ << " Returning candidate: " << candidate << std::endl;
+        std::cerr << name_ << " Returning candidate: "
+                           << candidate << std::endl;
         candidates.push_back(candidate);
       }
     }
 
     return candidates;
   }
 
   void SetExpectedTypes(NrIceCandidate::Type local,
@@ -547,35 +549,35 @@ class IceTestPeer : public sigslot::has_
       }
     }
     return host_net;
   }
 
   bool gathering_complete() { return gathering_complete_; }
   int ready_ct() { return ready_ct_; }
   bool is_ready_s(size_t stream) {
-    if (!ice_ctx_->ctx()->GetStream(stream)) {
+    RefPtr<NrIceMediaStream> media_stream = ice_ctx_->ctx()->GetStream(stream);
+    if (!media_stream) {
       EXPECT_TRUE(false) << "No such stream " << stream;
       return false;
     }
-    return ice_ctx_->ctx()->GetStream(stream)->state() == NrIceMediaStream::ICE_OPEN;
+    return media_stream->state() == NrIceMediaStream::ICE_OPEN;
   }
   bool is_ready(size_t stream)
   {
     bool result;
     test_utils->sts_target()->Dispatch(
         WrapRunnableRet(&result, this, &IceTestPeer::is_ready_s, stream),
         NS_DISPATCH_SYNC);
     return result;
   }
   bool ice_complete() { return ice_complete_; }
   bool ice_reached_checking() { return ice_reached_checking_; }
   size_t received() { return received_; }
   size_t sent() { return sent_; }
-  void resetStats() { received_ = sent_ = 0; }
 
 
   void RestartIce() {
     test_utils->sts_target()->Dispatch(
         WrapRunnable(this, &IceTestPeer::RestartIce_s),
         NS_DISPATCH_SYNC);
   }
 
@@ -682,18 +684,17 @@ class IceTestPeer : public sigslot::has_
         NS_DISPATCH_SYNC);
   }
 
   void SimulateTrickle(size_t stream) {
     std::cerr << name_ << " Doing trickle for stream " << stream << std::endl;
     // If we are in trickle deferred mode, now trickle in the candidates
     // for |stream|
 
-    // The size of streams is not going to change out from under us, so should
-    // be safe here.
+    // We should be safe here since stream changes happen on STS thread.
     ASSERT_GT(remote_->ice_ctx_->ctx()->GetStreamCount(), stream);
     ASSERT_TRUE(remote_->ice_ctx_->ctx()->GetStream(stream).get());
 
     std::vector<SchedulableTrickleCandidate*>& candidates =
       ControlTrickle(stream);
 
     for (auto i = candidates.begin(); i != candidates.end(); ++i) {
       (*i)->Schedule(0);
@@ -795,17 +796,18 @@ class IceTestPeer : public sigslot::has_
   void DumpAndCheckActiveCandidates_s() {
     std::cerr << name_ << " Active candidates:" << std::endl;
     for (size_t i=0; i < ice_ctx_->ctx()->GetStreamCount(); ++i) {
       if (!ice_ctx_->ctx()->GetStream(i)) {
         continue;
       }
 
       for (size_t j=0; j < ice_ctx_->ctx()->GetStream(i)->components(); ++j) {
-        std::cerr << name_ << " Stream " << i << " component " << j+1 << std::endl;
+        std::cerr << name_ << " Stream " << i
+                           << " component " << j+1 << std::endl;
 
         NrIceCandidate *local;
         NrIceCandidate *remote;
 
         nsresult res = ice_ctx_->ctx()->GetStream(i)->GetActivePair(j+1,
                                                                     &local,
                                                                     &remote);
         if (res == NS_ERROR_NOT_AVAILABLE) {
@@ -891,17 +893,17 @@ class IceTestPeer : public sigslot::has_
   // Handle events
   void GatheringStateChange(NrIceCtx* ctx,
                             NrIceCtx::GatheringState state) {
     (void)ctx;
     if (state != NrIceCtx::ICE_CTX_GATHER_COMPLETE) {
       return;
     }
 
-    std::cerr << "Gathering complete for " <<  name_ << std::endl;
+    std::cerr << name_ << " Gathering complete" << std::endl;
     gathering_complete_ = true;
 
     std::cerr << name_ << " CANDIDATES:" << std::endl;
     for (size_t i=0; i<ice_ctx_->ctx()->GetStreamCount(); ++i) {
       std::cerr << "Stream " << name_ << std::endl;
 
       if (!ice_ctx_->ctx()->GetStream(i)) {
         std::cerr << "DISABLED" << std::endl;
@@ -927,31 +929,27 @@ class IceTestPeer : public sigslot::has_
     std::cerr << "Candidate for stream " << stream->name() << " initialized: "
       << candidate << std::endl;
     candidates_[stream->name()].push_back(candidate);
 
     // If we are connected, then try to trickle to the other side.
     if (remote_ && remote_->remote_ && (trickle_mode_ != TRICKLE_SIMULATE)) {
       // first, find the index of the stream we've been given so
       // we can get the corresponding stream on the remote side
-      size_t index = -1;
       for (size_t i=0; i<ice_ctx_->ctx()->GetStreamCount(); ++i) {
         if (ice_ctx_->ctx()->GetStream(i) == stream) {
-          index = i;
-          break;
+          RefPtr<NrIceCtx> ctx = remote_->ice_ctx_->ctx();
+          ASSERT_GT(ctx->GetStreamCount(), i);
+          nsresult res = ctx->GetStream(i)->ParseTrickleCandidate(candidate);
+          ASSERT_TRUE(NS_SUCCEEDED(res));
+          ++trickled_;
+          return;
         }
       }
-      ASSERT_NE(index, -1);
-
-      ASSERT_GT(remote_->ice_ctx_->ctx()->GetStreamCount(), index);
-      nsresult res = 
-        remote_->ice_ctx_->ctx()->GetStream(index)->ParseTrickleCandidate(
-          candidate);
-      ASSERT_TRUE(NS_SUCCEEDED(res));
-      ++trickled_;
+      ADD_FAILURE() << "No matching stream found for " << stream;
     }
   }
 
   nsresult GetCandidatePairs_s(size_t stream_index,
                                std::vector<NrIceCandidatePair>* pairs)
   {
     MOZ_ASSERT(pairs);
     if (stream_index >= ice_ctx_->ctx()->GetStreamCount() ||
@@ -1086,57 +1084,60 @@ class IceTestPeer : public sigslot::has_
     }
 
     ASSERT_TRUE(removed_pairs.empty()) << "At least one candidate pair has "
                                           "gone missing.";
   }
 
   void StreamReady(NrIceMediaStream *stream) {
     ++ready_ct_;
-    std::cerr << "Stream ready for " << stream->name() << " ct=" << ready_ct_ << std::endl;
+    std::cerr << name_ << " Stream ready for " << stream->name()
+                       << " ct=" << ready_ct_ << std::endl;
     DumpCandidatePairs_s(stream);
   }
   void StreamFailed(NrIceMediaStream *stream) {
-    std::cerr << "Stream failed for " << stream->name() << " ct=" << ready_ct_ << std::endl;
+    std::cerr << name_ << " Stream failed for " << stream->name()
+                       << " ct=" << ready_ct_ << std::endl;
     DumpCandidatePairs_s(stream);
   }
 
   void ConnectionStateChange(NrIceCtx* ctx,
                              NrIceCtx::ConnectionState state) {
     (void)ctx;
     switch (state) {
       case NrIceCtx::ICE_CTX_INIT:
         break;
       case NrIceCtx::ICE_CTX_CHECKING:
-        std::cerr << "ICE reached checking for " << name_ << std::endl;
+        std::cerr << name_ << " ICE reached checking " << std::endl;
         ice_reached_checking_ = true;
         break;
       case NrIceCtx::ICE_CTX_OPEN:
-        std::cerr << "ICE completed for " << name_ << std::endl;
+        std::cerr << name_ << " ICE completed " << std::endl;
         ice_complete_ = true;
         break;
       case NrIceCtx::ICE_CTX_FAILED:
         break;
     }
   }
 
   void PacketReceived(NrIceMediaStream *stream, int component, const unsigned char *data,
                       int len) {
     std::cerr << name_ << ": received " << len << " bytes" << std::endl;
     ++received_;
   }
 
   void SendPacket(int stream, int component, const unsigned char *data,
                   int len) {
-    if (!ice_ctx_->ctx()->GetStream(stream)) {
+    RefPtr<NrIceMediaStream> media_stream = ice_ctx_->ctx()->GetStream(stream);
+    if (!media_stream) {
       ADD_FAILURE() << "No such stream " << stream;
       return;
     }
 
-    ASSERT_TRUE(NS_SUCCEEDED(ice_ctx_->ctx()->GetStream(stream)->SendPacket(component, data, len)));
+    ASSERT_TRUE(NS_SUCCEEDED(media_stream->SendPacket(component, data, len)));
 
     ++sent_;
     std::cerr << name_ << ": sent " << len << " bytes" << std::endl;
   }
 
   void SetCandidateFilter(CandidateFilter filter) {
     candidate_filter_ = filter;
   }
@@ -1157,17 +1158,18 @@ class IceTestPeer : public sigslot::has_
                         &IceTestPeer::ParseCandidate_s,
                         i,
                         candidate),
         NS_DISPATCH_SYNC);
   }
 
   void DisableComponent_s(size_t stream, int component_id) {
     ASSERT_LT(stream, ice_ctx_->ctx()->GetStreamCount());
-    ASSERT_TRUE(ice_ctx_->ctx()->GetStream(stream).get()) << "No such stream " << stream;
+    ASSERT_TRUE(ice_ctx_->ctx()->GetStream(stream).get()) << "No such stream " 
+                                                          << stream;
     nsresult res =
       ice_ctx_->ctx()->GetStream(stream)->DisableComponent(component_id);
     ASSERT_TRUE(NS_SUCCEEDED(res));
   }
 
   void DisableComponent(size_t stream, int component_id)
   {
     test_utils->sts_target()->Dispatch(
@@ -1425,17 +1427,17 @@ class IceGatherTest : public ::testing::
  protected:
   mozilla::ScopedDeletePtr<IceTestPeer> peer_;
 };
 
 class IceConnectTest : public ::testing::Test {
  public:
   IceConnectTest() :
     initted_(false),
-    test_stun_server_initedd_(false),
+    test_stun_server_inited_(false),
     use_nat_(false),
     filtering_type_(TestNat::ENDPOINT_INDEPENDENT),
     mapping_type_(TestNat::ENDPOINT_INDEPENDENT),
     block_udp_(false) {}
 
   void SetUp() {
     nsresult rv;
     target_ = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
@@ -1464,46 +1466,46 @@ class IceConnectTest : public ::testing:
   void RemoveStream(size_t index) {
     p1_->RemoveStream(index);
     p2_->RemoveStream(index);
   }
 
   void Init(bool allow_loopback,
             bool enable_tcp,
             bool default_only = false,
-            bool setupStunServers = true) {
+            bool setup_stun_servers = true) {
     if (initted_) {
         return;
     }
 
     p1_ = new IceTestPeer("P1", true, allow_loopback,
                           enable_tcp, false, default_only);
     p2_ = new IceTestPeer("P2", false, allow_loopback,
                           enable_tcp, false, default_only);
-    InitPeer(p1_, setupStunServers);
-    InitPeer(p2_, setupStunServers);
+    InitPeer(p1_, setup_stun_servers);
+    InitPeer(p2_, setup_stun_servers);
 
     initted_ = true;
   }
 
-  void InitPeer(IceTestPeer* peer, bool setupStunServers = true) {
+  void InitPeer(IceTestPeer* peer, bool setup_stun_servers = true) {
     if (use_nat_) {
       // If we enable nat simulation, but still use a real STUN server somewhere
       // on the internet, we will see failures if there is a real NAT in
       // addition to our simulated one, particularly if it disallows
       // hairpinning.
-      if (setupStunServers) {
+      if (setup_stun_servers) {
         InitTestStunServer();
         peer->UseTestStunServer();
       }
       peer->UseNat();
       peer->SetFilteringType(filtering_type_);
       peer->SetMappingType(mapping_type_);
       peer->SetBlockUdp(block_udp_);
-    } else if (setupStunServers) {
+    } else if (setup_stun_servers) {
       std::vector<NrIceStunServer> stun_servers;
 
       stun_servers.push_back(*NrIceStunServer::Create(g_stun_server_address,
                                                       kDefaultStunServerPort, kNrIceTransportUdp));
       stun_servers.push_back(*NrIceStunServer::Create(g_stun_server_address,
                                                       kDefaultStunServerPort, kNrIceTransportTcp));
 
       peer->SetStunServers(stun_servers);
@@ -1547,29 +1549,29 @@ class IceConnectTest : public ::testing:
 
   void SetMappingType(TestNat::NatBehavior type) {
     // to be useful, this method should be called before Init
     ASSERT_FALSE(initted_);
     mapping_type_ = type;
   }
 
   void BlockUdp() {
-    // to be useful, this method should be called before Init
-    ASSERT_FALSE(initted_);
+    // note: |block_udp_| is used only in InitPeer.
+    // Use IceTestPeer::SetBlockUdp to act on the peer directly.
     block_udp_ = true;
   }
 
   void InitTestStunServer() {
-    if (test_stun_server_initedd_) {
+    if (test_stun_server_inited_) {
       return;
     }
 
     std::cerr << "Resetting TestStunServer" << std::endl;
     TestStunServer::GetInstance(AF_INET)->Reset();
-    test_stun_server_initedd_ = true;
+    test_stun_server_inited_ = true;
   }
 
   void UseTestStunServer() {
     InitTestStunServer();
     p1_->UseTestStunServer();
     p2_->UseTestStunServer();
   }
 
@@ -1589,44 +1591,44 @@ class IceConnectTest : public ::testing:
   void SetCandidateFilter(CandidateFilter filter, bool both=true) {
     p1_->SetCandidateFilter(filter);
     if (both) {
       p2_->SetCandidateFilter(filter);
     }
   }
 
   void Connect() {
-    ConnectCallerAndCallee(p2_, p1_);
+    ConnectCallerAndCallee(p1_, p2_);
   }
 
   void ConnectCallerAndCallee(IceTestPeer* caller, IceTestPeer* callee) {
-    ASSERT_TRUE(caller->ready_ct() == 0 && 
-                caller->ice_complete() == 0 && 
-                caller->ice_reached_checking() == 0);
-    ASSERT_TRUE(callee->ready_ct() == 0 && 
-                callee->ice_complete() == 0 && 
-                callee->ice_reached_checking() == 0);
-
-    // IceTestPeer::Connect grabs attributes from the first arg, and gives them
-    // to |this|, meaning that p2_->Connect(p1_, ...) simulates p1 sending an
-    // offer to p2. Order matters here because it determines which peer is
-    // controlling.
+    ASSERT_TRUE(caller->ready_ct() == 0);
+    ASSERT_TRUE(caller->ice_complete() == 0);
+    ASSERT_TRUE(caller->ice_reached_checking() == 0);
+    ASSERT_TRUE(callee->ready_ct() == 0);
+    ASSERT_TRUE(callee->ice_complete() == 0);
+    ASSERT_TRUE(callee->ice_reached_checking() == 0);
+
+    // IceTestPeer::Connect grabs attributes from the first arg, and
+    // gives them to |this|, meaning that callee->Connect(caller, ...)
+    // simulates caller sending an offer to callee. Order matters here
+    // because it determines which peer is controlling.
+    callee->Connect(caller, TRICKLE_NONE);
     caller->Connect(callee, TRICKLE_NONE);
-    callee->Connect(caller, TRICKLE_NONE);
-
-    ASSERT_TRUE_WAIT(callee->ready_ct() == 1 && caller->ready_ct() == 1,
+
+    ASSERT_TRUE_WAIT(caller->ready_ct() == 1 && callee->ready_ct() == 1,
                      kDefaultTimeout);
-    ASSERT_TRUE_WAIT(callee->ice_complete() && caller->ice_complete(),
+    ASSERT_TRUE_WAIT(caller->ice_complete() && callee->ice_complete(),
                      kDefaultTimeout);
 
+    ASSERT_TRUE(caller->ice_reached_checking());
     ASSERT_TRUE(callee->ice_reached_checking());
-    ASSERT_TRUE(caller->ice_reached_checking());
-
+
+    caller->DumpAndCheckActiveCandidates();
     callee->DumpAndCheckActiveCandidates();
-    caller->DumpAndCheckActiveCandidates();
   }
 
   void SetExpectedTypes(NrIceCandidate::Type local, NrIceCandidate::Type remote,
                         std::string transport = kNrIceTransportUdp) {
     p1_->SetExpectedTypes(local, remote, transport);
     p2_->SetExpectedTypes(local, remote, transport);
   }
 
@@ -1706,39 +1708,43 @@ class IceConnectTest : public ::testing:
   }
 
   // default is p1_ sending to p2_
   void SendReceive() {
     SendReceive(p1_, p2_);
   }
 
   void SendReceive(IceTestPeer *p1, IceTestPeer *p2,
-                   bool expectTxFailure = false,
-                   bool expectRxFailure = false) {
+                   bool expect_tx_failure = false,
+                   bool expect_rx_failure = false) {
+    size_t previousSent = p1->sent();
+    size_t previousReceived = p2->received();
+
     test_utils->sts_target()->Dispatch(
         WrapRunnable(p1,
                      &IceTestPeer::SendPacket, 0, 1,
                      reinterpret_cast<const unsigned char *>("TEST"), 4),
         NS_DISPATCH_SYNC);
-    if (expectTxFailure) {
-      ASSERT_NE(1u, p1->sent());
+
+    if (expect_tx_failure) {
+      ASSERT_EQ(previousSent, p1->sent());
     } else {
-      ASSERT_EQ(1u, p1->sent());
+      ASSERT_EQ(previousSent+1, p1->sent());
     }
-    if (expectRxFailure) {
+    if (expect_rx_failure) {
       usleep(1000);
-      ASSERT_TRUE(p2->received() == 0);
+      ASSERT_EQ(previousReceived, p2->received());
     } else {
-      ASSERT_TRUE_WAIT(p2->received() == 1, 1000);
+      ASSERT_TRUE_WAIT(p2->received() == previousReceived+1, 1000);
     }
   }
 
  protected:
   bool initted_;
-  bool test_stun_server_initedd_;
+  bool test_stun_server_inited_;
   nsCOMPtr<nsIEventTarget> target_;
   mozilla::ScopedDeletePtr<IceTestPeer> p1_;
   mozilla::ScopedDeletePtr<IceTestPeer> p2_;
   bool use_nat_;
   TestNat::NatBehavior filtering_type_;
   TestNat::NatBehavior mapping_type_;
   bool block_udp_;
 };
@@ -2265,91 +2271,71 @@ TEST_F(IceConnectTest, TestConnect) {
 }
 
 
 TEST_F(IceConnectTest, TestConnectRestartIce) {
   AddStream("first", 1);
   ASSERT_TRUE(Gather());
   Connect();
   SendReceive(p1_, p2_);
-  p1_->resetStats();
-  p2_->resetStats();
 
   p2_->RestartIce();
   ASSERT_FALSE(p2_->gathering_complete());
 
   // verify p1 and p2 streams are still connected after restarting ice on p2
   SendReceive(p1_, p2_);
-  p1_->resetStats();
-  p2_->resetStats();
 
   mozilla::ScopedDeletePtr<IceTestPeer> p3_;
   p3_ = new IceTestPeer("P3", true, false, false, false, false);
   InitPeer(p3_);
   p3_->AddStream(1);
 
   p2_->AddStream(1);
   ASSERT_TRUE(GatherCallerAndCallee(p2_, p3_));
   std::cout << "-------------------------------------------------" << std::endl;
-  ConnectCallerAndCallee(p2_, p3_);
+  ConnectCallerAndCallee(p3_, p2_);
   SendReceive(p1_, p2_); // p1 and p2 still connected
-  p2_->resetStats();
   SendReceive(p3_, p2_); // p3 and p2 are now connected
 
   p2_->FinalizeIceRestart();
-  p1_->resetStats();
-  p2_->resetStats();
-  p3_->resetStats();
   SendReceive(p3_, p2_); // p3 and p2 are still connected
 
-  p1_->resetStats();
-  p2_->resetStats();
   SendReceive(p1_, p2_, false, true); // p1 and p2 not connected
 
   p3_ = nullptr;
 }
 
 
 TEST_F(IceConnectTest, TestConnectRestartIceThenAbort) {
   AddStream("first", 1);
   ASSERT_TRUE(Gather());
   Connect();
   SendReceive(p1_, p2_);
-  p1_->resetStats();
-  p2_->resetStats();
 
   p2_->RestartIce();
   ASSERT_FALSE(p2_->gathering_complete());
 
   // verify p1 and p2 streams are still connected after restarting ice on p2
   SendReceive(p1_, p2_);
-  p1_->resetStats();
-  p2_->resetStats();
 
   mozilla::ScopedDeletePtr<IceTestPeer> p3_;
   p3_ = new IceTestPeer("P3", true, false, false, false, false);
   InitPeer(p3_);
   p3_->AddStream(1);
 
   p2_->AddStream(1);
   ASSERT_TRUE(GatherCallerAndCallee(p2_, p3_));
   std::cout << "-------------------------------------------------" << std::endl;
-  ConnectCallerAndCallee(p2_, p3_);
+  ConnectCallerAndCallee(p3_, p2_);
   SendReceive(p1_, p2_); // p1 and p2 still connected
-  p2_->resetStats();
   SendReceive(p3_, p2_); // p3 and p2 are now connected
 
   p2_->RollbackIceRestart();
-  p1_->resetStats();
-  p2_->resetStats();
-  p3_->resetStats();
   SendReceive(p1_, p2_); // p1 and p2 are still connected
 
-  p3_->resetStats();
-  p2_->resetStats();
   SendReceive(p3_, p2_, false, true); // p3 and p2 not connected
 
   p3_ = nullptr;
 }
 
 
 TEST_F(IceConnectTest, TestConnectTcp) {
   Init(false, true);
@@ -3148,17 +3134,17 @@ TEST_F(IceConnectTest, TestPollCandPairs
   ASSERT_NE(0U, pairs.size());
   ASSERT_TRUE(p2_->CandidatePairsPriorityDescending(pairs));
   ASSERT_TRUE(ContainsSucceededPair(pairs));
 }
 
 TEST_F(IceConnectTest, TestHostCandPairingFilter) {
   Init(false, false, false, false);
   AddStream("first", 1);
-  ASSERT_TRUE(Gather(kDefaultTimeout));
+  ASSERT_TRUE(Gather());
   SetCandidateFilter(IsIpv4Candidate);
 
   int host_net = p1_->GetCandidatesPrivateIpv4Range(0);
   if (host_net <= 0) {
     // TODO bug 1226838: make this work with multiple private IPs
     FAIL() << "This test needs exactly one private IPv4 host candidate to work" << std::endl;
   }
 
@@ -3182,17 +3168,17 @@ TEST_F(IceConnectTest, TestHostCandPairi
 // TODO Bug 1226838 - See Comment 2 - this test can't work as written
 TEST_F(IceConnectTest, DISABLED_TestSrflxCandPairingFilter) {
   if (g_stun_server_address.empty()) {
     return;
   }
 
   Init(false, false, false, false);
   AddStream("first", 1);
-  ASSERT_TRUE(Gather(kDefaultTimeout));
+  ASSERT_TRUE(Gather());
   SetCandidateFilter(IsSrflxCandidate);
 
   if (p1_->GetCandidatesPrivateIpv4Range(0) <= 0) {
     // TODO bug 1226838: make this work with public IP addresses
     std::cerr << "Don't run this test at IETF meetings!" << std::endl;
     FAIL() << "This test needs one private IPv4 host candidate to work" << std::endl;
   }
 
--- a/media/mtransport/third_party/nICEr/src/ice/ice_ctx.c
+++ b/media/mtransport/third_party/nICEr/src/ice/ice_ctx.c
@@ -968,44 +968,48 @@ int nr_ice_ctx_hide_candidate(nr_ice_ctx
     if (ctx->flags & NR_ICE_CTX_FLAGS_ONLY_DEFAULT_ADDRS) {
       if (cand->type == HOST)
         return 1;
     }
 
     return 0;
   }
 
+#define ICE_UFRAG_LEN 8
 int nr_ice_get_new_ice_ufrag(char** ufrag)
   {
     int r,_status;
-    char buf[10];
+    char buf[ICE_UFRAG_LEN+1];
 
-    if(r=nr_ice_random_string(buf,8))
+    if(r=nr_ice_random_string(buf,ICE_UFRAG_LEN))
       ABORT(r);
     if(!(*ufrag=r_strdup(buf)))
       ABORT(r);
 
     _status=0;
   abort:
     if(_status) {
       RFREE(*ufrag);
+      *ufrag = 0;
     }
     return(_status);
   }
 
+#define ICE_PWD_LEN 32
 int nr_ice_get_new_ice_pwd(char** pwd)
   {
     int r,_status;
-    char buf[40];
+    char buf[ICE_PWD_LEN+1];
 
-    if(r=nr_ice_random_string(buf,32))
+    if(r=nr_ice_random_string(buf,ICE_PWD_LEN))
       ABORT(r);
     if(!(*pwd=r_strdup(buf)))
       ABORT(r);
 
     _status=0;
   abort:
     if(_status) {
       RFREE(*pwd);
+      *pwd = 0;
     }
     return(_status);
   }
 
--- a/media/mtransport/transportlayerice.cpp
+++ b/media/mtransport/transportlayerice.cpp
@@ -82,44 +82,39 @@ namespace mozilla {
 #undef ERROR
 #endif
 
 MOZ_MTLOG_MODULE("mtransport")
 
 TransportLayerIce::TransportLayerIce(const std::string& name)
     : name_(name),
       ctx_(nullptr), stream_(nullptr), component_(0),
-      old_ctx_(nullptr), old_stream_(nullptr), old_component_(0)
+      old_stream_(nullptr)
 {
-  // setup happens later 
+  // setup happens later
 }
 
 TransportLayerIce::~TransportLayerIce() {
   // No need to do anything here, since we use smart pointers
 }
 
 void TransportLayerIce::SetParameters(RefPtr<NrIceCtx> ctx,
                                       RefPtr<NrIceMediaStream> stream,
                                       int component) {
   // If SetParameters is called and we already have a stream_, this means
   // we're handling an ICE restart.  We need to hold the old stream until
   // we know the new stream is working.
   if (stream_ && !old_stream_) {
     MOZ_ASSERT(stream_ != stream); // make sure we're getting a different stream
-    MOZ_ASSERT(old_ctx_ == nullptr);
     MOZ_ASSERT(old_stream_ == nullptr);
-    MOZ_ASSERT(old_component_ == 0);
     // Here we leave the old stream's signals connected until we don't need
     // it anymore.  They will be disconnected if ice restart is successful.
-    old_ctx_ = ctx_;
     old_stream_ = stream_;
-    old_component_ = component_;
     MOZ_MTLOG(ML_INFO, LAYER_INFO << "SetParameters save old stream("
-      << old_stream_->name() << ","
-      << old_component_ << ")");
+                                  << old_stream_->name() << ")");
   }
 
   ctx_ = ctx;
   stream_ = stream;
   component_ = component;
 
   PostSetup();
 }
@@ -133,54 +128,56 @@ void TransportLayerIce::PostSetup() {
                                         &TransportLayerIce::IcePacketReceived);
   if (stream_->state() == NrIceMediaStream::ICE_OPEN) {
     TL_SET_STATE(TS_OPEN);
     // Reset old ice stream if new stream is good
     ResetOldStream();
   }
 }
 
-void
-TransportLayerIce::ResetOldStream()
-{
+void TransportLayerIce::ResetOldStream() {
   if (old_stream_ == nullptr) {
     return; // no work to do
   }
   // ICE Ready on the new stream, we can forget the old stream now
-  MOZ_MTLOG(ML_INFO, LAYER_INFO << "ResetOldStream(" << old_stream_->name() << ","
-    << old_component_ << ")");
+  MOZ_MTLOG(ML_INFO, LAYER_INFO << "ResetOldStream(" << old_stream_->name() 
+                                << ")");
   old_stream_->SignalReady.disconnect(this);
   old_stream_->SignalFailed.disconnect(this);
   old_stream_->SignalPacketReceived.disconnect(this);
-  old_ctx_ = nullptr;
   old_stream_ = nullptr;
-  old_component_ = 0;
 }
 
-void 
-TransportLayerIce::RestoreOldStream()
-{
+void TransportLayerIce::RestoreOldStream() {
   if (old_stream_ == nullptr) {
     return; // no work to do
   }
   // ICE Failed on the new stream, we need to restore the old stream now
-  MOZ_MTLOG(ML_INFO, LAYER_INFO << "RestoreOldStream(" << old_stream_->name() << ","
-    << old_component_ << ")");
+  MOZ_MTLOG(ML_INFO, LAYER_INFO << "RestoreOldStream(" << old_stream_->name() 
+                                << ")");
   stream_->SignalReady.disconnect(this);
   stream_->SignalFailed.disconnect(this);
   stream_->SignalPacketReceived.disconnect(this);
-  ctx_ = old_ctx_;
   stream_ = old_stream_;
-  component_ = old_component_;
+  old_stream_ = nullptr;
+
+  if (stream_->state() == NrIceMediaStream::ICE_OPEN) {
+    IceReady(stream_);
+  } else if (stream_->state() == NrIceMediaStream::ICE_CLOSED) {
+    IceFailed(stream_);
+  }
 }
 
 TransportResult TransportLayerIce::SendPacket(const unsigned char *data,
                                               size_t len) {
   CheckThread();
-  nsresult res = stream_->SendPacket(component_, data, len);
+  // use old_stream_ until stream_ is ready
+  nsresult res = (old_stream_?old_stream_:stream_)->SendPacket(component_,
+                                                               data,
+                                                               len);
 
   if (!NS_SUCCEEDED(res)) {
     return (res == NS_BASE_STREAM_WOULD_BLOCK) ?
         TE_WOULDBLOCK : TE_ERROR;
   }
 
   MOZ_MTLOG(ML_DEBUG, LAYER_INFO << " SendPacket(" << len << ") succeeded");
 
@@ -190,32 +187,36 @@ TransportResult TransportLayerIce::SendP
 
 void TransportLayerIce::IceCandidate(NrIceMediaStream *stream,
                                      const std::string&) {
   // NO-OP for now
 }
 
 void TransportLayerIce::IceReady(NrIceMediaStream *stream) {
   CheckThread();
+  // only handle the current stream (not the old stream during restart)
+  if (stream != stream_) {
+    return;
+  }
   MOZ_MTLOG(ML_INFO, LAYER_INFO << "ICE Ready(" << stream->name() << ","
     << component_ << ")");
   TL_SET_STATE(TS_OPEN);
   // Reset old ice stream if new stream is good after ice restart
-  // Possible to get IceReady call for old stream after restart? ?mjf?
   ResetOldStream();
 }
 
 void TransportLayerIce::IceFailed(NrIceMediaStream *stream) {
   CheckThread();
+  // only handle the current stream (not the old stream during restart)
+  if (stream != stream_) {
+    return;
+  }
   MOZ_MTLOG(ML_INFO, LAYER_INFO << "ICE Failed(" << stream->name() << ","
     << component_ << ")");
   TL_SET_STATE(TS_ERROR);
-  // Restore old ice stream if new stream fails during ice restart
-  // Possible to get IceFailed call for old stream after restart? ?mjf?
-  RestoreOldStream();
 }
 
 void TransportLayerIce::IcePacketReceived(NrIceMediaStream *stream, int component,
                        const unsigned char *data, int len) {
   CheckThread();
   // We get packets for both components, so ignore the ones that aren't
   // for us.
   if (component_ != component)
--- a/media/mtransport/transportlayerice.h
+++ b/media/mtransport/transportlayerice.h
@@ -57,17 +57,14 @@ class TransportLayerIce : public Transpo
   void ResetOldStream(); // called after successful ice restart
   void RestoreOldStream(); // called after unsuccessful ice restart
 
   const std::string name_;
   RefPtr<NrIceCtx> ctx_;
   RefPtr<NrIceMediaStream> stream_;
   int component_;
 
-  // used to hold the old ice ctx, stream, and component
-  // note: holding the old ctx and component are probably overkill (mjf)
-  RefPtr<NrIceCtx> old_ctx_;
+  // used to hold the old stream
   RefPtr<NrIceMediaStream> old_stream_;
-  int old_component_;
 };
 
 }  // close namespace
 #endif
--- a/media/webrtc/signaling/src/jsep/JsepSession.h
+++ b/media/webrtc/signaling/src/jsep/JsepSession.h
@@ -80,19 +80,21 @@ public:
   GetNegotiations() const
   {
     return mNegotiations;
   }
 
   // Set up the ICE And DTLS data.
   virtual nsresult SetIceCredentials(const std::string& ufrag,
                                      const std::string& pwd) = 0;
+  virtual const std::string& GetUfrag() const = 0;
+  virtual const std::string& GetPwd() const = 0;
   virtual nsresult SetBundlePolicy(JsepBundlePolicy policy) = 0;
   virtual bool RemoteIsIceLite() const = 0;
-  virtual bool RemoteIsIceRestarting() const = 0;
+  virtual bool RemoteIceIsRestarting() const = 0;
   virtual std::vector<std::string> GetIceOptions() const = 0;
 
   virtual nsresult AddDtlsFingerprint(const std::string& algorithm,
                                       const std::vector<uint8_t>& value) = 0;
 
   virtual nsresult AddAudioRtpExtension(const std::string& extensionName) = 0;
   virtual nsresult AddVideoRtpExtension(const std::string& extensionName) = 0;
 
--- a/media/webrtc/signaling/src/jsep/JsepSessionImpl.cpp
+++ b/media/webrtc/signaling/src/jsep/JsepSessionImpl.cpp
@@ -148,20 +148,16 @@ JsepSessionImpl::RemoveTrack(const std::
 nsresult
 JsepSessionImpl::SetIceCredentials(const std::string& ufrag,
                                    const std::string& pwd)
 {
   mLastError.clear();
   mIceUfrag = ufrag;
   mIcePwd = pwd;
 
-  if (mCurrentLocalDescription.get()) {
-    mLocalIsIceRestarting = true;
-  }
-
   return NS_OK;
 }
 
 nsresult
 JsepSessionImpl::SetBundlePolicy(JsepBundlePolicy policy)
 {
   mLastError.clear();
   if (mCurrentLocalDescription) {
@@ -639,42 +635,45 @@ JsepSessionImpl::CreateOffer(const JsepO
     JSEP_SET_ERROR("Cannot create offer in state " << GetStateStr(mState));
     return NS_ERROR_UNEXPECTED;
   }
 
   // Undo track assignments from a previous call to CreateOffer
   // (ie; if the track has not been negotiated yet, it doesn't necessarily need
   // to stay in the same m-section that it was in)
   for (JsepSendingTrack& trackWrapper : mLocalTracks) {
-    if (!trackWrapper.mTrack->GetNegotiatedDetails() || mLocalIsIceRestarting) {
+    if (!trackWrapper.mTrack->GetNegotiatedDetails()) {
       trackWrapper.mAssignedMLine.reset();
     }
   }
 
   UniquePtr<Sdp> sdp;
 
   // Make the basic SDP that is common to offer/answer.
   nsresult rv = CreateGenericSDP(&sdp);
   NS_ENSURE_SUCCESS(rv, rv);
 
-  if (mCurrentLocalDescription && !mLocalIsIceRestarting) {
+  if (mCurrentLocalDescription) {
     rv = AddReofferMsections(*mCurrentLocalDescription,
                              *GetAnswer(),
                              sdp.get());
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   // Ensure that we have all the m-sections we need, and disable extras
   rv = SetupOfferMSections(options, sdp.get());
   NS_ENSURE_SUCCESS(rv, rv);
 
   SetupBundle(sdp.get());
 
   if (mCurrentLocalDescription) {
-    rv = CopyPreviousTransportParams(*GetAnswer(), *sdp, sdp.get());
+    rv = CopyPreviousTransportParams(*GetAnswer(),
+                                     *mCurrentLocalDescription,
+                                     *sdp,
+                                     sdp.get());
     NS_ENSURE_SUCCESS(rv,rv);
   }
 
   *offer = sdp->ToString();
   mGeneratedLocalDescription = Move(sdp);
   ++mSessionVersion;
 
   return NS_OK;
@@ -802,17 +801,21 @@ JsepSessionImpl::CreateAnswer(const Jsep
 
   for (size_t i = 0; i < numMsections; ++i) {
     const SdpMediaSection& remoteMsection = offer.GetMediaSection(i);
     rv = CreateAnswerMSection(options, i, remoteMsection, sdp.get());
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   if (mCurrentLocalDescription) {
-    rv = CopyPreviousTransportParams(*GetAnswer(), *sdp, sdp.get());
+    // per discussion with bwc, 3rd parm here should be offer, not *sdp. (mjf)
+    rv = CopyPreviousTransportParams(*GetAnswer(),
+                                     *mCurrentRemoteDescription,
+                                     offer,
+                                     sdp.get());
     NS_ENSURE_SUCCESS(rv,rv);
   }
 
   *answer = sdp->ToString();
   mGeneratedLocalDescription = Move(sdp);
 
   return NS_OK;
 }
@@ -1208,36 +1211,34 @@ JsepSessionImpl::SetRemoteDescription(Js
 
   rv = ValidateRemoteDescription(*parsed);
   NS_ENSURE_SUCCESS(rv, rv);
 
   bool iceLite =
       parsed->GetAttributeList().HasAttribute(SdpAttribute::kIceLiteAttribute);
 
   // check for mismatch ufrag/pwd indicating ice restart
+  // can't just check the first one because it might be disabled
   bool iceRestarting = false;
   if (mCurrentRemoteDescription.get()) {
     for (size_t i = 0;
-         !iceRestarting && i < mCurrentRemoteDescription->GetMediaSectionCount();
+         !iceRestarting &&
+           i < mCurrentRemoteDescription->GetMediaSectionCount();
          ++i) {
-      if (mSdpHelper.MsectionIsDisabled(parsed->GetMediaSection(i)) ||
-          mSdpHelper.MsectionIsDisabled(mCurrentRemoteDescription->GetMediaSection(i))) {
+
+      const SdpMediaSection& newMsection = parsed->GetMediaSection(i);
+      const SdpMediaSection& oldMsection =
+        mCurrentRemoteDescription->GetMediaSection(i);
+
+      if (mSdpHelper.MsectionIsDisabled(newMsection) ||
+          mSdpHelper.MsectionIsDisabled(oldMsection)) {
         continue;
       }
 
-      const SdpAttributeList& newAttrs(
-          parsed->GetMediaSection(i).GetAttributeList());
-      const SdpAttributeList& oldAttrs(
-          mCurrentRemoteDescription->GetMediaSection(i).GetAttributeList());
-
-      if ((newAttrs.GetIceUfrag() != oldAttrs.GetIceUfrag()) ||
-          (newAttrs.GetIcePwd() != oldAttrs.GetIcePwd())) {
-        MOZ_MTLOG(ML_DEBUG, "Mismatched ice creds indicate ICE restart");
-        iceRestarting = true;
-      }
+      iceRestarting = mSdpHelper.IceCredentialsDiffer(newMsection, oldMsection);
     }
   }
 
   std::vector<std::string> iceOptions;
   if (parsed->GetAttributeList().HasAttribute(
           SdpAttribute::kIceOptionsAttribute)) {
     iceOptions = parsed->GetAttributeList().GetIceOptions().mValues;
   }
@@ -1252,17 +1253,17 @@ JsepSessionImpl::SetRemoteDescription(Js
       break;
     case kJsepSdpRollback:
       MOZ_CRASH(); // Handled above
   }
 
   if (NS_SUCCEEDED(rv)) {
     mRemoteIsIceLite = iceLite;
     mIceOptions = iceOptions;
-    mRemoteIsIceRestarting = iceRestarting;
+    mRemoteIceIsRestarting = iceRestarting;
   }
 
   return rv;
 }
 
 nsresult
 JsepSessionImpl::HandleNegotiatedSession(const UniquePtr<Sdp>& local,
                                          const UniquePtr<Sdp>& remote)
@@ -1544,23 +1545,27 @@ JsepSessionImpl::AddTransportAttributes(
 
   msection->GetAttributeList().SetAttribute(new SdpSetupAttribute(dtlsRole));
 
   return NS_OK;
 }
 
 nsresult
 JsepSessionImpl::CopyPreviousTransportParams(const Sdp& oldAnswer,
+                                             const Sdp& offerersPreviousSdp,
                                              const Sdp& newOffer,
                                              Sdp* newLocal)
 {
   for (size_t i = 0; i < oldAnswer.GetMediaSectionCount(); ++i) {
     if (!mSdpHelper.MsectionIsDisabled(newLocal->GetMediaSection(i)) &&
-        mSdpHelper.AreOldTransportParamsValid(oldAnswer, newOffer, i) &&
-        !(mLocalIsIceRestarting || mRemoteIsIceRestarting)
+        mSdpHelper.AreOldTransportParamsValid(oldAnswer,
+                                              offerersPreviousSdp,
+                                              newOffer,
+                                              i) &&
+        !mRemoteIceIsRestarting
        ) {
       // If newLocal is an offer, this will be the number of components we used
       // last time, and if it is an answer, this will be the number of
       // components we've decided we're using now.
       size_t numComponents = mTransports[i]->mComponents;
       nsresult rv = mSdpHelper.CopyTransportParams(
           numComponents,
           mCurrentLocalDescription->GetMediaSection(i),
@@ -1867,16 +1872,45 @@ JsepSessionImpl::ValidateRemoteDescripti
   SdpHelper::BundledMids bundledMids;
   nsresult rv = GetNegotiatedBundledMids(&bundledMids);
   NS_ENSURE_SUCCESS(rv, rv);
 
   SdpHelper::BundledMids newBundledMids;
   rv = mSdpHelper.GetBundledMids(description, &newBundledMids);
   NS_ENSURE_SUCCESS(rv, rv);
 
+  // check for partial ice restart, which is not supported
+  Maybe<bool> iceCredsDiffer;
+  for (size_t i = 0;
+       i < mCurrentRemoteDescription->GetMediaSectionCount();
+       ++i) {
+
+    const SdpMediaSection& newMsection = description.GetMediaSection(i);
+    const SdpMediaSection& oldMsection =
+      mCurrentRemoteDescription->GetMediaSection(i);
+
+    if (mSdpHelper.MsectionIsDisabled(newMsection) ||
+        mSdpHelper.MsectionIsDisabled(oldMsection)) {
+      continue;
+    }
+
+    bool differ = mSdpHelper.IceCredentialsDiffer(newMsection, oldMsection);
+    // Detect whether all the creds are the same or all are different
+    if (!iceCredsDiffer.isSome()) {
+      // for the first msection capture whether creds are different or same
+      iceCredsDiffer = mozilla::Some(differ);
+    } else if (iceCredsDiffer.isSome() && *iceCredsDiffer != differ) {
+      // subsequent msections must match the first sections
+      JSEP_SET_ERROR("Partial ICE restart is unsupported at this time "
+                     "(new remote description changes either the ice-ufrag "
+                     "or ice-pwd on fewer than all msections)");
+      return NS_ERROR_INVALID_ARG;
+    }
+  }
+
   return NS_OK;
 }
 
 nsresult
 JsepSessionImpl::ValidateAnswer(const Sdp& offer, const Sdp& answer)
 {
   if (offer.GetMediaSectionCount() != answer.GetMediaSectionCount()) {
     JSEP_SET_ERROR("Offer and answer have different number of m-lines "
--- a/media/webrtc/signaling/src/jsep/JsepSessionImpl.h
+++ b/media/webrtc/signaling/src/jsep/JsepSessionImpl.h
@@ -30,18 +30,17 @@ class JsepSessionImpl : public JsepSessi
 {
 public:
   JsepSessionImpl(const std::string& name, UniquePtr<JsepUuidGenerator> uuidgen)
       : JsepSession(name),
         mIsOfferer(false),
         mWasOffererLastTime(false),
         mIceControlling(false),
         mRemoteIsIceLite(false),
-        mLocalIsIceRestarting(false),
-        mRemoteIsIceRestarting(false),
+        mRemoteIceIsRestarting(false),
         mBundlePolicy(kBundleBalanced),
         mSessionId(0),
         mSessionVersion(0),
         mUuidGen(Move(uuidgen)),
         mSdpHelper(&mLastError)
   {
   }
 
@@ -50,28 +49,30 @@ public:
 
   virtual nsresult AddTrack(const RefPtr<JsepTrack>& track) override;
 
   virtual nsresult RemoveTrack(const std::string& streamId,
                                const std::string& trackId) override;
 
   virtual nsresult SetIceCredentials(const std::string& ufrag,
                                      const std::string& pwd) override;
+  virtual const std::string& GetUfrag() const override { return mIceUfrag; }
+  virtual const std::string& GetPwd() const override { return mIcePwd; }
   nsresult SetBundlePolicy(JsepBundlePolicy policy) override;
 
   virtual bool
   RemoteIsIceLite() const override
   {
     return mRemoteIsIceLite;
   }
-  
+
   virtual bool
-  RemoteIsIceRestarting() const override
+  RemoteIceIsRestarting() const override
   {
-    return mRemoteIsIceRestarting;
+    return mRemoteIceIsRestarting;
   }
 
   virtual std::vector<std::string>
   GetIceOptions() const override
   {
     return mIceOptions;
   }
 
@@ -225,16 +226,17 @@ private:
                                 const Sdp& sdp,
                                 const SdpMediaSection& msection,
                                 RefPtr<JsepTrack>* track);
   nsresult HandleNegotiatedSession(const UniquePtr<Sdp>& local,
                                    const UniquePtr<Sdp>& remote);
   nsresult AddTransportAttributes(SdpMediaSection* msection,
                                   SdpSetupAttribute::Role dtlsRole);
   nsresult CopyPreviousTransportParams(const Sdp& oldAnswer,
+                                       const Sdp& offerersPreviousSdp,
                                        const Sdp& newOffer,
                                        Sdp* newLocal);
   nsresult SetupOfferMSections(const JsepOfferOptions& options, Sdp* sdp);
   // Non-const so it can assign m-line index to tracks
   nsresult SetupOfferMSectionsByType(SdpMediaSection::MediaType type,
                                      Maybe<size_t> offerToReceive,
                                      Sdp* sdp);
   nsresult BindLocalTracks(SdpMediaSection::MediaType mediatype,
@@ -305,18 +307,17 @@ private:
   std::vector<JsepTrackPair> mNegotiatedTrackPairs;
 
   bool mIsOfferer;
   bool mWasOffererLastTime;
   bool mIceControlling;
   std::string mIceUfrag;
   std::string mIcePwd;
   bool mRemoteIsIceLite;
-  bool mLocalIsIceRestarting;
-  bool mRemoteIsIceRestarting;
+  bool mRemoteIceIsRestarting;
   std::vector<std::string> mIceOptions;
   JsepBundlePolicy mBundlePolicy;
   std::vector<JsepDtlsFingerprint> mDtlsFingerprints;
   uint64_t mSessionId;
   uint64_t mSessionVersion;
   std::vector<SdpExtmapAttributeList::Extmap> mAudioRtpExtensions;
   std::vector<SdpExtmapAttributeList::Extmap> mVideoRtpExtensions;
   UniquePtr<JsepUuidGenerator> mUuidGen;
--- a/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp
+++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.cpp
@@ -1542,24 +1542,19 @@ PeerConnectionImpl::CreateOffer(const Js
     return NS_OK;
   }
 
   CSFLogDebug(logTag, "CreateOffer()");
 
   nsresult nrv;
   if (aOptions.mIceRestart.isSome() && *(aOptions.mIceRestart)) {
     CSFLogInfo(logTag, "Offerer restarting ice");
-    std::string ufrag = mMedia->ice_ctx()->GetNewUfrag();
-    std::string pwd = mMedia->ice_ctx()->GetNewPwd();
-
-    mMedia->BeginIceRestart(ufrag, pwd);
-
-    nrv = mJsepSession->SetIceCredentials(ufrag, pwd);
+    nrv = SetupIceRestart();
     if (NS_FAILED(nrv)) {
-      CSFLogError(logTag, "%s: Couldn't set ICE credentials, res=%u",
+      CSFLogError(logTag, "%s: SetupIceRestart failed, res=%u",
                            __FUNCTION__,
                            static_cast<unsigned>(nrv));
       return nrv;
     }
   }
 
   nrv = ConfigureJsepSessionCodecs();
   if (NS_FAILED(nrv)) {
@@ -1603,26 +1598,21 @@ PeerConnectionImpl::CreateAnswer()
   RefPtr<PeerConnectionObserver> pco = do_QueryObjectReferent(mPCObserver);
   if (!pco) {
     return NS_OK;
   }
 
   CSFLogDebug(logTag, "CreateAnswer()");
 
   nsresult nrv;
-  if (mJsepSession->RemoteIsIceRestarting()) {
+  if (mJsepSession->RemoteIceIsRestarting()) {
     CSFLogInfo(logTag, "Answerer restarting ice");
-    std::string ufrag = mMedia->ice_ctx()->GetNewUfrag();
-    std::string pwd = mMedia->ice_ctx()->GetNewPwd();
-
-    mMedia->BeginIceRestart(ufrag, pwd);
-
-    nrv = mJsepSession->SetIceCredentials(ufrag, pwd);
+    nrv = SetupIceRestart();
     if (NS_FAILED(nrv)) {
-      CSFLogError(logTag, "%s: Couldn't set ICE credentials, res=%u",
+      CSFLogError(logTag, "%s: SetupIceRestart failed, res=%u",
                            __FUNCTION__,
                            static_cast<unsigned>(nrv));
       return nrv;
     }
   }
 
   STAMP_TIMECARD(mTimeCard, "Create Answer");
   // TODO(bug 1098015): Once RTCAnswerOptions is standardized, we'll need to
@@ -1650,16 +1640,50 @@ PeerConnectionImpl::CreateAnswer()
     pco->OnCreateAnswerSuccess(ObString(answer.c_str()), rv);
   }
 
   UpdateSignalingState();
 
   return NS_OK;
 }
 
+nsresult
+PeerConnectionImpl::SetupIceRestart()
+{
+  if (mMedia->ice_ctx_hdlr()->IsRestarting()) {
+    CSFLogError(logTag, "%s: ICE already restarting",
+                         __FUNCTION__);
+    return NS_ERROR_UNEXPECTED;
+  }
+
+  std::string ufrag = mMedia->ice_ctx()->GetNewUfrag();
+  std::string pwd = mMedia->ice_ctx()->GetNewPwd();
+  if (ufrag.empty() || pwd.empty()) {
+    CSFLogError(logTag, "%s: Bad ICE credentials (ufrag:'%s'/pwd:'%s')",
+                         __FUNCTION__,
+                         ufrag.c_str(), pwd.c_str());
+    return NS_ERROR_UNEXPECTED;
+  }
+
+  // hold on to the current ice creds in case of rollback
+  mPreviousIceUfrag = mJsepSession->GetUfrag();
+  mPreviousIcePwd = mJsepSession->GetPwd();
+  mMedia->BeginIceRestart(ufrag, pwd);
+
+  nsresult nrv = mJsepSession->SetIceCredentials(ufrag, pwd);
+  if (NS_FAILED(nrv)) {
+    CSFLogError(logTag, "%s: Couldn't set ICE credentials, res=%u",
+                         __FUNCTION__,
+                         static_cast<unsigned>(nrv));
+    return nrv;
+  }
+
+  return NS_OK;
+}
+
 NS_IMETHODIMP
 PeerConnectionImpl::SetLocalDescription(int32_t aAction, const char* aSDP)
 {
   PC_AUTO_ENTER_API_CALL(true);
 
   if (!aSDP) {
     CSFLogError(logTag, "%s - aSDP is NULL", __FUNCTION__);
     return NS_ERROR_FAILURE;
@@ -2777,16 +2801,20 @@ PeerConnectionImpl::SetSignalingState_m(
   }
 
   mSignalingState = aSignalingState;
 
   bool fireNegotiationNeeded = false;
   if (mSignalingState == PCImplSignalingState::SignalingStable) {
     if (rollback && mMedia->ice_ctx_hdlr()->IsRestarting()) {
       mMedia->RollbackIceRestart();
+      // put back the previous ice creds
+      mJsepSession->SetIceCredentials(mPreviousIceUfrag, mPreviousIcePwd);
+      mPreviousIceUfrag = "";
+      mPreviousIcePwd = "";
     }
 
     // Either negotiation is done, or we've rolled back. In either case, we
     // need to re-evaluate whether further negotiation is required.
     mNegotiationNeeded = false;
     // If we're rolling back a local offer, we might need to remove some
     // transports, but nothing further needs to be done.
     mMedia->ActivateOrRemoveTransports(*mJsepSession);
@@ -3071,19 +3099,23 @@ void PeerConnectionImpl::IceConnectionSt
           mAddCandidateErrorCount);
     }
   }
 #endif
 
   mIceConnectionState = domState;
 
   if (mIceConnectionState == PCImplIceConnectionState::Connected ||
-      mIceConnectionState == PCImplIceConnectionState::Completed) {
+      mIceConnectionState == PCImplIceConnectionState::Completed ||
+      mIceConnectionState == PCImplIceConnectionState::Failed) {
     if (mMedia->ice_ctx_hdlr()->IsRestarting()) {
       mMedia->FinalizeIceRestart();
+      // clear the previous ice creds since they are no longer needed
+      mPreviousIceUfrag = "";
+      mPreviousIcePwd = "";
     }
   }
 
   // Would be nice if we had a means of converting one of these dom enums
   // to a string that wasn't almost as much text as this switch statement...
   switch (mIceConnectionState) {
     case PCImplIceConnectionState::New:
       STAMP_TIMECARD(mTimeCard, "Ice state: new");
--- a/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.h
+++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionImpl.h
@@ -712,16 +712,18 @@ private:
                                             SdpMediaSection::MediaType type,
                                             const std::string& streamId,
                                             const std::string& trackId);
 
   nsresult AddTrackToJsepSession(SdpMediaSection::MediaType type,
                                  const std::string& streamId,
                                  const std::string& trackId);
 
+  nsresult SetupIceRestart();
+
 #if !defined(MOZILLA_EXTERNAL_LINKAGE)
   static void GetStatsForPCObserver_s(
       const std::string& pcHandle,
       nsAutoPtr<RTCStatsQuery> query);
 
   // Sends an RTCStatsReport to JS. Must run on main thread.
   static void DeliverStatsReportToPCObserver_m(
       const std::string& pcHandle,
@@ -804,16 +806,18 @@ private:
 
   bool mAllowIceLoopback;
   bool mAllowIceLinkLocal;
   RefPtr<PeerConnectionMedia> mMedia;
 
   // The JSEP negotiation session.
   mozilla::UniquePtr<PCUuidGenerator> mUuidGen;
   mozilla::UniquePtr<mozilla::JsepSession> mJsepSession;
+  std::string mPreviousIceUfrag; // used during rollback of ice restart
+  std::string mPreviousIcePwd; // used during rollback of ice restart
 
 #if !defined(MOZILLA_EXTERNAL_LINKAGE)
   // Start time of ICE, used for telemetry
   mozilla::TimeStamp mIceStartTime;
   // Start time of call used for Telemetry
   mozilla::TimeStamp mStartTime;
 #endif
 
--- a/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.cpp
+++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.cpp
@@ -353,26 +353,22 @@ nsresult PeerConnectionMedia::Init(const
     }
   } else if (turn_servers.size() != 0) {
     CSFLogError(logTag, "%s: Setting turn servers disabled", __FUNCTION__);
   }
   if (NS_FAILED(rv = mDNSResolver->Init())) {
     CSFLogError(logTag, "%s: Failed to initialize dns resolver", __FUNCTION__);
     return rv;
   }
-  if (NS_FAILED(rv = mIceCtxHdlr->ctx()->SetResolver(mDNSResolver->AllocateResolver()))) {
+  if (NS_FAILED(rv = 
+      mIceCtxHdlr->ctx()->SetResolver(mDNSResolver->AllocateResolver()))) {
     CSFLogError(logTag, "%s: Failed to get dns resolver", __FUNCTION__);
     return rv;
   }
-  mIceCtxHdlr->ctx()->SignalGatheringStateChange.connect(
-      this,
-      &PeerConnectionMedia::IceGatheringStateChange_s);
-  mIceCtxHdlr->ctx()->SignalConnectionStateChange.connect(
-      this,
-      &PeerConnectionMedia::IceConnectionStateChange_s);
+  ConnectSignals(mIceCtxHdlr->ctx().get());
 
   return NS_OK;
 }
 
 void
 PeerConnectionMedia::EnsureTransports(const JsepSession& aSession)
 {
   auto transports = aSession.GetTransports();
@@ -397,18 +393,19 @@ PeerConnectionMedia::EnsureTransport_s(s
   if (!stream) {
     CSFLogDebug(logTag, "%s: Creating ICE media stream=%u components=%u",
                 mParentHandle.c_str(),
                 static_cast<unsigned>(aLevel),
                 static_cast<unsigned>(aComponentCount));
 
     std::ostringstream os;
     os << mParentName << " aLevel=" << aLevel;
-    RefPtr<NrIceMediaStream> stream = mIceCtxHdlr->CreateStream(os.str().c_str(),
-                                                            aComponentCount);
+    RefPtr<NrIceMediaStream> stream = 
+      mIceCtxHdlr->CreateStream(os.str().c_str(),
+                                aComponentCount);
 
     if (!stream) {
       CSFLogError(logTag, "Failed to create ICE stream.");
       return;
     }
 
     stream->SetLevel(aLevel);
     stream->SignalReady.connect(this, &PeerConnectionMedia::IceStreamReady_s);
@@ -602,35 +599,33 @@ PeerConnectionMedia::BeginIceRestart(con
                                      const std::string& pwd)
 {
   ASSERT_ON_THREAD(mMainThread);
 
   RUN_ON_THREAD(GetSTSThread(),
                 WrapRunnable(
                     RefPtr<PeerConnectionMedia>(this),
                     &PeerConnectionMedia::BeginIceRestart_s,
-                    std::string(ufrag), // Make copies.
-                    std::string(pwd)),
+                    ufrag,
+                    pwd),
                 NS_DISPATCH_NORMAL);
 }
 
 void
 PeerConnectionMedia::BeginIceRestart_s(const std::string& ufrag,
                                        const std::string& pwd)
 {
   ASSERT_ON_THREAD(mSTSThread);
 
+  // hold the original context so we can disconnect signals if needed
+  RefPtr<NrIceCtx> originalCtx = mIceCtxHdlr->ctx();
+
   mIceCtxHdlr->BeginIceRestart(ufrag, pwd);
   if (mIceCtxHdlr->IsRestarting()) {
-  mIceCtxHdlr->ctx()->SignalGatheringStateChange.connect(
-      this,
-      &PeerConnectionMedia::IceGatheringStateChange_s);
-  mIceCtxHdlr->ctx()->SignalConnectionStateChange.connect(
-      this,
-      &PeerConnectionMedia::IceConnectionStateChange_s);
+    ConnectSignals(mIceCtxHdlr->ctx().get(), originalCtx.get());
   }
 }
 
 void
 PeerConnectionMedia::FinalizeIceRestart()
 {
   ASSERT_ON_THREAD(mMainThread);
 
@@ -660,18 +655,56 @@ PeerConnectionMedia::RollbackIceRestart(
                     &PeerConnectionMedia::RollbackIceRestart_s),
                 NS_DISPATCH_NORMAL);
 }
 
 void
 PeerConnectionMedia::RollbackIceRestart_s()
 {
   ASSERT_ON_THREAD(mSTSThread);
+  if (!mIceCtxHdlr->IsRestarting()) {
+    return;
+  }
+
+  // hold the restart context so we can disconnect signals
+  RefPtr<NrIceCtx> restartCtx = mIceCtxHdlr->ctx();
 
   mIceCtxHdlr->RollbackIceRestart();
+  ConnectSignals(mIceCtxHdlr->ctx().get(), restartCtx.get());
+}
+
+void
+PeerConnectionMedia::ConnectSignals(NrIceCtx *aCtx, NrIceCtx *aOldCtx)
+{
+  aCtx->SignalGatheringStateChange.connect(
+      this,
+      &PeerConnectionMedia::IceGatheringStateChange_s);
+  aCtx->SignalConnectionStateChange.connect(
+      this,
+      &PeerConnectionMedia::IceConnectionStateChange_s);
+
+  if (aOldCtx) {
+    MOZ_ASSERT(aCtx != aOldCtx);
+    aOldCtx->SignalGatheringStateChange.disconnect(this);
+    aOldCtx->SignalConnectionStateChange.disconnect(this);
+
+    // if the old and new connection state and/or gathering state is
+    // different fire the state update.  Note: we don't fire the update
+    // if the state is *INIT since updates for the INIT state aren't
+    // sent during the normal flow. (mjf)
+    if (aOldCtx->connection_state() != aCtx->connection_state() &&
+        aCtx->connection_state() != NrIceCtx::ICE_CTX_INIT) {
+      aCtx->SignalConnectionStateChange(aCtx, aCtx->connection_state());
+    }
+
+    if (aOldCtx->gathering_state() != aCtx->gathering_state() &&
+        aCtx->gathering_state() != NrIceCtx::ICE_CTX_GATHER_INIT) {
+      aCtx->SignalGatheringStateChange(aCtx, aCtx->gathering_state());
+    }
+  }
 }
 
 void
 PeerConnectionMedia::AddIceCandidate(const std::string& candidate,
                                      const std::string& mid,
                                      uint32_t aMLine) {
   RUN_ON_THREAD(GetSTSThread(),
                 WrapRunnable(
--- a/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.h
+++ b/media/webrtc/signaling/src/peerconnection/PeerConnectionMedia.h
@@ -451,16 +451,18 @@ class PeerConnectionMedia : public sigsl
                         bool aIsIceLite,
                         const std::vector<std::string>& aIceOptionsList);
 
   void BeginIceRestart_s(const std::string& ufrag,
                          const std::string& pwd);
   void FinalizeIceRestart_s();
   void RollbackIceRestart_s();
 
+  void ConnectSignals(NrIceCtx *aCtx, NrIceCtx *aOldCtx=nullptr);
+
   // Process a trickle ICE candidate.
   void AddIceCandidate_s(const std::string& aCandidate, const std::string& aMid,
                          uint32_t aMLine);
 
 
   // ICE events
   void IceGatheringStateChange_s(NrIceCtx* ctx,
                                NrIceCtx::GatheringState state);
--- a/media/webrtc/signaling/src/sdp/SdpHelper.cpp
+++ b/media/webrtc/signaling/src/sdp/SdpHelper.cpp
@@ -62,16 +62,17 @@ SdpHelper::CopyTransportParams(size_t nu
     newLocalAttrs.SetAttribute(new SdpRtcpAttribute(oldLocalAttrs.GetRtcp()));
   }
 
   return NS_OK;
 }
 
 bool
 SdpHelper::AreOldTransportParamsValid(const Sdp& oldAnswer,
+                                      const Sdp& offerersPreviousSdp,
                                       const Sdp& newOffer,
                                       size_t level)
 {
   if (MsectionIsDisabled(oldAnswer.GetMediaSection(level)) ||
       MsectionIsDisabled(newOffer.GetMediaSection(level))) {
     // Obvious
     return false;
   }
@@ -85,22 +86,39 @@ SdpHelper::AreOldTransportParamsValid(co
   if (newOffer.GetMediaSection(level).GetAttributeList().HasAttribute(
         SdpAttribute::kBundleOnlyAttribute) &&
       IsBundleSlave(newOffer, level)) {
     // It never makes sense to put transport attributes in a bundle-only
     // m-section
     return false;
   }
 
-  // TODO(bug 906986): Check for ICE restart (will need to pass the offerer's
-  // old SDP to compare it against |newOffer|)
+  if (IceCredentialsDiffer(newOffer.GetMediaSection(level),
+                           offerersPreviousSdp.GetMediaSection(level))) {
+    return false;
+  }
 
   return true;
 }
 
+bool
+SdpHelper::IceCredentialsDiffer(const SdpMediaSection& msection1,
+                                const SdpMediaSection& msection2)
+{
+  const SdpAttributeList& attrs1(msection1.GetAttributeList());
+  const SdpAttributeList& attrs2(msection2.GetAttributeList());
+
+  if ((attrs1.GetIceUfrag() != attrs2.GetIceUfrag()) ||
+      (attrs1.GetIcePwd() != attrs2.GetIcePwd())) {
+    return true;
+  }
+
+  return false;
+}
+
 nsresult
 SdpHelper::GetComponent(const std::string& candidate, size_t* component)
 {
   unsigned int temp;
   int32_t result = PR_sscanf(candidate.c_str(), "%*s %u", &temp);
   if (result == 1) {
     *component = temp;
     return NS_OK;
--- a/media/webrtc/signaling/src/sdp/SdpHelper.h
+++ b/media/webrtc/signaling/src/sdp/SdpHelper.h
@@ -33,18 +33,21 @@ class SdpHelper {
     explicit SdpHelper(std::string* errorDest) : mLastError(*errorDest) {}
     ~SdpHelper() {}
 
     nsresult GetComponent(const std::string& candidate, size_t* component);
     nsresult CopyTransportParams(size_t numComponents,
                                  const SdpMediaSection& source,
                                  SdpMediaSection* dest);
     bool AreOldTransportParamsValid(const Sdp& oldAnswer,
+                                    const Sdp& offerersPreviousSdp,
                                     const Sdp& newOffer,
                                     size_t level);
+    bool IceCredentialsDiffer(const SdpMediaSection& msection1,
+                              const SdpMediaSection& msection2);
 
     bool MsectionIsDisabled(const SdpMediaSection& msection) const;
     static void DisableMsection(Sdp* sdp, SdpMediaSection* msection);
 
     // Maps each mid to the m-section that is the master of its bundle.
     // Mids that do not appear in an a=group:BUNDLE do not appear here.
     typedef std::map<std::string, const SdpMediaSection*> BundledMids;