Use Environment to keep peer connection factory field trials in ConnectionContext

Bug: webrtc:15656
Change-Id: Ice52fcb9ba54a5d0034b59233ceae4f9cefbceae
Reviewed-on: https://webrtc-review.googlesource.com/c/src/+/328860
Reviewed-by: Harald Alvestrand <hta@webrtc.org>
Commit-Queue: Danil Chapovalov <danilchap@webrtc.org>
Cr-Commit-Position: refs/heads/main@{#41252}
diff --git a/pc/BUILD.gn b/pc/BUILD.gn
index dfb98ff..fe128c0 100644
--- a/pc/BUILD.gn
+++ b/pc/BUILD.gn
@@ -937,6 +937,7 @@
     "../api:refcountedbase",
     "../api:scoped_refptr",
     "../api:sequence_checker",
+    "../api/environment",
     "../api/neteq:neteq_api",
     "../api/transport:field_trial_based_config",
     "../api/transport:sctp_transport_factory_interface",
@@ -1522,6 +1523,7 @@
     "../api:rtp_parameters",
     "../api:scoped_refptr",
     "../api:sequence_checker",
+    "../api/environment",
     "../api/environment:environment_factory",
     "../api/metronome",
     "../api/neteq:neteq_api",
@@ -2446,6 +2448,7 @@
       "../api/crypto:frame_decryptor_interface",
       "../api/crypto:frame_encryptor_interface",
       "../api/crypto:options",
+      "../api/environment:environment_factory",
       "../api/rtc_event_log",
       "../api/rtc_event_log:rtc_event_log_factory",
       "../api/task_queue",
@@ -2810,6 +2813,7 @@
       "../api:sequence_checker",
       "../api/audio:audio_mixer_api",
       "../api/audio_codecs:audio_codecs_api",
+      "../api/environment:environment_factory",
       "../api/task_queue",
       "../api/task_queue:default_task_queue_factory",
       "../api/units:time_delta",
diff --git a/pc/connection_context.cc b/pc/connection_context.cc
index 09d4b4a..48ce899 100644
--- a/pc/connection_context.cc
+++ b/pc/connection_context.cc
@@ -78,6 +78,7 @@
 
 // Static
 rtc::scoped_refptr<ConnectionContext> ConnectionContext::Create(
+    const Environment& env,
     PeerConnectionFactoryDependencies* dependencies) {
 // TODO(bugs.webrtc.org/15574): Remove when call_factory and media_engine
 // are removed from PeerConnectionFactoryDependencies
@@ -92,10 +93,11 @@
 #pragma clang diagnostic pop
 
   return rtc::scoped_refptr<ConnectionContext>(
-      new ConnectionContext(dependencies));
+      new ConnectionContext(env, dependencies));
 }
 
 ConnectionContext::ConnectionContext(
+    const Environment& env,
     PeerConnectionFactoryDependencies* dependencies)
     : network_thread_(MaybeStartNetworkThread(dependencies->network_thread,
                                               owned_socket_factory_,
@@ -109,8 +111,7 @@
                      }),
       signaling_thread_(MaybeWrapThread(dependencies->signaling_thread,
                                         wraps_current_thread_)),
