Destroy stats collectors before destroying BaseChannels

Bug: None
Change-Id: I4b54cc0a3cf694f536ba1775d55dab58fd0df536
Reviewed-on: https://webrtc-review.googlesource.com/33561
Reviewed-by: Taylor Brandstetter <deadbeef@webrtc.org>
Commit-Queue: Steve Anton <steveanton@webrtc.org>
Cr-Commit-Position: refs/heads/master@{#21308}
diff --git a/pc/peerconnection.cc b/pc/peerconnection.cc
index 49ab979..6420596 100644
--- a/pc/peerconnection.cc
+++ b/pc/peerconnection.cc
@@ -726,16 +726,23 @@
   TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
   RTC_DCHECK_RUN_ON(signaling_thread());
 
-  StopAndDestroyChannels();
+  // Need to stop transceivers before destroying the stats collector because
+  // AudioRtpSender has a reference to the StatsCollector it will update when
+  // stopping.
+  for (auto transceiver : transceivers_) {
+    transceiver->Stop();
+  }
 
-  // Destroy stats after stopping all transceivers because the senders/receivers
-  // will update the stats collector before stopping.
   stats_.reset(nullptr);
   if (stats_collector_) {
     stats_collector_->WaitForPendingRequest();
     stats_collector_ = nullptr;
   }
 
+  // Don't destroy BaseChannels until after stats has been cleaned up so that
+  // the last stats request can still read from the channels.
+  DestroyAllChannels();
+
   RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
 
   webrtc_session_desc_factory_.reset();
@@ -753,10 +760,7 @@
   });
 }
 
-void PeerConnection::StopAndDestroyChannels() {
-  for (auto transceiver : transceivers_) {
-    transceiver->Stop();
-  }
+void PeerConnection::DestroyAllChannels() {
   // Destroy video channels first since they may have a pointer to a voice
   // channel.
   for (auto transceiver : transceivers_) {
@@ -2345,7 +2349,10 @@
 
   ChangeSignalingState(PeerConnectionInterface::kClosed);
 
-  StopAndDestroyChannels();
+  for (auto transceiver : transceivers_) {
+    transceiver->Stop();
+  }
+  DestroyAllChannels();
 
   network_thread()->Invoke<void>(
       RTC_FROM_HERE,