Delete TestListener and top-level thread wrapping.

Instead use rtc::AutoThread in tests that need that.

Bug: webrtc:9714
Change-Id: I1f33b1b2d321770d062504dd9ef86d66a345dd42
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/254681
Reviewed-by: Tomas Gunnarsson <tommi@webrtc.org>
Commit-Queue: Niels Moller <nisse@webrtc.org>
Reviewed-by: Mirko Bonadei <mbonadei@webrtc.org>
Cr-Commit-Position: refs/heads/main@{#36950}
diff --git a/audio/channel_receive_frame_transformer_delegate_unittest.cc b/audio/channel_receive_frame_transformer_delegate_unittest.cc
index 01aac45..075d8ae 100644
--- a/audio/channel_receive_frame_transformer_delegate_unittest.cc
+++ b/audio/channel_receive_frame_transformer_delegate_unittest.cc
@@ -68,6 +68,7 @@
 // transformer, it passes it to the channel using the ReceiveFrameCallback.
 TEST(ChannelReceiveFrameTransformerDelegateTest,
      TransformRunsChannelReceiveCallback) {
+  rtc::AutoThread main_thread;
   rtc::scoped_refptr<MockFrameTransformer> mock_frame_transformer =
       rtc::make_ref_counted<NiceMock<MockFrameTransformer>>();
   MockChannelReceive mock_channel;
@@ -99,6 +100,7 @@
 // after resetting the delegate.
 TEST(ChannelReceiveFrameTransformerDelegateTest,
      OnTransformedDoesNotRunChannelReceiveCallbackAfterReset) {
+  rtc::AutoThread main_thread;
   rtc::scoped_refptr<MockFrameTransformer> mock_frame_transformer =
       rtc::make_ref_counted<testing::NiceMock<MockFrameTransformer>>();
   MockChannelReceive mock_channel;
diff --git a/audio/voip/test/BUILD.gn b/audio/voip/test/BUILD.gn
index 132f448..a2cc1c5 100644
--- a/audio/voip/test/BUILD.gn
+++ b/audio/voip/test/BUILD.gn
@@ -33,6 +33,7 @@
         "../../../modules/utility:mock_process_thread",
         "../../../test:audio_codec_mocks",
         "../../../test:mock_transport",
+        "../../../test:run_loop",
         "../../../test:test_support",
       ]
     }
@@ -74,6 +75,7 @@
       "../../../rtc_base:logging",
       "../../../rtc_base:rtc_event",
       "../../../test:mock_transport",
+      "../../../test:run_loop",
       "../../../test:test_support",
     ]
   }
@@ -92,6 +94,7 @@
       "../../../rtc_base:logging",
       "../../../rtc_base:rtc_event",
       "../../../test:mock_transport",
+      "../../../test:run_loop",
       "../../../test:test_support",
     ]
   }
diff --git a/audio/voip/test/audio_egress_unittest.cc b/audio/voip/test/audio_egress_unittest.cc
index d114253..213a105 100644
--- a/audio/voip/test/audio_egress_unittest.cc
+++ b/audio/voip/test/audio_egress_unittest.cc
@@ -9,6 +9,7 @@
  */
 
 #include "audio/voip/audio_egress.h"
+
 #include "api/audio_codecs/builtin_audio_encoder_factory.h"
 #include "api/call/transport.h"
 #include "api/task_queue/default_task_queue_factory.h"
@@ -20,6 +21,7 @@
 #include "test/gmock.h"
 #include "test/gtest.h"
 #include "test/mock_transport.h"
+#include "test/run_loop.h"
 
 namespace webrtc {
 namespace {
@@ -98,6 +100,7 @@
     return frame;
   }
 
+  test::RunLoop run_loop_;
   // SimulatedClock doesn't directly affect this testcase as the the
   // AudioFrame's timestamp is driven by GetAudioFrame.
   SimulatedClock fake_clock_;
diff --git a/audio/voip/test/audio_ingress_unittest.cc b/audio/voip/test/audio_ingress_unittest.cc
index 55ecfec..753284a 100644
--- a/audio/voip/test/audio_ingress_unittest.cc
+++ b/audio/voip/test/audio_ingress_unittest.cc
@@ -9,6 +9,7 @@
  */
 
 #include "audio/voip/audio_ingress.h"
+
 #include "api/audio_codecs/builtin_audio_decoder_factory.h"
 #include "api/audio_codecs/builtin_audio_encoder_factory.h"
 #include "api/call/transport.h"
@@ -21,6 +22,7 @@
 #include "test/gmock.h"
 #include "test/gtest.h"
 #include "test/mock_transport.h"
+#include "test/run_loop.h"
 
 namespace webrtc {
 namespace {
@@ -91,6 +93,7 @@
     return frame;
   }
 
+  test::RunLoop run_loop_;
   SimulatedClock fake_clock_;
   SineWaveGenerator wave_generator_;
   NiceMock<MockTransport> transport_;
diff --git a/audio/voip/test/voip_core_unittest.cc b/audio/voip/test/voip_core_unittest.cc
index 896d0d9..b432506 100644
--- a/audio/voip/test/voip_core_unittest.cc
+++ b/audio/voip/test/voip_core_unittest.cc
@@ -9,6 +9,7 @@
  */
 
 #include "audio/voip/voip_core.h"
+
 #include "api/audio_codecs/builtin_audio_decoder_factory.h"
 #include "api/audio_codecs/builtin_audio_encoder_factory.h"
 #include "api/task_queue/default_task_queue_factory.h"
@@ -16,6 +17,7 @@
 #include "modules/audio_processing/include/mock_audio_processing.h"
 #include "test/gtest.h"
 #include "test/mock_transport.h"
+#include "test/run_loop.h"
 
 namespace webrtc {
 namespace {
@@ -46,6 +48,7 @@
         std::move(audio_processing));
   }
 
+  test::RunLoop run_loop_;
   std::unique_ptr<VoipCore> voip_core_;
   NiceMock<MockTransport> transport_;
   rtc::scoped_refptr<test::MockAudioDeviceModule> audio_device_;
diff --git a/call/BUILD.gn b/call/BUILD.gn
index 18bc566..594996d 100644
--- a/call/BUILD.gn
+++ b/call/BUILD.gn
@@ -505,6 +505,7 @@
         "../rtc_base:rtc_event",
         "../rtc_base:safe_conversions",
         "../rtc_base:task_queue_for_test",
+        "../rtc_base:threading",
         "../rtc_base:timeutils",
         "../rtc_base/synchronization:mutex",
         "../system_wrappers",
diff --git a/call/adaptation/resource_adaptation_processor_unittest.cc b/call/adaptation/resource_adaptation_processor_unittest.cc
index da2bc94..97c01b3 100644
--- a/call/adaptation/resource_adaptation_processor_unittest.cc
+++ b/call/adaptation/resource_adaptation_processor_unittest.cc
@@ -135,6 +135,7 @@
   }
 
  protected:
+  rtc::AutoThread main_thread_;
   webrtc::test::ScopedKeyValueConfig field_trials_;
   FakeFrameRateProvider frame_rate_provider_;
   VideoStreamInputStateProvider input_state_provider_;
diff --git a/call/flexfec_receive_stream_unittest.cc b/call/flexfec_receive_stream_unittest.cc
index 9885971..9ad350c 100644
--- a/call/flexfec_receive_stream_unittest.cc
+++ b/call/flexfec_receive_stream_unittest.cc
@@ -26,6 +26,7 @@
 #include "modules/rtp_rtcp/source/byte_io.h"
 #include "modules/rtp_rtcp/source/rtp_header_extensions.h"
 #include "modules/rtp_rtcp/source/rtp_packet_received.h"
+#include "rtc_base/thread.h"
 #include "test/gmock.h"
 #include "test/gtest.h"
 #include "test/mock_transport.h"
@@ -96,6 +97,7 @@
     receive_stream_->UnregisterFromTransport();
   }
 
+  rtc::AutoThread main_thread_;
   MockTransport rtcp_send_transport_;
   FlexfecReceiveStream::Config config_;
   MockRecoveredPacketReceiver recovered_packet_receiver_;
