Require webrtc::Environment to create fake video encoders

Bug: webrtc:15860
Change-Id: Ie1b03811f8082d5584434b46e552003bfbe5ea96
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/346620
Reviewed-by: Erik Språng <sprang@webrtc.org>
Commit-Queue: Danil Chapovalov <danilchap@webrtc.org>
Cr-Commit-Position: refs/heads/main@{#42078}
diff --git a/call/call_perf_tests.cc b/call/call_perf_tests.cc
index c6842a5..e4db74d 100644
--- a/call/call_perf_tests.cc
+++ b/call/call_perf_tests.cc
@@ -808,9 +808,9 @@
 
   class BitrateObserver : public test::EndToEndTest, public test::FakeEncoder {
    public:
-    explicit BitrateObserver(TaskQueueBase* task_queue)
+    explicit BitrateObserver(const Environment& env, TaskQueueBase* task_queue)
         : EndToEndTest(test::VideoTestConstants::kDefaultTimeout),
-          FakeEncoder(Clock::GetRealTimeClock()),
+          FakeEncoder(env),
           encoder_inits_(0),
           last_set_bitrate_kbps_(0),
           send_stream_(nullptr),
@@ -910,7 +910,7 @@
     std::unique_ptr<VideoBitrateAllocatorFactory> bitrate_allocator_factory_;
     VideoEncoderConfig encoder_config_;
     TaskQueueBase* task_queue_;
-  } test(task_queue());
+  } test(env(), task_queue());
 
   RunBaseTest(&test);
 }
diff --git a/media/engine/fake_video_codec_factory.cc b/media/engine/fake_video_codec_factory.cc
index 8caeb6d..9b544fb 100644
--- a/media/engine/fake_video_codec_factory.cc
+++ b/media/engine/fake_video_codec_factory.cc
@@ -40,7 +40,7 @@
 std::unique_ptr<VideoEncoder> FakeVideoEncoderFactory::Create(
     const Environment& env,
     const SdpVideoFormat& format) {
-  return std::make_unique<test::FakeEncoder>(&env.clock());
+  return std::make_unique<test::FakeEncoder>(env);
 }
 
 FakeVideoDecoderFactory::FakeVideoDecoderFactory() = default;
diff --git a/test/fake_encoder.cc b/test/fake_encoder.cc
index 437b127..10b25a4 100644
--- a/test/fake_encoder.cc
+++ b/test/fake_encoder.cc
@@ -50,13 +50,7 @@
 }  // namespace
 
 FakeEncoder::FakeEncoder(const Environment& env)
-    : FakeEncoder(env, &env.clock()) {}
-
-FakeEncoder::FakeEncoder(Clock* clock) : FakeEncoder(absl::nullopt, clock) {}
-
-FakeEncoder::FakeEncoder(absl::optional<Environment> env, Clock* clock)
     : env_(env),
-      clock_(clock),
       num_initializations_(0),
       callback_(nullptr),
       max_target_bitrate_kbps_(-1),
@@ -320,9 +314,6 @@
 FakeH264Encoder::FakeH264Encoder(const Environment& env)
     : FakeEncoder(env), idr_counter_(0) {}
 