-      trials_(dependencies->trials ? std::move(dependencies->trials)
-                                   : std::make_unique<FieldTrialBasedConfig>()),
+      env_(env),
       media_engine_(
           dependencies->media_factory != nullptr
               ? dependencies->media_factory->CreateMediaEngine(*dependencies)
@@ -131,7 +132,7 @@
       sctp_factory_(
           MaybeCreateSctpFactory(std::move(dependencies->sctp_factory),
                                  network_thread(),
-                                 *trials_.get())),
+                                 env_.field_trials())),
       use_rtx_(true) {
   RTC_DCHECK_RUN_ON(signaling_thread_);
   RTC_DCHECK(!(default_network_manager_ && network_monitor_factory_))
@@ -174,7 +175,7 @@
     // If network_monitor_factory_ is non-null, it will be used to create a
     // network monitor while on the network thread.
     default_network_manager_ = std::make_unique<rtc::BasicNetworkManager>(
-        network_monitor_factory_.get(), socket_factory, &field_trials());
+        network_monitor_factory_.get(), socket_factory, &env_.field_trials());
   }
   if (!default_socket_factory_) {
     default_socket_factory_ =
diff --git a/pc/connection_context.h b/pc/connection_context.h
index af5b7a9..148a9cb 100644
--- a/pc/connection_context.h
+++ b/pc/connection_context.h
@@ -15,6 +15,7 @@
 #include <string>
 
 #include "api/call/call_factory_interface.h"
+#include "api/environment/environment.h"
 #include "api/field_trials_view.h"
 #include "api/media_stream_interface.h"
 #include "api/peer_connection_interface.h"
@@ -39,8 +40,6 @@
 
 namespace webrtc {
 
-class RtcEventLog;
-
 // This class contains resources needed by PeerConnection and associated
 // objects. A reference to this object is passed to each PeerConnection. The
 // methods on this object are assumed not to change the state in any way that
@@ -54,6 +53,7 @@
   // The Dependencies class allows simple management of all new dependencies
   // being added to the ConnectionContext.
   static rtc::scoped_refptr<ConnectionContext> Create(
+      const Environment& env,
       PeerConnectionFactoryDependencies* dependencies);
 
   // This class is not copyable or movable.
@@ -80,7 +80,7 @@
   // Note: that there can be different field trials for different
   // PeerConnections (but they are not supposed change after creating the
   // PeerConnection).
-  const FieldTrialsView& field_trials() const { return *trials_.get(); }
+  const FieldTrialsView& field_trials() const { return env_.field_trials(); }
 
   // Accessors only used from the PeerConnectionFactory class
   rtc::NetworkManager* default_network_manager() {
@@ -106,7 +106,8 @@
   void set_use_rtx(bool use_rtx) { use_rtx_ = use_rtx; }
 
  protected:
-  explicit ConnectionContext(PeerConnectionFactoryDependencies* dependencies);
+  ConnectionContext(const Environment& env,
+                    PeerConnectionFactoryDependencies* dependencies);
 
   friend class rtc::RefCountedNonVirtual<ConnectionContext>;
   ~ConnectionContext();
@@ -122,8 +123,7 @@
   AlwaysValidPointer<rtc::Thread> const worker_thread_;
   rtc::Thread* const signaling_thread_;
 
-  // Accessed both on signaling thread and worker thread.
-  std::unique_ptr<FieldTrialsView> const trials_;
+  const Environment env_;
 
   // This object is const over the lifetime of the ConnectionContext, and is
   // only altered in the destructor.
diff --git a/pc/peer_connection_factory.cc b/pc/peer_connection_factory.cc
index 81780cf..c656a4f 100644
--- a/pc/peer_connection_factory.cc
+++ b/pc/peer_connection_factory.cc
@@ -16,6 +16,8 @@
 #include "absl/strings/match.h"
 #include "api/async_resolver_factory.h"
 #include "api/call/call_factory_interface.h"
+#include "api/environment/environment.h"
+#include "api/environment/environment_factory.h"
 #include "api/fec_controller.h"
 #include "api/ice_transport_interface.h"
 #include "api/network_state_predictor.h"
@@ -78,7 +80,13 @@
 // Static
 rtc::scoped_refptr<PeerConnectionFactory> PeerConnectionFactory::Create(
     PeerConnectionFactoryDependencies dependencies) {
-  auto context = ConnectionContext::Create(&dependencies);
+  // TODO(bugs.webrtc.org/15656): Move task_queue_factory into environment with
+  // ownership when MediaFactory::CreateMedia would use it from the
+  // Environment instead of the PeerConnectionFactoryDependencies.
+  auto context = ConnectionContext::Create(
+      CreateEnvironment(std::move(dependencies.trials),
+                        dependencies.task_queue_factory.get()),
+      &dependencies);
   if (!context) {
     return nullptr;
   }
@@ -103,10 +111,17 @@
               : std::make_unique<RtpTransportControllerSendFactory>()),
       metronome_(std::move(dependencies->metronome)) {}
 
+// TODO(bugs.webrtc.org/15656): Move task_queue_factory into environment with
+// ownership when MediaFactory::CreateMedia would use it from the
+// Environment instead of the PeerConnectionFactoryDependencies.
 PeerConnectionFactory::PeerConnectionFactory(
     PeerConnectionFactoryDependencies dependencies)
-    : PeerConnectionFactory(ConnectionContext::Create(&dependencies),
-                            &dependencies) {}
+    : PeerConnectionFactory(
+          ConnectionContext::Create(
+              CreateEnvironment(std::move(dependencies.trials),
+                                dependencies.task_queue_factory.get()),
+              &dependencies),
+          &dependencies) {}
 
 PeerConnectionFactory::~PeerConnectionFactory() {
   RTC_DCHECK_RUN_ON(signaling_thread());
diff --git a/pc/peer_connection_factory_unittest.cc b/pc/peer_connection_factory_unittest.cc
index 989b70f..618ac68 100644
--- a/pc/peer_connection_factory_unittest.cc
+++ b/pc/peer_connection_factory_unittest.cc
@@ -21,6 +21,7 @@
 #include "api/create_peerconnection_factory.h"
 #include "api/data_channel_interface.h"
 #include "api/enable_media.h"
+#include "api/environment/environment_factory.h"
 #include "api/jsep.h"
 #include "api/media_stream_interface.h"
 #include "api/task_queue/default_task_queue_factory.h"
@@ -269,7 +270,6 @@
   pcf_dependencies.worker_thread = rtc::Thread::Current();
   pcf_dependencies.network_thread = rtc::Thread::Current();
   pcf_dependencies.task_queue_factory = CreateDefaultTaskQueueFactory();
-  pcf_dependencies.trials = std::make_unique<FieldTrialBasedConfig>();
 
   pcf_dependencies.adm = FakeAudioCaptureModule::Create();
   pcf_dependencies.audio_encoder_factory = CreateBuiltinAudioEncoderFactory();
@@ -285,7 +285,7 @@
   EnableMedia(pcf_dependencies);
 
   rtc::scoped_refptr<ConnectionContext> context =
-      ConnectionContext::Create(&pcf_dependencies);
+      ConnectionContext::Create(CreateEnvironment(), &pcf_dependencies);
   context->set_use_rtx(false);
   return rtc::make_ref_counted<PeerConnectionFactory>(context,
                                                       &pcf_dependencies);
diff --git a/pc/rtp_transceiver_unittest.cc b/pc/rtp_transceiver_unittest.cc
index bd711f1..d75e9645 100644
--- a/pc/rtp_transceiver_unittest.cc
+++ b/pc/rtp_transceiver_unittest.cc
@@ -17,6 +17,7 @@
 
 #include "absl/strings/string_view.h"
 #include "absl/types/optional.h"
+#include "api/environment/environment_factory.h"
 #include "api/peer_connection_interface.h"
 #include "api/rtp_parameters.h"
 #include "media/base/media_engine.h"
@@ -44,7 +45,8 @@
  public:
   RtpTransceiverTest()
       : dependencies_(MakeDependencies()),
-        context_(ConnectionContext::Create(&dependencies_)) {}
+        context_(
+            ConnectionContext::Create(CreateEnvironment(), &dependencies_)) {}
 
  protected:
   cricket::MediaEngineInterface* media_engine() {
diff --git a/pc/test/fake_peer_connection_for_stats.h b/pc/test/fake_peer_connection_for_stats.h
index 33a5361..2883c86 100644
--- a/pc/test/fake_peer_connection_for_stats.h
+++ b/pc/test/fake_peer_connection_for_stats.h
@@ -18,6 +18,7 @@
 #include <utility>
 #include <vector>
 
+#include "api/environment/environment_factory.h"
 #include "media/base/media_channel.h"
 #include "pc/channel.h"
 #include "pc/stream_collection.h"
@@ -219,7 +220,8 @@
         signaling_thread_(rtc::Thread::Current()),
         // TODO(hta): remove separate thread variables and use context.
         dependencies_(MakeDependencies()),
-        context_(ConnectionContext::Create(&dependencies_)),
+        context_(
+            ConnectionContext::Create(CreateEnvironment(), &dependencies_)),
         local_streams_(StreamCollection::Create()),
         remote_streams_(StreamCollection::Create()),
         data_channel_controller_(network_thread_) {}