diff --git a/media/engine/webrtc_video_engine_unittest.cc b/media/engine/webrtc_video_engine_unittest.cc
index e1bfa73..21e37d0 100644
--- a/media/engine/webrtc_video_engine_unittest.cc
+++ b/media/engine/webrtc_video_engine_unittest.cc
@@ -1263,6 +1263,7 @@
 
 // Test behavior when decoder factory fails to create a decoder (returns null).
 TEST(WebRtcVideoEngineNewVideoCodecFactoryTest, NullDecoder) {
+  rtc::AutoThread main_thread_;
   // `engine` take ownership of the factories.
   webrtc::MockVideoEncoderFactory* encoder_factory =
       new webrtc::MockVideoEncoderFactory();
@@ -1439,6 +1440,7 @@
   }
 
   static const std::vector<webrtc::SdpVideoFormat> kSdpVideoFormats;
+  rtc::AutoThread main_thread_;
   webrtc::test::ScopedKeyValueConfig field_trials_;
   webrtc::RtcEventLogNull event_log_;
   std::unique_ptr<webrtc::TaskQueueFactory> task_queue_factory_;
@@ -1723,6 +1725,7 @@
     return cricket::StreamParams::CreateLegacy(kSsrc);
   }
 
+  rtc::AutoThread main_thread_;
   webrtc::RtcEventLogNull event_log_;
   webrtc::test::ScopedKeyValueConfig field_trials_;
   std::unique_ptr<webrtc::test::ScopedKeyValueConfig> override_field_trials_;
diff --git a/media/engine/webrtc_voice_engine_unittest.cc b/media/engine/webrtc_voice_engine_unittest.cc
index 130fff3..59a1d58 100644
--- a/media/engine/webrtc_voice_engine_unittest.cc
+++ b/media/engine/webrtc_voice_engine_unittest.cc
@@ -783,6 +783,7 @@
   }
 
  protected:
+  rtc::AutoThread main_thread_;
   const bool use_null_apm_;
   webrtc::test::ScopedKeyValueConfig field_trials_;
   std::unique_ptr<webrtc::TaskQueueFactory> task_queue_factory_;