-FakeH264Encoder::FakeH264Encoder(Clock* clock)
-    : FakeEncoder(clock), idr_counter_(0) {}
-
 CodecSpecificInfo FakeH264Encoder::EncodeHook(
     EncodedImage& encoded_image,
     rtc::scoped_refptr<EncodedImageBuffer> buffer) {
@@ -408,9 +399,9 @@
                                                  const Settings& settings) {
   RTC_DCHECK_RUN_ON(&sequence_checker_);
 
-  queue1_ = env_->task_queue_factory().CreateTaskQueue(
+  queue1_ = env_.task_queue_factory().CreateTaskQueue(
       "Queue 1", TaskQueueFactory::Priority::NORMAL);
-  queue2_ = env_->task_queue_factory().CreateTaskQueue(
+  queue2_ = env_.task_queue_factory().CreateTaskQueue(
       "Queue 2", TaskQueueFactory::Priority::NORMAL);
 
   return FakeH264Encoder::InitEncode(config, settings);
diff --git a/test/fake_encoder.h b/test/fake_encoder.h
index 9c1e87f..203e67c 100644
--- a/test/fake_encoder.h
+++ b/test/fake_encoder.h
@@ -38,9 +38,6 @@
 class FakeEncoder : public VideoEncoder {
  public:
   explicit FakeEncoder(const Environment& env_);
-  // TODO: bugs.webrtc.org/15860 - Delete constructor taking just `Clock` when
-  // users are migrated to pass full `Environment`
-  explicit FakeEncoder(Clock* clock);
   virtual ~FakeEncoder() = default;
 
   // Sets max bitrate. Not thread-safe, call before registering the encoder.
@@ -86,8 +83,6 @@
     std::vector<SpatialLayer> layers;
   };
 
-  FakeEncoder(absl::optional<Environment> env, Clock* clock);
-
   FrameInfo NextFrame(const std::vector<VideoFrameType>* frame_types,
                       bool keyframe,
                       uint8_t num_simulcast_streams,
@@ -105,11 +100,8 @@
   void SetRatesLocked(const RateControlParameters& parameters)
       RTC_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
 
-  // TODO: bugs.webrtc.org/15860 - Remove constructor that takes just the clock
-  // and make env_ non-optional.
-  const absl::optional<Environment> env_;
+  const Environment env_;
   FrameInfo last_frame_info_ RTC_GUARDED_BY(mutex_);
-  Clock* const clock_;
 
   VideoCodec config_ RTC_GUARDED_BY(mutex_);
   int num_initializations_ RTC_GUARDED_BY(mutex_);
@@ -131,7 +123,6 @@
 class FakeH264Encoder : public FakeEncoder {
  public:
   explicit FakeH264Encoder(const Environment& env);
-  [[deprecated]] explicit FakeH264Encoder(Clock* clock);
   virtual ~FakeH264Encoder() = default;
 
  private:
diff --git a/test/fake_vp8_encoder.cc b/test/fake_vp8_encoder.cc
index aeb36c9..50a3009 100644
--- a/test/fake_vp8_encoder.cc
+++ b/test/fake_vp8_encoder.cc
@@ -45,10 +45,6 @@
 
 namespace test {
 
-FakeVp8Encoder::FakeVp8Encoder(Clock* clock) : FakeEncoder(clock) {
-  sequence_checker_.Detach();
-}
-
 FakeVp8Encoder::FakeVp8Encoder(const Environment& env) : FakeEncoder(env) {
   sequence_checker_.Detach();
 }
diff --git a/video/end_to_end_tests/bandwidth_tests.cc b/video/end_to_end_tests/bandwidth_tests.cc
index 272e32b..7dd7556 100644
--- a/video/end_to_end_tests/bandwidth_tests.cc
+++ b/video/end_to_end_tests/bandwidth_tests.cc
@@ -317,9 +317,10 @@
   class EncoderRateStatsTest : public test::EndToEndTest,
                                public test::FakeEncoder {
    public:
-    explicit EncoderRateStatsTest(TaskQueueBase* task_queue)
+    explicit EncoderRateStatsTest(const Environment& env,
+                                  TaskQueueBase* task_queue)
         : EndToEndTest(test::VideoTestConstants::kDefaultTimeout),
-          FakeEncoder(Clock::GetRealTimeClock()),
+          FakeEncoder(env),
           task_queue_(task_queue),
           send_stream_(nullptr),
           encoder_factory_(this),
@@ -398,7 +399,7 @@
     test::VideoEncoderProxyFactory encoder_factory_;
     std::unique_ptr<VideoBitrateAllocatorFactory> bitrate_allocator_factory_;
     uint32_t bitrate_kbps_ RTC_GUARDED_BY(mutex_);
-  } test(task_queue());
+  } test(env(), task_queue());
 
   RunBaseTest(&test);
 }
diff --git a/video/end_to_end_tests/network_state_tests.cc b/video/end_to_end_tests/network_state_tests.cc
index 7e9c863..a80c5e2 100644
--- a/video/end_to_end_tests/network_state_tests.cc
+++ b/video/end_to_end_tests/network_state_tests.cc
@@ -155,11 +155,11 @@
   static const int kNumAcceptedDowntimeRtcp = 1;
   class NetworkStateTest : public test::EndToEndTest, public test::FakeEncoder {
    public:
-    explicit NetworkStateTest(TaskQueueBase* task_queue)
+    explicit NetworkStateTest(const Environment& env, TaskQueueBase* task_queue)
         : EndToEndTest(test::VideoTestConstants::kDefaultTimeout),
-          FakeEncoder(Clock::GetRealTimeClock()),
+          FakeEncoder(env),
           e2e_test_task_queue_(task_queue),
-          task_queue_(CreateDefaultTaskQueueFactory()->CreateTaskQueue(
+          task_queue_(env.task_queue_factory().CreateTaskQueue(
               "NetworkStateTest",
               TaskQueueFactory::Priority::NORMAL)),
           sender_call_(nullptr),
@@ -299,7 +299,7 @@
 
    private:
     void WaitForPacketsOrSilence(bool sender_down, bool receiver_down) {
-      int64_t initial_time_ms = clock_->TimeInMilliseconds();
+      int64_t initial_time_ms = env_.clock().TimeInMilliseconds();
       int initial_sender_rtp;
       int initial_sender_rtcp;
       int initial_receiver_rtcp;
@@ -313,7 +313,7 @@
       bool receiver_done = false;
       while (!sender_done || !receiver_done) {
         packet_event_.Wait(TimeDelta::Millis(kSilenceTimeoutMs));
-        int64_t time_now_ms = clock_->TimeInMilliseconds();
+        int64_t time_now_ms = env_.clock().TimeInMilliseconds();
         MutexLock lock(&test_mutex_);
         if (sender_down) {
           ASSERT_LE(sender_rtp_ - initial_sender_rtp - sender_padding_,
@@ -359,7 +359,7 @@
     int sender_rtcp_ RTC_GUARDED_BY(test_mutex_);
     int receiver_rtcp_ RTC_GUARDED_BY(test_mutex_);
     int down_frames_ RTC_GUARDED_BY(test_mutex_);
-  } test(task_queue());
+  } test(env(), task_queue());
 
   RunBaseTest(&test);
 }
@@ -367,7 +367,7 @@
 TEST_F(NetworkStateEndToEndTest, NewVideoSendStreamsRespectVideoNetworkDown) {
   class UnusedEncoder : public test::FakeEncoder {
    public:
-    UnusedEncoder() : FakeEncoder(Clock::GetRealTimeClock()) {}
+    explicit UnusedEncoder(const Environment& env) : FakeEncoder(env) {}
 
     int32_t InitEncode(const VideoCodec* config,
                        const Settings& settings) override {
@@ -381,7 +381,7 @@
     }
   };
 
-  UnusedEncoder unused_encoder;
+  UnusedEncoder unused_encoder(env());
   UnusedTransport unused_transport;
   VerifyNewVideoSendStreamsRespectNetworkState(
       MediaType::AUDIO, &unused_encoder, &unused_transport);
@@ -390,8 +390,8 @@
 TEST_F(NetworkStateEndToEndTest, NewVideoSendStreamsIgnoreAudioNetworkDown) {
   class RequiredEncoder : public test::FakeEncoder {
    public:
-    RequiredEncoder()
-        : FakeEncoder(Clock::GetRealTimeClock()), encoded_frame_(false) {}
+    explicit RequiredEncoder(const Environment& env)
+        : FakeEncoder(env), encoded_frame_(false) {}
     ~RequiredEncoder() {
       if (!encoded_frame_) {
         ADD_FAILURE() << "Didn't encode an expected frame";
@@ -408,7 +408,7 @@
   };
 
   RequiredTransport required_transport(true /*rtp*/, false /*rtcp*/);
-  RequiredEncoder required_encoder;
+  RequiredEncoder required_encoder(env());
   VerifyNewVideoSendStreamsRespectNetworkState(
       MediaType::VIDEO, &required_encoder, &required_transport);
 }
diff --git a/video/end_to_end_tests/resolution_bitrate_limits_tests.cc b/video/end_to_end_tests/resolution_bitrate_limits_tests.cc
index e110fb7..73df8dc 100644
--- a/video/end_to_end_tests/resolution_bitrate_limits_tests.cc
+++ b/video/end_to_end_tests/resolution_bitrate_limits_tests.cc
@@ -117,11 +117,12 @@
     const Bitrate ne_bitrate;
   };
 
-  InitEncodeTest(const std::string& payload_name,
+  InitEncodeTest(const Environment& env,
+                 const std::string& payload_name,
                  const std::vector<TestConfig>& configs,
                  const std::vector<Expectation>& expectations)
       : EndToEndTest(test::VideoTestConstants::kDefaultTimeout),
-        FakeEncoder(Clock::GetRealTimeClock()),
+        FakeEncoder(env),
         encoder_factory_(this),
         payload_name_(payload_name),
         configs_(configs),
@@ -222,7 +223,7 @@
       "min_bitrate_bps:32000,"
       "max_bitrate_bps:3333000/");
 
-  InitEncodeTest test(payload_name_, {{.active = true}},
+  InitEncodeTest test(env(), payload_name_, {{.active = true}},
                       // Expectations:
                       {{.pixels = 1280 * 720,
                         .eq_bitrate = {DataRate::KilobitsPerSec(32),
@@ -232,7 +233,7 @@
 
 TEST_F(ResolutionBitrateLimitsWithScalabilityModeTest,
        OneStreamDefaultMaxBitrateAppliedForOneSpatialLayer) {
-  InitEncodeTest test("VP9",
+  InitEncodeTest test(env(), "VP9",
                       {{.active = true,
                         .bitrate = {DataRate::KilobitsPerSec(30),
                                     DataRate::KilobitsPerSec(3000)},
@@ -247,7 +248,7 @@
 TEST_F(ResolutionBitrateLimitsWithScalabilityModeTest,
        OneStreamSvcMaxBitrateAppliedForTwoSpatialLayers) {
   InitEncodeTest test(
-      "VP9",
+      env(), "VP9",
       {{.active = true,
         .bitrate = {DataRate::KilobitsPerSec(30),
                     DataRate::KilobitsPerSec(3000)},
@@ -267,7 +268,8 @@
       "max_bitrate_bps:3333000/");
 
   InitEncodeTest test(
-      "VP9", {{.active = true, .scalability_mode = ScalabilityMode::kL1T1}},
+      env(), "VP9",
+      {{.active = true, .scalability_mode = ScalabilityMode::kL1T1}},
       // Expectations:
       {{.pixels = 1280 * 720,
         .eq_bitrate = {DataRate::KilobitsPerSec(32),
@@ -285,7 +287,8 @@
       "max_bitrate_bps:2222000|3333000/");
 
   InitEncodeTest test(
-      "VP9", {{.active = true, .scalability_mode = ScalabilityMode::kL2T1}},
+      env(), "VP9",
+      {{.active = true, .scalability_mode = ScalabilityMode::kL2T1}},
       // Expectations:
       {{.pixels = 640 * 360,
         .ne_bitrate = {DataRate::KilobitsPerSec(31),
@@ -297,7 +300,7 @@
 }
 
 TEST_P(ResolutionBitrateLimitsTest, EncodingsApplied) {
-  InitEncodeTest test(payload_name_,
+  InitEncodeTest test(env(), payload_name_,
                       {{.active = true,
                         .bitrate = {DataRate::KilobitsPerSec(22),
                                     DataRate::KilobitsPerSec(3555)}}},
@@ -316,7 +319,7 @@
       "min_bitrate_bps:32000,"
       "max_bitrate_bps:3333000/");
 
-  InitEncodeTest test(payload_name_,
+  InitEncodeTest test(env(), payload_name_,
                       {{.active = true,
                         .bitrate = {DataRate::KilobitsPerSec(22),
                                     DataRate::KilobitsPerSec(1555)}}},
@@ -335,7 +338,7 @@
       "min_bitrate_bps:21000|32000,"
       "max_bitrate_bps:2222000|3333000/");
 
-  InitEncodeTest test(payload_name_,
+  InitEncodeTest test(env(), payload_name_,
                       {{.active = false}, {.active = true}, {.active = false}},
                       // Expectations:
                       {{.pixels = 640 * 360,
@@ -352,7 +355,7 @@
       "min_bitrate_bps:31000|32000,"
       "max_bitrate_bps:2222000|3333000/");
 
-  InitEncodeTest test(payload_name_,
+  InitEncodeTest test(env(), payload_name_,
                       {{.active = false},
                        {.active = true,
                         .bitrate = {DataRate::KilobitsPerSec(30),
@@ -372,7 +375,8 @@
               PayloadStringToCodecType(payload_name_), 640 * 360);
 
   InitEncodeTest test(
-      payload_name_, {{.active = false}, {.active = true}, {.active = false}},
+      env(), payload_name_,
+      {{.active = false}, {.active = true}, {.active = false}},
       // Expectations:
       {{.pixels = 640 * 360,
         .eq_bitrate = {
@@ -390,7 +394,7 @@
               PayloadStringToCodecType("VP9"), 1280 * 720);
 
   InitEncodeTest test(
-      "VP9",
+      env(), "VP9",
       {{.active = true, .scalability_mode = ScalabilityMode::kL1T3},
        {.active = false}},
       // Expectations:
@@ -410,7 +414,7 @@
       "min_bitrate_bps:31000|32000,"
       "max_bitrate_bps:2222000|3333000/");
 
-  InitEncodeTest test(payload_name_,
+  InitEncodeTest test(env(), payload_name_,
                       {{.active = false}, {.active = false}, {.active = true}},
                       // Expectations:
                       {{.pixels = 1280 * 720,
@@ -427,7 +431,7 @@
       "min_bitrate_bps:31000|32000,"
       "max_bitrate_bps:2222000|3333000/");
 
-  InitEncodeTest test(payload_name_,
+  InitEncodeTest test(env(), payload_name_,
                       {{.active = false},
                        {.active = false},
                        {.active = true,
@@ -448,7 +452,8 @@
       "min_bitrate_bps:31000|32000,"
       "max_bitrate_bps:2222000|3333000/");
 
-  InitEncodeTest test(payload_name_, {{.active = true}, {.active = false}},
+  InitEncodeTest test(env(), payload_name_,
+                      {{.active = true}, {.active = false}},
                       // Expectations:
                       {{.pixels = 640 * 360,
                         .ne_bitrate = {DataRate::KilobitsPerSec(31),
@@ -469,7 +474,7 @@
       "max_bitrate_bps:2222000|3333000/");
 
   InitEncodeTest test(
-      "VP9",
+      env(), "VP9",
       {{.active = true, .scalability_mode = ScalabilityMode::kL1T1},
        {.active = false}},
       // Expectations:
@@ -489,7 +494,7 @@
       "max_bitrate_bps:2222000|3333000/");
 
   InitEncodeTest test(
-      "VP9",
+      env(), "VP9",
       {{.active = true, .scalability_mode = ScalabilityMode::kL2T1},
        {.active = false}},
       // Expectations:
@@ -512,7 +517,8 @@
       "max_bitrate_bps:133000/");
 
   InitEncodeTest test(
-      "AV1", {{.active = true, .scalability_mode = ScalabilityMode::kL1T1}},
+      env(), "AV1",
+      {{.active = true, .scalability_mode = ScalabilityMode::kL1T1}},
       // Expectations:
       {{.pixels = 1280 * 720,
         .eq_bitrate = {DataRate::KilobitsPerSec(32),
@@ -530,7 +536,7 @@
       "max_bitrate_bps:400000|1200000/");
 
   InitEncodeTest test(
-      "AV1",
+      env(), "AV1",
       {{.active = true, .scalability_mode = ScalabilityMode::kL1T1},
        {.active = false}},
       // Expectations:
@@ -550,7 +556,7 @@
       "max_bitrate_bps:900000|1333000/");
 
   InitEncodeTest test(
-      "AV1",
+      env(), "AV1",
       {{.active = true, .scalability_mode = ScalabilityMode::kL2T1},
        {.active = false}},
       // Expectations:
@@ -571,7 +577,8 @@
       "min_bitrate_bps:31000|32000,"
       "max_bitrate_bps:2222000|3333000/");
 
-  InitEncodeTest test(payload_name_, {{.active = true}, {.active = true}},
+  InitEncodeTest test(env(), payload_name_,
+                      {{.active = true}, {.active = true}},
                       // Expectations:
                       {{.pixels = 640 * 360,
                         .ne_bitrate = {DataRate::KilobitsPerSec(31),
diff --git a/video/video_send_stream_tests.cc b/video/video_send_stream_tests.cc
index e56161d..29230cb 100644
--- a/video/video_send_stream_tests.cc
+++ b/video/video_send_stream_tests.cc
@@ -2039,8 +2039,8 @@
        EncoderReconfigureOnResolutionChangeWhenNotSending) {
   class EncoderObserver : public test::FakeEncoder {
    public:
-    EncoderObserver()
-        : FakeEncoder(Clock::GetRealTimeClock()),
+    explicit EncoderObserver(const Environment& env)
+        : FakeEncoder(env),
           last_initialized_frame_width_(0),
           last_initialized_frame_height_(0) {}
 
@@ -2085,7 +2085,7 @@
   };
 
   test::NullTransport transport;
-  EncoderObserver encoder;
+  EncoderObserver encoder(env());
   test::VideoEncoderProxyFactory encoder_factory(&encoder);
 
   SendTask(task_queue(), [this, &transport, &encoder_factory]() {
@@ -2120,8 +2120,8 @@
 TEST_F(VideoSendStreamTest, CanReconfigureToUseStartBitrateAbovePreviousMax) {
   class StartBitrateObserver : public test::FakeEncoder {
    public:
-    StartBitrateObserver()
-        : FakeEncoder(Clock::GetRealTimeClock()), start_bitrate_kbps_(0) {}
+    explicit StartBitrateObserver(const Environment& env)
+        : FakeEncoder(env), start_bitrate_kbps_(0) {}
     int32_t InitEncode(const VideoCodec* config,
                        const Settings& settings) override {
       MutexLock lock(&mutex_);
@@ -2164,7 +2164,7 @@
   sender_call_->GetTransportControllerSend()->SetSdpBitrateParameters(
       bitrate_config);
 
-  StartBitrateObserver encoder;
+  StartBitrateObserver encoder(env());
   test::VideoEncoderProxyFactory encoder_factory(&encoder);
   GetVideoSendConfig()->encoder_settings.encoder_factory = &encoder_factory;
 
@@ -2205,52 +2205,6 @@
   DestroyStreams();
 }
 
-class StartStopBitrateObserver : public test::FakeEncoder {
- public:
-  StartStopBitrateObserver() : FakeEncoder(Clock::GetRealTimeClock()) {}
-  int32_t InitEncode(const VideoCodec* config,
-                     const Settings& settings) override {
-    MutexLock lock(&mutex_);
-    encoder_init_.Set();
-    return FakeEncoder::InitEncode(config, settings);
-  }
-
-  void SetRates(const RateControlParameters& parameters) override {
-    MutexLock lock(&mutex_);
-    bitrate_kbps_ = parameters.bitrate.get_sum_kbps();
-    bitrate_changed_.Set();
-    FakeEncoder::SetRates(parameters);
-  }
-
-  bool WaitForEncoderInit() {
-    return encoder_init_.Wait(test::VideoTestConstants::kDefaultTimeout);
-  }
-
-  bool WaitBitrateChanged(WaitUntil until) {
-    do {
-      absl::optional<int> bitrate_kbps;
-      {
-        MutexLock lock(&mutex_);
-        bitrate_kbps = bitrate_kbps_;
-      }
-      if (!bitrate_kbps)
-        continue;
-
-      if ((until == WaitUntil::kNonZero && *bitrate_kbps > 0) ||
-          (until == WaitUntil::kZero && *bitrate_kbps == 0)) {
-        return true;
-      }
-    } while (bitrate_changed_.Wait(test::VideoTestConstants::kDefaultTimeout));
-    return false;
-  }
-
- private:
-  Mutex mutex_;
-  rtc::Event encoder_init_;
-  rtc::Event bitrate_changed_;
-  absl::optional<int> bitrate_kbps_ RTC_GUARDED_BY(mutex_);
-};
-
 TEST_F(VideoSendStreamTest, EncoderIsProperlyInitializedAndDestroyed) {
   class EncoderStateObserver : public test::SendTest, public VideoEncoder {
    public:
@@ -2386,10 +2340,11 @@
 class VideoCodecConfigObserver : public test::SendTest,
                                  public test::FakeEncoder {
  public:
-  VideoCodecConfigObserver(VideoCodecType video_codec_type,
+  VideoCodecConfigObserver(const Environment& env,
+                           VideoCodecType video_codec_type,
                            TaskQueueBase* task_queue)
       : SendTest(test::VideoTestConstants::kDefaultTimeout),
-        FakeEncoder(Clock::GetRealTimeClock()),
+        FakeEncoder(env),
         video_codec_type_(video_codec_type),
         stream_(nullptr),
         encoder_factory_(this),
@@ -2566,12 +2521,14 @@
 }
 
 TEST_F(VideoSendStreamTest, EncoderSetupPropagatesVp8Config) {
-  VideoCodecConfigObserver<VideoCodecVP8> test(kVideoCodecVP8, task_queue());
+  VideoCodecConfigObserver<VideoCodecVP8> test(env(), kVideoCodecVP8,
+                                               task_queue());
   RunBaseTest(&test);
 }
 
 TEST_F(VideoSendStreamTest, EncoderSetupPropagatesVp9Config) {
-  VideoCodecConfigObserver<VideoCodecVP9> test(kVideoCodecVP9, task_queue());
+  VideoCodecConfigObserver<VideoCodecVP9> test(env(), kVideoCodecVP9,
+                                               task_queue());
   RunBaseTest(&test);
 }
 
@@ -2583,7 +2540,8 @@
 #define MAYBE_EncoderSetupPropagatesH264Config EncoderSetupPropagatesH264Config
 #endif
 TEST_F(VideoSendStreamTest, MAYBE_EncoderSetupPropagatesH264Config) {
-  VideoCodecConfigObserver<VideoCodecH264> test(kVideoCodecH264, task_queue());
+  VideoCodecConfigObserver<VideoCodecH264> test(env(), kVideoCodecH264,
+                                                task_queue());
   RunBaseTest(&test);
 }
 
@@ -2665,9 +2623,9 @@
   class ScreencastTargetBitrateTest : public test::SendTest,
                                       public test::FakeEncoder {
    public:
-    ScreencastTargetBitrateTest()
+    explicit ScreencastTargetBitrateTest(const Environment& env)
         : SendTest(test::VideoTestConstants::kDefaultTimeout),
-          test::FakeEncoder(Clock::GetRealTimeClock()),
+          test::FakeEncoder(env),
           encoder_factory_(this) {}
 
    private:
@@ -2699,7 +2657,7 @@
           << "Timed out while waiting for the encoder to be initialized.";
     }
     test::VideoEncoderProxyFactory encoder_factory_;
-  } test;
+  } test(env());
 
   RunBaseTest(&test);
 }
@@ -2723,9 +2681,10 @@
                                           public VideoBitrateAllocatorFactory,
                                           public test::FakeEncoder {
    public:
-    explicit EncoderBitrateThresholdObserver(TaskQueueBase* task_queue)
+    explicit EncoderBitrateThresholdObserver(const Environment& env,
+                                             TaskQueueBase* task_queue)
         : SendTest(test::VideoTestConstants::kDefaultTimeout),
-          FakeEncoder(Clock::GetRealTimeClock()),
+          FakeEncoder(env),
           task_queue_(task_queue),
           target_bitrate_(0),
           num_rate_allocator_creations_(0),
@@ -2909,7 +2868,7 @@
     test::VideoEncoderProxyFactory encoder_factory_;
     std::unique_ptr<VideoBitrateAllocatorFactory> bitrate_allocator_factory_;
     webrtc::VideoEncoderConfig encoder_config_;
-  } test(task_queue());
+  } test(env(), task_queue());
 
   RunBaseTest(&test);
 }
@@ -2924,9 +2883,10 @@
   class ScreencastTargetBitrateTest : public test::SendTest,
                                       public test::FakeEncoder {
    public:
-    explicit ScreencastTargetBitrateTest(TaskQueueBase* task_queue)
+    explicit ScreencastTargetBitrateTest(const Environment& env,
+                                         TaskQueueBase* task_queue)
         : SendTest(test::VideoTestConstants::kDefaultTimeout),
-          test::FakeEncoder(Clock::GetRealTimeClock()),
+          test::FakeEncoder(env),
           send_stream_(nullptr),
           encoder_factory_(this),
           task_queue_(task_queue) {}
@@ -3003,7 +2963,7 @@
     VideoSendStream* send_stream_;
     test::VideoEncoderProxyFactory encoder_factory_;
     TaskQueueBase* const task_queue_;
-  } test(task_queue());
+  } test(env(), task_queue());
 
   RunBaseTest(&test);
 }
@@ -3735,9 +3695,10 @@
   class RemoveOverheadFromBandwidthTest : public test::EndToEndTest,
                                           public test::FakeEncoder {
    public:
-    explicit RemoveOverheadFromBandwidthTest(TaskQueueBase* task_queue)
+    explicit RemoveOverheadFromBandwidthTest(const Environment& env,
+                                             TaskQueueBase* task_queue)
         : EndToEndTest(test::VideoTestConstants::kDefaultTimeout),
-          FakeEncoder(Clock::GetRealTimeClock()),
+          FakeEncoder(env),
           task_queue_(task_queue),
           encoder_factory_(this),
           call_(nullptr),
@@ -3807,7 +3768,7 @@
     uint32_t max_bitrate_bps_ RTC_GUARDED_BY(&mutex_);
     bool first_packet_sent_ RTC_GUARDED_BY(&mutex_);
     rtc::Event bitrate_changed_event_;
-  } test(task_queue());
+  } test(env(), task_queue());
   RunBaseTest(&test);
 }
 
diff --git a/video/video_stream_encoder_unittest.cc b/video/video_stream_encoder_unittest.cc
index 31c6ca5..dda377e 100644
--- a/video/video_stream_encoder_unittest.cc
+++ b/video/video_stream_encoder_unittest.cc
@@ -767,8 +767,10 @@
 
   test::ScopedKeyValueConfig field_trials_;
   GlobalSimulatedTimeController time_controller_{Timestamp::Zero()};
-  std::unique_ptr<TaskQueueFactory> task_queue_factory_{
-      time_controller_.CreateTaskQueueFactory()};
+  Environment env_ =
+      CreateEnvironment(&field_trials_,
+                        time_controller_.GetClock(),
+                        time_controller_.CreateTaskQueueFactory());
   std::unique_ptr<MockableSendStatisticsProxy> stats_proxy_ =
       std::make_unique<MockableSendStatisticsProxy>(
           time_controller_.GetClock(),
@@ -779,7 +781,7 @@
       CreateBuiltinVideoBitrateAllocatorFactory();
   VideoStreamEncoderSettings encoder_settings_{
       VideoEncoder::Capabilities(/*loss_notification=*/false)};
-  MockFakeEncoder mock_fake_encoder_{time_controller_.GetClock()};
+  MockFakeEncoder mock_fake_encoder_{env_};
   test::VideoEncoderProxyFactory encoder_factory_{&mock_fake_encoder_};
   NullEncoderSink sink_;
 };
@@ -851,7 +853,7 @@
         codec_width_(320),
         codec_height_(240),
         max_framerate_(kDefaultFramerate),
-        fake_encoder_(&time_controller_),
+        fake_encoder_(env_),
         encoder_factory_(&fake_encoder_),
         stats_proxy_(new MockableSendStatisticsProxy(
             time_controller_.GetClock(),
@@ -1063,11 +1065,7 @@
 
   class TestEncoder : public test::FakeEncoder {
    public:
-    explicit TestEncoder(TimeController* time_controller)
-        : FakeEncoder(time_controller->GetClock()),
-          time_controller_(time_controller) {
-      RTC_DCHECK(time_controller_);
-    }
+    explicit TestEncoder(const Environment& env) : FakeEncoder(env) {}
 
     VideoEncoder::EncoderInfo GetEncoderInfo() const override {
       MutexLock lock(&local_mutex_);
@@ -1343,7 +1341,6 @@
       FakeEncoder::SetRates(adjusted_paramters);
     }
 
-    TimeController* const time_controller_;
     mutable Mutex local_mutex_;
     enum class EncoderState {
       kUninitialized,
@@ -9410,8 +9407,7 @@
       &env.clock(), VideoSendStream::Config(nullptr),
       webrtc::VideoEncoderConfig::ContentType::kRealtimeVideo,
       env.field_trials());
-  SimpleVideoStreamEncoderFactory::MockFakeEncoder mock_fake_encoder(
-      time_controller.GetClock());
+  SimpleVideoStreamEncoderFactory::MockFakeEncoder mock_fake_encoder(env);
   test::VideoEncoderProxyFactory encoder_factory(&mock_fake_encoder);
   std::unique_ptr<VideoBitrateAllocatorFactory> bitrate_allocator_factory =
       CreateBuiltinVideoBitrateAllocatorFactory();