peer_connection_interface.h (74599B)
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 // This file contains the PeerConnection interface as defined in 12 // https://w3c.github.io/webrtc-pc/#peer-to-peer-connections 13 // 14 // The PeerConnectionFactory class provides factory methods to create 15 // PeerConnection, MediaStream and MediaStreamTrack objects. 16 // 17 // The following steps are needed to setup a typical call using WebRTC: 18 // 19 // 1. Create a PeerConnectionFactoryInterface. Check constructors for more 20 // information about input parameters. 21 // 22 // 2. Create a PeerConnection object. Provide a configuration struct which 23 // points to STUN and/or TURN servers used to generate ICE candidates, and 24 // provide an object that implements the PeerConnectionObserver interface, 25 // which is used to receive callbacks from the PeerConnection. 26 // 27 // 3. Create local MediaStreamTracks using the PeerConnectionFactory and add 28 // them to PeerConnection by calling AddTrack (or legacy method, AddStream). 29 // 30 // 4. Create an offer, call SetLocalDescription with it, serialize it, and send 31 // it to the remote peer 32 // 33 // 5. Once an ICE candidate has been gathered, the PeerConnection will call the 34 // observer function OnIceCandidate. The candidates must also be serialized and 35 // sent to the remote peer. 36 // 37 // 6. Once an answer is received from the remote peer, call 38 // SetRemoteDescription with the remote answer. 39 // 40 // 7. Once a remote candidate is received from the remote peer, provide it to 41 // the PeerConnection by calling AddIceCandidate. 42 // 43 // The receiver of a call (assuming the application is "call"-based) can decide 44 // to accept or reject the call; this decision will be taken by the application, 45 // not the PeerConnection. 46 // 47 // If the application decides to accept the call, it should: 48 // 49 // 1. Create PeerConnectionFactoryInterface if it doesn't exist. 50 // 51 // 2. Create a new PeerConnection. 52 // 53 // 3. Provide the remote offer to the new PeerConnection object by calling 54 // SetRemoteDescription. 55 // 56 // 4. Generate an answer to the remote offer by calling CreateAnswer and send it 57 // back to the remote peer. 58 // 59 // 5. Provide the local answer to the new PeerConnection by calling 60 // SetLocalDescription with the answer. 61 // 62 // 6. Provide the remote ICE candidates by calling AddIceCandidate. 63 // 64 // 7. Once a candidate has been gathered, the PeerConnection will call the 65 // observer function OnIceCandidate. Send these candidates to the remote peer. 66 67 #ifndef API_PEER_CONNECTION_INTERFACE_H_ 68 #define API_PEER_CONNECTION_INTERFACE_H_ 69 // IWYU pragma: no_include "pc/media_factory.h" 70 71 #include <stdint.h> 72 #include <stdio.h> 73 74 #include <functional> 75 #include <memory> 76 #include <optional> 77 #include <string> 78 #include <vector> 79 80 #include "absl/base/attributes.h" 81 #include "absl/strings/string_view.h" 82 #include "api/adaptation/resource.h" 83 #include "api/async_dns_resolver.h" 84 #include "api/audio/audio_device.h" 85 #include "api/audio/audio_mixer.h" 86 #include "api/audio/audio_processing.h" 87 #include "api/audio_codecs/audio_decoder_factory.h" 88 #include "api/audio_codecs/audio_encoder_factory.h" 89 #include "api/audio_options.h" 90 #include "api/crypto/crypto_options.h" 91 #include "api/data_channel_event_observer_interface.h" 92 #include "api/data_channel_interface.h" 93 #include "api/dtls_transport_interface.h" 94 #include "api/environment/environment.h" 95 #include "api/fec_controller.h" 96 #include "api/field_trials_view.h" 97 #include "api/ice_transport_interface.h" 98 #include "api/jsep.h" 99 #include "api/legacy_stats_types.h" 100 #include "api/local_network_access_permission.h" 101 #include "api/media_stream_interface.h" 102 #include "api/media_types.h" 103 #include "api/metronome/metronome.h" 104 #include "api/neteq/neteq_factory.h" 105 #include "api/network_state_predictor.h" 106 #include "api/packet_socket_factory.h" 107 #include "api/rtc_error.h" 108 #include "api/rtc_event_log/rtc_event_log_factory_interface.h" 109 #include "api/rtc_event_log_output.h" 110 #include "api/rtp_parameters.h" 111 #include "api/rtp_receiver_interface.h" 112 #include "api/rtp_sender_interface.h" 113 #include "api/rtp_transceiver_interface.h" 114 #include "api/scoped_refptr.h" 115 #include "api/sctp_transport_interface.h" 116 #include "api/set_local_description_observer_interface.h" 117 #include "api/set_remote_description_observer_interface.h" 118 #include "api/stats/rtc_stats_collector_callback.h" 119 #include "api/transport/bandwidth_estimation_settings.h" 120 #include "api/transport/bitrate_settings.h" 121 #include "api/transport/enums.h" 122 #include "api/transport/network_control.h" 123 #include "api/transport/sctp_transport_factory_interface.h" 124 #include "api/turn_customizer.h" 125 #include "api/video/video_bitrate_allocator_factory.h" 126 #include "api/video_codecs/video_decoder_factory.h" 127 #include "api/video_codecs/video_encoder_factory.h" 128 #include "media/base/media_config.h" 129 // TODO(bugs.webrtc.org/7447): We plan to provide a way to let applications 130 // inject a PacketSocketFactory and/or NetworkManager, and not expose 131 // PortAllocator in the PeerConnection api. 132 #include "api/audio/audio_frame_processor.h" 133 #include "api/ref_count.h" 134 #include "api/units/time_delta.h" 135 #include "p2p/base/port.h" 136 #include "p2p/base/port_allocator.h" 137 #include "rtc_base/checks.h" 138 #include "rtc_base/network.h" 139 #include "rtc_base/network_constants.h" 140 #include "rtc_base/network_monitor_factory.h" 141 #include "rtc_base/rtc_certificate.h" 142 #include "rtc_base/rtc_certificate_generator.h" 143 #include "rtc_base/socket_factory.h" 144 #include "rtc_base/ssl_certificate.h" 145 #include "rtc_base/ssl_stream_adapter.h" 146 #include "rtc_base/system/rtc_export.h" 147 #include "rtc_base/thread.h" 148 149 namespace webrtc { 150 // IWYU pragma: begin_keep 151 // MediaFactory class definition is not part of the api. 152 class MediaFactory; 153 154 // IWYU pragma: end_keep 155 // MediaStream container interface. 156 class StreamCollectionInterface : public RefCountInterface { 157 public: 158 // TODO(ronghuawu): Update the function names to c++ style, e.g. find -> Find. 159 virtual size_t count() = 0; 160 virtual MediaStreamInterface* at(size_t index) = 0; 161 virtual MediaStreamInterface* find(const std::string& label) = 0; 162 virtual MediaStreamTrackInterface* FindAudioTrack(const std::string& id) = 0; 163 virtual MediaStreamTrackInterface* FindVideoTrack(const std::string& id) = 0; 164 165 protected: 166 // Dtor protected as objects shouldn't be deleted via this interface. 167 ~StreamCollectionInterface() override = default; 168 }; 169 170 class StatsObserver : public RefCountInterface { 171 public: 172 virtual void OnComplete(const StatsReports& reports) = 0; 173 174 protected: 175 ~StatsObserver() override = default; 176 }; 177 178 enum class SdpSemantics { 179 // TODO(https://crbug.com/webrtc/13528): Remove support for kPlanB. 180 kPlanB_DEPRECATED, 181 kPlanB [[deprecated]] = kPlanB_DEPRECATED, 182 kUnifiedPlan, 183 }; 184 185 class RTC_EXPORT PeerConnectionInterface : public RefCountInterface { 186 public: 187 // See https://w3c.github.io/webrtc-pc/#dom-rtcsignalingstate 188 enum SignalingState { 189 kStable, 190 kHaveLocalOffer, 191 kHaveLocalPrAnswer, 192 kHaveRemoteOffer, 193 kHaveRemotePrAnswer, 194 kClosed, 195 }; 196 static constexpr absl::string_view AsString(SignalingState); 197 198 // See https://w3c.github.io/webrtc-pc/#dom-rtcicegatheringstate 199 enum IceGatheringState { 200 kIceGatheringNew, 201 kIceGatheringGathering, 202 kIceGatheringComplete 203 }; 204 static constexpr absl::string_view AsString(IceGatheringState state); 205 206 // See https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnectionstate 207 enum class PeerConnectionState { 208 kNew, 209 kConnecting, 210 kConnected, 211 kDisconnected, 212 kFailed, 213 kClosed, 214 }; 215 static constexpr absl::string_view AsString(PeerConnectionState state); 216 217 // See https://w3c.github.io/webrtc-pc/#dom-rtciceconnectionstate 218 enum IceConnectionState { 219 kIceConnectionNew, 220 kIceConnectionChecking, 221 kIceConnectionConnected, 222 kIceConnectionCompleted, 223 kIceConnectionFailed, 224 kIceConnectionDisconnected, 225 kIceConnectionClosed, 226 kIceConnectionMax, 227 }; 228 static constexpr absl::string_view AsString(IceConnectionState state); 229 template <typename Sink> 230 void AbslStringify(Sink& sink, IceConnectionState state) { 231 sink.Append(AsString(state)); 232 } 233 234 // TLS certificate policy. 235 enum TlsCertPolicy { 236 // For TLS based protocols, ensure the connection is secure by not 237 // circumventing certificate validation. 238 kTlsCertPolicySecure, 239 // For TLS based protocols, disregard security completely by skipping 240 // certificate validation. This is insecure and should never be used unless 241 // security is irrelevant in that particular context. 242 kTlsCertPolicyInsecureNoCheck, 243 }; 244 245 struct RTC_EXPORT IceServer { 246 IceServer(); 247 IceServer(const IceServer&); 248 ~IceServer(); 249 250 // TODO(jbauch): Remove uri when all code using it has switched to urls. 251 // List of URIs associated with this server. Valid formats are described 252 // in RFC7064 and RFC7065, and more may be added in the future. The "host" 253 // part of the URI may contain either an IP address or a hostname. 254 std::string uri; 255 std::vector<std::string> urls; 256 std::string username; 257 std::string password; 258 TlsCertPolicy tls_cert_policy = kTlsCertPolicySecure; 259 // If the URIs in `urls` only contain IP addresses, this field can be used 260 // to indicate the hostname, which may be necessary for TLS (using the SNI 261 // extension). If `urls` itself contains the hostname, this isn't 262 // necessary. 263 std::string hostname; 264 // List of protocols to be used in the TLS ALPN extension. 265 std::vector<std::string> tls_alpn_protocols; 266 // List of elliptic curves to be used in the TLS elliptic curves extension. 267 std::vector<std::string> tls_elliptic_curves; 268 269 bool operator==(const IceServer& o) const { 270 return uri == o.uri && urls == o.urls && username == o.username && 271 password == o.password && tls_cert_policy == o.tls_cert_policy && 272 hostname == o.hostname && 273 tls_alpn_protocols == o.tls_alpn_protocols && 274 tls_elliptic_curves == o.tls_elliptic_curves; 275 } 276 bool operator!=(const IceServer& o) const { return !(*this == o); } 277 }; 278 typedef std::vector<IceServer> IceServers; 279 280 enum IceTransportsType { 281 // TODO(pthatcher): Rename these kTransporTypeXXX, but update 282 // Chromium at the same time. 283 kNone, 284 kRelay, 285 kNoHost, 286 kAll 287 }; 288 289 // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-24#section-4.1.1 290 enum BundlePolicy { 291 kBundlePolicyBalanced, 292 kBundlePolicyMaxBundle, 293 kBundlePolicyMaxCompat 294 }; 295 296 // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-24#section-4.1.1 297 enum RtcpMuxPolicy { 298 kRtcpMuxPolicyNegotiate, 299 kRtcpMuxPolicyRequire, 300 }; 301 302 enum TcpCandidatePolicy { 303 kTcpCandidatePolicyEnabled, 304 kTcpCandidatePolicyDisabled 305 }; 306 307 enum CandidateNetworkPolicy { 308 kCandidateNetworkPolicyAll, 309 kCandidateNetworkPolicyLowCost 310 }; 311 312 enum ContinualGatheringPolicy { GATHER_ONCE, GATHER_CONTINUALLY }; 313 314 struct PortAllocatorConfig { 315 // For min_port and max_port, 0 means not specified. 316 int min_port = 0; 317 int max_port = 0; 318 uint32_t flags = 0; // Same as kDefaultPortAllocatorFlags. 319 }; 320 321 enum class RTCConfigurationType { 322 // A configuration that is safer to use, despite not having the best 323 // performance. Currently this is the default configuration. 324 kSafe, 325 // An aggressive configuration that has better performance, although it 326 // may be riskier and may need extra support in the application. 327 kAggressive 328 }; 329 330 // TODO(hbos): Change into class with private data and public getters. 331 // TODO(nisse): In particular, accessing fields directly from an 332 // application is brittle, since the organization mirrors the 333 // organization of the implementation, which isn't stable. So we 334 // need getters and setters at least for fields which applications 335 // are interested in. 336 struct RTC_EXPORT RTCConfiguration { 337 // This struct is subject to reorganization, both for naming 338 // consistency, and to group settings to match where they are used 339 // in the implementation. To do that, we need getter and setter 340 // methods for all settings which are of interest to applications, 341 // Chrome in particular. 342 343 RTCConfiguration(); 344 RTCConfiguration(const RTCConfiguration&); 345 explicit RTCConfiguration(RTCConfigurationType type); 346 ~RTCConfiguration(); 347 348 bool operator==(const RTCConfiguration& o) const; 349 bool operator!=(const RTCConfiguration& o) const; 350 351 bool dscp() const { return media_config.enable_dscp; } 352 void set_dscp(bool enable) { media_config.enable_dscp = enable; } 353 354 bool stats_timestamp_with_environment_clock() const { 355 return media_config.stats_timestamp_with_environment_clock; 356 } 357 void set_stats_timestamp_with_environment_clock(bool enable) { 358 media_config.stats_timestamp_with_environment_clock = enable; 359 } 360 361 bool cpu_adaptation() const { 362 return media_config.video.enable_cpu_adaptation; 363 } 364 void set_cpu_adaptation(bool enable) { 365 media_config.video.enable_cpu_adaptation = enable; 366 } 367 368 bool suspend_below_min_bitrate() const { 369 return media_config.video.suspend_below_min_bitrate; 370 } 371 void set_suspend_below_min_bitrate(bool enable) { 372 media_config.video.suspend_below_min_bitrate = enable; 373 } 374 375 bool prerenderer_smoothing() const { 376 return media_config.video.enable_prerenderer_smoothing; 377 } 378 void set_prerenderer_smoothing(bool enable) { 379 media_config.video.enable_prerenderer_smoothing = enable; 380 } 381 382 bool experiment_cpu_load_estimator() const { 383 return media_config.video.experiment_cpu_load_estimator; 384 } 385 void set_experiment_cpu_load_estimator(bool enable) { 386 media_config.video.experiment_cpu_load_estimator = enable; 387 } 388 389 int audio_rtcp_report_interval_ms() const { 390 return media_config.audio.rtcp_report_interval_ms; 391 } 392 void set_audio_rtcp_report_interval_ms(int audio_rtcp_report_interval_ms) { 393 media_config.audio.rtcp_report_interval_ms = 394 audio_rtcp_report_interval_ms; 395 } 396 397 int video_rtcp_report_interval_ms() const { 398 return media_config.video.rtcp_report_interval_ms; 399 } 400 void set_video_rtcp_report_interval_ms(int video_rtcp_report_interval_ms) { 401 media_config.video.rtcp_report_interval_ms = 402 video_rtcp_report_interval_ms; 403 } 404 405 // Settings for the port allcoator. Applied only if the port allocator is 406 // created by PeerConnectionFactory, not if it is injected with 407 // PeerConnectionDependencies 408 int min_port() const { return port_allocator_config.min_port; } 409 void set_min_port(int port) { port_allocator_config.min_port = port; } 410 int max_port() const { return port_allocator_config.max_port; } 411 void set_max_port(int port) { port_allocator_config.max_port = port; } 412 uint32_t port_allocator_flags() { return port_allocator_config.flags; } 413 void set_port_allocator_flags(uint32_t flags) { 414 port_allocator_config.flags = flags; 415 } 416 417 static const int kUndefined = -1; 418 // Default maximum number of packets in the audio jitter buffer. 419 static const int kAudioJitterBufferMaxPackets = 200; 420 // ICE connection receiving timeout for aggressive configuration. 421 static const int kAggressiveIceConnectionReceivingTimeout = 1000; 422 423 //////////////////////////////////////////////////////////////////////// 424 // The below few fields mirror the standard RTCConfiguration dictionary: 425 // https://w3c.github.io/webrtc-pc/#rtcconfiguration-dictionary 426 //////////////////////////////////////////////////////////////////////// 427 428 // TODO(pthatcher): Rename this ice_servers, but update Chromium 429 // at the same time. 430 IceServers servers; 431 // TODO(pthatcher): Rename this ice_transport_type, but update 432 // Chromium at the same time. 433 IceTransportsType type = kAll; 434 BundlePolicy bundle_policy = kBundlePolicyBalanced; 435 RtcpMuxPolicy rtcp_mux_policy = kRtcpMuxPolicyRequire; 436 std::vector<scoped_refptr<RTCCertificate>> certificates; 437 int ice_candidate_pool_size = 0; 438 439 ////////////////////////////////////////////////////////////////////////// 440 // The below fields correspond to constraints from the deprecated 441 // constraints interface for constructing a PeerConnection. 442 // 443 // std::optional fields can be "missing", in which case the implementation 444 // default will be used. 445 ////////////////////////////////////////////////////////////////////////// 446 447 // If set to true, don't gather IPv6 ICE candidates on Wi-Fi. 448 // Only intended to be used on specific devices. Certain phones disable IPv6 449 // when the screen is turned off and it would be better to just disable the 450 // IPv6 ICE candidates on Wi-Fi in those cases. 451 bool disable_ipv6_on_wifi = false; 452 453 // By default, the PeerConnection will use a limited number of IPv6 network 454 // interfaces, in order to avoid too many ICE candidate pairs being created 455 // and delaying ICE completion. 456 // 457 // Can be set to INT_MAX to effectively disable the limit. 458 int max_ipv6_networks = kDefaultMaxIPv6Networks; 459 460 // Exclude link-local network interfaces 461 // from consideration for gathering ICE candidates. 462 bool disable_link_local_networks = false; 463 464 // Minimum bitrate at which screencast video tracks will be encoded at. 465 // This means adding padding bits up to this bitrate, which can help 466 // when switching from a static scene to one with motion. 467 std::optional<int> screencast_min_bitrate; 468 469 ///////////////////////////////////////////////// 470 // The below fields are not part of the standard. 471 ///////////////////////////////////////////////// 472 473 // Can be used to disable TCP candidate generation. 474 TcpCandidatePolicy tcp_candidate_policy = kTcpCandidatePolicyEnabled; 475 476 // Can be used to avoid gathering candidates for a "higher cost" network, 477 // if a lower cost one exists. For example, if both Wi-Fi and cellular 478 // interfaces are available, this could be used to avoid using the cellular 479 // interface. 480 CandidateNetworkPolicy candidate_network_policy = 481 kCandidateNetworkPolicyAll; 482 483 // The maximum number of packets that can be stored in the NetEq audio 484 // jitter buffer. Can be reduced to lower tolerated audio latency. 485 int audio_jitter_buffer_max_packets = kAudioJitterBufferMaxPackets; 486 487 // Whether to use the NetEq "fast mode" which will accelerate audio quicker 488 // if it falls behind. 489 bool audio_jitter_buffer_fast_accelerate = false; 490 491 // The minimum delay in milliseconds for the audio jitter buffer. 492 int audio_jitter_buffer_min_delay_ms = 0; 493 494 // Timeout in milliseconds before an ICE candidate pair is considered to be 495 // "not receiving", after which a lower priority candidate pair may be 496 // selected. 497 int ice_connection_receiving_timeout = kUndefined; 498 499 // Interval in milliseconds at which an ICE "backup" candidate pair will be 500 // pinged. This is a candidate pair which is not actively in use, but may 501 // be switched to if the active candidate pair becomes unusable. 502 // 503 // This is relevant mainly to Wi-Fi/cell handoff; the application may not 504 // want this backup cellular candidate pair pinged frequently, since it 505 // consumes data/battery. 506 int ice_backup_candidate_pair_ping_interval = kUndefined; 507 508 // Can be used to enable continual gathering, which means new candidates 509 // will be gathered as network interfaces change. Note that if continual 510 // gathering is used, the candidate removal API should also be used, to 511 // avoid an ever-growing list of candidates. 512 ContinualGatheringPolicy continual_gathering_policy = GATHER_ONCE; 513 514 // If set to true, candidate pairs will be pinged in order of most likely 515 // to work (which means using a TURN server, generally), rather than in 516 // standard priority order. 517 bool prioritize_most_likely_ice_candidate_pairs = false; 518 519 // Implementation defined settings. A public member only for the benefit of 520 // the implementation. Applications must not access it directly, and should 521 // instead use provided accessor methods, e.g., set_cpu_adaptation. 522 struct MediaConfig media_config; 523 524 // If set to true, only one preferred TURN allocation will be used per 525 // network interface. UDP is preferred over TCP and IPv6 over IPv4. This 526 // can be used to cut down on the number of candidate pairings. 527 // Deprecated. TODO(webrtc:11026) Remove this flag once the downstream 528 // dependency is removed. 529 bool prune_turn_ports = false; 530 531 // The policy used to prune turn port. 532 PortPrunePolicy turn_port_prune_policy = NO_PRUNE; 533 534 PortPrunePolicy GetTurnPortPrunePolicy() const { 535 return prune_turn_ports ? PRUNE_BASED_ON_PRIORITY 536 : turn_port_prune_policy; 537 } 538 539 // If set to true, this means the ICE transport should presume TURN-to-TURN 540 // candidate pairs will succeed, even before a binding response is received. 541 // This can be used to optimize the initial connection time, since the DTLS 542 // handshake can begin immediately. 543 bool presume_writable_when_fully_relayed = false; 544 545 // If true, "renomination" will be added to the ice options in the transport 546 // description. 547 // See: https://tools.ietf.org/html/draft-thatcher-ice-renomination-00 548 bool enable_ice_renomination = false; 549 550 // If true, the ICE role is re-determined when the PeerConnection sets a 551 // local transport description that indicates an ICE restart. 552 // 553 // This is standard RFC5245 ICE behavior, but causes unnecessary role 554 // thrashing, so an application may wish to avoid it. This role 555 // re-determining was removed in ICEbis (ICE v2). 556 bool redetermine_role_on_ice_restart = true; 557 558 // This flag is only effective when `continual_gathering_policy` is 559 // GATHER_CONTINUALLY. 560 // 561 // If true, after the ICE transport type is changed such that new types of 562 // ICE candidates are allowed by the new transport type, e.g. from 563 // IceTransportsType::kRelay to IceTransportsType::kAll, candidates that 564 // have been gathered by the ICE transport but not matching the previous 565 // transport type and as a result not observed by PeerConnectionObserver, 566 // will be surfaced to the observer. 567 bool surface_ice_candidates_on_ice_transport_type_changed = false; 568 569 // The following fields define intervals in milliseconds at which ICE 570 // connectivity checks are sent. 571 // 572 // We consider ICE is "strongly connected" for an agent when there is at 573 // least one candidate pair that currently succeeds in connectivity check 574 // from its direction i.e. sending a STUN ping and receives a STUN ping 575 // response, AND all candidate pairs have sent a minimum number of pings for 576 // connectivity (this number is implementation-specific). Otherwise, ICE is 577 // considered in "weak connectivity". 578 // 579 // Note that the above notion of strong and weak connectivity is not defined 580 // in RFC 5245, and they apply to our current ICE implementation only. 581 // 582 // 1) ice_check_interval_strong_connectivity defines the interval applied to 583 // ALL candidate pairs when ICE is strongly connected, and it overrides the 584 // default value of this interval in the ICE implementation; 585 // 2) ice_check_interval_weak_connectivity defines the counterpart for ALL 586 // pairs when ICE is weakly connected, and it overrides the default value of 587 // this interval in the ICE implementation; 588 // 3) ice_check_min_interval defines the minimal interval (equivalently the 589 // maximum rate) that overrides the above two intervals when either of them 590 // is less. 591 std::optional<int> ice_check_interval_strong_connectivity; 592 std::optional<int> ice_check_interval_weak_connectivity; 593 std::optional<int> ice_check_min_interval; 594 595 // The min time period for which a candidate pair must wait for response to 596 // connectivity checks before it becomes unwritable. This parameter 597 // overrides the default value in the ICE implementation if set. 598 std::optional<int> ice_unwritable_timeout; 599 600 // The min number of connectivity checks that a candidate pair must sent 601 // without receiving response before it becomes unwritable. This parameter 602 // overrides the default value in the ICE implementation if set. 603 std::optional<int> ice_unwritable_min_checks; 604 605 // The min time period for which a candidate pair must wait for response to 606 // connectivity checks it becomes inactive. This parameter overrides the 607 // default value in the ICE implementation if set. 608 std::optional<int> ice_inactive_timeout; 609 610 // The interval in milliseconds at which STUN candidates will resend STUN 611 // binding requests to keep NAT bindings open. 612 std::optional<int> stun_candidate_keepalive_interval; 613 614 // Optional TurnCustomizer. 615 // With this class one can modify outgoing TURN messages. 616 // The object passed in must remain valid until PeerConnection::Close() is 617 // called. 618 TurnCustomizer* turn_customizer = nullptr; 619 620 // Preferred network interface. 621 // A candidate pair on a preferred network has a higher precedence in ICE 622 // than one on an un-preferred network, regardless of priority or network 623 // cost. 624 std::optional<AdapterType> network_preference; 625 626 // Configure the SDP semantics used by this PeerConnection. By default, this 627 // is Unified Plan which is compliant to the WebRTC 1.0 specification. It is 628 // possible to overrwite this to the deprecated Plan B SDP format, but note 629 // that kPlanB will be deleted at some future date, see 630 // https://crbug.com/webrtc/13528. 631 // 632 // kUnifiedPlan will cause the PeerConnection to create offers and answers 633 // with multiple m= sections where each m= section maps to one RtpSender and 634 // one RtpReceiver (an RtpTransceiver), either both audio or both video. 635 // This will also cause the PeerConnection to ignore all but the first 636 // a=ssrc lines that form a Plan B streams (if the PeerConnection is given 637 // Plan B SDP to process). 638 // 639 // kPlanB will cause the PeerConnection to create offers and answers with at 640 // most one audio and one video m= section with multiple RtpSenders and 641 // RtpReceivers specified as multiple a=ssrc lines within the section. This 642 // will also cause PeerConnection to ignore all but the first m= section of 643 // the same media type (if the PeerConnection is given Unified Plan SDP to 644 // process). 645 SdpSemantics sdp_semantics = SdpSemantics::kUnifiedPlan; 646 647 // TODO(bugs.webrtc.org/9891) - Move to crypto_options or remove. 648 // Actively reset the SRTP parameters whenever the DTLS transports 649 // underneath are reset for every offer/answer negotiation. 650 // This is only intended to be a workaround for crbug.com/835958 651 // WARNING: This would cause RTP/RTCP packets decryption failure if not used 652 // correctly. This flag will be deprecated soon. Do not rely on it. 653 bool active_reset_srtp_params = false; 654 655 // Defines advanced optional cryptographic settings related to SRTP and 656 // frame encryption for native WebRTC. 657 CryptoOptions crypto_options; 658 659 // Configure if we should include the SDP attribute extmap-allow-mixed in 660 // our offer on session level. 661 bool offer_extmap_allow_mixed = true; 662 663 // TURN logging identifier. 664 // This identifier is added to a TURN allocation 665 // and it intended to be used to be able to match client side 666 // logs with TURN server logs. It will not be added if it's an empty string. 667 std::string turn_logging_id; 668 669 // Added to be able to control rollout of this feature. 670 bool enable_implicit_rollback = false; 671 672 // The delay before doing a usage histogram report for long-lived 673 // PeerConnections. Used for testing only. 674 std::optional<int> report_usage_pattern_delay_ms; 675 676 // The ping interval (ms) when the connection is stable and writable. This 677 // parameter overrides the default value in the ICE implementation if set. 678 std::optional<int> stable_writable_connection_ping_interval_ms; 679 680 // Whether this PeerConnection will avoid VPNs (kAvoidVpn), prefer VPNs 681 // (kPreferVpn), only work over VPN (kOnlyUseVpn) or only work over non-VPN 682 // (kNeverUseVpn) interfaces. This controls which local interfaces the 683 // PeerConnection will prefer to connect over. Since VPN detection is not 684 // perfect, adherence to this preference cannot be guaranteed. 685 VpnPreference vpn_preference = VpnPreference::kDefault; 686 687 // List of address/length subnets that should be treated like 688 // VPN (in case webrtc fails to auto detect them). 689 std::vector<NetworkMask> vpn_list; 690 691 PortAllocatorConfig port_allocator_config; 692 693 // The burst interval of the pacer, see TaskQueuePacedSender constructor. 694 std::optional<TimeDelta> pacer_burst_interval; 695 696 // 697 // Don't forget to update operator== if adding something. 698 // 699 }; 700 701 // See: https://www.w3.org/TR/webrtc/#idl-def-rtcofferansweroptions 702 struct RTCOfferAnswerOptions { 703 static const int kUndefined = -1; 704 static const int kMaxOfferToReceiveMedia = 1; 705 706 // The default value for constraint offerToReceiveX:true. 707 static const int kOfferToReceiveMediaTrue = 1; 708 709 // These options are left as backwards compatibility for clients who need 710 // "Plan B" semantics. Clients who have switched to "Unified Plan" semantics 711 // should use the RtpTransceiver API (AddTransceiver) instead. 712 // 713 // offer_to_receive_X set to 1 will cause a media description to be 714 // generated in the offer, even if no tracks of that type have been added. 715 // Values greater than 1 are treated the same. 716 // 717 // If set to 0, the generated directional attribute will not include the 718 // "recv" direction (meaning it will be "sendonly" or "inactive". 719 int offer_to_receive_video = kUndefined; 720 int offer_to_receive_audio = kUndefined; 721 722 bool voice_activity_detection = true; 723 bool ice_restart = false; 724 725 // If true, will offer to BUNDLE audio/video/data together. Not to be 726 // confused with RTCP mux (multiplexing RTP and RTCP together). 727 bool use_rtp_mux = true; 728 729 // If true, "a=packetization:<payload_type> raw" attribute will be offered 730 // in the SDP for all video payload and accepted in the answer if offered. 731 bool raw_packetization_for_video = false; 732 733 // This will apply to all video tracks with a Plan B SDP offer/answer. 734 int num_simulcast_layers = 1; 735 736 // If true: Use SDP format from draft-ietf-mmusic-scdp-sdp-03 737 // If false: Use SDP format from draft-ietf-mmusic-sdp-sdp-26 or later 738 bool use_obsolete_sctp_sdp = false; 739 740 RTCOfferAnswerOptions() = default; 741 742 RTCOfferAnswerOptions(int offer_to_receive_video, 743 int offer_to_receive_audio, 744 bool voice_activity_detection, 745 bool ice_restart, 746 bool use_rtp_mux) 747 : offer_to_receive_video(offer_to_receive_video), 748 offer_to_receive_audio(offer_to_receive_audio), 749 voice_activity_detection(voice_activity_detection), 750 ice_restart(ice_restart), 751 use_rtp_mux(use_rtp_mux) {} 752 }; 753 754 // Used by GetStats to decide which stats to include in the stats reports. 755 // `kStatsOutputLevelStandard` includes the standard stats for Javascript API; 756 // `kStatsOutputLevelDebug` includes both the standard stats and additional 757 // stats for debugging purposes. 758 enum StatsOutputLevel { 759 kStatsOutputLevelStandard, 760 kStatsOutputLevelDebug, 761 }; 762 763 // Accessor methods to active local streams. 764 // This method is not supported with kUnifiedPlan semantics. Please use 765 // GetSenders() instead. 766 virtual scoped_refptr<StreamCollectionInterface> local_streams() = 0; 767 768 // Accessor methods to remote streams. 769 // This method is not supported with kUnifiedPlan semantics. Please use 770 // GetReceivers() instead. 771 virtual scoped_refptr<StreamCollectionInterface> remote_streams() = 0; 772 773 // Add a new MediaStream to be sent on this PeerConnection. 774 // Note that a SessionDescription negotiation is needed before the 775 // remote peer can receive the stream. 776 // 777 // This has been removed from the standard in favor of a track-based API. So, 778 // this is equivalent to simply calling AddTrack for each track within the 779 // stream, with the one difference that if "stream->AddTrack(...)" is called 780 // later, the PeerConnection will automatically pick up the new track. Though 781 // this functionality will be deprecated in the future. 782 // 783 // This method is not supported with kUnifiedPlan semantics. Please use 784 // AddTrack instead. 785 virtual bool AddStream(MediaStreamInterface* stream) = 0; 786 787 // Remove a MediaStream from this PeerConnection. 788 // Note that a SessionDescription negotiation is needed before the 789 // remote peer is notified. 790 // 791 // This method is not supported with kUnifiedPlan semantics. Please use 792 // RemoveTrack instead. 793 virtual void RemoveStream(MediaStreamInterface* stream) = 0; 794 795 // Add a new MediaStreamTrack to be sent on this PeerConnection, and return 796 // the newly created RtpSender. The RtpSender will be associated with the 797 // streams specified in the `stream_ids` list. 798 // 799 // Errors: 800 // - INVALID_PARAMETER: `track` is null, has a kind other than audio or video, 801 // or a sender already exists for the track. 802 // - INVALID_STATE: The PeerConnection is closed. 803 virtual RTCErrorOr<scoped_refptr<RtpSenderInterface>> AddTrack( 804 scoped_refptr<MediaStreamTrackInterface> track, 805 const std::vector<std::string>& stream_ids) = 0; 806 807 // Add a new MediaStreamTrack as above, but with an additional parameter, 808 // `init_send_encodings` : initial RtpEncodingParameters for RtpSender, 809 // similar to init_send_encodings in RtpTransceiverInit. 810 // Note that a new transceiver will always be created. 811 // 812 virtual RTCErrorOr<scoped_refptr<RtpSenderInterface>> AddTrack( 813 scoped_refptr<MediaStreamTrackInterface> track, 814 const std::vector<std::string>& stream_ids, 815 const std::vector<RtpEncodingParameters>& init_send_encodings) = 0; 816 817 // Removes the connection between a MediaStreamTrack and the PeerConnection. 818 // Stops sending on the RtpSender and marks the 819 // corresponding RtpTransceiver direction as no longer sending. 820 // https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-removetrack 821 // 822 // Errors: 823 // - INVALID_PARAMETER: `sender` is null or (Plan B only) the sender is not 824 // associated with this PeerConnection. 825 // - INVALID_STATE: PeerConnection is closed. 826 // 827 // Plan B semantics: Removes the RtpSender from this PeerConnection. 828 // 829 // TODO(bugs.webrtc.org/9534): Rename to RemoveTrack once the other signature 830 // is removed; remove default implementation once upstream is updated. 831 virtual RTCError RemoveTrackOrError( 832 scoped_refptr<RtpSenderInterface> /* sender */) { 833 RTC_CHECK_NOTREACHED(); 834 return RTCError(); 835 } 836 837 // AddTransceiver creates a new RtpTransceiver and adds it to the set of 838 // transceivers. Adding a transceiver will cause future calls to CreateOffer 839 // to add a media description for the corresponding transceiver. 840 // 841 // The initial value of `mid` in the returned transceiver is null. Setting a 842 // new session description may change it to a non-null value. 843 // 844 // https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-addtransceiver 845 // 846 // Optionally, an RtpTransceiverInit structure can be specified to configure 847 // the transceiver from construction. If not specified, the transceiver will 848 // default to having a direction of kSendRecv and not be part of any streams. 849 // 850 // These methods are only available when Unified Plan is enabled (see 851 // RTCConfiguration). 852 // 853 // Common errors: 854 // - INTERNAL_ERROR: The configuration does not have Unified Plan enabled. 855 856 // Adds a transceiver with a sender set to transmit the given track. The kind 857 // of the transceiver (and sender/receiver) will be derived from the kind of 858 // the track. 859 // Errors: 860 // - INVALID_PARAMETER: `track` is null. 861 virtual RTCErrorOr<scoped_refptr<RtpTransceiverInterface>> AddTransceiver( 862 scoped_refptr<MediaStreamTrackInterface> track) = 0; 863 virtual RTCErrorOr<scoped_refptr<RtpTransceiverInterface>> AddTransceiver( 864 scoped_refptr<MediaStreamTrackInterface> track, 865 const RtpTransceiverInit& init) = 0; 866 867 // Adds a transceiver with the given kind. Can either be 868 // MediaType::AUDIO or MediaType::VIDEO. Errors: 869 // - INVALID_PARAMETER: `media_type` is not MediaType::AUDIO or 870 // MediaType::VIDEO. 871 virtual RTCErrorOr<scoped_refptr<RtpTransceiverInterface>> AddTransceiver( 872 MediaType media_type) = 0; 873 virtual RTCErrorOr<scoped_refptr<RtpTransceiverInterface>> AddTransceiver( 874 MediaType media_type, 875 const RtpTransceiverInit& init) = 0; 876 877 // Creates a sender without a track. Can be used for "early media"/"warmup" 878 // use cases, where the application may want to negotiate video attributes 879 // before a track is available to send. 880 // 881 // The standard way to do this would be through "addTransceiver", but we 882 // don't support that API yet. 883 // 884 // `kind` must be "audio" or "video". 885 // 886 // `stream_id` is used to populate the msid attribute; if empty, one will 887 // be generated automatically. 888 // 889 // This method is not supported with kUnifiedPlan semantics. Please use 890 // AddTransceiver instead. 891 virtual scoped_refptr<RtpSenderInterface> CreateSender( 892 const std::string& kind, 893 const std::string& stream_id) = 0; 894 895 // If Plan B semantics are specified, gets all RtpSenders, created either 896 // through AddStream, AddTrack, or CreateSender. All senders of a specific 897 // media type share the same media description. 898 // 899 // If Unified Plan semantics are specified, gets the RtpSender for each 900 // RtpTransceiver. 901 virtual std::vector<scoped_refptr<RtpSenderInterface>> GetSenders() const = 0; 902 903 // If Plan B semantics are specified, gets all RtpReceivers created when a 904 // remote description is applied. All receivers of a specific media type share 905 // the same media description. It is also possible to have a media description 906 // with no associated RtpReceivers, if the directional attribute does not 907 // indicate that the remote peer is sending any media. 908 // 909 // If Unified Plan semantics are specified, gets the RtpReceiver for each 910 // RtpTransceiver. 911 virtual std::vector<scoped_refptr<RtpReceiverInterface>> GetReceivers() 912 const = 0; 913 914 // Get all RtpTransceivers, created either through AddTransceiver, AddTrack or 915 // by a remote description applied with SetRemoteDescription. 916 // 917 // Note: This method is only available when Unified Plan is enabled (see 918 // RTCConfiguration). 919 virtual std::vector<scoped_refptr<RtpTransceiverInterface>> GetTransceivers() 920 const = 0; 921 922 // The legacy non-compliant GetStats() API. This correspond to the 923 // callback-based version of getStats() in JavaScript. The returned metrics 924 // are UNDOCUMENTED and many of them rely on implementation-specific details. 925 // The goal is to DELETE THIS VERSION but we can't today because it is heavily 926 // relied upon by third parties. See https://crbug.com/822696. 927 // 928 // This version is wired up into Chrome. Any stats implemented are 929 // automatically exposed to the Web Platform. This has BYPASSED the Chrome 930 // release processes for years and lead to cross-browser incompatibility 931 // issues and web application reliance on Chrome-only behavior. 932 // 933 // This API is in "maintenance mode", serious regressions should be fixed but 934 // adding new stats is highly discouraged. 935 // 936 // TODO(hbos): Deprecate and remove this when third parties have migrated to 937 // the spec-compliant GetStats() API. https://crbug.com/822696 938 virtual bool GetStats(StatsObserver* observer, 939 MediaStreamTrackInterface* track, // Optional 940 StatsOutputLevel level) = 0; 941 // The spec-compliant GetStats() API. This correspond to the promise-based 942 // version of getStats() in JavaScript. Implementation status is described in 943 // api/stats/rtcstats_objects.h. For more details on stats, see spec: 944 // https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-getstats 945 // TODO(hbos): Takes shared ownership, use scoped_refptr<> instead. 946 // This requires stop overriding the current version in third party or making 947 // third party calls explicit to avoid ambiguity during switch. Make the 948 // future version abstract as soon as third party projects implement it. 949 virtual void GetStats(RTCStatsCollectorCallback* callback) = 0; 950 // Spec-compliant getStats() performing the stats selection algorithm with the 951 // sender. https://w3c.github.io/webrtc-pc/#dom-rtcrtpsender-getstats 952 virtual void GetStats(scoped_refptr<RtpSenderInterface> selector, 953 scoped_refptr<RTCStatsCollectorCallback> callback) = 0; 954 // Spec-compliant getStats() performing the stats selection algorithm with the 955 // receiver. https://w3c.github.io/webrtc-pc/#dom-rtcrtpreceiver-getstats 956 virtual void GetStats(scoped_refptr<RtpReceiverInterface> selector, 957 scoped_refptr<RTCStatsCollectorCallback> callback) = 0; 958 // Clear cached stats in the RTCStatsCollector. 959 virtual void ClearStatsCache() {} 960 961 // Create a data channel with the provided config, or default config if none 962 // is provided. Note that an offer/answer negotiation is still necessary 963 // before the data channel can be used. 964 // 965 // Also, calling CreateDataChannel is the only way to get a data "m=" section 966 // in SDP, so it should be done before CreateOffer is called, if the 967 // application plans to use data channels. 968 virtual RTCErrorOr<scoped_refptr<DataChannelInterface>> 969 CreateDataChannelOrError(const std::string& /* label */, 970 const DataChannelInit* /* config */) { 971 return RTCError(RTCErrorType::INTERNAL_ERROR, "dummy function called"); 972 } 973 // TODO(crbug.com/788659): Remove "virtual" below and default implementation 974 // above once mock in Chrome is fixed. 975 ABSL_DEPRECATED("Use CreateDataChannelOrError") 976 virtual scoped_refptr<DataChannelInterface> CreateDataChannel( 977 const std::string& label, 978 const DataChannelInit* config) { 979 auto result = CreateDataChannelOrError(label, config); 980 if (!result.ok()) { 981 return nullptr; 982 } else { 983 return result.MoveValue(); 984 } 985 } 986 987 // NOTE: For the following 6 methods, it's only safe to dereference the 988 // SessionDescriptionInterface on signaling_thread() (for example, calling 989 // ToString). 990 991 // Returns the more recently applied description; "pending" if it exists, and 992 // otherwise "current". See below. 993 virtual const SessionDescriptionInterface* local_description() const = 0; 994 virtual const SessionDescriptionInterface* remote_description() const = 0; 995 996 // A "current" description the one currently negotiated from a complete 997 // offer/answer exchange. 998 virtual const SessionDescriptionInterface* current_local_description() 999 const = 0; 1000 virtual const SessionDescriptionInterface* current_remote_description() 1001 const = 0; 1002 1003 // A "pending" description is one that's part of an incomplete offer/answer 1004 // exchange (thus, either an offer or a pranswer). Once the offer/answer 1005 // exchange is finished, the "pending" description will become "current". 1006 virtual const SessionDescriptionInterface* pending_local_description() 1007 const = 0; 1008 virtual const SessionDescriptionInterface* pending_remote_description() 1009 const = 0; 1010 1011 // Tells the PeerConnection that ICE should be restarted. This triggers a need 1012 // for negotiation and subsequent CreateOffer() calls will act as if 1013 // RTCOfferAnswerOptions::ice_restart is true. 1014 // https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-restartice 1015 virtual void RestartIce() = 0; 1016 1017 // Create a new offer. 1018 // The CreateSessionDescriptionObserver callback will be called when done. 1019 virtual void CreateOffer(CreateSessionDescriptionObserver* observer, 1020 const RTCOfferAnswerOptions& options) = 0; 1021 1022 // Create an answer to an offer. 1023 // The CreateSessionDescriptionObserver callback will be called when done. 1024 virtual void CreateAnswer(CreateSessionDescriptionObserver* observer, 1025 const RTCOfferAnswerOptions& options) = 0; 1026 1027 // Sets the local session description. 1028 // 1029 // According to spec, the local session description MUST be the same as was 1030 // returned by CreateOffer() or CreateAnswer() or else the operation should 1031 // fail. Our implementation however allows some amount of "SDP munging", but 1032 // please note that this is HIGHLY DISCOURAGED. If you do not intent to munge 1033 // SDP, the method below that doesn't take `desc` as an argument will create 1034 // the offer or answer for you. 1035 // 1036 // The observer is invoked as soon as the operation completes, which could be 1037 // before or after the SetLocalDescription() method has exited. 1038 virtual void SetLocalDescription( 1039 std::unique_ptr<SessionDescriptionInterface> /* desc */, 1040 scoped_refptr<SetLocalDescriptionObserverInterface> /* observer */) {} 1041 // Creates an offer or answer (depending on current signaling state) and sets 1042 // it as the local session description. 1043 // 1044 // The observer is invoked as soon as the operation completes, which could be 1045 // before or after the SetLocalDescription() method has exited. 1046 virtual void SetLocalDescription( 1047 scoped_refptr<SetLocalDescriptionObserverInterface> /* observer */) {} 1048 // Like SetLocalDescription() above, but the observer is invoked with a delay 1049 // after the operation completes. This helps avoid recursive calls by the 1050 // observer but also makes it possible for states to change in-between the 1051 // operation completing and the observer getting called. This makes them racy 1052 // for synchronizing peer connection states to the application. 1053 // TODO(https://crbug.com/webrtc/11798): Delete these methods in favor of the 1054 // ones taking SetLocalDescriptionObserverInterface as argument. 1055 virtual void SetLocalDescription(SetSessionDescriptionObserver* observer, 1056 SessionDescriptionInterface* desc) = 0; 1057 virtual void SetLocalDescription( 1058 SetSessionDescriptionObserver* /* observer */) {} 1059 1060 // Sets the remote session description. 1061 // 1062 // (Unlike "SDP munging" before SetLocalDescription(), modifying a remote 1063 // offer or answer is allowed by the spec.) 1064 // 1065 // The observer is invoked as soon as the operation completes, which could be 1066 // before or after the SetRemoteDescription() method has exited. 1067 virtual void SetRemoteDescription( 1068 std::unique_ptr<SessionDescriptionInterface> desc, 1069 scoped_refptr<SetRemoteDescriptionObserverInterface> observer) = 0; 1070 // Like SetRemoteDescription() above, but the observer is invoked with a delay 1071 // after the operation completes. This helps avoid recursive calls by the 1072 // observer but also makes it possible for states to change in-between the 1073 // operation completing and the observer getting called. This makes them racy 1074 // for synchronizing peer connection states to the application. 1075 // TODO(https://crbug.com/webrtc/11798): Delete this method in favor of the 1076 // ones taking SetRemoteDescriptionObserverInterface as argument. 1077 virtual void SetRemoteDescription( 1078 SetSessionDescriptionObserver* /* observer */, 1079 SessionDescriptionInterface* /* desc */) {} 1080 1081 // According to spec, we must only fire "negotiationneeded" if the Operations 1082 // Chain is empty. This method takes care of validating an event previously 1083 // generated with PeerConnectionObserver::OnNegotiationNeededEvent() to make 1084 // sure that even if there was a delay (e.g. due to a PostTask) between the 1085 // event being generated and the time of firing, the Operations Chain is empty 1086 // and the event is still valid to be fired. 1087 virtual bool ShouldFireNegotiationNeededEvent(uint32_t event_id) = 0; 1088 1089 virtual PeerConnectionInterface::RTCConfiguration GetConfiguration() = 0; 1090 1091 // Sets the PeerConnection's global configuration to `config`. 1092 // 1093 // The members of `config` that may be changed are `type`, `servers`, 1094 // `ice_candidate_pool_size` and `prune_turn_ports` (though the candidate 1095 // pool size can't be changed after the first call to SetLocalDescription). 1096 // Note that this means the BUNDLE and RTCP-multiplexing policies cannot be 1097 // changed with this method. 1098 // 1099 // Any changes to STUN/TURN servers or ICE candidate policy will affect the 1100 // next gathering phase, and cause the next call to createOffer to generate 1101 // new ICE credentials, as described in JSEP. This also occurs when 1102 // `prune_turn_ports` changes, for the same reasoning. 1103 // 1104 // If an error occurs, returns false and populates `error` if non-null: 1105 // - INVALID_MODIFICATION if `config` contains a modified parameter other 1106 // than one of the parameters listed above. 1107 // - INVALID_RANGE if `ice_candidate_pool_size` is out of range. 1108 // - SYNTAX_ERROR if parsing an ICE server URL failed. 1109 // - INVALID_PARAMETER if a TURN server is missing `username` or `password`. 1110 // - INTERNAL_ERROR if an unexpected error occurred. 1111 virtual RTCError SetConfiguration( 1112 const PeerConnectionInterface::RTCConfiguration& config) = 0; 1113 1114 // Provides a remote candidate to the ICE Agent. 1115 // A copy of the `candidate` will be created and added to the remote 1116 // description. So the caller of this method still has the ownership of the 1117 // `candidate`. 1118 // TODO(hbos): The spec mandates chaining this operation onto the operations 1119 // chain; deprecate and remove this version in favor of the callback-based 1120 // signature. 1121 virtual bool AddIceCandidate(const IceCandidate* candidate) = 0; 1122 // TODO(hbos): Remove default implementation once implemented by downstream 1123 // projects. 1124 virtual void AddIceCandidate(std::unique_ptr<IceCandidate> candidate, 1125 std::function<void(RTCError)> callback) {} 1126 virtual bool RemoveIceCandidate(const IceCandidate* candidate) = 0; 1127 1128 // SetBitrate limits the bandwidth allocated for all RTP streams sent by 1129 // this PeerConnection. Other limitations might affect these limits and 1130 // are respected (for example "b=AS" in SDP). 1131 // 1132 // Setting `current_bitrate_bps` will reset the current bitrate estimate 1133 // to the provided value. 1134 virtual RTCError SetBitrate(const BitrateSettings& bitrate) = 0; 1135 1136 // Allows an application to reconfigure bandwidth estimation. 1137 // The method can be called both before and after estimation has started. 1138 // Estimation starts when the first RTP packet is sent. 1139 // Estimation will be restarted if already started. 1140 virtual void ReconfigureBandwidthEstimation( 1141 const BandwidthEstimationSettings& settings) = 0; 1142 1143 // Enable/disable playout of received audio streams. Enabled by default. Note 1144 // that even if playout is enabled, streams will only be played out if the 1145 // appropriate SDP is also applied. Setting `playout` to false will stop 1146 // playout of the underlying audio device but starts a task which will poll 1147 // for audio data every 10ms to ensure that audio processing happens and the 1148 // audio statistics are updated. 1149 virtual void SetAudioPlayout(bool playout) = 0; 1150 1151 // Enable/disable recording of transmitted audio streams. Enabled by default. 1152 // Note that even if recording is enabled, streams will only be recorded if 1153 // the appropriate SDP is also applied. 1154 virtual void SetAudioRecording(bool recording) = 0; 1155 1156 // Looks up the DtlsTransport associated with a MID value. 1157 // In the Javascript API, DtlsTransport is a property of a sender, but 1158 // because the PeerConnection owns the DtlsTransport in this implementation, 1159 // it is better to look them up on the PeerConnection. 1160 virtual scoped_refptr<DtlsTransportInterface> LookupDtlsTransportByMid( 1161 const std::string& mid) = 0; 1162 1163 // Returns the SCTP transport, if any. 1164 virtual scoped_refptr<SctpTransportInterface> GetSctpTransport() const = 0; 1165 1166 // Returns the current SignalingState. 1167 virtual SignalingState signaling_state() = 0; 1168 1169 // Returns an aggregate state of all ICE *and* DTLS transports. 1170 // This is left in place to avoid breaking native clients who expect our old, 1171 // nonstandard behavior. 1172 // TODO(jonasolsson): deprecate and remove this. 1173 virtual IceConnectionState ice_connection_state() = 0; 1174 1175 // Returns an aggregated state of all ICE transports. 1176 virtual IceConnectionState standardized_ice_connection_state() = 0; 1177 1178 // Returns an aggregated state of all ICE and DTLS transports. 1179 virtual PeerConnectionState peer_connection_state() = 0; 1180 1181 virtual IceGatheringState ice_gathering_state() = 0; 1182 1183 // Returns the current state of canTrickleIceCandidates per 1184 // https://w3c.github.io/webrtc-pc/#attributes-1 1185 virtual std::optional<bool> can_trickle_ice_candidates() = 0; 1186 1187 // When a resource is overused, the PeerConnection will try to reduce the load 1188 // on the sysem, for example by reducing the resolution or frame rate of 1189 // encoded streams. The Resource API allows injecting platform-specific usage 1190 // measurements. The conditions to trigger kOveruse or kUnderuse are up to the 1191 // implementation. 1192 virtual void AddAdaptationResource(scoped_refptr<Resource> resource) = 0; 1193 1194 // Start RtcEventLog using an existing output-sink. Takes ownership of 1195 // `output` and passes it on to Call, which will take the ownership. If 1196 // the operation fails the output will be closed and deallocated. The 1197 // event log will send serialized events to the output object every 1198 // `output_period_ms`. Applications using the event log should generally 1199 // make their own trade-off regarding the output period. A long period is 1200 // generally more efficient, with potential drawbacks being more bursty 1201 // thread usage, and more events lost in case the application crashes. If 1202 // the `output_period_ms` argument is omitted, webrtc selects a default 1203 // deemed to be workable in most cases. 1204 virtual bool StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output, 1205 int64_t output_period_ms) = 0; 1206 virtual bool StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output) = 0; 1207 1208 // Stops logging the RtcEventLog. 1209 virtual void StopRtcEventLog() = 0; 1210 1211 virtual void SetDataChannelEventObserver( 1212 std::unique_ptr<DataChannelEventObserverInterface> observer) = 0; 1213 1214 // Terminates all media, closes the transports, and in general releases any 1215 // resources used by the PeerConnection. This is an irreversible operation. 1216 // 1217 // Note that after this method completes, the PeerConnection will no longer 1218 // use the PeerConnectionObserver interface passed in on construction, and 1219 // thus the observer object can be safely destroyed. 1220 virtual void Close() = 0; 1221 1222 // The thread on which all PeerConnectionObserver callbacks will be invoked, 1223 // as well as callbacks for other classes such as DataChannelObserver. 1224 // 1225 // Also the only thread on which it's safe to use SessionDescriptionInterface 1226 // pointers. 1227 virtual Thread* signaling_thread() const = 0; 1228 1229 protected: 1230 // Dtor protected as objects shouldn't be deleted via this interface. 1231 ~PeerConnectionInterface() override = default; 1232 }; 1233 1234 // PeerConnection callback interface, used for RTCPeerConnection events. 1235 // Application should implement these methods. 1236 class PeerConnectionObserver { 1237 public: 1238 virtual ~PeerConnectionObserver() = default; 1239 1240 // Triggered when the SignalingState changed. 1241 virtual void OnSignalingChange( 1242 PeerConnectionInterface::SignalingState new_state) = 0; 1243 1244 // Triggered when media is received on a new stream from remote peer. 1245 virtual void OnAddStream(scoped_refptr<MediaStreamInterface> /* stream */) {} 1246 1247 // Triggered when a remote peer closes a stream. 1248 virtual void OnRemoveStream( 1249 scoped_refptr<MediaStreamInterface> /* stream */) {} 1250 1251 // Triggered when a remote peer opens a data channel. 1252 virtual void OnDataChannel( 1253 scoped_refptr<DataChannelInterface> data_channel) = 0; 1254 1255 // Triggered when renegotiation is needed. For example, an ICE restart 1256 // has begun. 1257 // TODO(hbos): Delete in favor of OnNegotiationNeededEvent() when downstream 1258 // projects have migrated. 1259 virtual void OnRenegotiationNeeded() {} 1260 // Used to fire spec-compliant onnegotiationneeded events, which should only 1261 // fire when the Operations Chain is empty. The observer is responsible for 1262 // queuing a task (e.g. Chromium: jump to main thread) to maybe fire the 1263 // event. The event identified using `event_id` must only fire if 1264 // PeerConnection::ShouldFireNegotiationNeededEvent() returns true since it is 1265 // possible for the event to become invalidated by operations subsequently 1266 // chained. 1267 virtual void OnNegotiationNeededEvent(uint32_t /* event_id */) {} 1268 1269 // Called any time the legacy IceConnectionState changes. 1270 // 1271 // Note that our ICE states lag behind the standard slightly. The most 1272 // notable differences include the fact that "failed" occurs after 15 1273 // seconds, not 30, and this actually represents a combination ICE + DTLS 1274 // state, so it may be "failed" if DTLS fails while ICE succeeds. 1275 // 1276 // TODO(jonasolsson): deprecate and remove this. 1277 virtual void OnIceConnectionChange( 1278 PeerConnectionInterface::IceConnectionState /* new_state */) {} 1279 1280 // Called any time the standards-compliant IceConnectionState changes. 1281 virtual void OnStandardizedIceConnectionChange( 1282 PeerConnectionInterface::IceConnectionState /* new_state */) {} 1283 1284 // Called any time the PeerConnectionState changes. 1285 virtual void OnConnectionChange( 1286 PeerConnectionInterface::PeerConnectionState /* new_state */) {} 1287 1288 // Called any time the IceGatheringState changes. 1289 virtual void OnIceGatheringChange( 1290 PeerConnectionInterface::IceGatheringState new_state) = 0; 1291 1292 // A new ICE candidate has been gathered. 1293 virtual void OnIceCandidate(const IceCandidate* candidate) = 0; 1294 1295 // Gathering of an ICE candidate failed. 1296 // See https://w3c.github.io/webrtc-pc/#event-icecandidateerror 1297 virtual void OnIceCandidateError(const std::string& /* address */, 1298 int /* port */, 1299 const std::string& /* url */, 1300 int /* error_code */, 1301 const std::string& /* error_text */) {} 1302 1303 // Fired when an IceCandidate has been removed. 1304 virtual void OnIceCandidateRemoved(const IceCandidate* candidate) { 1305 } 1306 1307 // Called when the ICE connection receiving status changes. 1308 virtual void OnIceConnectionReceivingChange(bool /* receiving */) {} 1309 1310 // Called when the selected candidate pair for the ICE connection changes. 1311 virtual void OnIceSelectedCandidatePairChanged( 1312 const CandidatePairChangeEvent& /* event */) {} 1313 1314 // This is called when a receiver and its track are created. 1315 // TODO(zhihuang): Make this pure virtual when all subclasses implement it. 1316 // Note: This is called with both Plan B and Unified Plan semantics. Unified 1317 // Plan users should prefer OnTrack, OnAddTrack is only called as backwards 1318 // compatibility (and is called in the exact same situations as OnTrack). 1319 virtual void OnAddTrack( 1320 scoped_refptr<RtpReceiverInterface> /* receiver */, 1321 const std::vector<scoped_refptr<MediaStreamInterface>>& /* streams */) {} 1322 1323 // This is called when signaling indicates a transceiver will be receiving 1324 // media from the remote endpoint. This is fired during a call to 1325 // SetRemoteDescription. The receiving track can be accessed by: 1326 // `transceiver->receiver()->track()` and its associated streams by 1327 // `transceiver->receiver()->streams()`. 1328 // Note: This will only be called if Unified Plan semantics are specified. 1329 // This behavior is specified in section 2.2.8.2.5 of the "Set the 1330 // RTCSessionDescription" algorithm: 1331 // https://w3c.github.io/webrtc-pc/#set-description 1332 virtual void OnTrack( 1333 scoped_refptr<RtpTransceiverInterface> /* transceiver */) {} 1334 1335 // Called when signaling indicates that media will no longer be received on a 1336 // track. 1337 // With Plan B semantics, the given receiver will have been removed from the 1338 // PeerConnection and the track muted. 1339 // With Unified Plan semantics, the receiver will remain but the transceiver 1340 // will have changed direction to either sendonly or inactive. 1341 // https://w3c.github.io/webrtc-pc/#process-remote-track-removal 1342 // TODO(hbos,deadbeef): Make pure virtual when all subclasses implement it. 1343 virtual void OnRemoveTrack( 1344 scoped_refptr<RtpReceiverInterface> /* receiver */) {} 1345 1346 // Called when an interesting usage is detected by WebRTC. 1347 // An appropriate action is to add information about the context of the 1348 // PeerConnection and write the event to some kind of "interesting events" 1349 // log function. 1350 // The heuristics for defining what constitutes "interesting" are 1351 // implementation-defined. 1352 virtual void OnInterestingUsage(int /* usage_pattern */) {} 1353 }; 1354 1355 // PeerConnectionDependencies holds all of PeerConnections dependencies. 1356 // A dependency is distinct from a configuration as it defines significant 1357 // executable code that can be provided by a user of the API. 1358 // 1359 // All new dependencies should be added as a unique_ptr to allow the 1360 // PeerConnection object to be the definitive owner of the dependencies 1361 // lifetime making injection safer. 1362 struct RTC_EXPORT PeerConnectionDependencies final { 1363 explicit PeerConnectionDependencies(PeerConnectionObserver* observer_in); 1364 // This object is not copyable or assignable. 1365 PeerConnectionDependencies(const PeerConnectionDependencies&) = delete; 1366 PeerConnectionDependencies& operator=(const PeerConnectionDependencies&) = 1367 delete; 1368 // This object is only moveable. 1369 PeerConnectionDependencies(PeerConnectionDependencies&&); 1370 PeerConnectionDependencies& operator=(PeerConnectionDependencies&&) = default; 1371 ~PeerConnectionDependencies(); 1372 // Mandatory dependencies 1373 PeerConnectionObserver* observer = nullptr; 1374 // Optional dependencies 1375 // TODO(bugs.webrtc.org/7447): remove port allocator once downstream is 1376 // updated. The recommended way to inject networking components is to pass a 1377 // PacketSocketFactory when creating the PeerConnectionFactory. 1378 std::unique_ptr<PortAllocator> allocator; 1379 // Factory for creating resolvers that look up hostnames in DNS 1380 std::unique_ptr<AsyncDnsResolverFactoryInterface> async_dns_resolver_factory; 1381 std::unique_ptr<IceTransportFactory> ice_transport_factory; 1382 std::unique_ptr<RTCCertificateGeneratorInterface> cert_generator; 1383 std::unique_ptr<SSLCertificateVerifier> tls_cert_verifier; 1384 std::unique_ptr<VideoBitrateAllocatorFactory> video_bitrate_allocator_factory; 1385 1386 // Optional permission factory to request Local Network Access permission. 1387 std::unique_ptr<LocalNetworkAccessPermissionFactoryInterface> 1388 lna_permission_factory; 1389 1390 // Optional field trials to use. 1391 // Overrides those from PeerConnectionFactoryDependencies. 1392 std::unique_ptr<FieldTrialsView> trials; 1393 }; 1394 1395 // PeerConnectionFactoryDependencies holds all of the PeerConnectionFactory 1396 // dependencies. All new dependencies should be added here instead of 1397 // overloading the function. This simplifies dependency injection and makes it 1398 // clear which are mandatory and optional. If possible please allow the peer 1399 // connection factory to take ownership of the dependency by adding a unique_ptr 1400 // to this structure. 1401 struct RTC_EXPORT PeerConnectionFactoryDependencies final { 1402 PeerConnectionFactoryDependencies(); 1403 // This object is not copyable or assignable. 1404 PeerConnectionFactoryDependencies(const PeerConnectionFactoryDependencies&) = 1405 delete; 1406 PeerConnectionFactoryDependencies& operator=( 1407 const PeerConnectionFactoryDependencies&) = delete; 1408 // This object is only moveable. 1409 PeerConnectionFactoryDependencies(PeerConnectionFactoryDependencies&&); 1410 PeerConnectionFactoryDependencies& operator=( 1411 PeerConnectionFactoryDependencies&&) = default; 1412 ~PeerConnectionFactoryDependencies(); 1413 1414 // Optional dependencies 1415 Thread* network_thread = nullptr; 1416 Thread* worker_thread = nullptr; 1417 Thread* signaling_thread = nullptr; 1418 SocketFactory* socket_factory = nullptr; 1419 1420 // Provides common widely used dependencies for webrtc subcomponents. 1421 std::optional<Environment> env; 1422 1423 // The `packet_socket_factory` will only be used if CreatePeerConnection is 1424 // called without a `port_allocator`. 1425 std::unique_ptr<PacketSocketFactory> packet_socket_factory; 1426 std::unique_ptr<RtcEventLogFactoryInterface> event_log_factory; 1427 std::unique_ptr<FecControllerFactoryInterface> fec_controller_factory; 1428 std::unique_ptr<NetworkStatePredictorFactoryInterface> 1429 network_state_predictor_factory; 1430 std::unique_ptr<NetworkControllerFactoryInterface> network_controller_factory; 1431 // The `network_manager` will only be used if CreatePeerConnection is called 1432 // without a `port_allocator`, causing the default allocator and network 1433 // manager to be used. 1434 std::unique_ptr<NetworkManager> network_manager; 1435 // The `network_monitor_factory` will only be used if CreatePeerConnection is 1436 // called without a `port_allocator`, and the above `network_manager' is null. 1437 std::unique_ptr<NetworkMonitorFactory> network_monitor_factory; 1438 std::unique_ptr<NetEqFactory> neteq_factory; 1439 std::unique_ptr<SctpTransportFactoryInterface> sctp_factory; 1440 // Metronome used for decoding, must be called on the worker thread. 1441 std::unique_ptr<Metronome> decode_metronome; 1442 // Metronome used for encoding, must be called on the worker thread. 1443 // TODO(b/304158952): Consider merging into a single metronome for all codec 1444 // usage. 1445 std::unique_ptr<Metronome> encode_metronome; 1446 1447 // Media specific dependencies. Unused when `media_factory == nullptr`. 1448 scoped_refptr<AudioDeviceModule> adm; 1449 scoped_refptr<AudioEncoderFactory> audio_encoder_factory; 1450 scoped_refptr<AudioDecoderFactory> audio_decoder_factory; 1451 scoped_refptr<AudioMixer> audio_mixer; 1452 std::unique_ptr<AudioProcessingBuilderInterface> audio_processing_builder; 1453 std::unique_ptr<AudioFrameProcessor> audio_frame_processor; 1454 std::unique_ptr<VideoEncoderFactory> video_encoder_factory; 1455 std::unique_ptr<VideoDecoderFactory> video_decoder_factory; 1456 1457 // The `media_factory` members allows webrtc to be optionally built without 1458 // media support (i.e., if only being used for data channels). 1459 // By default media is disabled. To enable media call 1460 // `EnableMedia(PeerConnectionFactoryDependencies&)`. Definition of the 1461 // `MediaFactory` interface is a webrtc implementation detail. 1462 std::unique_ptr<MediaFactory> media_factory; 1463 }; 1464 1465 // PeerConnectionFactoryInterface is the factory interface used for creating 1466 // PeerConnection, MediaStream and MediaStreamTrack objects. 1467 // 1468 // The simplest method for obtaiing one, CreatePeerConnectionFactory will 1469 // create the required libjingle threads, socket and network manager factory 1470 // classes for networking if none are provided, though it requires that the 1471 // application runs a message loop on the thread that called the method (see 1472 // explanation below) 1473 // 1474 // If an application decides to provide its own threads and/or implementation 1475 // of networking classes, it should use the alternate 1476 // CreatePeerConnectionFactory method which accepts threads as input, and use 1477 // the CreatePeerConnection version that takes a PortAllocator as an argument. 1478 class RTC_EXPORT PeerConnectionFactoryInterface : public RefCountInterface { 1479 public: 1480 class Options { 1481 public: 1482 Options() {} 1483 1484 // If set to true, created PeerConnections won't enforce any SRTP 1485 // requirement, allowing unsecured media. Should only be used for 1486 // testing/debugging. 1487 bool disable_encryption = false; 1488 1489 // If set to true, any platform-supported network monitoring capability 1490 // won't be used, and instead networks will only be updated via polling. 1491 // 1492 // This only has an effect if a PeerConnection is created with the default 1493 // PortAllocator implementation. 1494 bool disable_network_monitor = false; 1495 1496 // Sets the network types to ignore. For instance, calling this with 1497 // ADAPTER_TYPE_ETHERNET | ADAPTER_TYPE_LOOPBACK will ignore Ethernet and 1498 // loopback interfaces. 1499 int network_ignore_mask = kDefaultNetworkIgnoreMask; 1500 1501 // Sets the maximum supported protocol version. The highest version 1502 // supported by both ends will be used for the connection, i.e. if one 1503 // party supports DTLS 1.0 and the other DTLS 1.2, DTLS 1.0 will be used. 1504 SSLProtocolVersion ssl_max_version = SSL_PROTOCOL_DTLS_12; 1505 }; 1506 1507 // Set the options to be used for subsequently created PeerConnections. 1508 virtual void SetOptions(const Options& options) = 0; 1509 1510 // The preferred way to create a new peer connection. Simply provide the 1511 // configuration and a PeerConnectionDependencies structure. 1512 virtual RTCErrorOr<scoped_refptr<PeerConnectionInterface>> 1513 CreatePeerConnectionOrError( 1514 const PeerConnectionInterface::RTCConfiguration& configuration, 1515 PeerConnectionDependencies dependencies) = 0; 1516 1517 // Returns the capabilities of an RTP sender of type `kind`. 1518 // If for some reason you pass in MediaType::DATA, returns an empty 1519 // structure. 1520 virtual RtpCapabilities GetRtpSenderCapabilities(MediaType kind) const = 0; 1521 1522 // Returns the capabilities of an RTP receiver of type `kind`. 1523 // If for some reason you pass in MediaType::DATA, returns an empty 1524 // structure. 1525 virtual RtpCapabilities GetRtpReceiverCapabilities(MediaType kind) const = 0; 1526 1527 virtual scoped_refptr<MediaStreamInterface> CreateLocalMediaStream( 1528 const std::string& stream_id) = 0; 1529 1530 // Creates an AudioSourceInterface. 1531 // `options` decides audio processing settings. 1532 virtual scoped_refptr<AudioSourceInterface> CreateAudioSource( 1533 const AudioOptions& options) = 0; 1534 1535 // Creates a new local VideoTrack. The same `source` can be used in several 1536 // tracks. 1537 virtual scoped_refptr<VideoTrackInterface> CreateVideoTrack( 1538 scoped_refptr<VideoTrackSourceInterface> source, 1539 absl::string_view label) = 0; 1540 1541 // Creates an new AudioTrack. At the moment `source` can be null. 1542 virtual scoped_refptr<AudioTrackInterface> CreateAudioTrack( 1543 const std::string& label, 1544 AudioSourceInterface* source) = 0; 1545 1546 // Starts AEC dump using existing file. Takes ownership of `file` and passes 1547 // it on to VoiceEngine (via other objects) immediately, which will take 1548 // the ownerhip. If the operation fails, the file will be closed. 1549 // A maximum file size in bytes can be specified. When the file size limit is 1550 // reached, logging is stopped automatically. If max_size_bytes is set to a 1551 // value <= 0, no limit will be used, and logging will continue until the 1552 // StopAecDump function is called. 1553 // TODO(webrtc:6463): Delete default implementation when downstream mocks 1554 // classes are updated. 1555 virtual bool StartAecDump(FILE* /* file */, int64_t /* max_size_bytes */) { 1556 return false; 1557 } 1558 1559 // Stops logging the AEC dump. 1560 virtual void StopAecDump() = 0; 1561 1562 protected: 1563 // Dtor and ctor protected as objects shouldn't be created or deleted via 1564 // this interface. 1565 PeerConnectionFactoryInterface() {} 1566 ~PeerConnectionFactoryInterface() override = default; 1567 }; 1568 1569 // https://w3c.github.io/webrtc-pc/#dom-rtcsignalingstate 1570 inline constexpr absl::string_view PeerConnectionInterface::AsString( 1571 SignalingState state) { 1572 switch (state) { 1573 case SignalingState::kStable: 1574 return "stable"; 1575 case SignalingState::kHaveLocalOffer: 1576 return "have-local-offer"; 1577 case SignalingState::kHaveLocalPrAnswer: 1578 return "have-local-pranswer"; 1579 case SignalingState::kHaveRemoteOffer: 1580 return "have-remote-offer"; 1581 case SignalingState::kHaveRemotePrAnswer: 1582 return "have-remote-pranswer"; 1583 case SignalingState::kClosed: 1584 return "closed"; 1585 } 1586 // This cannot happen. 1587 // Not using "RTC_CHECK_NOTREACHED()" because AsString() is constexpr. 1588 return ""; 1589 } 1590 1591 // https://w3c.github.io/webrtc-pc/#dom-rtcicegatheringstate 1592 inline constexpr absl::string_view PeerConnectionInterface::AsString( 1593 IceGatheringState state) { 1594 switch (state) { 1595 case IceGatheringState::kIceGatheringNew: 1596 return "new"; 1597 case IceGatheringState::kIceGatheringGathering: 1598 return "gathering"; 1599 case IceGatheringState::kIceGatheringComplete: 1600 return "complete"; 1601 } 1602 // This cannot happen. 1603 // Not using "RTC_CHECK_NOTREACHED()" because AsString() is constexpr. 1604 return ""; 1605 } 1606 1607 // https://w3c.github.io/webrtc-pc/#dom-rtciceconnectionstate 1608 inline constexpr absl::string_view PeerConnectionInterface::AsString( 1609 PeerConnectionState state) { 1610 switch (state) { 1611 case PeerConnectionState::kNew: 1612 return "new"; 1613 case PeerConnectionState::kConnecting: 1614 return "connecting"; 1615 case PeerConnectionState::kConnected: 1616 return "connected"; 1617 case PeerConnectionState::kDisconnected: 1618 return "disconnected"; 1619 case PeerConnectionState::kFailed: 1620 return "failed"; 1621 case PeerConnectionState::kClosed: 1622 return "closed"; 1623 } 1624 // This cannot happen. 1625 // Not using "RTC_CHECK_NOTREACHED()" because AsString() is constexpr. 1626 return ""; 1627 } 1628 1629 inline constexpr absl::string_view PeerConnectionInterface::AsString( 1630 IceConnectionState state) { 1631 switch (state) { 1632 case kIceConnectionNew: 1633 return "new"; 1634 case kIceConnectionChecking: 1635 return "checking"; 1636 case kIceConnectionConnected: 1637 return "connected"; 1638 case kIceConnectionCompleted: 1639 return "completed"; 1640 case kIceConnectionFailed: 1641 return "failed"; 1642 case kIceConnectionDisconnected: 1643 return "disconnected"; 1644 case kIceConnectionClosed: 1645 return "closed"; 1646 case kIceConnectionMax: 1647 // This cannot happen. 1648 // Not using "RTC_CHECK_NOTREACHED()" because AsString() is constexpr. 1649 return ""; 1650 } 1651 // This cannot happen. 1652 // Not using "RTC_CHECK_NOTREACHED()" because AsString() is constexpr. 1653 return ""; 1654 } 1655 1656 } // namespace webrtc 1657 1658 #endif // API_PEER_CONNECTION_INTERFACE_H_