@@ -3600,6 +3601,7 @@
 
 // Tests that the library initializes and shuts down properly.
 TEST(WebRtcVoiceEngineTest, StartupShutdown) {
+  rtc::AutoThread main_thread;
   for (bool use_null_apm : {false, true}) {
     // If the VoiceEngine wants to gather available codecs early, that's fine
     // but we never want it to create a decoder at this stage.
@@ -3631,6 +3633,7 @@
 
 // Tests that reference counting on the external ADM is correct.
 TEST(WebRtcVoiceEngineTest, StartupShutdownWithExternalADM) {
+  rtc::AutoThread main_thread;
   for (bool use_null_apm : {false, true}) {
     std::unique_ptr<webrtc::TaskQueueFactory> task_queue_factory =
         webrtc::CreateDefaultTaskQueueFactory();
@@ -3720,6 +3723,7 @@
 
 // Tests that VoE supports at least 32 channels
 TEST(WebRtcVoiceEngineTest, Has32Channels) {
+  rtc::AutoThread main_thread;
   for (bool use_null_apm : {false, true}) {
     std::unique_ptr<webrtc::TaskQueueFactory> task_queue_factory =
         webrtc::CreateDefaultTaskQueueFactory();
@@ -3762,6 +3766,7 @@
 
 // Test that we set our preferred codecs properly.
 TEST(WebRtcVoiceEngineTest, SetRecvCodecs) {
+  rtc::AutoThread main_thread;
   for (bool use_null_apm : {false, true}) {
     std::unique_ptr<webrtc::TaskQueueFactory> task_queue_factory =
         webrtc::CreateDefaultTaskQueueFactory();
diff --git a/media/sctp/dcsctp_transport_unittest.cc b/media/sctp/dcsctp_transport_unittest.cc
index 119922c..9d78d1d 100644
--- a/media/sctp/dcsctp_transport_unittest.cc
+++ b/media/sctp/dcsctp_transport_unittest.cc
@@ -78,6 +78,7 @@
 }  // namespace
 
 TEST(DcSctpTransportTest, OpenSequence) {
+  rtc::AutoThread main_thread;
   Peer peer_a;
   peer_a.fake_packet_transport_.SetWritable(true);
 
@@ -94,6 +95,7 @@
 // Tests that the close sequence invoked from one end results in the stream to
 // be reset from both ends and all the proper signals are sent.
 TEST(DcSctpTransportTest, CloseSequence) {
+  rtc::AutoThread main_thread;
   Peer peer_a;
   Peer peer_b;
   peer_a.fake_packet_transport_.SetDestination(&peer_b.fake_packet_transport_,
@@ -135,6 +137,7 @@
 // terminates properly. Both peers will think they initiated it, so no
 // OnSignalClosingProcedureStartedRemotely should be called.
 TEST(DcSctpTransportTest, CloseSequenceSimultaneous) {
+  rtc::AutoThread main_thread;
   Peer peer_a;
   Peer peer_b;
   peer_a.fake_packet_transport_.SetDestination(&peer_b.fake_packet_transport_,
diff --git a/modules/rtp_rtcp/BUILD.gn b/modules/rtp_rtcp/BUILD.gn
index 7b8f259..ce9c409 100644
--- a/modules/rtp_rtcp/BUILD.gn
+++ b/modules/rtp_rtcp/BUILD.gn
@@ -648,6 +648,7 @@
       "../../rtc_base:rtc_numerics",
       "../../rtc_base:stringutils",
       "../../rtc_base:task_queue_for_test",
+      "../../rtc_base:threading",
       "../../rtc_base:timeutils",
       "../../rtc_base/task_utils:to_queued_task",
       "../../system_wrappers",
diff --git a/modules/rtp_rtcp/source/nack_rtx_unittest.cc b/modules/rtp_rtcp/source/nack_rtx_unittest.cc
index fc03504..2f14820 100644
--- a/modules/rtp_rtcp/source/nack_rtx_unittest.cc
+++ b/modules/rtp_rtcp/source/nack_rtx_unittest.cc
@@ -24,6 +24,7 @@
 #include "modules/rtp_rtcp/source/rtp_rtcp_impl2.h"
 #include "modules/rtp_rtcp/source/rtp_sender_video.h"
 #include "rtc_base/rate_limiter.h"
+#include "rtc_base/thread.h"
 #include "test/gtest.h"
 
 namespace webrtc {
@@ -224,6 +225,7 @@
     media_stream_.sequence_numbers_.sort();
   }
 
+  rtc::AutoThread main_thread_;
   std::unique_ptr<ReceiveStatistics> receive_statistics_;
   std::unique_ptr<ModuleRtpRtcpImpl2> rtp_rtcp_module_;
   std::unique_ptr<RTPSenderVideo> rtp_sender_video_;
diff --git a/modules/rtp_rtcp/source/rtcp_sender_unittest.cc b/modules/rtp_rtcp/source/rtcp_sender_unittest.cc
index 38a9302..73e2f7f 100644
--- a/modules/rtp_rtcp/source/rtcp_sender_unittest.cc
+++ b/modules/rtp_rtcp/source/rtcp_sender_unittest.cc
@@ -21,6 +21,7 @@
 #include "modules/rtp_rtcp/source/rtp_packet_received.h"
 #include "modules/rtp_rtcp/source/rtp_rtcp_impl2.h"
 #include "rtc_base/rate_limiter.h"
+#include "rtc_base/thread.h"
 #include "test/gmock.h"
 #include "test/gtest.h"
 #include "test/mock_transport.h"
@@ -131,6 +132,7 @@
     return rtp_rtcp_impl_->GetFeedbackState();
   }
 
+  rtc::AutoThread main_thread_;
   SimulatedClock clock_;
   TestTransport test_transport_;
   std::unique_ptr<ReceiveStatistics> receive_statistics_;
diff --git a/modules/rtp_rtcp/source/rtp_sender_audio_unittest.cc b/modules/rtp_rtcp/source/rtp_sender_audio_unittest.cc
index 52880b9..7397a3a 100644
--- a/modules/rtp_rtcp/source/rtp_sender_audio_unittest.cc
+++ b/modules/rtp_rtcp/source/rtp_sender_audio_unittest.cc
@@ -19,6 +19,7 @@
 #include "modules/rtp_rtcp/source/rtp_header_extensions.h"
 #include "modules/rtp_rtcp/source/rtp_packet_received.h"
 #include "modules/rtp_rtcp/source/rtp_rtcp_impl2.h"
+#include "rtc_base/thread.h"
 #include "test/field_trial.h"
 #include "test/gmock.h"
 #include "test/gtest.h"
@@ -82,6 +83,7 @@
     rtp_module_->SetSequenceNumber(kSeqNum);
   }
 
+  rtc::AutoThread main_thread_;
   SimulatedClock fake_clock_;
   LoopbackTransportTest transport_;
   std::unique_ptr<ModuleRtpRtcpImpl2> rtp_module_;
diff --git a/modules/rtp_rtcp/source/rtp_sender_video_unittest.cc b/modules/rtp_rtcp/source/rtp_sender_video_unittest.cc
index c7fc778..ca8e8d9 100644
--- a/modules/rtp_rtcp/source/rtp_sender_video_unittest.cc
+++ b/modules/rtp_rtcp/source/rtp_sender_video_unittest.cc
@@ -38,6 +38,7 @@
 #include "rtc_base/arraysize.h"
 #include "rtc_base/rate_limiter.h"
 #include "rtc_base/task_queue_for_test.h"
+#include "rtc_base/thread.h"
 #include "test/gmock.h"
 #include "test/gtest.h"
 #include "test/mock_frame_transformer.h"
@@ -197,6 +198,7 @@
       int version);
 
  protected:
+  rtc::AutoThread main_thread_;
   const RtpRtcpInterface::Configuration config_;
   FieldTrials field_trials_;
   SimulatedClock fake_clock_;
@@ -1416,6 +1418,7 @@
   }
 
  protected:
+  rtc::AutoThread main_thread_;
   FieldTrialBasedConfig field_trials_;
   SimulatedClock fake_clock_;
   LoopbackTransportTest transport_;
diff --git a/modules/video_coding/nack_requester_unittest.cc b/modules/video_coding/nack_requester_unittest.cc
index 2234249..cdbf2e0 100644
--- a/modules/video_coding/nack_requester_unittest.cc
+++ b/modules/video_coding/nack_requester_unittest.cc
@@ -92,6 +92,7 @@
   }
 
   static constexpr int64_t kDefaultRttMs = 20;
+  rtc::AutoThread main_thread_;
   test::RunLoop loop_;
   std::unique_ptr<SimulatedClock> clock_;
   test::ScopedKeyValueConfig field_trial_;
@@ -400,6 +401,7 @@
   void RequestKeyFrame() override { ++keyframes_requested_; }
 
   test::ScopedKeyValueConfig nack_delay_field_trial_;
+  rtc::AutoThread main_thread_;
   std::unique_ptr<SimulatedClock> clock_;
   NackPeriodicProcessor nack_periodic_processor_;
   NackRequester nack_module_;
diff --git a/p2p/base/basic_async_resolver_factory_unittest.cc b/p2p/base/basic_async_resolver_factory_unittest.cc
index 6706f50..77b97e7 100644
--- a/p2p/base/basic_async_resolver_factory_unittest.cc
+++ b/p2p/base/basic_async_resolver_factory_unittest.cc
@@ -49,10 +49,12 @@
 // This test is primarily intended to let tools check that the created resolver
 // doesn't leak.
 TEST_F(BasicAsyncResolverFactoryTest, TestCreate) {
+  rtc::AutoThread main_thread;
   TestCreate();
 }
 
 TEST(WrappingAsyncDnsResolverFactoryTest, TestCreateAndResolve) {
+  rtc::AutoThread main_thread;
   WrappingAsyncDnsResolverFactory factory(
       std::make_unique<BasicAsyncResolverFactory>());
 
@@ -67,6 +69,7 @@
 }
 
 TEST(WrappingAsyncDnsResolverFactoryTest, WrapOtherResolver) {
+  rtc::AutoThread main_thread;
   BasicAsyncResolverFactory non_owned_factory;
   WrappingAsyncDnsResolverFactory factory(&non_owned_factory);
   std::unique_ptr<AsyncDnsResolverInterface> resolver(factory.Create());
@@ -92,11 +95,7 @@
 }
 
 TEST(WrappingAsyncDnsResolverFactoryDeathTest, DestroyResolverInCallback) {
-  // This test requires the main thread to be wrapped. So we defeat the
-  // workaround in test/test_main_lib.cc by explicitly wrapping the main
-  // thread here.
-  auto thread = rtc::Thread::CreateWithSocketServer();
-  thread->WrapCurrent();
+  rtc::AutoThread main_thread;
   // TODO(bugs.webrtc.org/12652): Rewrite as death test in loop style when it
   // works.
   WrappingAsyncDnsResolverFactory factory(
@@ -106,11 +105,6 @@
   // we wrap the whole creation section in EXPECT_DEATH.
   RTC_EXPECT_DEATH(CallResolver(factory),
                    "Check failed: !within_resolve_result_");
-  // If we get here, we have to unwrap the thread.
-  thread->Quit();
-  thread->Run();
-  thread->UnwrapCurrent();
-  thread = nullptr;
 }
 #endif
 
diff --git a/p2p/base/dtls_transport_unittest.cc b/p2p/base/dtls_transport_unittest.cc
index 851c1ea..80691ab 100644
--- a/p2p/base/dtls_transport_unittest.cc
+++ b/p2p/base/dtls_transport_unittest.cc
@@ -380,6 +380,7 @@
   }
 
  protected:
+  rtc::AutoThread main_thread_;
   rtc::ScopedFakeClock fake_clock_;
   DtlsTestClient client1_;
   DtlsTestClient client2_;
diff --git a/p2p/base/fake_ice_transport.h b/p2p/base/fake_ice_transport.h
index c053abd..3ee4cd3 100644
--- a/p2p/base/fake_ice_transport.h
+++ b/p2p/base/fake_ice_transport.h
@@ -37,7 +37,9 @@
       : name_(name),
         component_(component),
         network_thread_(network_thread ? network_thread
-                                       : rtc::Thread::Current()) {}
+                                       : rtc::Thread::Current()) {
+    RTC_DCHECK(network_thread_);
+  }
   // Must be called either on the network thread, or after the network thread
   // has been shut down.
   ~FakeIceTransport() override {
diff --git a/p2p/base/p2p_transport_channel_unittest.cc b/p2p/base/p2p_transport_channel_unittest.cc
index 04d4850..2a1e993 100644
--- a/p2p/base/p2p_transport_channel_unittest.cc
+++ b/p2p/base/p2p_transport_channel_unittest.cc
@@ -5150,6 +5150,7 @@
 // if the channel is not destroyed.
 TEST(P2PTransportChannelResolverTest, HostnameCandidateIsResolved) {
   ResolverFactoryFixture resolver_fixture;
+  rtc::AutoThread main_thread;
   FakePortAllocator allocator(rtc::Thread::Current(), nullptr);
   webrtc::IceTransportInit init;
   init.set_port_allocator(&allocator);
@@ -6082,6 +6083,7 @@
 }
 
 TEST(P2PTransportChannel, InjectIceController) {
+  rtc::AutoThread main_thread_;
   MockIceControllerFactory factory;
   FakePortAllocator pa(rtc::Thread::Current(), nullptr);
   EXPECT_CALL(factory, RecordIceControllerCreated()).Times(1);
diff --git a/p2p/base/pseudo_tcp_unittest.cc b/p2p/base/pseudo_tcp_unittest.cc
index 386f2e7..25a7397 100644
--- a/p2p/base/pseudo_tcp_unittest.cc
+++ b/p2p/base/pseudo_tcp_unittest.cc
@@ -218,6 +218,7 @@
     delete message->pdata;
   }
 
+  rtc::AutoThread main_thread_;
   PseudoTcpForTest local_;
   PseudoTcpForTest remote_;
   rtc::MemoryStream send_stream_;
diff --git a/p2p/base/regathering_controller.cc b/p2p/base/regathering_controller.cc
index 293e9db..9326c1a 100644
--- a/p2p/base/regathering_controller.cc
+++ b/p2p/base/regathering_controller.cc
@@ -18,6 +18,7 @@
     cricket::IceTransportInternal* ice_transport,
     rtc::Thread* thread)
     : config_(config), ice_transport_(ice_transport), thread_(thread) {
+  RTC_DCHECK(thread_);
   RTC_DCHECK_RUN_ON(thread_);
   RTC_DCHECK(ice_transport_);
   ice_transport_->SignalStateChanged.connect(
diff --git a/p2p/base/stun_request_unittest.cc b/p2p/base/stun_request_unittest.cc
index 050df0b..79c2c3f 100644
--- a/p2p/base/stun_request_unittest.cc
+++ b/p2p/base/stun_request_unittest.cc
@@ -67,6 +67,7 @@
   void OnTimeout() { timeout_ = true; }
 
  protected:
+  rtc::AutoThread main_thread_;
   StunRequestManager manager_;
   int request_count_;
   StunMessage* response_;
diff --git a/p2p/base/stun_server_unittest.cc b/p2p/base/stun_server_unittest.cc
index b1142f7..842cede 100644
--- a/p2p/base/stun_server_unittest.cc
+++ b/p2p/base/stun_server_unittest.cc
@@ -64,6 +64,7 @@
   }
 
  private:
+  rtc::AutoThread main_thread;
   std::unique_ptr<rtc::VirtualSocketServer> ss_;
   rtc::Thread network_;
   std::unique_ptr<StunServer> server_;
diff --git a/pc/audio_rtp_receiver_unittest.cc b/pc/audio_rtp_receiver_unittest.cc
index de72d3f..91652f1 100644
--- a/pc/audio_rtp_receiver_unittest.cc
+++ b/pc/audio_rtp_receiver_unittest.cc
@@ -50,6 +50,7 @@
     receiver_->SetMediaChannel(nullptr);
   }
 
+  rtc::AutoThread main_thread_;
   rtc::Thread* worker_;
   rtc::scoped_refptr<AudioRtpReceiver> receiver_;
   cricket::MockVoiceMediaChannel media_channel_;
diff --git a/pc/channel_manager_unittest.cc b/pc/channel_manager_unittest.cc
index ccf541c..16630c4 100644
--- a/pc/channel_manager_unittest.cc
+++ b/pc/channel_manager_unittest.cc
@@ -87,6 +87,7 @@
     // go out of scope.
   }
 
+  rtc::AutoThread main_thread_;
   std::unique_ptr<rtc::Thread> network_;
   rtc::Thread* const worker_;
   std::unique_ptr<webrtc::VideoBitrateAllocatorFactory>
diff --git a/pc/channel_unittest.cc b/pc/channel_unittest.cc
index 725ee34..201fd45 100644
--- a/pc/channel_unittest.cc
+++ b/pc/channel_unittest.cc
@@ -1412,6 +1412,7 @@
     return static_cast<typename T::MediaChannel*>(channel2_->media_channel());
   }
 
+  rtc::AutoThread main_thread_;
   // TODO(pbos): Remove playout from all media channels and let renderers mute
   // themselves.
   const bool verify_playout_;
diff --git a/pc/data_channel_controller_unittest.cc b/pc/data_channel_controller_unittest.cc
index 7a1f68a..2f5c924 100644
--- a/pc/data_channel_controller_unittest.cc
+++ b/pc/data_channel_controller_unittest.cc
@@ -33,6 +33,7 @@
         .WillByDefault(Return(rtc::Thread::Current()));
   }
 
+  rtc::AutoThread main_thread_;
   rtc::scoped_refptr<NiceMock<MockPeerConnectionInternal>> pc_;
 };
 
diff --git a/pc/data_channel_unittest.cc b/pc/data_channel_unittest.cc
index 55f9c34..7b3e865 100644
--- a/pc/data_channel_unittest.cc
+++ b/pc/data_channel_unittest.cc
@@ -100,6 +100,7 @@
     webrtc_data_channel_->RegisterObserver(observer_.get());
   }
 
+  rtc::AutoThread main_thread_;
   webrtc::InternalDataChannelInit init_;
   std::unique_ptr<FakeDataChannelController> controller_;
   std::unique_ptr<FakeDataChannelObserver> observer_;
diff --git a/pc/dtls_srtp_transport_unittest.cc b/pc/dtls_srtp_transport_unittest.cc
index 30f09e7..5c4eac0 100644
--- a/pc/dtls_srtp_transport_unittest.cc
+++ b/pc/dtls_srtp_transport_unittest.cc
@@ -251,6 +251,7 @@
     SendRecvRtcpPackets();
   }
 
