Use Environment instead of Clock in ModuleRtpRtcp2 and its RTP subcomponents

Bug: webrtc:362762208
Change-Id: Ie9bbb7f3b505acd8aab1b8552ba64e09a5a1bddf
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/361481
Commit-Queue: Danil Chapovalov <danilchap@webrtc.org>
Reviewed-by: Åsa Persson <asapersson@webrtc.org>
Cr-Commit-Position: refs/heads/main@{#42949}
diff --git a/call/rtp_transport_controller_send.cc b/call/rtp_transport_controller_send.cc
index 9ff82f4..c0150f8 100644
--- a/call/rtp_transport_controller_send.cc
+++ b/call/rtp_transport_controller_send.cc
@@ -23,6 +23,7 @@
 #include "api/call/transport.h"
 #include "api/fec_controller.h"
 #include "api/frame_transformer_interface.h"
+#include "api/rtc_event_log/rtc_event_log.h"
 #include "api/rtp_packet_sender.h"
 #include "api/scoped_refptr.h"
 #include "api/sequence_checker.h"
diff --git a/modules/rtp_rtcp/source/rtp_rtcp_impl2.cc b/modules/rtp_rtcp/source/rtp_rtcp_impl2.cc
index 985f102..43ae7d5 100644
--- a/modules/rtp_rtcp/source/rtp_rtcp_impl2.cc
+++ b/modules/rtp_rtcp/source/rtp_rtcp_impl2.cc
@@ -19,7 +19,6 @@
 #include <utility>
 #include <vector>
 
-#include "absl/memory/memory.h"
 #include "absl/strings/string_view.h"
 #include "api/array_view.h"
 #include "api/environment/environment.h"
@@ -71,17 +70,19 @@
 }  // namespace
 
 ModuleRtpRtcpImpl2::RtpSenderContext::RtpSenderContext(
+    const Environment& env,
     TaskQueueBase& worker_queue,
     const RtpRtcpInterface::Configuration& config)
-    : packet_history(config.clock,
+    : packet_history(&env.clock(),
                      RtpPacketHistory::PaddingMode::kRecentLargePacket),
       sequencer(config.local_media_ssrc,
                 config.rtx_send_ssrc,
                 /*require_marker_before_media_padding=*/!config.audio,
-                config.clock),
-      packet_sender(config, &packet_history),
+                &env.clock()),
+      packet_sender(env, config, &packet_history),
       non_paced_sender(worker_queue, &packet_sender, &sequencer),
       packet_generator(
+          env,
           config,
           &packet_history,
           config.paced_sender ? config.paced_sender : &non_paced_sender) {}
@@ -91,7 +92,7 @@
 // Merge two constructors into single one after that.
 ModuleRtpRtcpImpl2::ModuleRtpRtcpImpl2(const Environment& env,
                                        const Configuration& configuration)
