xref: /aosp_15_r20/external/webrtc/pc/peer_connection.h (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright 2012 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #ifndef PC_PEER_CONNECTION_H_
12 #define PC_PEER_CONNECTION_H_
13 
14 #include <stdint.h>
15 
16 #include <functional>
17 #include <map>
18 #include <memory>
19 #include <set>
20 #include <string>
21 #include <vector>
22 
23 #include "absl/types/optional.h"
24 #include "api/adaptation/resource.h"
25 #include "api/async_dns_resolver.h"
26 #include "api/candidate.h"
27 #include "api/crypto/crypto_options.h"
28 #include "api/data_channel_interface.h"
29 #include "api/dtls_transport_interface.h"
30 #include "api/field_trials_view.h"
31 #include "api/ice_transport_interface.h"
32 #include "api/jsep.h"
33 #include "api/media_stream_interface.h"
34 #include "api/media_types.h"
35 #include "api/peer_connection_interface.h"
36 #include "api/rtc_error.h"
37 #include "api/rtc_event_log/rtc_event_log.h"
38 #include "api/rtc_event_log_output.h"
39 #include "api/rtp_receiver_interface.h"
40 #include "api/rtp_sender_interface.h"
41 #include "api/rtp_transceiver_interface.h"
42 #include "api/scoped_refptr.h"
43 #include "api/sctp_transport_interface.h"
44 #include "api/sequence_checker.h"
45 #include "api/set_local_description_observer_interface.h"
46 #include "api/set_remote_description_observer_interface.h"
47 #include "api/stats/rtc_stats_collector_callback.h"
48 #include "api/task_queue/pending_task_safety_flag.h"
49 #include "api/transport/bitrate_settings.h"
50 #include "api/transport/data_channel_transport_interface.h"
51 #include "api/transport/enums.h"
52 #include "api/turn_customizer.h"
53 #include "call/call.h"
54 #include "p2p/base/ice_transport_internal.h"
55 #include "p2p/base/port.h"
56 #include "p2p/base/port_allocator.h"
57 #include "p2p/base/transport_description.h"
58 #include "pc/channel_interface.h"
59 #include "pc/connection_context.h"
60 #include "pc/data_channel_controller.h"
61 #include "pc/data_channel_utils.h"
62 #include "pc/dtls_transport.h"
63 #include "pc/jsep_transport_controller.h"
64 #include "pc/legacy_stats_collector.h"
65 #include "pc/peer_connection_internal.h"
66 #include "pc/peer_connection_message_handler.h"
67 #include "pc/rtc_stats_collector.h"
68 #include "pc/rtp_transceiver.h"
69 #include "pc/rtp_transmission_manager.h"
70 #include "pc/rtp_transport_internal.h"
71 #include "pc/sctp_data_channel.h"
72 #include "pc/sdp_offer_answer.h"
73 #include "pc/session_description.h"
74 #include "pc/transceiver_list.h"
75 #include "pc/transport_stats.h"
76 #include "pc/usage_pattern.h"
77 #include "rtc_base/checks.h"
78 #include "rtc_base/copy_on_write_buffer.h"
79 #include "rtc_base/rtc_certificate.h"
80 #include "rtc_base/ssl_certificate.h"
81 #include "rtc_base/ssl_stream_adapter.h"
82 #include "rtc_base/third_party/sigslot/sigslot.h"
83 #include "rtc_base/thread.h"
84 #include "rtc_base/thread_annotations.h"
85 #include "rtc_base/weak_ptr.h"
86 
87 namespace webrtc {
88 
89 // PeerConnection is the implementation of the PeerConnection object as defined
90 // by the PeerConnectionInterface API surface.
91 // The class currently is solely responsible for the following:
92 // - Managing the session state machine (signaling state).
93 // - Creating and initializing lower-level objects, like PortAllocator and
94 //   BaseChannels.
95 // - Owning and managing the life cycle of the RtpSender/RtpReceiver and track
96 //   objects.
97 // - Tracking the current and pending local/remote session descriptions.
98 // The class currently is jointly responsible for the following:
99 // - Parsing and interpreting SDP.
100 // - Generating offers and answers based on the current state.
101 // - The ICE state machine.
102 // - Generating stats.
103 class PeerConnection : public PeerConnectionInternal,
104                        public JsepTransportController::Observer {
105  public:
106   // Creates a PeerConnection and initializes it with the given values.
107   // If the initialization fails, the function releases the PeerConnection
108   // and returns nullptr.
109   //
110   // Note that the function takes ownership of dependencies, and will
111   // either use them or release them, whether it succeeds or fails.
112   static RTCErrorOr<rtc::scoped_refptr<PeerConnection>> Create(
113       rtc::scoped_refptr<ConnectionContext> context,
114       const PeerConnectionFactoryInterface::Options& options,
115       std::unique_ptr<RtcEventLog> event_log,
116       std::unique_ptr<Call> call,
117       const PeerConnectionInterface::RTCConfiguration& configuration,
118       PeerConnectionDependencies dependencies);
119 
120   rtc::scoped_refptr<StreamCollectionInterface> local_streams() override;
121   rtc::scoped_refptr<StreamCollectionInterface> remote_streams() override;
122   bool AddStream(MediaStreamInterface* local_stream) override;
123   void RemoveStream(MediaStreamInterface* local_stream) override;
124 
125   RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> AddTrack(
126       rtc::scoped_refptr<MediaStreamTrackInterface> track,
127       const std::vector<std::string>& stream_ids) override;
128   RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> AddTrack(
129       rtc::scoped_refptr<MediaStreamTrackInterface> track,
130       const std::vector<std::string>& stream_ids,
131       const std::vector<RtpEncodingParameters>& init_send_encodings) override;
132   RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> AddTrack(
133       rtc::scoped_refptr<MediaStreamTrackInterface> track,
134       const std::vector<std::string>& stream_ids,
135       const std::vector<RtpEncodingParameters>* init_send_encodings);
136   RTCError RemoveTrackOrError(
137       rtc::scoped_refptr<RtpSenderInterface> sender) override;
138 
139   RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>> AddTransceiver(
140       rtc::scoped_refptr<MediaStreamTrackInterface> track) override;
141   RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>> AddTransceiver(
142       rtc::scoped_refptr<MediaStreamTrackInterface> track,
143       const RtpTransceiverInit& init) override;
144   RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>> AddTransceiver(
145       cricket::MediaType media_type) override;
146   RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>> AddTransceiver(
147       cricket::MediaType media_type,
148       const RtpTransceiverInit& init) override;
149 
150   rtc::scoped_refptr<RtpSenderInterface> CreateSender(
151       const std::string& kind,
152       const std::string& stream_id) override;
153 
154   std::vector<rtc::scoped_refptr<RtpSenderInterface>> GetSenders()
155       const override;
156   std::vector<rtc::scoped_refptr<RtpReceiverInterface>> GetReceivers()
157       const override;
158   std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> GetTransceivers()
159       const override;
160 
161   RTCErrorOr<rtc::scoped_refptr<DataChannelInterface>> CreateDataChannelOrError(
162       const std::string& label,
163       const DataChannelInit* config) override;
164   // WARNING: LEGACY. See peerconnectioninterface.h
165   bool GetStats(StatsObserver* observer,
166                 webrtc::MediaStreamTrackInterface* track,
167                 StatsOutputLevel level) override;
168   // Spec-complaint GetStats(). See peerconnectioninterface.h
169   void GetStats(RTCStatsCollectorCallback* callback) override;
170   void GetStats(
171       rtc::scoped_refptr<RtpSenderInterface> selector,
172       rtc::scoped_refptr<RTCStatsCollectorCallback> callback) override;
173   void GetStats(
174       rtc::scoped_refptr<RtpReceiverInterface> selector,
175       rtc::scoped_refptr<RTCStatsCollectorCallback> callback) override;
176   void ClearStatsCache() override;
177 
178   SignalingState signaling_state() override;
179 
180   IceConnectionState ice_connection_state() override;
ice_connection_state_internal()181   IceConnectionState ice_connection_state_internal() override {
182     return ice_connection_state();
183   }
184   IceConnectionState standardized_ice_connection_state() override;
185   PeerConnectionState peer_connection_state() override;
186   IceGatheringState ice_gathering_state() override;
187   absl::optional<bool> can_trickle_ice_candidates() override;
188 
189   const SessionDescriptionInterface* local_description() const override;
190   const SessionDescriptionInterface* remote_description() const override;
191   const SessionDescriptionInterface* current_local_description() const override;
192   const SessionDescriptionInterface* current_remote_description()
193       const override;
194   const SessionDescriptionInterface* pending_local_description() const override;
195   const SessionDescriptionInterface* pending_remote_description()
196       const override;
197 
198   void RestartIce() override;
199 
200   // JSEP01
201   void CreateOffer(CreateSessionDescriptionObserver* observer,
202                    const RTCOfferAnswerOptions& options) override;
203   void CreateAnswer(CreateSessionDescriptionObserver* observer,
204                     const RTCOfferAnswerOptions& options) override;
205 
206   void SetLocalDescription(
207       std::unique_ptr<SessionDescriptionInterface> desc,
208       rtc::scoped_refptr<SetLocalDescriptionObserverInterface> observer)
209       override;
210   void SetLocalDescription(
211       rtc::scoped_refptr<SetLocalDescriptionObserverInterface> observer)
212       override;
213   // TODO(https://crbug.com/webrtc/11798): Delete these methods in favor of the
214   // ones taking SetLocalDescriptionObserverInterface as argument.
215   void SetLocalDescription(SetSessionDescriptionObserver* observer,
216                            SessionDescriptionInterface* desc) override;
217   void SetLocalDescription(SetSessionDescriptionObserver* observer) override;
218 
219   void SetRemoteDescription(
220       std::unique_ptr<SessionDescriptionInterface> desc,
221       rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer)
222       override;
223   // TODO(https://crbug.com/webrtc/11798): Delete this methods in favor of the
224   // ones taking SetRemoteDescriptionObserverInterface as argument.
225   void SetRemoteDescription(SetSessionDescriptionObserver* observer,
226                             SessionDescriptionInterface* desc) override;
227 
228   PeerConnectionInterface::RTCConfiguration GetConfiguration() override;
229   RTCError SetConfiguration(
230       const PeerConnectionInterface::RTCConfiguration& configuration) override;
231   bool AddIceCandidate(const IceCandidateInterface* candidate) override;
232   void AddIceCandidate(std::unique_ptr<IceCandidateInterface> candidate,
233                        std::function<void(RTCError)> callback) override;
234   bool RemoveIceCandidates(
235       const std::vector<cricket::Candidate>& candidates) override;
236 
237   RTCError SetBitrate(const BitrateSettings& bitrate) override;
238 
239   void SetAudioPlayout(bool playout) override;
240   void SetAudioRecording(bool recording) override;
241 
242   rtc::scoped_refptr<DtlsTransportInterface> LookupDtlsTransportByMid(
243       const std::string& mid) override;
244   rtc::scoped_refptr<DtlsTransport> LookupDtlsTransportByMidInternal(
245       const std::string& mid);
246 
247   rtc::scoped_refptr<SctpTransportInterface> GetSctpTransport() const override;
248 
249   void AddAdaptationResource(rtc::scoped_refptr<Resource> resource) override;
250 
251   bool StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
252                         int64_t output_period_ms) override;
253   bool StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output) override;
254   void StopRtcEventLog() override;
255 
256   void Close() override;
257 
signaling_thread()258   rtc::Thread* signaling_thread() const final {
259     return context_->signaling_thread();
260   }
261 
network_thread()262   rtc::Thread* network_thread() const final {
263     return context_->network_thread();
264   }
worker_thread()265   rtc::Thread* worker_thread() const final { return context_->worker_thread(); }
266 
session_id()267   std::string session_id() const override {
268     return session_id_;
269   }
270 
initial_offerer()271   bool initial_offerer() const override {
272     RTC_DCHECK_RUN_ON(signaling_thread());
273     return sdp_handler_->initial_offerer();
274   }
275 
276   std::vector<
277       rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
GetTransceiversInternal()278   GetTransceiversInternal() const override {
279     RTC_DCHECK_RUN_ON(signaling_thread());
280     if (!ConfiguredForMedia()) {
281       return {};
282     }
283     return rtp_manager()->transceivers()->List();
284   }
285 
SignalSctpDataChannelCreated()286   sigslot::signal1<SctpDataChannel*>& SignalSctpDataChannelCreated() override {
287     RTC_DCHECK_RUN_ON(signaling_thread());
288     return data_channel_controller_.SignalSctpDataChannelCreated();
289   }
290 
291   std::vector<DataChannelStats> GetDataChannelStats() const override;
292 
293   absl::optional<std::string> sctp_transport_name() const override;
294   absl::optional<std::string> sctp_mid() const override;
295 
296   cricket::CandidateStatsList GetPooledCandidateStats() const override;
297   std::map<std::string, cricket::TransportStats> GetTransportStatsByNames(
298       const std::set<std::string>& transport_names) override;
299   Call::Stats GetCallStats() override;
300 
301   bool GetLocalCertificate(
302       const std::string& transport_name,
303       rtc::scoped_refptr<rtc::RTCCertificate>* certificate) override;
304   std::unique_ptr<rtc::SSLCertChain> GetRemoteSSLCertChain(
305       const std::string& transport_name) override;
306   bool IceRestartPending(const std::string& content_name) const override;
307   bool NeedsIceRestart(const std::string& content_name) const override;
308   bool GetSslRole(const std::string& content_name, rtc::SSLRole* role) override;
309 
310   // Functions needed by DataChannelController
NoteDataAddedEvent()311   void NoteDataAddedEvent() override { NoteUsageEvent(UsageEvent::DATA_ADDED); }
312   // Returns the observer. Will crash on CHECK if the observer is removed.
313   PeerConnectionObserver* Observer() const override;
IsClosed()314   bool IsClosed() const override {
315     RTC_DCHECK_RUN_ON(signaling_thread());
316     return !sdp_handler_ ||
317            sdp_handler_->signaling_state() == PeerConnectionInterface::kClosed;
318   }
319   // Get current SSL role used by SCTP's underlying transport.
320   bool GetSctpSslRole(rtc::SSLRole* role) override;
321   // Handler for the "channel closed" signal
322   void OnSctpDataChannelClosed(DataChannelInterface* channel) override;
323 
324   bool ShouldFireNegotiationNeededEvent(uint32_t event_id) override;
325 
326   // Functions needed by SdpOfferAnswerHandler
legacy_stats()327   LegacyStatsCollector* legacy_stats() override {
328     RTC_DCHECK_RUN_ON(signaling_thread());
329     return legacy_stats_.get();
330   }
data_channel_controller()331   DataChannelController* data_channel_controller() override {
332     RTC_DCHECK_RUN_ON(signaling_thread());
333     return &data_channel_controller_;
334   }
dtls_enabled()335   bool dtls_enabled() const override {
336     RTC_DCHECK_RUN_ON(signaling_thread());
337     return dtls_enabled_;
338   }
configuration()339   const PeerConnectionInterface::RTCConfiguration* configuration()
340       const override {
341     RTC_DCHECK_RUN_ON(signaling_thread());
342     return &configuration_;
343   }
message_handler()344   PeerConnectionMessageHandler* message_handler() override {
345     RTC_DCHECK_RUN_ON(signaling_thread());
346     return &message_handler_;
347   }
348 
rtp_manager()349   RtpTransmissionManager* rtp_manager() override { return rtp_manager_.get(); }
rtp_manager()350   const RtpTransmissionManager* rtp_manager() const override {
351     return rtp_manager_.get();
352   }
353 
transport_controller_s()354   JsepTransportController* transport_controller_s() override {
355     RTC_DCHECK_RUN_ON(signaling_thread());
356     return transport_controller_copy_;
357   }
transport_controller_n()358   JsepTransportController* transport_controller_n() override {
359     RTC_DCHECK_RUN_ON(network_thread());
360     return transport_controller_.get();
361   }
port_allocator()362   cricket::PortAllocator* port_allocator() override {
363     return port_allocator_.get();
364   }
call_ptr()365   Call* call_ptr() override { return call_ptr_; }
366 
context()367   ConnectionContext* context() { return context_.get(); }
options()368   const PeerConnectionFactoryInterface::Options* options() const override {
369     return &options_;
370   }
371   void SetIceConnectionState(IceConnectionState new_state) override;
372   void NoteUsageEvent(UsageEvent event) override;
373 
374   // Asynchronously adds a remote candidate on the network thread.
375   void AddRemoteCandidate(const std::string& mid,
376                           const cricket::Candidate& candidate) override;
377 
378   // Report the UMA metric BundleUsage for the given remote description.
379   void ReportSdpBundleUsage(
380       const SessionDescriptionInterface& remote_description) override;
381 
382   // Report several UMA metrics on establishing the connection.
383   void ReportFirstConnectUsageMetrics() RTC_RUN_ON(signaling_thread());
384 
385   // Returns true if the PeerConnection is configured to use Unified Plan
386   // semantics for creating offers/answers and setting local/remote
387   // descriptions. If this is true the RtpTransceiver API will also be available
388   // to the user. If this is false, Plan B semantics are assumed.
389   // TODO(bugs.webrtc.org/8530): Flip the default to be Unified Plan once
390   // sufficient time has passed.
IsUnifiedPlan()391   bool IsUnifiedPlan() const override {
392     RTC_DCHECK_RUN_ON(signaling_thread());
393     return is_unified_plan_;
394   }
395   bool ValidateBundleSettings(
396       const cricket::SessionDescription* desc,
397       const std::map<std::string, const cricket::ContentGroup*>&
398           bundle_groups_by_mid) override;
399 
400   // Returns the MID for the data section associated with the
401   // SCTP data channel, if it has been set. If no data
402   // channels are configured this will return nullopt.
403   absl::optional<std::string> GetDataMid() const override;
404 
405   void SetSctpDataMid(const std::string& mid) override;
406 
407   void ResetSctpDataMid() override;
408 
409   // Asynchronously calls SctpTransport::Start() on the network thread for
410   // `sctp_mid()` if set. Called as part of setting the local description.
411   void StartSctpTransport(int local_port,
412                           int remote_port,
413                           int max_message_size) override;
414 
415   // Returns the CryptoOptions for this PeerConnection. This will always
416   // return the RTCConfiguration.crypto_options if set and will only default
417   // back to the PeerConnectionFactory settings if nothing was set.
418   CryptoOptions GetCryptoOptions() override;
419 
420   // Internal implementation for AddTransceiver family of methods. If
421   // `fire_callback` is set, fires OnRenegotiationNeeded callback if successful.
422   RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>> AddTransceiver(
423       cricket::MediaType media_type,
424       rtc::scoped_refptr<MediaStreamTrackInterface> track,
425       const RtpTransceiverInit& init,
426       bool fire_callback = true) override;
427 
428   // Returns rtp transport, result can not be nullptr.
429   RtpTransportInternal* GetRtpTransport(const std::string& mid);
430 
431   // Returns true if SRTP (either using DTLS-SRTP or SDES) is required by
432   // this session.
433   bool SrtpRequired() const override;
434 
435   bool SetupDataChannelTransport_n(const std::string& mid) override
436       RTC_RUN_ON(network_thread());
437   void TeardownDataChannelTransport_n() override RTC_RUN_ON(network_thread());
438 
trials()439   const FieldTrialsView& trials() const override { return *trials_; }
440 
441   bool ConfiguredForMedia() const;
442 
443   // Functions made public for testing.
ReturnHistogramVeryQuicklyForTesting()444   void ReturnHistogramVeryQuicklyForTesting() {
445     RTC_DCHECK_RUN_ON(signaling_thread());
446     return_histogram_very_quickly_ = true;
447   }
448   void RequestUsagePatternReportForTesting();
449 
450  protected:
451   // Available for rtc::scoped_refptr creation
452   PeerConnection(rtc::scoped_refptr<ConnectionContext> context,
453                  const PeerConnectionFactoryInterface::Options& options,
454                  bool is_unified_plan,
455                  std::unique_ptr<RtcEventLog> event_log,
456                  std::unique_ptr<Call> call,
457                  PeerConnectionDependencies& dependencies,
458                  bool dtls_enabled);
459 
460   ~PeerConnection() override;
461 
462  private:
463   RTCError Initialize(
464       const PeerConnectionInterface::RTCConfiguration& configuration,
465       PeerConnectionDependencies dependencies);
466   JsepTransportController* InitializeTransportController_n(
467       const RTCConfiguration& configuration,
468       const PeerConnectionDependencies& dependencies)
469       RTC_RUN_ON(network_thread());
470 
471   rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
472   FindTransceiverBySender(rtc::scoped_refptr<RtpSenderInterface> sender)
473       RTC_RUN_ON(signaling_thread());
474 
475   void SetStandardizedIceConnectionState(
476       PeerConnectionInterface::IceConnectionState new_state)
477       RTC_RUN_ON(signaling_thread());
478   void SetConnectionState(
479       PeerConnectionInterface::PeerConnectionState new_state)
480       RTC_RUN_ON(signaling_thread());
481 
482   // Called any time the IceGatheringState changes.
483   void OnIceGatheringChange(IceGatheringState new_state)
484       RTC_RUN_ON(signaling_thread());
485   // New ICE candidate has been gathered.
486   void OnIceCandidate(std::unique_ptr<IceCandidateInterface> candidate)
487       RTC_RUN_ON(signaling_thread());
488   // Gathering of an ICE candidate failed.
489   void OnIceCandidateError(const std::string& address,
490                            int port,
491                            const std::string& url,
492                            int error_code,
493                            const std::string& error_text)
494       RTC_RUN_ON(signaling_thread());
495   // Some local ICE candidates have been removed.
496   void OnIceCandidatesRemoved(const std::vector<cricket::Candidate>& candidates)
497       RTC_RUN_ON(signaling_thread());
498 
499   void OnSelectedCandidatePairChanged(
500       const cricket::CandidatePairChangeEvent& event)
501       RTC_RUN_ON(signaling_thread());
502 
503   void OnNegotiationNeeded();
504 
505   // Called when first configuring the port allocator.
506   struct InitializePortAllocatorResult {
507     bool enable_ipv6;
508   };
509   InitializePortAllocatorResult InitializePortAllocator_n(
510       const cricket::ServerAddresses& stun_servers,
511       const std::vector<cricket::RelayServerConfig>& turn_servers,
512       const RTCConfiguration& configuration);
513   // Called when SetConfiguration is called to apply the supported subset
514   // of the configuration on the network thread.
515   bool ReconfigurePortAllocator_n(
516       const cricket::ServerAddresses& stun_servers,
517       const std::vector<cricket::RelayServerConfig>& turn_servers,
518       IceTransportsType type,
519       int candidate_pool_size,
520       PortPrunePolicy turn_port_prune_policy,
521       webrtc::TurnCustomizer* turn_customizer,
522       absl::optional<int> stun_candidate_keepalive_interval,
523       bool have_local_description);
524 
525   // Starts output of an RTC event log to the given output object.
526   // This function should only be called from the worker thread.
527   bool StartRtcEventLog_w(std::unique_ptr<RtcEventLogOutput> output,
528                           int64_t output_period_ms);
529 
530   // Stops recording an RTC event log.
531   // This function should only be called from the worker thread.
532   void StopRtcEventLog_w();
533 
534   // Returns true and the TransportInfo of the given `content_name`
535   // from `description`. Returns false if it's not available.
536   static bool GetTransportDescription(
537       const cricket::SessionDescription* description,
538       const std::string& content_name,
539       cricket::TransportDescription* info);
540 
541   // Returns the media index for a local ice candidate given the content name.
542   // Returns false if the local session description does not have a media
543   // content called  `content_name`.
544   bool GetLocalCandidateMediaIndex(const std::string& content_name,
545                                    int* sdp_mline_index)
546       RTC_RUN_ON(signaling_thread());
547 
548   // JsepTransportController signal handlers.
549   void OnTransportControllerConnectionState(cricket::IceConnectionState state)
550       RTC_RUN_ON(signaling_thread());
551   void OnTransportControllerGatheringState(cricket::IceGatheringState state)
552       RTC_RUN_ON(signaling_thread());
553   void OnTransportControllerCandidatesGathered(
554       const std::string& transport_name,
555       const std::vector<cricket::Candidate>& candidates)
556       RTC_RUN_ON(signaling_thread());
557   void OnTransportControllerCandidateError(
558       const cricket::IceCandidateErrorEvent& event)
559       RTC_RUN_ON(signaling_thread());
560   void OnTransportControllerCandidatesRemoved(
561       const std::vector<cricket::Candidate>& candidates)
562       RTC_RUN_ON(signaling_thread());
563   void OnTransportControllerCandidateChanged(
564       const cricket::CandidatePairChangeEvent& event)
565       RTC_RUN_ON(signaling_thread());
566   void OnTransportControllerDtlsHandshakeError(rtc::SSLHandshakeError error);
567 
568   // Invoked when TransportController connection completion is signaled.
569   // Reports stats for all transports in use.
570   void ReportTransportStats() RTC_RUN_ON(network_thread());
571 
572   // Gather the usage of IPv4/IPv6 as best connection.
573   static void ReportBestConnectionState(const cricket::TransportStats& stats);
574 
575   static void ReportNegotiatedCiphers(
576       bool dtls_enabled,
577       const cricket::TransportStats& stats,
578       const std::set<cricket::MediaType>& media_types);
579   void ReportIceCandidateCollected(const cricket::Candidate& candidate)
580       RTC_RUN_ON(signaling_thread());
581 
582   void ReportUsagePattern() const RTC_RUN_ON(signaling_thread());
583 
584   void ReportRemoteIceCandidateAdded(const cricket::Candidate& candidate);
585 
586   // JsepTransportController::Observer override.
587   //
588   // Called by `transport_controller_` when processing transport information
589   // from a session description, and the mapping from m= sections to transports
590   // changed (as a result of BUNDLE negotiation, or m= sections being
591   // rejected).
592   bool OnTransportChanged(
593       const std::string& mid,
594       RtpTransportInternal* rtp_transport,
595       rtc::scoped_refptr<DtlsTransport> dtls_transport,
596       DataChannelTransportInterface* data_channel_transport) override;
597 
598   std::function<void(const rtc::CopyOnWriteBuffer& packet,
599                      int64_t packet_time_us)>
600   InitializeRtcpCallback();
601 
602   const rtc::scoped_refptr<ConnectionContext> context_;
603   // Field trials active for this PeerConnection is the first of:
604   // a) Specified in PeerConnectionDependencies (owned).
605   // b) Accessed via ConnectionContext (e.g PeerConnectionFactoryDependencies>
606   // c) Created as Default (FieldTrialBasedConfig).
607   const webrtc::AlwaysValidPointer<const FieldTrialsView, FieldTrialBasedConfig>
608       trials_;
609   const PeerConnectionFactoryInterface::Options options_;
610   PeerConnectionObserver* observer_ RTC_GUARDED_BY(signaling_thread()) =
611       nullptr;
612 
613   const bool is_unified_plan_;
614 
615   // The EventLog needs to outlive `call_` (and any other object that uses it).
616   std::unique_ptr<RtcEventLog> event_log_ RTC_GUARDED_BY(worker_thread());
617 
618   // Points to the same thing as `event_log_`. Since it's const, we may read the
619   // pointer (but not touch the object) from any thread.
620   RtcEventLog* const event_log_ptr_ RTC_PT_GUARDED_BY(worker_thread());
621 
622   IceConnectionState ice_connection_state_ RTC_GUARDED_BY(signaling_thread()) =
623       kIceConnectionNew;
624   PeerConnectionInterface::IceConnectionState standardized_ice_connection_state_
625       RTC_GUARDED_BY(signaling_thread()) = kIceConnectionNew;
626   PeerConnectionInterface::PeerConnectionState connection_state_
627       RTC_GUARDED_BY(signaling_thread()) = PeerConnectionState::kNew;
628 
629   IceGatheringState ice_gathering_state_ RTC_GUARDED_BY(signaling_thread()) =
630       kIceGatheringNew;
631   PeerConnectionInterface::RTCConfiguration configuration_
632       RTC_GUARDED_BY(signaling_thread());
633 
634   const std::unique_ptr<AsyncDnsResolverFactoryInterface>
635       async_dns_resolver_factory_;
636   std::unique_ptr<cricket::PortAllocator>
637       port_allocator_;  // TODO(bugs.webrtc.org/9987): Accessed on both
638                         // signaling and network thread.
639   const std::unique_ptr<webrtc::IceTransportFactory>
640       ice_transport_factory_;  // TODO(bugs.webrtc.org/9987): Accessed on the
641                                // signaling thread but the underlying raw
642                                // pointer is given to
643                                // `jsep_transport_controller_` and used on the
644                                // network thread.
645   const std::unique_ptr<rtc::SSLCertificateVerifier> tls_cert_verifier_
646       RTC_GUARDED_BY(network_thread());
647 
648   // The unique_ptr belongs to the worker thread, but the Call object manages
649   // its own thread safety.
650   std::unique_ptr<Call> call_ RTC_GUARDED_BY(worker_thread());
651   ScopedTaskSafety signaling_thread_safety_;
652   rtc::scoped_refptr<PendingTaskSafetyFlag> network_thread_safety_;
653   rtc::scoped_refptr<PendingTaskSafetyFlag> worker_thread_safety_;
654 
655   // Points to the same thing as `call_`. Since it's const, we may read the
656   // pointer from any thread.
657   // TODO(bugs.webrtc.org/11992): Remove this workaround (and potential dangling
658   // pointer).
659   Call* const call_ptr_;
660 
661   std::unique_ptr<LegacyStatsCollector> legacy_stats_
662       RTC_GUARDED_BY(signaling_thread());  // A pointer is passed to senders_
663   rtc::scoped_refptr<RTCStatsCollector> stats_collector_
664       RTC_GUARDED_BY(signaling_thread());
665 
666   const std::string session_id_;
667 
668   // The transport controller is set and used on the network thread.
669   // Some functions pass the value of the transport_controller_ pointer
670   // around as arguments while running on the signaling thread; these
671   // use the transport_controller_copy.
672   std::unique_ptr<JsepTransportController> transport_controller_
673       RTC_GUARDED_BY(network_thread());
674   JsepTransportController* transport_controller_copy_
675       RTC_GUARDED_BY(signaling_thread()) = nullptr;
676 
677   // `sctp_mid_` is the content name (MID) in SDP.
678   // Note: this is used as the data channel MID by both SCTP and data channel
679   // transports.  It is set when either transport is initialized and unset when
680   // both transports are deleted.
681   // There is one copy on the signaling thread and another copy on the
682   // networking thread. Changes are always initiated from the signaling
683   // thread, but applied first on the networking thread via an invoke().
684   absl::optional<std::string> sctp_mid_s_ RTC_GUARDED_BY(signaling_thread());
685   absl::optional<std::string> sctp_mid_n_ RTC_GUARDED_BY(network_thread());
686   std::string sctp_transport_name_s_ RTC_GUARDED_BY(signaling_thread());
687 
688   // The machinery for handling offers and answers. Const after initialization.
689   std::unique_ptr<SdpOfferAnswerHandler> sdp_handler_
690       RTC_GUARDED_BY(signaling_thread()) RTC_PT_GUARDED_BY(signaling_thread());
691 
692   const bool dtls_enabled_;
693 
694   UsagePattern usage_pattern_ RTC_GUARDED_BY(signaling_thread());
695   bool return_histogram_very_quickly_ RTC_GUARDED_BY(signaling_thread()) =
696       false;
697 
698   // The DataChannelController is accessed from both the signaling thread
699   // and networking thread. It is a thread-aware object.
700   DataChannelController data_channel_controller_;
701 
702   // Machinery for handling messages posted to oneself
703   PeerConnectionMessageHandler message_handler_
704       RTC_GUARDED_BY(signaling_thread());
705 
706   // Administration of senders, receivers and transceivers
707   // Accessed on both signaling and network thread. Const after Initialize().
708   std::unique_ptr<RtpTransmissionManager> rtp_manager_;
709 
710   // Did the connectionState ever change to `connected`?
711   // Used to gather metrics only the first such state change.
712   bool was_ever_connected_ RTC_GUARDED_BY(signaling_thread()) = false;
713 
714   // This variable needs to be the last one in the class.
715   rtc::WeakPtrFactory<PeerConnection> weak_factory_;
716 };
717 
718 }  // namespace webrtc
719 
720 #endif  // PC_PEER_CONNECTION_H_
721