+  rtc::AutoThread main_thread_;
   std::unique_ptr<DtlsSrtpTransport> dtls_srtp_transport1_;
   std::unique_ptr<DtlsSrtpTransport> dtls_srtp_transport2_;
   webrtc::TransportObserver transport_observer1_;
diff --git a/pc/dtls_transport_unittest.cc b/pc/dtls_transport_unittest.cc
index a9ac73c..4d48920 100644
--- a/pc/dtls_transport_unittest.cc
+++ b/pc/dtls_transport_unittest.cc
@@ -85,6 +85,7 @@
     fake_dtls1->SetDestination(fake_dtls2.get());
   }
 
+  rtc::AutoThread main_thread_;
   rtc::scoped_refptr<DtlsTransport> transport_;
   TestDtlsTransportObserver observer_;
 };
diff --git a/pc/dtmf_sender_unittest.cc b/pc/dtmf_sender_unittest.cc
index 270b3e2..922abdc 100644
--- a/pc/dtmf_sender_unittest.cc
+++ b/pc/dtmf_sender_unittest.cc
@@ -214,6 +214,7 @@
     }
   }
 
+  rtc::AutoThread main_thread_;
   std::unique_ptr<FakeDtmfObserver> observer_;
   std::unique_ptr<FakeDtmfProvider> provider_;
   rtc::scoped_refptr<DtmfSender> dtmf_;
diff --git a/pc/ice_transport_unittest.cc b/pc/ice_transport_unittest.cc
index 95af2cd..2862599 100644
--- a/pc/ice_transport_unittest.cc
+++ b/pc/ice_transport_unittest.cc
@@ -22,7 +22,10 @@
 
 namespace webrtc {
 
-class IceTransportTest : public ::testing::Test {};
+class IceTransportTest : public ::testing::Test {
+ private:
+  rtc::AutoThread main_thread_;
+};
 
 TEST_F(IceTransportTest, CreateNonSelfDeletingTransport) {
   auto cricket_transport =
diff --git a/pc/jsep_transport_controller_unittest.cc b/pc/jsep_transport_controller_unittest.cc
index ee306f0..0fbdff5 100644
--- a/pc/jsep_transport_controller_unittest.cc
+++ b/pc/jsep_transport_controller_unittest.cc
@@ -346,6 +346,7 @@
     return true;
   }
 
+  rtc::AutoThread main_thread_;
   // Information received from signals from transport controller.
   cricket::IceConnectionState connection_state_ =
       cricket::kIceConnectionConnecting;
diff --git a/pc/jsep_transport_unittest.cc b/pc/jsep_transport_unittest.cc
index c63dc49..630a189 100644
--- a/pc/jsep_transport_unittest.cc
+++ b/pc/jsep_transport_unittest.cc
@@ -188,6 +188,7 @@
 
   void OnRtcpMuxActive() { signal_rtcp_mux_active_received_ = true; }
 
+  rtc::AutoThread main_thread_;
   std::unique_ptr<JsepTransport> jsep_transport_;
   bool signal_rtcp_mux_active_received_ = false;
   // The SrtpTransport is owned by `jsep_transport_`. Keep a raw pointer here
diff --git a/pc/media_stream_unittest.cc b/pc/media_stream_unittest.cc
index a1146a3..f55ea20 100644
--- a/pc/media_stream_unittest.cc
+++ b/pc/media_stream_unittest.cc
@@ -80,6 +80,7 @@
     EXPECT_FALSE(track->enabled());
   }
 