-    : ModuleRtpRtcpImpl2([&] {
+    : ModuleRtpRtcpImpl2({}, env, [&] {
         // Check users of this constructor switch to not duplicate
         // utilities passed with environment.
         RTC_DCHECK(configuration.field_trials == nullptr);
@@ -105,15 +106,17 @@
         return config;
       }()) {}
 
-ModuleRtpRtcpImpl2::ModuleRtpRtcpImpl2(const Configuration& configuration)
-    : worker_queue_(TaskQueueBase::Current()),
+ModuleRtpRtcpImpl2::ModuleRtpRtcpImpl2(TagConfigurationIncludesEnvironment,
+                                       const Environment& env,
+                                       const Configuration& configuration)
+    : env_(env),
+      worker_queue_(TaskQueueBase::Current()),
       rtcp_sender_(AddRtcpSendEvaluationCallback(
           RTCPSender::Configuration::FromRtpRtcpConfiguration(configuration),
           [this](TimeDelta duration) {
             ScheduleRtcpSendEvaluation(duration);
           })),
       rtcp_receiver_(configuration, this),
-      clock_(configuration.clock),
       packet_overhead_(28),  // IPV4 UDP.
       nack_last_time_sent_full_ms_(0),
       nack_last_seq_number_sent_(0),
@@ -123,7 +126,7 @@
   rtcp_thread_checker_.Detach();
   if (!configuration.receiver_only) {
     rtp_sender_ =
-        std::make_unique<RtpSenderContext>(*worker_queue_, configuration);
+        std::make_unique<RtpSenderContext>(env_, *worker_queue_, configuration);
     rtp_sender_->sequencing_checker.Detach();
     // Make sure rtcp sender use same timestamp offset as rtp sender.
     rtcp_sender_.SetTimestampOffset(
@@ -149,15 +152,6 @@
   rtt_update_task_.Stop();
 }
 
-// static
-std::unique_ptr<ModuleRtpRtcpImpl2> ModuleRtpRtcpImpl2::Create(
-    const Configuration& configuration) {
-  RTC_DCHECK(configuration.clock);
-  RTC_DCHECK(TaskQueueBase::Current());
-  // Use WrapUnique to access private constructor.
-  return absl::WrapUnique(new ModuleRtpRtcpImpl2(configuration));
-}
-
 void ModuleRtpRtcpImpl2::SetRtxSendStatus(int mode) {
   rtp_sender_->packet_generator.SetRtxStatus(mode);
 }
@@ -289,7 +283,8 @@
     state.media_bytes_sent = rtp_stats.transmitted.payload_bytes +
                              rtx_stats.transmitted.payload_bytes;
     state.send_bitrate =
-        rtp_sender_->packet_sender.GetSendRates(clock_->CurrentTime()).Sum();
+        rtp_sender_->packet_sender.GetSendRates(env_.clock().CurrentTime())
+            .Sum();
   }
   state.receiver = &rtcp_receiver_;
 
@@ -606,7 +601,7 @@
                                      const uint16_t size) {
   uint16_t nack_length = size;
   uint16_t start_id = 0;
-  int64_t now_ms = clock_->TimeInMilliseconds();
+  int64_t now_ms = env_.clock().TimeInMilliseconds();
   if (TimeToSendFullNackList(now_ms)) {
     nack_last_time_sent_full_ms_ = now_ms;
   } else {
@@ -703,7 +698,7 @@
 
 RtpSendRates ModuleRtpRtcpImpl2::GetSendRates() const {
   RTC_DCHECK_RUN_ON(&rtp_sender_->sequencing_checker);
-  return rtp_sender_->packet_sender.GetSendRates(clock_->CurrentTime());
+  return rtp_sender_->packet_sender.GetSendRates(env_.clock().CurrentTime());
 }
 
 void ModuleRtpRtcpImpl2::OnRequestSendReport() {
@@ -781,7 +776,7 @@
 void ModuleRtpRtcpImpl2::PeriodicUpdate() {
   RTC_DCHECK_RUN_ON(worker_queue_);
 
-  Timestamp check_since = clock_->CurrentTime() - kRttUpdateInterval;
+  Timestamp check_since = env_.clock().CurrentTime() - kRttUpdateInterval;
   std::optional<TimeDelta> rtt =
       rtcp_receiver_.OnPeriodicRttUpdate(check_since, rtcp_sender_.Sending());
   if (rtt) {
@@ -803,7 +798,7 @@
 void ModuleRtpRtcpImpl2::MaybeSendRtcpAtOrAfterTimestamp(
     Timestamp execution_time) {
   RTC_DCHECK_RUN_ON(worker_queue_);
-  Timestamp now = clock_->CurrentTime();
+  Timestamp now = env_.clock().CurrentTime();
   if (now >= execution_time) {
     MaybeSendRtcp();
     return;
@@ -831,7 +826,7 @@
       MaybeSendRtcp();
     }));
   } else {
-    Timestamp execution_time = clock_->CurrentTime() + duration;
+    Timestamp execution_time = env_.clock().CurrentTime() + duration;
     ScheduleMaybeSendRtcpAtOrAfterTimestamp(execution_time, duration);
   }
 }
diff --git a/modules/rtp_rtcp/source/rtp_rtcp_impl2.h b/modules/rtp_rtcp/source/rtp_rtcp_impl2.h
index 87896c7..4951790 100644
--- a/modules/rtp_rtcp/source/rtp_rtcp_impl2.h
+++ b/modules/rtp_rtcp/source/rtp_rtcp_impl2.h
@@ -61,13 +61,6 @@
                      const RtpRtcpInterface::Configuration& configuration);
   ~ModuleRtpRtcpImpl2() override;
 
-  // This method is provided to easy with migrating away from the
-  // RtpRtcp::Create factory method. Since this is an internal implementation
-  // detail though, creating an instance of ModuleRtpRtcpImpl2 directly should
-  // be fine.
-  static std::unique_ptr<ModuleRtpRtcpImpl2> Create(
-      const Configuration& configuration);
-
   // Receiver part.
 
   // Called when we receive an RTCP packet.
@@ -264,7 +257,8 @@
   FRIEND_TEST_ALL_PREFIXES(RtpRtcpImpl2Test, RttForReceiverOnly);
 
   struct RtpSenderContext {
-    explicit RtpSenderContext(TaskQueueBase& worker_queue,
+    explicit RtpSenderContext(const Environment& env,
+                              TaskQueueBase& worker_queue,
                               const RtpRtcpInterface::Configuration& config);
     // Storage of packets, for retransmissions and padding, if applicable.
     RtpPacketHistory packet_history;
@@ -280,7 +274,10 @@
     RTPSender packet_generator;
   };
 
-  explicit ModuleRtpRtcpImpl2(const Configuration& configuration);
+  struct TagConfigurationIncludesEnvironment {};
+  explicit ModuleRtpRtcpImpl2(TagConfigurationIncludesEnvironment,
+                              const Environment& env,
+                              const Configuration& configuration);
 
   void set_rtt_ms(int64_t rtt_ms);
   int64_t rtt_ms() const;
@@ -311,6 +308,7 @@
   void ScheduleMaybeSendRtcpAtOrAfterTimestamp(Timestamp execution_time,
                                                TimeDelta duration);
 
+  const Environment env_;
   TaskQueueBase* const worker_queue_;
   RTC_NO_UNIQUE_ADDRESS SequenceChecker rtcp_thread_checker_;
 
@@ -318,8 +316,6 @@
   RTCPSender rtcp_sender_;
   RTCPReceiver rtcp_receiver_;
 
-  Clock* const clock_;
-
   uint16_t packet_overhead_;
 
   // Send side
diff --git a/modules/rtp_rtcp/source/rtp_sender.cc b/modules/rtp_rtcp/source/rtp_sender.cc
index bfdaca0..9d1f423 100644
--- a/modules/rtp_rtcp/source/rtp_sender.cc
+++ b/modules/rtp_rtcp/source/rtp_sender.cc
@@ -22,6 +22,7 @@
 
 #include "absl/strings/string_view.h"
 #include "api/array_view.h"
+#include "api/environment/environment.h"
 #include "api/rtp_headers.h"
 #include "api/rtp_packet_sender.h"
 #include "api/units/time_delta.h"
@@ -152,10 +153,22 @@
 
 }  // namespace
 
+RTPSender::RTPSender(const Environment& env,
+                     const RtpRtcpInterface::Configuration& config,
+                     RtpPacketHistory* packet_history,
+                     RtpPacketSender* packet_sender)
+    : RTPSender(&env.clock(), config, packet_history, packet_sender) {}
+
 RTPSender::RTPSender(const RtpRtcpInterface::Configuration& config,
                      RtpPacketHistory* packet_history,
                      RtpPacketSender* packet_sender)
-    : clock_(config.clock),
+    : RTPSender(config.clock, config, packet_history, packet_sender) {}
+
+RTPSender::RTPSender(Clock* clock,
+                     const RtpRtcpInterface::Configuration& config,
+                     RtpPacketHistory* packet_history,
+                     RtpPacketSender* packet_sender)
+    : clock_(clock),
       random_(clock_->TimeInMicroseconds()),
       audio_configured_(config.audio),
       ssrc_(config.local_media_ssrc),
diff --git a/modules/rtp_rtcp/source/rtp_sender.h b/modules/rtp_rtcp/source/rtp_sender.h
index 9ecf781..903900e 100644
--- a/modules/rtp_rtcp/source/rtp_sender.h
+++ b/modules/rtp_rtcp/source/rtp_sender.h
@@ -21,6 +21,7 @@
 
 #include "absl/strings/string_view.h"
 #include "api/array_view.h"
+#include "api/environment/environment.h"
 #include "api/rtp_packet_sender.h"
 #include "modules/rtp_rtcp/include/flexfec_sender.h"
 #include "modules/rtp_rtcp/include/rtp_header_extension_map.h"
@@ -36,7 +37,6 @@
 
 class FrameEncryptorInterface;
 class RateLimiter;
-class RtcEventLog;
 class RtpPacketToSend;
 
 // Maximum amount of padding in RFC 3550 is 255 bytes.
@@ -44,6 +44,11 @@
 
 class RTPSender {
  public:
+  RTPSender(const Environment& env,
+            const RtpRtcpInterface::Configuration& config,
+            RtpPacketHistory* packet_history,
+            RtpPacketSender* packet_sender);
+
   RTPSender(const RtpRtcpInterface::Configuration& config,
             RtpPacketHistory* packet_history,
             RtpPacketSender* packet_sender);
@@ -155,6 +160,11 @@
   RtpState GetRtxRtpState() const RTC_LOCKS_EXCLUDED(send_mutex_);
 
  private:
+  RTPSender(Clock* clock,
+            const RtpRtcpInterface::Configuration& config,
+            RtpPacketHistory* packet_history,
+            RtpPacketSender* packet_sender);
+
   std::unique_ptr<RtpPacketToSend> BuildRtxPacket(
       const RtpPacketToSend& packet);
 
diff --git a/modules/rtp_rtcp/source/rtp_sender_egress.cc b/modules/rtp_rtcp/source/rtp_sender_egress.cc
index 5c4d218..c29e391 100644
--- a/modules/rtp_rtcp/source/rtp_sender_egress.cc
+++ b/modules/rtp_rtcp/source/rtp_sender_egress.cc
@@ -20,7 +20,9 @@
 
 #include "api/array_view.h"
 #include "api/call/transport.h"
+#include "api/environment/environment.h"
 #include "api/field_trials_view.h"
+#include "api/rtc_event_log/rtc_event_log.h"
 #include "api/sequence_checker.h"
 #include "api/task_queue/pending_task_safety_flag.h"
 #include "api/task_queue/task_queue_base.h"
@@ -109,19 +111,19 @@
   packet->ReserveExtension<AbsoluteSendTime>();
 }
 
-RtpSenderEgress::RtpSenderEgress(const RtpRtcpInterface::Configuration& config,
+RtpSenderEgress::RtpSenderEgress(const Environment& env,
+                                 const RtpRtcpInterface::Configuration& config,
                                  RtpPacketHistory* packet_history)
-    : enable_send_packet_batching_(config.enable_send_packet_batching),
+    : env_(env),
+      enable_send_packet_batching_(config.enable_send_packet_batching),
       worker_queue_(TaskQueueBase::Current()),
       ssrc_(config.local_media_ssrc),
       rtx_ssrc_(config.rtx_send_ssrc),
       flexfec_ssrc_(config.fec_generator ? config.fec_generator->FecSsrc()
                                          : std::nullopt),
       populate_network2_timestamp_(config.populate_network2_timestamp),
-      clock_(config.clock),
       packet_history_(packet_history),
       transport_(config.outgoing_transport),
-      event_log_(config.event_log),
       is_audio_(config.audio),
       need_rtp_packet_infos_(config.need_rtp_packet_infos),
       fec_generator_(config.fec_generator),
@@ -182,7 +184,7 @@
     RTC_DCHECK(packet->retransmitted_sequence_number().has_value());
   }
 
-  const Timestamp now = clock_->CurrentTime();
+  const Timestamp now = env_.clock().CurrentTime();
   if (need_rtp_packet_infos_ &&
       packet->packet_type() == RtpPacketToSend::Type::kVideo) {
     // Last packet of a frame, add it to sequence number info map.
@@ -240,8 +242,8 @@
   }
   if (packet->HasExtension<AbsoluteSendTime>()) {
     if (use_ntp_time_for_absolute_send_time_) {
-      packet->SetExtension<AbsoluteSendTime>(
-          AbsoluteSendTime::To24Bits(clock_->ConvertTimestampToNtpTime(now)));
+      packet->SetExtension<AbsoluteSendTime>(AbsoluteSendTime::To24Bits(
+          env_.clock().ConvertTimestampToNtpTime(now)));
     } else {
       packet->SetExtension<AbsoluteSendTime>(AbsoluteSendTime::To24Bits(now));
     }
@@ -453,21 +455,13 @@
                                           const PacketOptions& options,
                                           const PacedPacketInfo& pacing_info) {
   RTC_DCHECK_RUN_ON(worker_queue_);
-  int bytes_sent = -1;
-  if (transport_) {
-    bytes_sent = transport_->SendRtp(packet, options)
-                     ? static_cast<int>(packet.size())
-                     : -1;
-    if (event_log_ && bytes_sent > 0) {
-      event_log_->Log(std::make_unique<RtcEventRtpPacketOutgoing>(
-          packet, pacing_info.probe_cluster_id));
-    }
-  }
-
-  if (bytes_sent <= 0) {
+  if (transport_ == nullptr || !transport_->SendRtp(packet, options)) {
     RTC_LOG(LS_WARNING) << "Transport failed to send packet.";
     return false;
   }
+
+  env_.event_log().Log(std::make_unique<RtcEventRtpPacketOutgoing>(
+      packet, pacing_info.probe_cluster_id));
   return true;
 }
 
@@ -515,7 +509,7 @@
 void RtpSenderEgress::PeriodicUpdate() {
   RTC_DCHECK_RUN_ON(worker_queue_);
   RTC_DCHECK(bitrate_callback_);
-  RtpSendRates send_rates = GetSendRates(clock_->CurrentTime());
+  RtpSendRates send_rates = GetSendRates(env_.clock().CurrentTime());
   bitrate_callback_->Notify(
       send_rates.Sum().bps(),
       send_rates[RtpPacketMediaType::kRetransmission].bps(), ssrc_);
diff --git a/modules/rtp_rtcp/source/rtp_sender_egress.h b/modules/rtp_rtcp/source/rtp_sender_egress.h
index 7dec18e..3090c4c 100644
--- a/modules/rtp_rtcp/source/rtp_sender_egress.h
+++ b/modules/rtp_rtcp/source/rtp_sender_egress.h
@@ -20,7 +20,7 @@
 
 #include "api/array_view.h"
 #include "api/call/transport.h"
-#include "api/rtc_event_log/rtc_event_log.h"
+#include "api/environment/environment.h"
 #include "api/rtp_packet_sender.h"
 #include "api/task_queue/pending_task_safety_flag.h"
 #include "api/task_queue/task_queue_base.h"
@@ -65,7 +65,8 @@
     ScopedTaskSafety task_safety_;
   };
 
-  RtpSenderEgress(const RtpRtcpInterface::Configuration& config,
+  RtpSenderEgress(const Environment& env,
+                  const RtpRtcpInterface::Configuration& config,
                   RtpPacketHistory* packet_history);
   ~RtpSenderEgress();
 
@@ -124,16 +125,15 @@
   // Called on a timer, once a second, on the worker_queue_.
   void PeriodicUpdate();
 
+  const Environment env_;
   const bool enable_send_packet_batching_;
   TaskQueueBase* const worker_queue_;
   const uint32_t ssrc_;
   const std::optional<uint32_t> rtx_ssrc_;
   const std::optional<uint32_t> flexfec_ssrc_;
   const bool populate_network2_timestamp_;
-  Clock* const clock_;
   RtpPacketHistory* const packet_history_ RTC_GUARDED_BY(worker_queue_);
   Transport* const transport_;
-  RtcEventLog* const event_log_;
   const bool is_audio_;
   const bool need_rtp_packet_infos_;
   VideoFecGenerator* const fec_generator_ RTC_GUARDED_BY(worker_queue_);
diff --git a/modules/rtp_rtcp/source/rtp_sender_egress_unittest.cc b/modules/rtp_rtcp/source/rtp_sender_egress_unittest.cc
index ab1dd35..b62239e 100644
--- a/modules/rtp_rtcp/source/rtp_sender_egress_unittest.cc
+++ b/modules/rtp_rtcp/source/rtp_sender_egress_unittest.cc
@@ -25,7 +25,6 @@
 #include "api/units/time_delta.h"
 #include "api/units/timestamp.h"
 #include "api/video/video_timing.h"
-#include "logging/rtc_event_log/mock/mock_rtc_event_log.h"
 #include "modules/rtp_rtcp/include/flexfec_sender.h"
 #include "modules/rtp_rtcp/include/rtp_header_extension_map.h"
 #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
@@ -124,29 +123,26 @@
   RtpSenderEgressTest()
       : time_controller_(kStartTime),
         env_(CreateEnvironment(time_controller_.GetClock())),
-        clock_(time_controller_.GetClock()),
         transport_(&header_extensions_),
-        packet_history_(clock_,
+        packet_history_(&env_.clock(),
                         RtpPacketHistory::PaddingMode::kRecentLargePacket),
         sequence_number_(kStartSequenceNumber) {}
 
   std::unique_ptr<RtpSenderEgress> CreateRtpSenderEgress() {
-    return std::make_unique<RtpSenderEgress>(DefaultConfig(), &packet_history_);
+    return std::make_unique<RtpSenderEgress>(env_, DefaultConfig(),
+                                             &packet_history_);
   }
 
   RtpRtcpInterface::Configuration DefaultConfig() {
     RtpRtcpInterface::Configuration config;
     config.audio = false;
-    config.clock = clock_;
     config.outgoing_transport = &transport_;
     config.local_media_ssrc = kSsrc;
     config.rtx_send_ssrc = kRtxSsrc;
     config.fec_generator = nullptr;
-    config.event_log = &mock_rtc_event_log_;
     config.send_packet_observer = &send_packet_observer_;
     config.rtp_stats_callback = &mock_rtp_stats_callback_;
     config.populate_network2_timestamp = false;
-    config.field_trials = &env_.field_trials();
     return config;
   }
 
@@ -168,13 +164,11 @@
   }
 
   std::unique_ptr<RtpPacketToSend> BuildRtpPacket() {
-    return BuildRtpPacket(/*marker_bit=*/true, clock_->CurrentTime().ms());
+    return BuildRtpPacket(/*marker_bit=*/true, env_.clock().CurrentTime().ms());
   }
 
   GlobalSimulatedTimeController time_controller_;
   const Environment env_;
-  Clock* const clock_;
-  NiceMock<MockRtcEventLog> mock_rtc_event_log_;
   NiceMock<MockStreamDataCountersCallback> mock_rtp_stats_callback_;
   NiceMock<MockSendPacketObserver> send_packet_observer_;
   RtpHeaderExtensionMap header_extensions_;
@@ -195,7 +189,8 @@
   auto config = DefaultConfig();
   config.enable_send_packet_batching = true;
   config.audio = true;
-  auto sender = std::make_unique<RtpSenderEgress>(config, &packet_history_);
+  auto sender =
+      std::make_unique<RtpSenderEgress>(env_, config, &packet_history_);
   EXPECT_CALL(transport_,
               SentRtp(AllOf(Field(&PacketOptions::last_packet_in_batch, false),
                             Field(&PacketOptions::batchable, false))))
@@ -207,9 +202,9 @@
 TEST_F(RtpSenderEgressTest, CollectsPacketsWhenBatchingWithVideo) {
   auto config = DefaultConfig();
   config.enable_send_packet_batching = true;
-  auto sender = std::make_unique<RtpSenderEgress>(config, &packet_history_);
-  sender->SendPacket(BuildRtpPacket(), PacedPacketInfo());
-  sender->SendPacket(BuildRtpPacket(), PacedPacketInfo());
+  RtpSenderEgress sender(env_, config, &packet_history_);
+  sender.SendPacket(BuildRtpPacket(), PacedPacketInfo());
+  sender.SendPacket(BuildRtpPacket(), PacedPacketInfo());
   InSequence s;
   EXPECT_CALL(transport_,
               SentRtp(AllOf(Field(&PacketOptions::last_packet_in_batch, false),
@@ -217,7 +212,7 @@
   EXPECT_CALL(transport_,
               SentRtp(AllOf(Field(&PacketOptions::last_packet_in_batch, true),
                             Field(&PacketOptions::batchable, true))));
-  sender->OnBatchComplete();
+  sender.OnBatchComplete();
 }
 
 TEST_F(RtpSenderEgressTest, PacketOptionsIsRetransmitSetByPacketType) {
@@ -324,7 +319,7 @@
 TEST_F(RtpSenderEgressTest, WritesNetwork2ToTimingExtension) {
   RtpRtcpInterface::Configuration rtp_config = DefaultConfig();
   rtp_config.populate_network2_timestamp = true;
-  auto sender = std::make_unique<RtpSenderEgress>(rtp_config, &packet_history_);
+  RtpSenderEgress sender(env_, rtp_config, &packet_history_);
   header_extensions_.RegisterByUri(kVideoTimingExtensionId,
                                    VideoTimingExtension::Uri());
 
@@ -336,7 +331,7 @@
 
   const int kStoredTimeInMs = 100;
   time_controller_.AdvanceTime(TimeDelta::Millis(kStoredTimeInMs));
-  sender->SendPacket(std::move(packet), PacedPacketInfo());
+  sender.SendPacket(std::move(packet), PacedPacketInfo());
   ASSERT_TRUE(transport_.last_packet().has_value());
 
   VideoSendTiming video_timing;
@@ -348,7 +343,7 @@
 }
 
 TEST_F(RtpSenderEgressTest, WritesTransportSequenceNumberExtensionIfAllocated) {
-  RtpSenderEgress sender(DefaultConfig(), &packet_history_);
+  RtpSenderEgress sender(env_, DefaultConfig(), &packet_history_);
   header_extensions_.RegisterByUri(kTransportSequenceNumberExtensionId,
                                    TransportSequenceNumber::Uri());
   std::unique_ptr<RtpPacketToSend> packet = BuildRtpPacket();
@@ -370,9 +365,9 @@
                                    TransportSequenceNumber::Uri());
 
   const uint16_t kTransportSequenceNumber = 1;
-  EXPECT_CALL(
-      send_packet_observer_,
-      OnSendPacket(Eq(kTransportSequenceNumber), clock_->CurrentTime(), kSsrc));
+  EXPECT_CALL(send_packet_observer_,
+              OnSendPacket(Eq(kTransportSequenceNumber),
+                           env_.clock().CurrentTime(), kSsrc));
   std::unique_ptr<RtpPacketToSend> packet = BuildRtpPacket();
   packet->set_transport_sequence_number(kTransportSequenceNumber);
   sender->SendPacket(std::move(packet), PacedPacketInfo());
@@ -381,8 +376,9 @@
 TEST_F(RtpSenderEgressTest, OnSendPacketUpdatedWithoutTransportSequenceNumber) {
   std::unique_ptr<RtpSenderEgress> sender = CreateRtpSenderEgress();
 
-  EXPECT_CALL(send_packet_observer_,
-              OnSendPacket(Eq(std::nullopt), clock_->CurrentTime(), kSsrc));
+  EXPECT_CALL(
+      send_packet_observer_,
+      OnSendPacket(Eq(std::nullopt), env_.clock().CurrentTime(), kSsrc));
   sender->SendPacket(BuildRtpPacket(), PacedPacketInfo());
 }
 
@@ -440,7 +436,7 @@
 
   RtpRtcpInterface::Configuration config = DefaultConfig();
   config.send_bitrate_observer = &observer;
-  auto sender = std::make_unique<RtpSenderEgress>(config, &packet_history_);
+  RtpSenderEgress sender(env_, config, &packet_history_);
 
   // Simulate kNumPackets sent with kPacketInterval intervals, with the
   // number of packets selected so that we fill (but don't overflow) the one
@@ -474,7 +470,7 @@
           EXPECT_NEAR(retransmission_bitrate_bps, expected_bitrate_bps, 500);
         });
 
-    sender->SendPacket(std::move(packet), PacedPacketInfo());
+    sender.SendPacket(std::move(packet), PacedPacketInfo());
     time_controller_.AdvanceTime(kPacketInterval);
   }
 }
@@ -751,7 +747,7 @@
   std::unique_ptr<RtpSenderEgress> sender = CreateRtpSenderEgress();
 
   std::unique_ptr<RtpPacketToSend> packet = BuildRtpPacket();
-  packet->set_packetization_finish_time(clock_->CurrentTime());
+  packet->set_packetization_finish_time(env_.clock().CurrentTime());
 
   const int32_t kDiffMs = 10;
   time_controller_.AdvanceTime(TimeDelta::Millis(kDiffMs));
@@ -763,7 +759,7 @@
   EXPECT_EQ(received_packet.GetExtension<TransmissionOffset>(), kDiffMs * 90);
 
   EXPECT_EQ(received_packet.GetExtension<AbsoluteSendTime>(),
-            AbsoluteSendTime::To24Bits(clock_->CurrentTime()));
+            AbsoluteSendTime::To24Bits(env_.clock().CurrentTime()));
 
   VideoSendTiming timing;
   EXPECT_TRUE(received_packet.GetExtension<VideoTimingExtension>(&timing));
@@ -804,7 +800,7 @@
 TEST_F(RtpSenderEgressTest, SendPacketSetsPacketOptionsIdFromExtension) {
   header_extensions_.RegisterByUri(kTransportSequenceNumberExtensionId,
                                    TransportSequenceNumber::Uri());
-  RtpSenderEgress sender(DefaultConfig(), &packet_history_);
+  RtpSenderEgress sender(env_, DefaultConfig(), &packet_history_);
 
   // 64-bit transport sequence number.
   const int64_t kTransportSequenceNumber = 0xFFFF000F;
@@ -825,7 +821,7 @@
 
 TEST_F(RtpSenderEgressTest,
        SendPacketSetsPacketOptionsIdFromRtpSendPacketIfNotUsingExtension) {
-  RtpSenderEgress sender(DefaultConfig(), &packet_history_);
+  RtpSenderEgress sender(env_, DefaultConfig(), &packet_history_);
   // 64-bit transport sequence number.
   const int64_t kTransportSequenceNumber = 0xFFFF000F;
   std::unique_ptr<RtpPacketToSend> packet = BuildRtpPacket();
@@ -851,12 +847,12 @@
                         /*rtp_state=*/nullptr);
   RtpRtcpInterface::Configuration config = DefaultConfig();
   config.fec_generator = &flexfec;
-  auto sender = std::make_unique<RtpSenderEgress>(config, &packet_history_);
+  RtpSenderEgress sender(env_, config, &packet_history_);
 
   header_extensions_.RegisterByUri(kTransportSequenceNumberExtensionId,
                                    TransportSequenceNumber::Uri());
 
-  const Timestamp capture_time = clock_->CurrentTime();
+  const Timestamp capture_time = env_.clock().CurrentTime();
 
   std::unique_ptr<RtpPacketToSend> video_packet = BuildRtpPacket();
   video_packet->set_packet_type(RtpPacketMediaType::kVideo);
@@ -882,20 +878,20 @@
 
   EXPECT_CALL(send_packet_observer_, OnSendPacket(Eq(1), capture_time, kSsrc));
 
-  sender->SendPacket(std::move(video_packet), PacedPacketInfo());
+  sender.SendPacket(std::move(video_packet), PacedPacketInfo());
 
   // Send packet observer not called for padding/retransmissions.
   EXPECT_CALL(send_packet_observer_, OnSendPacket(Eq(2), _, _)).Times(0);
-  sender->SendPacket(std::move(rtx_packet), PacedPacketInfo());
+  sender.SendPacket(std::move(rtx_packet), PacedPacketInfo());
 
   EXPECT_CALL(send_packet_observer_,
               OnSendPacket(Eq(3), capture_time, kFlexFecSsrc));
-  sender->SendPacket(std::move(fec_packet), PacedPacketInfo());
+  sender.SendPacket(std::move(fec_packet), PacedPacketInfo());
 
   time_controller_.AdvanceTime(TimeDelta::Zero());
   StreamDataCounters rtp_stats;
   StreamDataCounters rtx_stats;
-  sender->GetDataCounters(&rtp_stats, &rtx_stats);
+  sender.GetDataCounters(&rtp_stats, &rtx_stats);
   EXPECT_EQ(rtp_stats.transmitted.packets, 2u);
   EXPECT_EQ(rtp_stats.fec.packets, 1u);
   EXPECT_EQ(rtx_stats.retransmitted.packets, 1u);