+  rtc::AutoThread main_thread_;
   scoped_refptr<MediaStreamInterface> stream_;
   scoped_refptr<AudioTrackInterface> audio_track_;
   scoped_refptr<VideoTrackInterface> video_track_;
diff --git a/pc/peer_connection_end_to_end_unittest.cc b/pc/peer_connection_end_to_end_unittest.cc
index 08e3cb1..1d0f4ec 100644
--- a/pc/peer_connection_end_to_end_unittest.cc
+++ b/pc/peer_connection_end_to_end_unittest.cc
@@ -220,6 +220,7 @@
   }
 
  protected:
+  rtc::AutoThread main_thread_;
   rtc::PhysicalSocketServer pss_;
   std::unique_ptr<rtc::Thread> network_thread_;
   std::unique_ptr<rtc::Thread> worker_thread_;
diff --git a/pc/peer_connection_factory_unittest.cc b/pc/peer_connection_factory_unittest.cc
index 442a331..128f72c 100644
--- a/pc/peer_connection_factory_unittest.cc
+++ b/pc/peer_connection_factory_unittest.cc
@@ -154,6 +154,7 @@
     EXPECT_GT(codec.clock_rate, 0);
   }
 
+  rtc::AutoThread main_thread_;
   rtc::scoped_refptr<PeerConnectionFactoryInterface> factory_;
   NullPeerConnectionObserver observer_;
   std::unique_ptr<cricket::FakePortAllocator> port_allocator_;
diff --git a/pc/peer_connection_header_extension_unittest.cc b/pc/peer_connection_header_extension_unittest.cc
index ba78dd8..060bb9b 100644
--- a/pc/peer_connection_header_extension_unittest.cc
+++ b/pc/peer_connection_header_extension_unittest.cc
@@ -111,6 +111,7 @@
         pc_factory, result.MoveValue(), std::move(observer));
   }
 
+  rtc::AutoThread main_thread_;
   std::vector<RtpHeaderExtensionCapability> extensions_;
 };
 
diff --git a/pc/peer_connection_ice_unittest.cc b/pc/peer_connection_ice_unittest.cc
index 5676837..c51970e 100644
--- a/pc/peer_connection_ice_unittest.cc
+++ b/pc/peer_connection_ice_unittest.cc
@@ -1425,6 +1425,7 @@
     pc_ = result.MoveValue();
   }
 
+  rtc::AutoThread main_thread_;
   rtc::scoped_refptr<PeerConnectionFactoryInterface> pc_factory_ = nullptr;
   rtc::scoped_refptr<PeerConnectionInterface> pc_ = nullptr;
   cricket::FakePortAllocator* port_allocator_ = nullptr;
diff --git a/pc/peer_connection_rtp_unittest.cc b/pc/peer_connection_rtp_unittest.cc
index 80a4a46..6382a30 100644
--- a/pc/peer_connection_rtp_unittest.cc
+++ b/pc/peer_connection_rtp_unittest.cc
@@ -142,6 +142,8 @@
     return std::make_unique<PeerConnectionWrapper>(
         pc_factory_, result.MoveValue(), std::move(observer));
   }
+
+  rtc::AutoThread main_thread_;
 };
 
 class PeerConnectionRtpTest
diff --git a/pc/remote_audio_source.cc b/pc/remote_audio_source.cc
index 781e451..597d199 100644
--- a/pc/remote_audio_source.cc
+++ b/pc/remote_audio_source.cc
@@ -62,7 +62,6 @@
 }
 
 RemoteAudioSource::~RemoteAudioSource() {
-  RTC_DCHECK_RUN_ON(main_thread_);
   RTC_DCHECK(audio_observers_.empty());
   if (!sinks_.empty()) {
     RTC_LOG(LS_WARNING)
diff --git a/pc/rtc_stats_collector_unittest.cc b/pc/rtc_stats_collector_unittest.cc
index f5cf39d..889bd8e 100644
--- a/pc/rtc_stats_collector_unittest.cc
+++ b/pc/rtc_stats_collector_unittest.cc
@@ -917,6 +917,7 @@
 
  protected:
   rtc::ScopedFakeClock fake_clock_;
+  rtc::AutoThread main_thread_;
   rtc::scoped_refptr<FakePeerConnectionForStats> pc_;
   std::unique_ptr<RTCStatsCollectorWrapper> stats_;
 };
@@ -3529,6 +3530,7 @@
 };
 
 TEST(RTCStatsCollectorTestWithFakeCollector, ThreadUsageAndResultsMerging) {
+  rtc::AutoThread main_thread_;
   auto pc = rtc::make_ref_counted<FakePeerConnectionForStats>();
   rtc::scoped_refptr<FakeRTCStatsCollector> stats_collector(
       FakeRTCStatsCollector::Create(pc.get(),
diff --git a/pc/rtp_transceiver_unittest.cc b/pc/rtp_transceiver_unittest.cc
index 680fe11..ffa5374 100644
--- a/pc/rtp_transceiver_unittest.cc
+++ b/pc/rtp_transceiver_unittest.cc
@@ -53,6 +53,7 @@
   cricket::ChannelManager* channel_manager() { return channel_manager_.get(); }
 
  private:
+  rtc::AutoThread main_thread_;
   cricket::FakeMediaEngine fake_media_engine_;
   rtc::UniqueRandomIdGenerator ssrc_generator_;
   std::unique_ptr<cricket::ChannelManager> channel_manager_;
@@ -151,6 +152,7 @@
     return sender;
   }
 
+  rtc::AutoThread main_thread_;
   rtc::scoped_refptr<MockRtpReceiverInternal> receiver_ = MockReceiver();
   rtc::scoped_refptr<MockRtpSenderInternal> sender_ = MockSender();
   rtc::scoped_refptr<RtpTransceiver> transceiver_;
@@ -222,6 +224,7 @@
     transceiver_->ClearChannel();
   }
 
+  rtc::AutoThread main_thread_;
   rtc::scoped_refptr<MockRtpReceiverInternal> receiver_ = MockReceiver();
   rtc::scoped_refptr<MockRtpSenderInternal> sender_ = MockSender();
 
diff --git a/pc/sctp_transport_unittest.cc b/pc/sctp_transport_unittest.cc
index e3168d8..3f417dd 100644
--- a/pc/sctp_transport_unittest.cc
+++ b/pc/sctp_transport_unittest.cc
@@ -147,12 +147,14 @@
     return static_cast<FakeCricketSctpTransport*>(transport_->internal());
   }
 
+  rtc::AutoThread main_thread_;
   rtc::scoped_refptr<SctpTransport> transport_;
   rtc::scoped_refptr<DtlsTransport> dtls_transport_;
   TestSctpTransportObserver observer_;
 };
 
 TEST(SctpTransportSimpleTest, CreateClearDelete) {
+  rtc::AutoThread main_thread;
   std::unique_ptr<cricket::SctpTransportInternal> fake_cricket_sctp_transport =
       absl::WrapUnique(new FakeCricketSctpTransport());
   rtc::scoped_refptr<SctpTransport> sctp_transport =
diff --git a/pc/sdp_offer_answer_unittest.cc b/pc/sdp_offer_answer_unittest.cc
index 2ce9e52..4f16de4 100644
--- a/pc/sdp_offer_answer_unittest.cc
+++ b/pc/sdp_offer_answer_unittest.cc
@@ -95,6 +95,7 @@
   rtc::scoped_refptr<PeerConnectionFactoryInterface> pc_factory_;
 
  private:
+  rtc::AutoThread main_thread_;
 };
 
 TEST_F(SdpOfferAnswerTest, OnTrackReturnsProxiedObject) {
diff --git a/pc/stats_collector_unittest.cc b/pc/stats_collector_unittest.cc
index 5af8be7..e14de1a 100644
--- a/pc/stats_collector_unittest.cc
+++ b/pc/stats_collector_unittest.cc
@@ -731,6 +731,9 @@
     EXPECT_EQ(rtc::SrtpCryptoSuiteToName(rtc::kSrtpAes128CmSha1_80),
               srtp_crypto_suite);
   }
+
+ private:
+  rtc::AutoThread main_thread_;
 };
 
 static rtc::scoped_refptr<MockRtpSenderInternal> CreateMockSender(
diff --git a/pc/test/fake_audio_capture_module_unittest.cc b/pc/test/fake_audio_capture_module_unittest.cc
index 63b41cd..64141b1 100644
--- a/pc/test/fake_audio_capture_module_unittest.cc
+++ b/pc/test/fake_audio_capture_module_unittest.cc
@@ -115,6 +115,8 @@
     return min_buffer_size;
   }
 
+  rtc::AutoThread main_thread_;
+
   mutable webrtc::Mutex mutex_;
 
   int push_iterations_;
diff --git a/pc/test/integration_test_helpers.h b/pc/test/integration_test_helpers.h
index f408e0c..35aedbd 100644
--- a/pc/test/integration_test_helpers.h
+++ b/pc/test/integration_test_helpers.h
@@ -1896,6 +1896,7 @@
   SdpSemantics sdp_semantics_;
 
  private:
+  rtc::AutoThread main_thread_;  // Used as the signal thread by most tests.
   // `ss_` is used by `network_thread_` so it must be destroyed later.
   std::unique_ptr<rtc::VirtualSocketServer> ss_;
   std::unique_ptr<rtc::FirewallSocketServer> fss_;
diff --git a/pc/track_media_info_map_unittest.cc b/pc/track_media_info_map_unittest.cc
index e9428ca..370fd0b 100644
--- a/pc/track_media_info_map_unittest.cc
+++ b/pc/track_media_info_map_unittest.cc
@@ -191,6 +191,7 @@
   }
 
  protected:
+  rtc::AutoThread main_thread_;
   cricket::VoiceMediaInfo* voice_media_info_;
   cricket::VideoMediaInfo* video_media_info_;
   std::vector<rtc::scoped_refptr<RtpSenderInternal>> rtp_senders_;
diff --git a/pc/video_rtp_receiver_unittest.cc b/pc/video_rtp_receiver_unittest.cc
index c13214f..0d3fc57 100644
--- a/pc/video_rtp_receiver_unittest.cc
+++ b/pc/video_rtp_receiver_unittest.cc
@@ -86,6 +86,7 @@
     return receiver_->streams()[0]->FindVideoTrack("receiver")->GetSource();
   }
 
+  rtc::AutoThread main_thread_;
   std::unique_ptr<rtc::Thread> worker_thread_;
   NiceMock<MockVideoMediaChannel> channel_;
   rtc::scoped_refptr<VideoRtpReceiver> receiver_;
diff --git a/pc/video_track_unittest.cc b/pc/video_track_unittest.cc
index 2a10c93..7d00522 100644
--- a/pc/video_track_unittest.cc
+++ b/pc/video_track_unittest.cc
@@ -39,6 +39,7 @@
   }
 
  protected:
+  rtc::AutoThread main_thread_;
   rtc::scoped_refptr<FakeVideoTrackSource> video_track_source_;
   rtc::scoped_refptr<VideoTrack> video_track_;
   cricket::FakeFrameSource frame_source_;
diff --git a/rtc_base/memory/fifo_buffer_unittest.cc b/rtc_base/memory/fifo_buffer_unittest.cc
index b602f0a..0e44bf2 100644
--- a/rtc_base/memory/fifo_buffer_unittest.cc
+++ b/rtc_base/memory/fifo_buffer_unittest.cc
@@ -17,6 +17,7 @@
 namespace rtc {
 
 TEST(FifoBufferTest, TestAll) {
+  rtc::AutoThread main_thread;
   const size_t kSize = 16;
   const char in[kSize * 2 + 1] = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
   char out[kSize * 2];
@@ -213,6 +214,7 @@
 }
 
 TEST(FifoBufferTest, FullBufferCheck) {
+  rtc::AutoThread main_thread;
   FifoBuffer buff(10);
   buff.ConsumeWriteBuffer(10);
 
diff --git a/rtc_base/nat_unittest.cc b/rtc_base/nat_unittest.cc
index f7f2fb4..f6dd83c 100644
--- a/rtc_base/nat_unittest.cc
+++ b/rtc_base/nat_unittest.cc
@@ -221,6 +221,7 @@
 
 void TestPhysicalInternal(const SocketAddress& int_addr) {
   webrtc::test::ScopedKeyValueConfig field_trials;
+  rtc::AutoThread main_thread;
   PhysicalSocketServer socket_server;
   BasicNetworkManager network_manager(nullptr, &socket_server, &field_trials);
   network_manager.StartUpdating();
@@ -292,6 +293,7 @@
 }  // namespace
 
 void TestVirtualInternal(int family) {
+  rtc::AutoThread main_thread;
   std::unique_ptr<TestVirtualSocketServer> int_vss(
       new TestVirtualSocketServer());
   std::unique_ptr<TestVirtualSocketServer> ext_vss(
diff --git a/rtc_base/network_unittest.cc b/rtc_base/network_unittest.cc
index bfb30b2..de731fa 100644
--- a/rtc_base/network_unittest.cc
+++ b/rtc_base/network_unittest.cc
@@ -319,6 +319,7 @@
 
  protected:
   webrtc::test::ScopedKeyValueConfig field_trials_;
+  rtc::AutoThread main_thread_;
   bool callback_called_;
 };
 
diff --git a/rtc_base/openssl_adapter_unittest.cc b/rtc_base/openssl_adapter_unittest.cc
index 21da777..ce351dc 100644
--- a/rtc_base/openssl_adapter_unittest.cc
+++ b/rtc_base/openssl_adapter_unittest.cc
@@ -84,6 +84,7 @@
 // Verifies that SSLStart works when OpenSSLAdapter is started in standalone
 // mode.
 TEST(OpenSSLAdapterTest, TestBeginSSLBeforeConnection) {
+  rtc::AutoThread main_thread;
   Socket* async_socket = new MockAsyncSocket();
   OpenSSLAdapter adapter(async_socket);
   EXPECT_EQ(adapter.StartSSL("webrtc.org"), 0);
@@ -91,6 +92,7 @@
 
 // Verifies that the adapter factory can create new adapters.
 TEST(OpenSSLAdapterFactoryTest, CreateSingleOpenSSLAdapter) {
+  rtc::AutoThread main_thread;
   OpenSSLAdapterFactory adapter_factory;
   Socket* async_socket = new MockAsyncSocket();
   auto simple_adapter = std::unique_ptr<OpenSSLAdapter>(
@@ -101,6 +103,7 @@
 // Verifies that setting a custom verifier still allows for adapters to be
 // created.
 TEST(OpenSSLAdapterFactoryTest, CreateWorksWithCustomVerifier) {
+  rtc::AutoThread main_thread;
   MockCertVerifier* mock_verifier = new MockCertVerifier();
   EXPECT_CALL(*mock_verifier, Verify(_)).WillRepeatedly(Return(true));
   auto cert_verifier = std::unique_ptr<SSLCertificateVerifier>(mock_verifier);
diff --git a/rtc_base/operations_chain_unittest.cc b/rtc_base/operations_chain_unittest.cc
index b598cb9..59980a2 100644
--- a/rtc_base/operations_chain_unittest.cc
+++ b/rtc_base/operations_chain_unittest.cc
@@ -392,6 +392,7 @@
 }
 
 TEST(OperationsChainTest, OnChainEmptyCallback) {
+  rtc::AutoThread main_thread;
   OperationTrackerProxy operation_tracker_proxy;
   operation_tracker_proxy.Initialize()->Wait(Event::kForever);
 
diff --git a/rtc_base/rtc_certificate_generator_unittest.cc b/rtc_base/rtc_certificate_generator_unittest.cc
index 076f643..53ae973 100644
--- a/rtc_base/rtc_certificate_generator_unittest.cc
+++ b/rtc_base/rtc_certificate_generator_unittest.cc
@@ -75,6 +75,7 @@
  protected:
   static constexpr int kGenerationTimeoutMs = 10000;
 
+  rtc::AutoThread main_thread_;
   scoped_refptr<RTCCertificateGeneratorFixture> fixture_;
 };
 
diff --git a/rtc_base/ssl_stream_adapter_unittest.cc b/rtc_base/ssl_stream_adapter_unittest.cc
index 2305bce..4786876 100644
--- a/rtc_base/ssl_stream_adapter_unittest.cc
+++ b/rtc_base/ssl_stream_adapter_unittest.cc
@@ -762,6 +762,7 @@
     return server_ssl_->GetIdentityForTesting();
   }
 
+  rtc::AutoThread main_thread_;
   std::string client_cert_pem_;
   std::string client_private_key_pem_;
   rtc::KeyParams client_key_type_;
diff --git a/rtc_base/test_client_unittest.cc b/rtc_base/test_client_unittest.cc
index e150102..a0c8b88 100644
--- a/rtc_base/test_client_unittest.cc
+++ b/rtc_base/test_client_unittest.cc
@@ -17,8 +17,8 @@
 #include "rtc_base/async_udp_socket.h"
 #include "rtc_base/logging.h"
 #include "rtc_base/net_helpers.h"
+#include "rtc_base/physical_socket_server.h"
 #include "rtc_base/socket.h"
-#include "rtc_base/socket_server.h"
 #include "rtc_base/test_echo_server.h"
 #include "rtc_base/thread.h"
 #include "test/gtest.h"
@@ -39,9 +39,9 @@
   }
 
 void TestUdpInternal(const SocketAddress& loopback) {
-  Thread* main = Thread::Current();
-  Socket* socket =
-      main->socketserver()->CreateSocket(loopback.family(), SOCK_DGRAM);
+  rtc::PhysicalSocketServer socket_server;
+  rtc::AutoSocketServerThread main_thread(&socket_server);
+  Socket* socket = socket_server.CreateSocket(loopback.family(), SOCK_DGRAM);
   socket->Bind(loopback);
 
   TestClient client(std::make_unique<AsyncUDPSocket>(socket));
@@ -53,11 +53,11 @@
 }
 
 void TestTcpInternal(const SocketAddress& loopback) {
-  Thread* main = Thread::Current();
-  TestEchoServer server(main, loopback);
+  rtc::PhysicalSocketServer socket_server;
+  rtc::AutoSocketServerThread main_thread(&socket_server);
+  TestEchoServer server(&main_thread, loopback);
 
-  Socket* socket =
-      main->socketserver()->CreateSocket(loopback.family(), SOCK_STREAM);
+  Socket* socket = socket_server.CreateSocket(loopback.family(), SOCK_STREAM);
   std::unique_ptr<AsyncTCPSocket> tcp_socket = absl::WrapUnique(
       AsyncTCPSocket::Create(socket, loopback, server.address()));
   ASSERT_TRUE(tcp_socket != nullptr);
diff --git a/rtc_base/thread_unittest.cc b/rtc_base/thread_unittest.cc
index 53b23ad..5497f8d 100644
--- a/rtc_base/thread_unittest.cc
+++ b/rtc_base/thread_unittest.cc
@@ -260,12 +260,12 @@
 }
 
 TEST(ThreadTest, CountBlockingCalls) {
+  rtc::AutoThread current;
+
   // When the test runs, this will print out:
   //   (thread_unittest.cc:262): Blocking TestBody: total=2 (actual=1, could=1)
   RTC_LOG_THREAD_BLOCK_COUNT();
 #if RTC_DCHECK_IS_ON
-  rtc::Thread* current = rtc::Thread::Current();
-  ASSERT_TRUE(current);
   rtc::Thread::ScopedCountBlockingCalls blocked_calls(
       [&](uint32_t actual_block, uint32_t could_block) {
         EXPECT_EQ(1u, actual_block);
@@ -280,7 +280,7 @@
   // invoke, but should still count as an invoke that could block since we
   // that the call to Invoke serves a purpose in some configurations (and should
   // not be used a general way to call methods on the same thread).
-  current->Invoke<void>(RTC_FROM_HERE, []() {});
+  current.Invoke<void>(RTC_FROM_HERE, []() {});
   EXPECT_EQ(0u, blocked_calls.GetBlockingCallCount());
   EXPECT_EQ(1u, blocked_calls.GetCouldBeBlockingCallCount());
   EXPECT_EQ(1u, blocked_calls.GetTotalBlockedCallCount());
@@ -302,22 +302,20 @@
 
 #if RTC_DCHECK_IS_ON
 TEST(ThreadTest, CountBlockingCallsOneCallback) {
-  rtc::Thread* current = rtc::Thread::Current();
-  ASSERT_TRUE(current);
+  rtc::AutoThread current;
   bool was_called_back = false;
   {
     rtc::Thread::ScopedCountBlockingCalls blocked_calls(
         [&](uint32_t actual_block, uint32_t could_block) {
           was_called_back = true;
         });
-    current->Invoke<void>(RTC_FROM_HERE, []() {});
+    current.Invoke<void>(RTC_FROM_HERE, []() {});
   }
   EXPECT_TRUE(was_called_back);
 }
 
 TEST(ThreadTest, CountBlockingCallsSkipCallback) {
-  rtc::Thread* current = rtc::Thread::Current();
-  ASSERT_TRUE(current);
+  rtc::AutoThread current;
   bool was_called_back = false;
   {
     rtc::Thread::ScopedCountBlockingCalls blocked_calls(
@@ -327,7 +325,7 @@
     // Changed `blocked_calls` to not issue the callback if there are 1 or
     // fewer blocking calls (i.e. we set the minimum required number to 2).
     blocked_calls.set_minimum_call_count_for_callback(2);
-    current->Invoke<void>(RTC_FROM_HERE, []() {});
+    current.Invoke<void>(RTC_FROM_HERE, []() {});
   }
   // We should not have gotten a call back.
   EXPECT_FALSE(was_called_back);
@@ -371,17 +369,18 @@
 
 #if (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
 TEST(ThreadTest, InvokeToThreadAllowedReturnsTrueWithoutPolicies) {
+  rtc::AutoThread main_thread;
   // Create and start the thread.
   auto thread1 = Thread::CreateWithSocketServer();
   auto thread2 = Thread::CreateWithSocketServer();
 
   thread1->PostTask(ToQueuedTask(
       [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); }));
-  Thread* th_main = Thread::Current();
-  th_main->ProcessMessages(100);
+  main_thread.ProcessMessages(100);
 }
 
 TEST(ThreadTest, InvokeAllowedWhenThreadsAdded) {
+  rtc::AutoThread main_thread;
   // Create and start the thread.
   auto thread1 = Thread::CreateWithSocketServer();
   auto thread2 = Thread::CreateWithSocketServer();
@@ -396,11 +395,11 @@
     EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread3.get()));
     EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread4.get()));
   }));
-  Thread* th_main = Thread::Current();
-  th_main->ProcessMessages(100);
+  main_thread.ProcessMessages(100);
 }
 
 TEST(ThreadTest, InvokesDisallowedWhenDisallowAllInvokes) {
+  rtc::AutoThread main_thread;
   // Create and start the thread.
   auto thread1 = Thread::CreateWithSocketServer();
   auto thread2 = Thread::CreateWithSocketServer();
@@ -410,20 +409,19 @@
   thread1->PostTask(ToQueuedTask([&]() {
     EXPECT_FALSE(thread1->IsInvokeToThreadAllowed(thread2.get()));
   }));
-  Thread* th_main = Thread::Current();
-  th_main->ProcessMessages(100);
+  main_thread.ProcessMessages(100);
 }
 #endif  // (!defined(NDEBUG) || RTC_DCHECK_IS_ON)
 
 TEST(ThreadTest, InvokesAllowedByDefault) {
+  rtc::AutoThread main_thread;
   // Create and start the thread.
   auto thread1 = Thread::CreateWithSocketServer();
   auto thread2 = Thread::CreateWithSocketServer();
 
   thread1->PostTask(ToQueuedTask(
       [&]() { EXPECT_TRUE(thread1->IsInvokeToThreadAllowed(thread2.get())); }));
-  Thread* th_main = Thread::Current();
-  th_main->ProcessMessages(100);
+  main_thread.ProcessMessages(100);
 }
 
 TEST(ThreadTest, Invoke) {
@@ -653,6 +651,7 @@
 // all messages (both delayed and non delayed) up until the current time, on
 // all registered message queues.
 TEST(ThreadManager, ProcessAllMessageQueues) {
+  rtc::AutoThread main_thread;
   Event entered_process_all_message_queues(true, false);
   auto a = Thread::CreateWithSocketServer();
   auto b = Thread::CreateWithSocketServer();
@@ -678,7 +677,7 @@
   b->PostTask(ToQueuedTask(incrementer));
   a->PostDelayedTask(ToQueuedTask(incrementer), 0);
   b->PostDelayedTask(ToQueuedTask(incrementer), 0);
-  rtc::Thread::Current()->PostTask(ToQueuedTask(event_signaler));
+  main_thread.PostTask(ToQueuedTask(event_signaler));
 
   ThreadManager::ProcessAllMessageQueuesForTesting();
   EXPECT_EQ(4, AtomicOps::AcquireLoad(&messages_processed));
@@ -695,6 +694,7 @@
 // Test that ProcessAllMessageQueues doesn't hang if a queue clears its
 // messages.
 TEST(ThreadManager, ProcessAllMessageQueuesWithClearedQueue) {
+  rtc::AutoThread main_thread;
   Event entered_process_all_message_queues(true, false);
   auto t = Thread::CreateWithSocketServer();
   t->Start();
@@ -713,7 +713,7 @@
 
   // Post messages (both delayed and non delayed) to both threads.
   t->PostTask(clearer);
-  rtc::Thread::Current()->PostTask(event_signaler);
+  main_thread.PostTask(event_signaler);
   ThreadManager::ProcessAllMessageQueuesForTesting();
 }
 
@@ -759,6 +759,7 @@
   enum { kWaitTimeout = 1000 };
   DEPRECATED_AsyncInvokeTest() : int_value_(0), expected_thread_(nullptr) {}
 
+  rtc::AutoThread main_thread_;
   int int_value_;
   Thread* expected_thread_;
 };
diff --git a/sdk/android/native_unittests/android_network_monitor_unittest.cc b/sdk/android/native_unittests/android_network_monitor_unittest.cc
index 455e4f2..6844e87 100644
--- a/sdk/android/native_unittests/android_network_monitor_unittest.cc
+++ b/sdk/android/native_unittests/android_network_monitor_unittest.cc
@@ -12,6 +12,7 @@
 
 #include "rtc_base/ip_address.h"
 #include "rtc_base/logging.h"
+#include "rtc_base/thread.h"
 #include "sdk/android/native_unittests/application_context_provider.h"
 #include "sdk/android/src/jni/jni_helpers.h"
 #include "test/gtest.h"
@@ -67,6 +68,7 @@
 
  protected:
   test::ScopedKeyValueConfig field_trials_;
+  rtc::AutoThread main_thread_;
   std::unique_ptr<jni::AndroidNetworkMonitor> network_monitor_;
 };
 
diff --git a/test/test_main_lib.cc b/test/test_main_lib.cc
index 839f76c..7867d2f 100644
--- a/test/test_main_lib.cc
+++ b/test/test_main_lib.cc
@@ -102,62 +102,6 @@
 
 class TestMainImpl : public TestMain {
  public:
-  // In order to set up a fresh rtc::Thread state for each test and avoid
-  // accidentally carrying over pending tasks that might be sent from one test
-  // and executed while another test is running, we inject a TestListener
-  // that sets up a new rtc::Thread instance for the main thread, per test.
-  class TestListener : public ::testing::EmptyTestEventListener {
-   public:
-    TestListener() = default;
-
-   private:
-    bool IsDeathTest(const char* test_case_name, const char* test_name) {
-      // Workaround to avoid wrapping the main thread when we run death tests.
-      // The approach we take for detecting death tests is essentially the same
-      // as gtest does internally. Gtest does this:
-      //
-      // static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*";
-      // ::testing::internal::UnitTestOptions::MatchesFilter(
-      //     test_case_name, kDeathTestCaseFilter);
-      //
-      // Our approach is a little more straight forward.
-      if (absl::EndsWith(test_case_name, "DeathTest"))
-        return true;
-
-      return absl::EndsWith(test_name, "DeathTest");
-    }
-
-    void OnTestStart(const ::testing::TestInfo& test_info) override {
-      if (!IsDeathTest(test_info.test_suite_name(), test_info.name())) {
-        // Ensure that main thread gets wrapped as an rtc::Thread.
-        // TODO(bugs.webrtc.org/9714): It might be better to avoid wrapping the
-        // main thread, or leave it to individual tests that need it. But as
-        // long as we have automatic thread wrapping, we need this to avoid that
-        // some other random thread (which one depending on which tests are run)
-        // gets automatically wrapped.
-        thread_ = rtc::Thread::CreateWithSocketServer();
-        thread_->WrapCurrent();
-        RTC_DCHECK_EQ(rtc::Thread::Current(), thread_.get());
-      } else {
-        RTC_LOG(LS_INFO) << "No thread auto wrap for death test.";
-      }
-    }
-
-    void OnTestEnd(const ::testing::TestInfo& test_info) override {
-      // Terminate the message loop. Note that if the test failed to clean
-      // up pending messages, this may execute part of the test. Ideally we
-      // should print a warning message here, or even fail the test if it leaks.
-      if (thread_) {
-        thread_->Quit();  // Signal quit.
-        thread_->Run();   // Flush + process Quit signal.
-        thread_->UnwrapCurrent();
-        thread_ = nullptr;
-      }
-    }
-
-    std::unique_ptr<rtc::Thread> thread_;
-  };
-
   int Init(int* argc, char* argv[]) override { return Init(); }
 
   int Init() override {
@@ -191,8 +135,6 @@
     rtc::InitializeSSL();
     rtc::SSLStreamAdapter::EnableTimeCallbackForTesting();
 
-    ::testing::UnitTest::GetInstance()->listeners().Append(new TestListener());
-
     return 0;
   }
 
diff --git a/video/adaptation/BUILD.gn b/video/adaptation/BUILD.gn
index 48e19c5..2f47b03 100644
--- a/video/adaptation/BUILD.gn
+++ b/video/adaptation/BUILD.gn
@@ -110,6 +110,7 @@
       "../../rtc_base:rtc_numerics",
       "../../rtc_base:rtc_task_queue",
       "../../rtc_base:task_queue_for_test",
+      "../../rtc_base:threading",
       "../../rtc_base/task_utils:to_queued_task",
       "../../test:field_trial",
       "../../test:rtc_expect_death",
diff --git a/video/adaptation/quality_scaler_resource_unittest.cc b/video/adaptation/quality_scaler_resource_unittest.cc
index 1a3175a..70d2975 100644
--- a/video/adaptation/quality_scaler_resource_unittest.cc
+++ b/video/adaptation/quality_scaler_resource_unittest.cc
@@ -16,6 +16,7 @@
 #include "api/task_queue/task_queue_base.h"
 #include "api/video_codecs/video_encoder.h"
 #include "call/adaptation/test/mock_resource_listener.h"
+#include "rtc_base/thread.h"
 #include "test/gmock.h"
 #include "test/gtest.h"
 
@@ -52,6 +53,7 @@
   }
 
  protected:
+  rtc::AutoThread main_thread_;
   StrictMock<MockResourceListener> fake_resource_listener_;
   FakeDegradationPreferenceProvider degradation_preference_provider_;
   rtc::scoped_refptr<QualityScalerResource> quality_scaler_resource_;
diff --git a/video/rtp_video_stream_receiver_frame_transformer_delegate_unittest.cc b/video/rtp_video_stream_receiver_frame_transformer_delegate_unittest.cc
index c3b2ece..5211a1d 100644
--- a/video/rtp_video_stream_receiver_frame_transformer_delegate_unittest.cc
+++ b/video/rtp_video_stream_receiver_frame_transformer_delegate_unittest.cc
@@ -97,6 +97,7 @@
 
 TEST(RtpVideoStreamReceiverFrameTransformerDelegateTest,
      ManageFrameOnTransformedFrame) {
+  rtc::AutoThread main_thread_;
   TestRtpVideoFrameReceiver receiver;
   auto mock_frame_transformer(
       rtc::make_ref_counted<NiceMock<MockFrameTransformer>>());