| 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 | #include "pc/peer_connection.h" |
| 12 |
| 13 | #include <limits.h> |
| 14 | #include <stddef.h> |
| 15 |
| 16 | #include <algorithm> |
| 17 | #include <memory> |
| 18 | #include <set> |
| 19 | #include <string> |
| 20 | #include <utility> |
| 21 |
| 22 | #include "absl/algorithm/container.h" |
| 23 | #include "absl/strings/match.h" |
| 24 | #include "absl/strings/string_view.h" |
| 25 | #include "api/jsep_ice_candidate.h" |
| 26 | #include "api/rtp_parameters.h" |
| 27 | #include "api/rtp_transceiver_direction.h" |
| 28 | #include "api/uma_metrics.h" |
| 29 | #include "api/video/video_codec_constants.h" |
| 30 | #include "call/audio_state.h" |
| 31 | #include "call/packet_receiver.h" |
| 32 | #include "media/base/media_channel.h" |
| 33 | #include "media/base/media_config.h" |
| 34 | #include "media/base/media_engine.h" |
| 35 | #include "media/base/rid_description.h" |
| 36 | #include "media/base/stream_params.h" |
| 37 | #include "modules/rtp_rtcp/include/rtp_rtcp_defines.h" |
| 38 | #include "p2p/base/basic_async_resolver_factory.h" |
| 39 | #include "p2p/base/connection.h" |
| 40 | #include "p2p/base/connection_info.h" |
| 41 | #include "p2p/base/dtls_transport_internal.h" |
| 42 | #include "p2p/base/p2p_constants.h" |
| 43 | #include "p2p/base/p2p_transport_channel.h" |
| 44 | #include "p2p/base/transport_info.h" |
| 45 | #include "pc/ice_server_parsing.h" |
| 46 | #include "pc/rtp_receiver.h" |
| 47 | #include "pc/rtp_receiver_proxy.h" |
| 48 | #include "pc/rtp_sender.h" |
| 49 | #include "pc/rtp_sender_proxy.h" |
| 50 | #include "pc/sctp_transport.h" |
| 51 | #include "pc/simulcast_description.h" |
| 52 | #include "pc/webrtc_session_description_factory.h" |
| 53 | #include "rtc_base/helpers.h" |
| 54 | #include "rtc_base/ip_address.h" |
| 55 | #include "rtc_base/logging.h" |
| 56 | #include "rtc_base/net_helper.h" |
| 57 | #include "rtc_base/network.h" |
| 58 | #include "rtc_base/network_constants.h" |
| 59 | #include "rtc_base/socket_address.h" |
| 60 | #include "rtc_base/string_encode.h" |
| 61 | #include "rtc_base/trace_event.h" |
| 62 | #include "rtc_base/unique_id_generator.h" |
| 63 | #include "system_wrappers/include/metrics.h" |
| 64 |
| 65 | using cricket::ContentInfo; |
| 66 | using cricket::ContentInfos; |
| 67 | using cricket::MediaContentDescription; |
| 68 | using cricket::MediaProtocolType; |
| 69 | using cricket::RidDescription; |
| 70 | using cricket::RidDirection; |
| 71 | using cricket::SessionDescription; |
| 72 | using cricket::SimulcastDescription; |
| 73 | using cricket::SimulcastLayer; |
| 74 | using cricket::SimulcastLayerList; |
| 75 | using cricket::StreamParams; |
| 76 | using cricket::TransportInfo; |
| 77 |
| 78 | using cricket::LOCAL_PORT_TYPE; |
| 79 | using cricket::PRFLX_PORT_TYPE; |
| 80 | using cricket::RELAY_PORT_TYPE; |
| 81 | using cricket::STUN_PORT_TYPE; |
| 82 |
| 83 | namespace webrtc { |
| 84 |
| 85 | namespace { |
| 86 |
| 87 | // UMA metric names. |
| 88 | const char kSimulcastNumberOfEncodings[] = |
| 89 | "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings"; |
| 90 |
| 91 | static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000; |
| 92 |
| 93 | uint32_t ConvertIceTransportTypeToCandidateFilter( |
| 94 | PeerConnectionInterface::IceTransportsType type) { |
| 95 | switch (type) { |
| 96 | case PeerConnectionInterface::kNone: |
| 97 | return cricket::CF_NONE; |
| 98 | case PeerConnectionInterface::kRelay: |
| 99 | return cricket::CF_RELAY; |
| 100 | case PeerConnectionInterface::kNoHost: |
| 101 | return (cricket::CF_ALL & ~cricket::CF_HOST); |
| 102 | case PeerConnectionInterface::kAll: |
| 103 | return cricket::CF_ALL; |
| 104 | default: |
| 105 | RTC_DCHECK_NOTREACHED(); |
| 106 | } |
| 107 | return cricket::CF_NONE; |
| 108 | } |
| 109 |
| 110 | IceCandidatePairType GetIceCandidatePairCounter( |
| 111 | const cricket::Candidate& local, |
| 112 | const cricket::Candidate& remote) { |
| 113 | const auto& l = local.type(); |
| 114 | const auto& r = remote.type(); |
| 115 | const auto& host = LOCAL_PORT_TYPE; |
| 116 | const auto& srflx = STUN_PORT_TYPE; |
| 117 | const auto& relay = RELAY_PORT_TYPE; |
| 118 | const auto& prflx = PRFLX_PORT_TYPE; |
| 119 | if (l == host && r == host) { |
| 120 | bool local_hostname = |
| 121 | !local.address().hostname().empty() && local.address().IsUnresolvedIP(); |
| 122 | bool remote_hostname = !remote.address().hostname().empty() && |
| 123 | remote.address().IsUnresolvedIP(); |
| 124 | bool local_private = IPIsPrivate(local.address().ipaddr()); |
| 125 | bool remote_private = IPIsPrivate(remote.address().ipaddr()); |
| 126 | if (local_hostname) { |
| 127 | if (remote_hostname) { |
| 128 | return kIceCandidatePairHostNameHostName; |
| 129 | } else if (remote_private) { |
| 130 | return kIceCandidatePairHostNameHostPrivate; |
| 131 | } else { |
| 132 | return kIceCandidatePairHostNameHostPublic; |
| 133 | } |
| 134 | } else if (local_private) { |
| 135 | if (remote_hostname) { |
| 136 | return kIceCandidatePairHostPrivateHostName; |
| 137 | } else if (remote_private) { |
| 138 | return kIceCandidatePairHostPrivateHostPrivate; |
| 139 | } else { |
| 140 | return kIceCandidatePairHostPrivateHostPublic; |
| 141 | } |
| 142 | } else { |
| 143 | if (remote_hostname) { |
| 144 | return kIceCandidatePairHostPublicHostName; |
| 145 | } else if (remote_private) { |
| 146 | return kIceCandidatePairHostPublicHostPrivate; |
| 147 | } else { |
| 148 | return kIceCandidatePairHostPublicHostPublic; |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | if (l == host && r == srflx) |
| 153 | return kIceCandidatePairHostSrflx; |
| 154 | if (l == host && r == relay) |
| 155 | return kIceCandidatePairHostRelay; |
| 156 | if (l == host && r == prflx) |
| 157 | return kIceCandidatePairHostPrflx; |
| 158 | if (l == srflx && r == host) |
| 159 | return kIceCandidatePairSrflxHost; |
| 160 | if (l == srflx && r == srflx) |
| 161 | return kIceCandidatePairSrflxSrflx; |
| 162 | if (l == srflx && r == relay) |
| 163 | return kIceCandidatePairSrflxRelay; |
| 164 | if (l == srflx && r == prflx) |
| 165 | return kIceCandidatePairSrflxPrflx; |
| 166 | if (l == relay && r == host) |
| 167 | return kIceCandidatePairRelayHost; |
| 168 | if (l == relay && r == srflx) |
| 169 | return kIceCandidatePairRelaySrflx; |
| 170 | if (l == relay && r == relay) |
| 171 | return kIceCandidatePairRelayRelay; |
| 172 | if (l == relay && r == prflx) |
| 173 | return kIceCandidatePairRelayPrflx; |
| 174 | if (l == prflx && r == host) |
| 175 | return kIceCandidatePairPrflxHost; |
| 176 | if (l == prflx && r == srflx) |
| 177 | return kIceCandidatePairPrflxSrflx; |
| 178 | if (l == prflx && r == relay) |
| 179 | return kIceCandidatePairPrflxRelay; |
| 180 | return kIceCandidatePairMax; |
| 181 | } |
| 182 |
| 183 | absl::optional<int> RTCConfigurationToIceConfigOptionalInt( |
| 184 | int rtc_configuration_parameter) { |
| 185 | if (rtc_configuration_parameter == |
| 186 | webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) { |
| 187 | return absl::nullopt; |
| 188 | } |
| 189 | return rtc_configuration_parameter; |
| 190 | } |
| 191 |
| 192 | // Check if the changes of IceTransportsType motives an ice restart. |
| 193 | bool NeedIceRestart(bool surface_ice_candidates_on_ice_transport_type_changed, |
| 194 | PeerConnectionInterface::IceTransportsType current, |
| 195 | PeerConnectionInterface::IceTransportsType modified) { |
| 196 | if (current == modified) { |
| 197 | return false; |
| 198 | } |
| 199 |
| 200 | if (!surface_ice_candidates_on_ice_transport_type_changed) { |
| 201 | return true; |
| 202 | } |
| 203 |
| 204 | auto current_filter = ConvertIceTransportTypeToCandidateFilter(current); |
| 205 | auto modified_filter = ConvertIceTransportTypeToCandidateFilter(modified); |
| 206 |
| 207 | // If surface_ice_candidates_on_ice_transport_type_changed is true and we |
| 208 | // extend the filter, then no ice restart is needed. |
| 209 | return (current_filter & modified_filter) != current_filter; |
| 210 | } |
| 211 |
| 212 | cricket::IceConfig ParseIceConfig( |
| 213 | const PeerConnectionInterface::RTCConfiguration& config) { |
| 214 | cricket::ContinualGatheringPolicy gathering_policy; |
| 215 | switch (config.continual_gathering_policy) { |
| 216 | case PeerConnectionInterface::GATHER_ONCE: |
| 217 | gathering_policy = cricket::GATHER_ONCE; |
| 218 | break; |
| 219 | case PeerConnectionInterface::GATHER_CONTINUALLY: |
| 220 | gathering_policy = cricket::GATHER_CONTINUALLY; |
| 221 | break; |
| 222 | default: |
| 223 | RTC_DCHECK_NOTREACHED(); |
| 224 | gathering_policy = cricket::GATHER_ONCE; |
| 225 | } |
| 226 |
| 227 | cricket::IceConfig ice_config; |
| 228 | ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt( |
| 229 | config.ice_connection_receiving_timeout); |
| 230 | ice_config.prioritize_most_likely_candidate_pairs = |
| 231 | config.prioritize_most_likely_ice_candidate_pairs; |
| 232 | ice_config.backup_connection_ping_interval = |
| 233 | RTCConfigurationToIceConfigOptionalInt( |
| 234 | config.ice_backup_candidate_pair_ping_interval); |
| 235 | ice_config.continual_gathering_policy = gathering_policy; |
| 236 | ice_config.presume_writable_when_fully_relayed = |
| 237 | config.presume_writable_when_fully_relayed; |
| 238 | ice_config.surface_ice_candidates_on_ice_transport_type_changed = |
| 239 | config.surface_ice_candidates_on_ice_transport_type_changed; |
| 240 | ice_config.ice_check_interval_strong_connectivity = |
| 241 | config.ice_check_interval_strong_connectivity; |
| 242 | ice_config.ice_check_interval_weak_connectivity = |
| 243 | config.ice_check_interval_weak_connectivity; |
| 244 | ice_config.ice_check_min_interval = config.ice_check_min_interval; |
| 245 | ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout; |
| 246 | ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks; |
| 247 | ice_config.ice_inactive_timeout = config.ice_inactive_timeout; |
| 248 | ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval; |
| 249 | ice_config.network_preference = config.network_preference; |
| 250 | ice_config.stable_writable_connection_ping_interval = |
| 251 | config.stable_writable_connection_ping_interval_ms; |
| 252 | return ice_config; |
| 253 | } |
| 254 |
| 255 | // Ensures the configuration doesn't have any parameters with invalid values, |
| 256 | // or values that conflict with other parameters. |
| 257 | // |
| 258 | // Returns RTCError::OK() if there are no issues. |
| 259 | RTCError ValidateConfiguration( |
| 260 | const PeerConnectionInterface::RTCConfiguration& config) { |
| 261 | return cricket::P2PTransportChannel::ValidateIceConfig( |
| 262 | ParseIceConfig(config)); |
| 263 | } |
| 264 |
| 265 | bool HasRtcpMuxEnabled(const cricket::ContentInfo* content) { |
| 266 | return content->media_description()->rtcp_mux(); |
| 267 | } |
| 268 |
| 269 | bool DtlsEnabled(const PeerConnectionInterface::RTCConfiguration& configuration, |
| 270 | const PeerConnectionFactoryInterface::Options& options, |
| 271 | const PeerConnectionDependencies& dependencies) { |
| 272 | if (options.disable_encryption) |
| 273 | return false; |
| 274 |
| 275 | // Enable DTLS by default if we have an identity store or a certificate. |
| 276 | bool default_enabled = |
| 277 | (dependencies.cert_generator || !configuration.certificates.empty()); |
| 278 |
| 279 | #if defined(WEBRTC_FUCHSIA) |
| 280 | // The `configuration` can override the default value. |
| 281 | return configuration.enable_dtls_srtp.value_or(default_enabled); |
| 282 | #else |
| 283 | return default_enabled; |
| 284 | #endif |
| 285 | } |
| 286 |
| 287 | } // namespace |
| 288 |
| 289 | bool PeerConnectionInterface::RTCConfiguration::operator==( |
| 290 | const PeerConnectionInterface::RTCConfiguration& o) const { |
| 291 | // This static_assert prevents us from accidentally breaking operator==. |
| 292 | // Note: Order matters! Fields must be ordered the same as RTCConfiguration. |
| 293 | struct stuff_being_tested_for_equality { |
| 294 | IceServers servers; |
| 295 | IceTransportsType type; |
| 296 | BundlePolicy bundle_policy; |
| 297 | RtcpMuxPolicy rtcp_mux_policy; |
| 298 | std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates; |
| 299 | int ice_candidate_pool_size; |
| 300 | bool disable_ipv6; |
| 301 | bool disable_ipv6_on_wifi; |
| 302 | int max_ipv6_networks; |
| 303 | bool disable_link_local_networks; |
| 304 | absl::optional<int> screencast_min_bitrate; |
| 305 | absl::optional<bool> combined_audio_video_bwe; |
| 306 | #if defined(WEBRTC_FUCHSIA) |
| 307 | absl::optional<bool> enable_dtls_srtp; |
| 308 | #endif |
| 309 | TcpCandidatePolicy tcp_candidate_policy; |
| 310 | CandidateNetworkPolicy candidate_network_policy; |
| 311 | int audio_jitter_buffer_max_packets; |
| 312 | bool audio_jitter_buffer_fast_accelerate; |
| 313 | int audio_jitter_buffer_min_delay_ms; |
| 314 | int ice_connection_receiving_timeout; |
| 315 | int ice_backup_candidate_pair_ping_interval; |
| 316 | ContinualGatheringPolicy continual_gathering_policy; |
| 317 | bool prioritize_most_likely_ice_candidate_pairs; |
| 318 | struct cricket::MediaConfig media_config; |
| 319 | bool prune_turn_ports; |
| 320 | PortPrunePolicy turn_port_prune_policy; |
| 321 | bool presume_writable_when_fully_relayed; |
| 322 | bool enable_ice_renomination; |
| 323 | bool redetermine_role_on_ice_restart; |
| 324 | bool surface_ice_candidates_on_ice_transport_type_changed; |
| 325 | absl::optional<int> ice_check_interval_strong_connectivity; |
| 326 | absl::optional<int> ice_check_interval_weak_connectivity; |
| 327 | absl::optional<int> ice_check_min_interval; |
| 328 | absl::optional<int> ice_unwritable_timeout; |
| 329 | absl::optional<int> ice_unwritable_min_checks; |
| 330 | absl::optional<int> ice_inactive_timeout; |
| 331 | absl::optional<int> stun_candidate_keepalive_interval; |
| 332 | webrtc::TurnCustomizer* turn_customizer; |
| 333 | SdpSemantics sdp_semantics; |
| 334 | absl::optional<rtc::AdapterType> network_preference; |
| 335 | bool active_reset_srtp_params; |
| 336 | absl::optional<CryptoOptions> crypto_options; |
| 337 | bool offer_extmap_allow_mixed; |
| 338 | std::string turn_logging_id; |
| 339 | bool enable_implicit_rollback; |
| 340 | absl::optional<bool> allow_codec_switching; |
| 341 | absl::optional<int> report_usage_pattern_delay_ms; |
| 342 | absl::optional<int> stable_writable_connection_ping_interval_ms; |
| 343 | webrtc::VpnPreference vpn_preference; |
| 344 | std::vector<rtc::NetworkMask> vpn_list; |
| 345 | PortAllocatorConfig port_allocator_config; |
| 346 | }; |
| 347 | static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this), |
| 348 | "Did you add something to RTCConfiguration and forget to " |
| 349 | "update operator==?"); |
| 350 | return type == o.type && servers == o.servers && |
| 351 | bundle_policy == o.bundle_policy && |
| 352 | rtcp_mux_policy == o.rtcp_mux_policy && |
| 353 | tcp_candidate_policy == o.tcp_candidate_policy && |
| 354 | candidate_network_policy == o.candidate_network_policy && |
| 355 | audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets && |
| 356 | audio_jitter_buffer_fast_accelerate == |
| 357 | o.audio_jitter_buffer_fast_accelerate && |
| 358 | audio_jitter_buffer_min_delay_ms == |
| 359 | o.audio_jitter_buffer_min_delay_ms && |
| 360 | ice_connection_receiving_timeout == |
| 361 | o.ice_connection_receiving_timeout && |
| 362 | ice_backup_candidate_pair_ping_interval == |
| 363 | o.ice_backup_candidate_pair_ping_interval && |
| 364 | continual_gathering_policy == o.continual_gathering_policy && |
| 365 | certificates == o.certificates && |
| 366 | prioritize_most_likely_ice_candidate_pairs == |
| 367 | o.prioritize_most_likely_ice_candidate_pairs && |
| 368 | media_config == o.media_config && disable_ipv6 == o.disable_ipv6 && |
| 369 | disable_ipv6_on_wifi == o.disable_ipv6_on_wifi && |
| 370 | max_ipv6_networks == o.max_ipv6_networks && |
| 371 | disable_link_local_networks == o.disable_link_local_networks && |
| 372 | screencast_min_bitrate == o.screencast_min_bitrate && |
| 373 | combined_audio_video_bwe == o.combined_audio_video_bwe && |
| 374 | #if defined(WEBRTC_FUCHSIA) |
| 375 | enable_dtls_srtp == o.enable_dtls_srtp && |
| 376 | #endif |
| 377 | ice_candidate_pool_size == o.ice_candidate_pool_size && |
| 378 | prune_turn_ports == o.prune_turn_ports && |
| 379 | turn_port_prune_policy == o.turn_port_prune_policy && |
| 380 | presume_writable_when_fully_relayed == |
| 381 | o.presume_writable_when_fully_relayed && |
| 382 | enable_ice_renomination == o.enable_ice_renomination && |
| 383 | redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart && |
| 384 | surface_ice_candidates_on_ice_transport_type_changed == |
| 385 | o.surface_ice_candidates_on_ice_transport_type_changed && |
| 386 | ice_check_interval_strong_connectivity == |
| 387 | o.ice_check_interval_strong_connectivity && |
| 388 | ice_check_interval_weak_connectivity == |
| 389 | o.ice_check_interval_weak_connectivity && |
| 390 | ice_check_min_interval == o.ice_check_min_interval && |
| 391 | ice_unwritable_timeout == o.ice_unwritable_timeout && |
| 392 | ice_unwritable_min_checks == o.ice_unwritable_min_checks && |
| 393 | ice_inactive_timeout == o.ice_inactive_timeout && |
| 394 | stun_candidate_keepalive_interval == |
| 395 | o.stun_candidate_keepalive_interval && |
| 396 | turn_customizer == o.turn_customizer && |
| 397 | sdp_semantics == o.sdp_semantics && |
| 398 | network_preference == o.network_preference && |
| 399 | active_reset_srtp_params == o.active_reset_srtp_params && |
| 400 | crypto_options == o.crypto_options && |
| 401 | offer_extmap_allow_mixed == o.offer_extmap_allow_mixed && |
| 402 | turn_logging_id == o.turn_logging_id && |
| 403 | enable_implicit_rollback == o.enable_implicit_rollback && |
| 404 | allow_codec_switching == o.allow_codec_switching && |
| 405 | report_usage_pattern_delay_ms == o.report_usage_pattern_delay_ms && |
| 406 | stable_writable_connection_ping_interval_ms == |
| 407 | o.stable_writable_connection_ping_interval_ms && |
| 408 | vpn_preference == o.vpn_preference && vpn_list == o.vpn_list && |
| 409 | port_allocator_config.min_port == o.port_allocator_config.min_port && |
| 410 | port_allocator_config.max_port == o.port_allocator_config.max_port && |
| 411 | port_allocator_config.flags == o.port_allocator_config.flags; |
| 412 | } |
| 413 |
| 414 | bool PeerConnectionInterface::RTCConfiguration::operator!=( |
| 415 | const PeerConnectionInterface::RTCConfiguration& o) const { |
| 416 | return !(*this == o); |
| 417 | } |
| 418 |
| 419 | RTCErrorOr<rtc::scoped_refptr<PeerConnection>> PeerConnection::Create( |
| 420 | rtc::scoped_refptr<ConnectionContext> context, |
| 421 | const PeerConnectionFactoryInterface::Options& options, |
| 422 | std::unique_ptr<RtcEventLog> event_log, |
| 423 | std::unique_ptr<Call> call, |
| 424 | const PeerConnectionInterface::RTCConfiguration& configuration, |
| 425 | PeerConnectionDependencies dependencies) { |
| 426 | // TODO(https://crbug.com/webrtc/13528): Remove support for kPlanB. |
| 427 | if (configuration.sdp_semantics == SdpSemantics::kPlanB_DEPRECATED) { |
| 428 | RTC_LOG(LS_WARNING) |
| 429 | << "PeerConnection constructed with legacy SDP semantics!"; |
| 430 | } |
| 431 |
| 432 | RTCError config_error = cricket::P2PTransportChannel::ValidateIceConfig( |
| 433 | ParseIceConfig(configuration)); |
| 434 | if (!config_error.ok()) { |
| 435 | RTC_LOG(LS_ERROR) << "Invalid ICE configuration: " |
| 436 | << config_error.message(); |
| 437 | return config_error; |
| 438 | } |
| 439 |
| 440 | if (!dependencies.allocator) { |
| 441 | RTC_LOG(LS_ERROR) |
| 442 | << "PeerConnection initialized without a PortAllocator? " |
| 443 | "This shouldn't happen if using PeerConnectionFactory."; |
| 444 | return RTCError( |
| 445 | RTCErrorType::INVALID_PARAMETER, |
| 446 | "Attempt to create a PeerConnection without a PortAllocatorFactory"); |
| 447 | } |
| 448 |
| 449 | if (!dependencies.observer) { |
| 450 | // TODO(deadbeef): Why do we do this? |
| 451 | RTC_LOG(LS_ERROR) << "PeerConnection initialized without a " |
| 452 | "PeerConnectionObserver"; |
| 453 | return RTCError(RTCErrorType::INVALID_PARAMETER, |
| 454 | "Attempt to create a PeerConnection without an observer"); |
| 455 | } |
| 456 |
| 457 | bool is_unified_plan = |
| 458 | configuration.sdp_semantics == SdpSemantics::kUnifiedPlan; |
| 459 | bool dtls_enabled = DtlsEnabled(configuration, options, dependencies); |
| 460 |
| 461 | // Interim code: If an AsyncResolverFactory is given, but not an |
| 462 | // AsyncDnsResolverFactory, wrap it in a WrappingAsyncDnsResolverFactory |
| 463 | // If neither is given, create a WrappingAsyncDnsResolverFactory wrapping |
| 464 | // a BasicAsyncResolver. |
| 465 | // TODO(bugs.webrtc.org/12598): Remove code once all callers pass a |
| 466 | // AsyncDnsResolverFactory. |
| 467 | if (dependencies.async_dns_resolver_factory && |
| 468 | dependencies.async_resolver_factory) { |
| 469 | RTC_LOG(LS_ERROR) |
| 470 | << "Attempt to set both old and new type of DNS resolver factory"; |
| 471 | return RTCError(RTCErrorType::INVALID_PARAMETER, |
| 472 | "Both old and new type of DNS resolver given"); |
| 473 | } |
| 474 | if (dependencies.async_resolver_factory) { |
| 475 | dependencies.async_dns_resolver_factory = |
| 476 | std::make_unique<WrappingAsyncDnsResolverFactory>( |
| 477 | std::move(dependencies.async_resolver_factory)); |
| 478 | } else { |
| 479 | dependencies.async_dns_resolver_factory = |
| 480 | std::make_unique<WrappingAsyncDnsResolverFactory>( |
| 481 | std::make_unique<BasicAsyncResolverFactory>()); |
| 482 | } |
| 483 |
| 484 | // The PeerConnection constructor consumes some, but not all, dependencies. |
| 485 | auto pc = rtc::make_ref_counted<PeerConnection>( |
| 486 | context, options, is_unified_plan, std::move(event_log), std::move(call), |
| 487 | dependencies, dtls_enabled); |
| 488 | RTCError init_error = pc->Initialize(configuration, std::move(dependencies)); |
| 489 | if (!init_error.ok()) { |
| 490 | RTC_LOG(LS_ERROR) << "PeerConnection initialization failed"; |
| 491 | return init_error; |
| 492 | } |
| 493 | return pc; |
| 494 | } |
| 495 |
| 496 | PeerConnection::PeerConnection( |
| 497 | rtc::scoped_refptr<ConnectionContext> context, |
| 498 | const PeerConnectionFactoryInterface::Options& options, |
| 499 | bool is_unified_plan, |
| 500 | std::unique_ptr<RtcEventLog> event_log, |
| 501 | std::unique_ptr<Call> call, |
| 502 | PeerConnectionDependencies& dependencies, |
| 503 | bool dtls_enabled) |
| 504 | : context_(context), |
| 505 | trials_(std::move(dependencies.trials), &context->field_trials()), |
| 506 | options_(options), |
| 507 | observer_(dependencies.observer), |
| 508 | is_unified_plan_(is_unified_plan), |
| 509 | event_log_(std::move(event_log)), |
| 510 | event_log_ptr_(event_log_.get()), |
| 511 | async_dns_resolver_factory_( |
| 512 | std::move(dependencies.async_dns_resolver_factory)), |
| 513 | port_allocator_(std::move(dependencies.allocator)), |
| 514 | ice_transport_factory_(std::move(dependencies.ice_transport_factory)), |
| 515 | tls_cert_verifier_(std::move(dependencies.tls_cert_verifier)), |
| 516 | call_(std::move(call)), |
| 517 | call_ptr_(call_.get()), |
| 518 | // RFC 3264: The numeric value of the session id and version in the |
| 519 | // o line MUST be representable with a "64 bit signed integer". |
| 520 | // Due to this constraint session id `session_id_` is max limited to |
| 521 | // LLONG_MAX. |
| 522 | session_id_(rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX)), |
| 523 | dtls_enabled_(dtls_enabled), |
| 524 | data_channel_controller_(this), |
| 525 | message_handler_(signaling_thread()), |
| 526 | weak_factory_(this) { |
| 527 | worker_thread()->BlockingCall([this] { |
| 528 | RTC_DCHECK_RUN_ON(worker_thread()); |
| 529 | worker_thread_safety_ = PendingTaskSafetyFlag::Create(); |
| 530 | if (!call_) |
| 531 | worker_thread_safety_->SetNotAlive(); |
| 532 | }); |
| 533 | } |
| 534 |
| 535 | PeerConnection::~PeerConnection() { |
| 536 | TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection"); |
| 537 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 538 |
| 539 | if (sdp_handler_) { |
| 540 | sdp_handler_->PrepareForShutdown(); |
| 541 | } |
| 542 |
| 543 | // Need to stop transceivers before destroying the stats collector because |
| 544 | // AudioRtpSender has a reference to the LegacyStatsCollector it will update |
| 545 | // when stopping. |
| 546 | if (rtp_manager()) { |
| 547 | for (const auto& transceiver : rtp_manager()->transceivers()->List()) { |
| 548 | transceiver->StopInternal(); |
| 549 | } |
| 550 | } |
| 551 |
| 552 | legacy_stats_.reset(nullptr); |
| 553 | if (stats_collector_) { |
| 554 | stats_collector_->WaitForPendingRequest(); |
| 555 | stats_collector_ = nullptr; |
| 556 | } |
| 557 |
| 558 | if (sdp_handler_) { |
| 559 | // Don't destroy BaseChannels until after stats has been cleaned up so that |
| 560 | // the last stats request can still read from the channels. |
| 561 | sdp_handler_->DestroyAllChannels(); |
| 562 |
| 563 | RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed."; |
| 564 |
| 565 | sdp_handler_->ResetSessionDescFactory(); |
| 566 | } |
| 567 |
| 568 | // port_allocator_ and transport_controller_ live on the network thread and |
| 569 | // should be destroyed there. |
| 570 | transport_controller_copy_ = nullptr; |
| 571 | network_thread()->BlockingCall([this] { |
| 572 | RTC_DCHECK_RUN_ON(network_thread()); |
| 573 | TeardownDataChannelTransport_n(); |
| 574 | transport_controller_.reset(); |
| 575 | port_allocator_.reset(); |
| 576 | if (network_thread_safety_) |
| 577 | network_thread_safety_->SetNotAlive(); |
| 578 | }); |
| 579 |
| 580 | // call_ and event_log_ must be destroyed on the worker thread. |
| 581 | worker_thread()->BlockingCall([this] { |
| 582 | RTC_DCHECK_RUN_ON(worker_thread()); |
| 583 | worker_thread_safety_->SetNotAlive(); |
| 584 | call_.reset(); |
| 585 | // The event log must outlive call (and any other object that uses it). |
| 586 | event_log_.reset(); |
| 587 | }); |
| 588 | } |
| 589 |
| 590 | RTCError PeerConnection::Initialize( |
| 591 | const PeerConnectionInterface::RTCConfiguration& configuration, |
| 592 | PeerConnectionDependencies dependencies) { |
| 593 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 594 | TRACE_EVENT0("webrtc", "PeerConnection::Initialize"); |
| 595 |
| 596 | cricket::ServerAddresses stun_servers; |
| 597 | std::vector<cricket::RelayServerConfig> turn_servers; |
| 598 |
| 599 | RTCError parse_error = ParseIceServersOrError(configuration.servers, |
| 600 | &stun_servers, &turn_servers); |
| 601 | if (!parse_error.ok()) { |
| 602 | return parse_error; |
| 603 | } |
| 604 |
| 605 | // Add the turn logging id to all turn servers |
| 606 | for (cricket::RelayServerConfig& turn_server : turn_servers) { |
| 607 | turn_server.turn_logging_id = configuration.turn_logging_id; |
| 608 | } |
| 609 |
| 610 | // Note if STUN or TURN servers were supplied. |
| 611 | if (!stun_servers.empty()) { |
| 612 | NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED); |
| 613 | } |
| 614 | if (!turn_servers.empty()) { |
| 615 | NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED); |
| 616 | } |
| 617 |
| 618 | // Network thread initialization. |
| 619 | transport_controller_copy_ = |
| 620 | network_thread()->BlockingCall([&] { |
| 621 | RTC_DCHECK_RUN_ON(network_thread()); |
| 622 | network_thread_safety_ = PendingTaskSafetyFlag::Create(); |
| 623 | InitializePortAllocatorResult pa_result = InitializePortAllocator_n( |
| 624 | stun_servers, turn_servers, configuration); |
| 625 | // Send information about IPv4/IPv6 status. |
| 626 | PeerConnectionAddressFamilyCounter address_family = |
| 627 | pa_result.enable_ipv6 ? kPeerConnection_IPv6 : kPeerConnection_IPv4; |
| 628 | RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", |
| 629 | address_family, |
| 630 | kPeerConnectionAddressFamilyCounter_Max); |
| 631 | return InitializeTransportController_n(configuration, dependencies); |
| 632 | }); |
| 633 |
| 634 | configuration_ = configuration; |
| 635 |
| 636 | legacy_stats_ = std::make_unique<LegacyStatsCollector>(this); |
| 637 | stats_collector_ = RTCStatsCollector::Create(this); |
| 638 |
| 639 | sdp_handler_ = SdpOfferAnswerHandler::Create(this, configuration, |
| 640 | dependencies, context_.get()); |
| 641 |
| 642 | rtp_manager_ = std::make_unique<RtpTransmissionManager>( |
| 643 | IsUnifiedPlan(), context_.get(), &usage_pattern_, observer_, |
| 644 | legacy_stats_.get(), [this]() { |
| 645 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 646 | sdp_handler_->UpdateNegotiationNeeded(); |
| 647 | }); |
| 648 |
| 649 | // Add default audio/video transceivers for Plan B SDP. |
| 650 | if (!IsUnifiedPlan()) { |
| 651 | rtp_manager()->transceivers()->Add( |
| 652 | RtpTransceiverProxyWithInternal<RtpTransceiver>::Create( |
| 653 | signaling_thread(), rtc::make_ref_counted<RtpTransceiver>( |
| 654 | cricket::MEDIA_TYPE_AUDIO, context()))); |
| 655 | rtp_manager()->transceivers()->Add( |
| 656 | RtpTransceiverProxyWithInternal<RtpTransceiver>::Create( |
| 657 | signaling_thread(), rtc::make_ref_counted<RtpTransceiver>( |
| 658 | cricket::MEDIA_TYPE_VIDEO, context()))); |
| 659 | } |
| 660 |
| 661 | int delay_ms = configuration.report_usage_pattern_delay_ms |
| 662 | ? *configuration.report_usage_pattern_delay_ms |
| 663 | : REPORT_USAGE_PATTERN_DELAY_MS; |
| 664 | message_handler_.RequestUsagePatternReport( |
| 665 | [this]() { |
| 666 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 667 | ReportUsagePattern(); |
| 668 | }, |
| 669 | delay_ms); |
| 670 |
| 671 | return RTCError::OK(); |
| 672 | } |
| 673 |
| 674 | JsepTransportController* PeerConnection::InitializeTransportController_n( |
| 675 | const RTCConfiguration& configuration, |
| 676 | const PeerConnectionDependencies& dependencies) { |
| 677 | JsepTransportController::Config config; |
| 678 | config.redetermine_role_on_ice_restart = |
| 679 | configuration.redetermine_role_on_ice_restart; |
| 680 | config.ssl_max_version = options_.ssl_max_version; |
| 681 | config.disable_encryption = options_.disable_encryption; |
| 682 | config.bundle_policy = configuration.bundle_policy; |
| 683 | config.rtcp_mux_policy = configuration.rtcp_mux_policy; |
| 684 | // TODO(bugs.webrtc.org/9891) - Remove options_.crypto_options then remove |
| 685 | // this stub. |
| 686 | config.crypto_options = configuration.crypto_options.has_value() |
| 687 | ? *configuration.crypto_options |
| 688 | : options_.crypto_options; |
| 689 | config.transport_observer = this; |
| 690 | config.rtcp_handler = InitializeRtcpCallback(); |
| 691 | config.event_log = event_log_ptr_; |
| 692 | #if defined(ENABLE_EXTERNAL_AUTH) |
| 693 | config.enable_external_auth = true; |
| 694 | #endif |
| 695 | config.active_reset_srtp_params = configuration.active_reset_srtp_params; |
| 696 |
| 697 | // DTLS has to be enabled to use SCTP. |
| 698 | if (dtls_enabled_) { |
| 699 | config.sctp_factory = context_->sctp_transport_factory(); |
| 700 | } |
| 701 |
| 702 | config.ice_transport_factory = ice_transport_factory_.get(); |
| 703 | config.on_dtls_handshake_error_ = |
| 704 | [weak_ptr = weak_factory_.GetWeakPtr()](rtc::SSLHandshakeError s) { |
| 705 | if (weak_ptr) { |
| 706 | weak_ptr->OnTransportControllerDtlsHandshakeError(s); |
| 707 | } |
| 708 | }; |
| 709 |
| 710 | config.field_trials = trials_.get(); |
| 711 |
| 712 | transport_controller_.reset( |
| 713 | new JsepTransportController(network_thread(), port_allocator_.get(), |
| 714 | async_dns_resolver_factory_.get(), config)); |
| 715 |
| 716 | transport_controller_->SubscribeIceConnectionState( |
| 717 | [this](cricket::IceConnectionState s) { |
| 718 | RTC_DCHECK_RUN_ON(network_thread()); |
| 719 | if (s == cricket::kIceConnectionConnected) { |
| 720 | ReportTransportStats(); |
| 721 | } |
| 722 | signaling_thread()->PostTask( |
| 723 | SafeTask(signaling_thread_safety_.flag(), [this, s]() { |
| 724 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 725 | OnTransportControllerConnectionState(s); |
| 726 | })); |
| 727 | }); |
| 728 | transport_controller_->SubscribeConnectionState( |
| 729 | [this](PeerConnectionInterface::PeerConnectionState s) { |
| 730 | RTC_DCHECK_RUN_ON(network_thread()); |
| 731 | signaling_thread()->PostTask( |
| 732 | SafeTask(signaling_thread_safety_.flag(), [this, s]() { |
| 733 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 734 | SetConnectionState(s); |
| 735 | })); |
| 736 | }); |
| 737 | transport_controller_->SubscribeStandardizedIceConnectionState( |
| 738 | [this](PeerConnectionInterface::IceConnectionState s) { |
| 739 | RTC_DCHECK_RUN_ON(network_thread()); |
| 740 | signaling_thread()->PostTask( |
| 741 | SafeTask(signaling_thread_safety_.flag(), [this, s]() { |
| 742 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 743 | SetStandardizedIceConnectionState(s); |
| 744 | })); |
| 745 | }); |
| 746 | transport_controller_->SubscribeIceGatheringState( |
| 747 | [this](cricket::IceGatheringState s) { |
| 748 | RTC_DCHECK_RUN_ON(network_thread()); |
| 749 | signaling_thread()->PostTask( |
| 750 | SafeTask(signaling_thread_safety_.flag(), [this, s]() { |
| 751 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 752 | OnTransportControllerGatheringState(s); |
| 753 | })); |
| 754 | }); |
| 755 | transport_controller_->SubscribeIceCandidateGathered( |
| 756 | [this](const std::string& transport, |
| 757 | const std::vector<cricket::Candidate>& candidates) { |
| 758 | RTC_DCHECK_RUN_ON(network_thread()); |
| 759 | signaling_thread()->PostTask( |
| 760 | SafeTask(signaling_thread_safety_.flag(), |
| 761 | [this, t = transport, c = candidates]() { |
| 762 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 763 | OnTransportControllerCandidatesGathered(t, c); |
| 764 | })); |
| 765 | }); |
| 766 | transport_controller_->SubscribeIceCandidateError( |
| 767 | [this](const cricket::IceCandidateErrorEvent& event) { |
| 768 | RTC_DCHECK_RUN_ON(network_thread()); |
| 769 | signaling_thread()->PostTask( |
| 770 | SafeTask(signaling_thread_safety_.flag(), [this, event = event]() { |
| 771 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 772 | OnTransportControllerCandidateError(event); |
| 773 | })); |
| 774 | }); |
| 775 | transport_controller_->SubscribeIceCandidatesRemoved( |
| 776 | [this](const std::vector<cricket::Candidate>& c) { |
| 777 | RTC_DCHECK_RUN_ON(network_thread()); |
| 778 | signaling_thread()->PostTask( |
| 779 | SafeTask(signaling_thread_safety_.flag(), [this, c = c]() { |
| 780 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 781 | OnTransportControllerCandidatesRemoved(c); |
| 782 | })); |
| 783 | }); |
| 784 | transport_controller_->SubscribeIceCandidatePairChanged( |
| 785 | [this](const cricket::CandidatePairChangeEvent& event) { |
| 786 | RTC_DCHECK_RUN_ON(network_thread()); |
| 787 | signaling_thread()->PostTask( |
| 788 | SafeTask(signaling_thread_safety_.flag(), [this, event = event]() { |
| 789 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 790 | OnTransportControllerCandidateChanged(event); |
| 791 | })); |
| 792 | }); |
| 793 |
| 794 | transport_controller_->SetIceConfig(ParseIceConfig(configuration)); |
| 795 | return transport_controller_.get(); |
| 796 | } |
| 797 |
| 798 | rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() { |
| 799 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 800 | RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified " |
| 801 | "Plan SdpSemantics. Please use GetSenders " |
| 802 | "instead."; |
| 803 | return sdp_handler_->local_streams(); |
| 804 | } |
| 805 |
| 806 | rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() { |
| 807 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 808 | RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified " |
| 809 | "Plan SdpSemantics. Please use GetReceivers " |
| 810 | "instead."; |
| 811 | return sdp_handler_->remote_streams(); |
| 812 | } |
| 813 |
| 814 | bool PeerConnection::AddStream(MediaStreamInterface* local_stream) { |
| 815 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 816 | RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan " |
| 817 | "SdpSemantics. Please use AddTrack instead."; |
| 818 | TRACE_EVENT0("webrtc", "PeerConnection::AddStream"); |
| 819 | if (!ConfiguredForMedia()) { |
| 820 | RTC_LOG(LS_ERROR) << "AddStream: Not configured for media"; |
| 821 | return false; |
| 822 | } |
| 823 | return sdp_handler_->AddStream(local_stream); |
| 824 | } |
| 825 |
| 826 | void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) { |
| 827 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 828 | RTC_DCHECK(ConfiguredForMedia()); |
| 829 | RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified " |
| 830 | "Plan SdpSemantics. Please use RemoveTrack " |
| 831 | "instead."; |
| 832 | TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream"); |
| 833 | sdp_handler_->RemoveStream(local_stream); |
| 834 | } |
| 835 |
| 836 | RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack( |
| 837 | rtc::scoped_refptr<MediaStreamTrackInterface> track, |
| 838 | const std::vector<std::string>& stream_ids) { |
| 839 | return AddTrack(std::move(track), stream_ids, nullptr); |
| 840 | } |
| 841 |
| 842 | RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack( |
| 843 | rtc::scoped_refptr<MediaStreamTrackInterface> track, |
| 844 | const std::vector<std::string>& stream_ids, |
| 845 | const std::vector<RtpEncodingParameters>& init_send_encodings) { |
| 846 | return AddTrack(std::move(track), stream_ids, &init_send_encodings); |
| 847 | } |
| 848 |
| 849 | RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack( |
| 850 | rtc::scoped_refptr<MediaStreamTrackInterface> track, |
| 851 | const std::vector<std::string>& stream_ids, |
| 852 | const std::vector<RtpEncodingParameters>* init_send_encodings) { |
| 853 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 854 | TRACE_EVENT0("webrtc", "PeerConnection::AddTrack"); |
| 855 | if (!ConfiguredForMedia()) { |
| 856 | LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION, |
| 857 | "Not configured for media"); |
| 858 | } |
| 859 | if (!track) { |
| 860 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null."); |
| 861 | } |
| 862 | if (!(track->kind() == MediaStreamTrackInterface::kAudioKind || |
| 863 | track->kind() == MediaStreamTrackInterface::kVideoKind)) { |
| 864 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 865 | "Track has invalid kind: " + track->kind()); |
| 866 | } |
| 867 | if (IsClosed()) { |
| 868 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE, |
| 869 | "PeerConnection is closed."); |
| 870 | } |
| 871 | if (rtp_manager()->FindSenderForTrack(track.get())) { |
| 872 | LOG_AND_RETURN_ERROR( |
| 873 | RTCErrorType::INVALID_PARAMETER, |
| 874 | "Sender already exists for track " + track->id() + "."); |
| 875 | } |
| 876 | auto sender_or_error = |
| 877 | rtp_manager()->AddTrack(track, stream_ids, init_send_encodings); |
| 878 | if (sender_or_error.ok()) { |
| 879 | sdp_handler_->UpdateNegotiationNeeded(); |
| 880 | legacy_stats_->AddTrack(track.get()); |
| 881 | } |
| 882 | return sender_or_error; |
| 883 | } |
| 884 |
| 885 | RTCError PeerConnection::RemoveTrackOrError( |
| 886 | rtc::scoped_refptr<RtpSenderInterface> sender) { |
| 887 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 888 | if (!ConfiguredForMedia()) { |
| 889 | LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION, |
| 890 | "Not configured for media"); |
| 891 | } |
| 892 | if (!sender) { |
| 893 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null."); |
| 894 | } |
| 895 | if (IsClosed()) { |
| 896 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE, |
| 897 | "PeerConnection is closed."); |
| 898 | } |
| 899 | if (IsUnifiedPlan()) { |
| 900 | auto transceiver = FindTransceiverBySender(sender); |
| 901 | if (!transceiver || !sender->track()) { |
| 902 | return RTCError::OK(); |
| 903 | } |
| 904 | sender->SetTrack(nullptr); |
| 905 | if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) { |
| 906 | transceiver->internal()->set_direction( |
| 907 | RtpTransceiverDirection::kRecvOnly); |
| 908 | } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) { |
| 909 | transceiver->internal()->set_direction( |
| 910 | RtpTransceiverDirection::kInactive); |
| 911 | } |
| 912 | } else { |
| 913 | bool removed; |
| 914 | if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) { |
| 915 | removed = rtp_manager()->GetAudioTransceiver()->internal()->RemoveSender( |
| 916 | sender.get()); |
| 917 | } else { |
| 918 | RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type()); |
| 919 | removed = rtp_manager()->GetVideoTransceiver()->internal()->RemoveSender( |
| 920 | sender.get()); |
| 921 | } |
| 922 | if (!removed) { |
| 923 | LOG_AND_RETURN_ERROR( |
| 924 | RTCErrorType::INVALID_PARAMETER, |
| 925 | "Couldn't find sender " + sender->id() + " to remove."); |
| 926 | } |
| 927 | } |
| 928 | sdp_handler_->UpdateNegotiationNeeded(); |
| 929 | return RTCError::OK(); |
| 930 | } |
| 931 |
| 932 | rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>> |
| 933 | PeerConnection::FindTransceiverBySender( |
| 934 | rtc::scoped_refptr<RtpSenderInterface> sender) { |
| 935 | return rtp_manager()->transceivers()->FindBySender(sender); |
| 936 | } |
| 937 |
| 938 | RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>> |
| 939 | PeerConnection::AddTransceiver( |
| 940 | rtc::scoped_refptr<MediaStreamTrackInterface> track) { |
| 941 | if (!ConfiguredForMedia()) { |
| 942 | LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION, |
| 943 | "Not configured for media"); |
| 944 | } |
| 945 |
| 946 | return AddTransceiver(track, RtpTransceiverInit()); |
| 947 | } |
| 948 |
| 949 | RtpTransportInternal* PeerConnection::GetRtpTransport(const std::string& mid) { |
| 950 | // TODO(bugs.webrtc.org/9987): Avoid the thread jump. |
| 951 | // This might be done by caching the value on the signaling thread. |
| 952 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 953 | return network_thread()->BlockingCall([this, &mid] { |
| 954 | RTC_DCHECK_RUN_ON(network_thread()); |
| 955 | auto rtp_transport = transport_controller_->GetRtpTransport(mid); |
| 956 | RTC_DCHECK(rtp_transport); |
| 957 | return rtp_transport; |
| 958 | }); |
| 959 | } |
| 960 |
| 961 | RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>> |
| 962 | PeerConnection::AddTransceiver( |
| 963 | rtc::scoped_refptr<MediaStreamTrackInterface> track, |
| 964 | const RtpTransceiverInit& init) { |
| 965 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 966 | if (!ConfiguredForMedia()) { |
| 967 | LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION, |
| 968 | "Not configured for media"); |
| 969 | } |
| 970 | RTC_CHECK(IsUnifiedPlan()) |
| 971 | << "AddTransceiver is only available with Unified Plan SdpSemantics"; |
| 972 | if (!track) { |
| 973 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null"); |
| 974 | } |
| 975 | cricket::MediaType media_type; |
| 976 | if (track->kind() == MediaStreamTrackInterface::kAudioKind) { |
| 977 | media_type = cricket::MEDIA_TYPE_AUDIO; |
| 978 | } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) { |
| 979 | media_type = cricket::MEDIA_TYPE_VIDEO; |
| 980 | } else { |
| 981 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 982 | "Track kind is not audio or video"); |
| 983 | } |
| 984 | return AddTransceiver(media_type, track, init); |
| 985 | } |
| 986 |
| 987 | RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>> |
| 988 | PeerConnection::AddTransceiver(cricket::MediaType media_type) { |
| 989 | return AddTransceiver(media_type, RtpTransceiverInit()); |
| 990 | } |
| 991 |
| 992 | RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>> |
| 993 | PeerConnection::AddTransceiver(cricket::MediaType media_type, |
| 994 | const RtpTransceiverInit& init) { |
| 995 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 996 | if (!ConfiguredForMedia()) { |
| 997 | LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION, |
| 998 | "Not configured for media"); |
| 999 | } |
| 1000 | RTC_CHECK(IsUnifiedPlan()) |
| 1001 | << "AddTransceiver is only available with Unified Plan SdpSemantics"; |
| 1002 | if (!(media_type == cricket::MEDIA_TYPE_AUDIO || |
| 1003 | media_type == cricket::MEDIA_TYPE_VIDEO)) { |
| 1004 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 1005 | "media type is not audio or video"); |
| 1006 | } |
| 1007 | return AddTransceiver(media_type, nullptr, init); |
| 1008 | } |
| 1009 |
| 1010 | RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>> |
| 1011 | PeerConnection::AddTransceiver( |
| 1012 | cricket::MediaType media_type, |
| 1013 | rtc::scoped_refptr<MediaStreamTrackInterface> track, |
| 1014 | const RtpTransceiverInit& init, |
| 1015 | bool update_negotiation_needed) { |
| 1016 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1017 | if (!ConfiguredForMedia()) { |
| 1018 | LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION, |
| 1019 | "Not configured for media"); |
| 1020 | } |
| 1021 | RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO || |
| 1022 | media_type == cricket::MEDIA_TYPE_VIDEO)); |
| 1023 | if (track) { |
| 1024 | RTC_DCHECK_EQ(media_type, |
| 1025 | (track->kind() == MediaStreamTrackInterface::kAudioKind |
| 1026 | ? cricket::MEDIA_TYPE_AUDIO |
| 1027 | : cricket::MEDIA_TYPE_VIDEO)); |
| 1028 | } |
| 1029 |
| 1030 | RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings, |
| 1031 | init.send_encodings.size(), 0, 7, 8); |
| 1032 |
| 1033 | size_t num_rids = absl::c_count_if(init.send_encodings, |
| 1034 | [](const RtpEncodingParameters& encoding) { |
| 1035 | return !encoding.rid.empty(); |
| 1036 | }); |
| 1037 | if (num_rids > 0 && num_rids != init.send_encodings.size()) { |
| 1038 | LOG_AND_RETURN_ERROR( |
| 1039 | RTCErrorType::INVALID_PARAMETER, |
| 1040 | "RIDs must be provided for either all or none of the send encodings."); |
| 1041 | } |
| 1042 |
| 1043 | if (num_rids > 0 && absl::c_any_of(init.send_encodings, |
| 1044 | [](const RtpEncodingParameters& encoding) { |
| 1045 | return !IsLegalRsidName(encoding.rid); |
| 1046 | })) { |
| 1047 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 1048 | "Invalid RID value provided."); |
| 1049 | } |
| 1050 |
| 1051 | if (absl::c_any_of(init.send_encodings, |
| 1052 | [](const RtpEncodingParameters& encoding) { |
| 1053 | return encoding.ssrc.has_value(); |
| 1054 | })) { |
| 1055 | LOG_AND_RETURN_ERROR( |
| 1056 | RTCErrorType::UNSUPPORTED_PARAMETER, |
| 1057 | "Attempted to set an unimplemented parameter of RtpParameters."); |
| 1058 | } |
| 1059 |
| 1060 | RtpParameters parameters; |
| 1061 | parameters.encodings = init.send_encodings; |
| 1062 |
| 1063 | // Encodings are dropped from the tail if too many are provided. |
| 1064 | size_t max_simulcast_streams = |
| 1065 | media_type == cricket::MEDIA_TYPE_VIDEO ? kMaxSimulcastStreams : 1u; |
| 1066 | if (parameters.encodings.size() > max_simulcast_streams) { |
| 1067 | parameters.encodings.erase( |
| 1068 | parameters.encodings.begin() + max_simulcast_streams, |
| 1069 | parameters.encodings.end()); |
| 1070 | } |
| 1071 |
| 1072 | // Single RID should be removed. |
| 1073 | if (parameters.encodings.size() == 1 && |
| 1074 | !parameters.encodings[0].rid.empty()) { |
| 1075 | RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << "."; |
| 1076 | parameters.encodings[0].rid.clear(); |
| 1077 | } |
| 1078 |
| 1079 | // If RIDs were not provided, they are generated for simulcast scenario. |
| 1080 | if (parameters.encodings.size() > 1 && num_rids == 0) { |
| 1081 | rtc::UniqueStringGenerator rid_generator; |
| 1082 | for (RtpEncodingParameters& encoding : parameters.encodings) { |
| 1083 | encoding.rid = rid_generator(); |
| 1084 | } |
| 1085 | } |
| 1086 |
| 1087 | if (UnimplementedRtpParameterHasValue(parameters)) { |
| 1088 | LOG_AND_RETURN_ERROR( |
| 1089 | RTCErrorType::UNSUPPORTED_PARAMETER, |
| 1090 | "Attempted to set an unimplemented parameter of RtpParameters."); |
| 1091 | } |
| 1092 |
| 1093 | std::vector<cricket::VideoCodec> codecs; |
| 1094 | if (media_type == cricket::MEDIA_TYPE_VIDEO) { |
| 1095 | // Gather the current codec capabilities to allow checking scalabilityMode |
| 1096 | // against supported values. |
| 1097 | codecs = context_->media_engine()->video().send_codecs(false); |
| 1098 | } |
| 1099 |
| 1100 | auto result = cricket::CheckRtpParametersValues(parameters, codecs); |
| 1101 | if (!result.ok()) { |
| 1102 | LOG_AND_RETURN_ERROR(result.type(), result.message()); |
| 1103 | } |
| 1104 |
| 1105 | RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type) |
| 1106 | << " transceiver in response to a call to AddTransceiver."; |
| 1107 | // Set the sender ID equal to the track ID if the track is specified unless |
| 1108 | // that sender ID is already in use. |
| 1109 | std::string sender_id = (track && !rtp_manager()->FindSenderById(track->id()) |
| 1110 | ? track->id() |
| 1111 | : rtc::CreateRandomUuid()); |
| 1112 | auto sender = rtp_manager()->CreateSender( |
| 1113 | media_type, sender_id, track, init.stream_ids, parameters.encodings); |
| 1114 | auto receiver = |
| 1115 | rtp_manager()->CreateReceiver(media_type, rtc::CreateRandomUuid()); |
| 1116 | auto transceiver = rtp_manager()->CreateAndAddTransceiver(sender, receiver); |
| 1117 | transceiver->internal()->set_direction(init.direction); |
| 1118 |
| 1119 | if (update_negotiation_needed) { |
| 1120 | sdp_handler_->UpdateNegotiationNeeded(); |
| 1121 | } |
| 1122 |
| 1123 | return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver); |
| 1124 | } |
| 1125 |
| 1126 | void PeerConnection::OnNegotiationNeeded() { |
| 1127 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1128 | RTC_DCHECK(!IsClosed()); |
| 1129 | sdp_handler_->UpdateNegotiationNeeded(); |
| 1130 | } |
| 1131 |
| 1132 | rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender( |
| 1133 | const std::string& kind, |
| 1134 | const std::string& stream_id) { |
| 1135 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1136 | if (!ConfiguredForMedia()) { |
| 1137 | RTC_LOG(LS_ERROR) << "Not configured for media"; |
| 1138 | return nullptr; |
| 1139 | } |
| 1140 | RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified " |
| 1141 | "Plan SdpSemantics. Please use AddTransceiver " |
| 1142 | "instead."; |
| 1143 | TRACE_EVENT0("webrtc", "PeerConnection::CreateSender"); |
| 1144 | if (IsClosed()) { |
| 1145 | return nullptr; |
| 1146 | } |
| 1147 |
| 1148 | // Internally we need to have one stream with Plan B semantics, so we |
| 1149 | // generate a random stream ID if not specified. |
| 1150 | std::vector<std::string> stream_ids; |
| 1151 | if (stream_id.empty()) { |
| 1152 | stream_ids.push_back(rtc::CreateRandomUuid()); |
| 1153 | RTC_LOG(LS_INFO) |
| 1154 | << "No stream_id specified for sender. Generated stream ID: " |
| 1155 | << stream_ids[0]; |
| 1156 | } else { |
| 1157 | stream_ids.push_back(stream_id); |
| 1158 | } |
| 1159 |
| 1160 | // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver. |
| 1161 | rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender; |
| 1162 | if (kind == MediaStreamTrackInterface::kAudioKind) { |
| 1163 | auto audio_sender = |
| 1164 | AudioRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), |
| 1165 | legacy_stats_.get(), rtp_manager()); |
| 1166 | audio_sender->SetMediaChannel(rtp_manager()->voice_media_channel()); |
| 1167 | new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create( |
| 1168 | signaling_thread(), audio_sender); |
| 1169 | rtp_manager()->GetAudioTransceiver()->internal()->AddSender(new_sender); |
| 1170 | } else if (kind == MediaStreamTrackInterface::kVideoKind) { |
| 1171 | auto video_sender = VideoRtpSender::Create( |
| 1172 | worker_thread(), rtc::CreateRandomUuid(), rtp_manager()); |
| 1173 | video_sender->SetMediaChannel(rtp_manager()->video_media_channel()); |
| 1174 | new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create( |
| 1175 | signaling_thread(), video_sender); |
| 1176 | rtp_manager()->GetVideoTransceiver()->internal()->AddSender(new_sender); |
| 1177 | } else { |
| 1178 | RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind; |
| 1179 | return nullptr; |
| 1180 | } |
| 1181 | new_sender->internal()->set_stream_ids(stream_ids); |
| 1182 |
| 1183 | return new_sender; |
| 1184 | } |
| 1185 |
| 1186 | std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders() |
| 1187 | const { |
| 1188 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1189 | std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret; |
| 1190 | if (ConfiguredForMedia()) { |
| 1191 | for (const auto& sender : rtp_manager()->GetSendersInternal()) { |
| 1192 | ret.push_back(sender); |
| 1193 | } |
| 1194 | } |
| 1195 | return ret; |
| 1196 | } |
| 1197 |
| 1198 | std::vector<rtc::scoped_refptr<RtpReceiverInterface>> |
| 1199 | PeerConnection::GetReceivers() const { |
| 1200 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1201 | std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret; |
| 1202 | if (ConfiguredForMedia()) { |
| 1203 | for (const auto& receiver : rtp_manager()->GetReceiversInternal()) { |
| 1204 | ret.push_back(receiver); |
| 1205 | } |
| 1206 | } |
| 1207 | return ret; |
| 1208 | } |
| 1209 |
| 1210 | std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> |
| 1211 | PeerConnection::GetTransceivers() const { |
| 1212 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1213 | RTC_CHECK(IsUnifiedPlan()) |
| 1214 | << "GetTransceivers is only supported with Unified Plan SdpSemantics."; |
| 1215 | std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers; |
| 1216 | if (ConfiguredForMedia()) { |
| 1217 | for (const auto& transceiver : rtp_manager()->transceivers()->List()) { |
| 1218 | all_transceivers.push_back(transceiver); |
| 1219 | } |
| 1220 | } |
| 1221 | return all_transceivers; |
| 1222 | } |
| 1223 |
| 1224 | bool PeerConnection::GetStats(StatsObserver* observer, |
| 1225 | MediaStreamTrackInterface* track, |
| 1226 | StatsOutputLevel level) { |
| 1227 | TRACE_EVENT0("webrtc", "PeerConnection::GetStats (legacy)"); |
| 1228 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1229 | if (!observer) { |
| 1230 | RTC_LOG(LS_ERROR) << "Legacy GetStats - observer is NULL."; |
| 1231 | return false; |
| 1232 | } |
| 1233 |
| 1234 | RTC_LOG_THREAD_BLOCK_COUNT(); |
| 1235 |
| 1236 | legacy_stats_->UpdateStats(level); |
| 1237 |
| 1238 | RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(4); |
| 1239 |
| 1240 | // The LegacyStatsCollector is used to tell if a track is valid because it may |
| 1241 | // remember tracks that the PeerConnection previously removed. |
| 1242 | if (track && !legacy_stats_->IsValidTrack(track->id())) { |
| 1243 | RTC_LOG(LS_WARNING) << "Legacy GetStats is called with an invalid track: " |
| 1244 | << track->id(); |
| 1245 | return false; |
| 1246 | } |
| 1247 | message_handler_.PostGetStats(observer, legacy_stats_.get(), track); |
| 1248 |
| 1249 | return true; |
| 1250 | } |
| 1251 |
| 1252 | void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) { |
| 1253 | TRACE_EVENT0("webrtc", "PeerConnection::GetStats"); |
| 1254 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1255 | RTC_DCHECK(stats_collector_); |
| 1256 | RTC_DCHECK(callback); |
| 1257 | RTC_LOG_THREAD_BLOCK_COUNT(); |
| 1258 | stats_collector_->GetStatsReport( |
| 1259 | rtc::scoped_refptr<RTCStatsCollectorCallback>(callback)); |
| 1260 | RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(2); |
| 1261 | } |
| 1262 |
| 1263 | void PeerConnection::GetStats( |
| 1264 | rtc::scoped_refptr<RtpSenderInterface> selector, |
| 1265 | rtc::scoped_refptr<RTCStatsCollectorCallback> callback) { |
| 1266 | TRACE_EVENT0("webrtc", "PeerConnection::GetStats"); |
| 1267 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1268 | RTC_DCHECK(callback); |
| 1269 | RTC_DCHECK(stats_collector_); |
| 1270 | RTC_LOG_THREAD_BLOCK_COUNT(); |
| 1271 | rtc::scoped_refptr<RtpSenderInternal> internal_sender; |
| 1272 | if (selector) { |
| 1273 | for (const auto& proxy_transceiver : |
| 1274 | rtp_manager()->transceivers()->List()) { |
| 1275 | for (const auto& proxy_sender : |
| 1276 | proxy_transceiver->internal()->senders()) { |
| 1277 | if (proxy_sender == selector) { |
| 1278 | internal_sender = proxy_sender->internal(); |
| 1279 | break; |
| 1280 | } |
| 1281 | } |
| 1282 | if (internal_sender) |
| 1283 | break; |
| 1284 | } |
| 1285 | } |
| 1286 | // If there is no `internal_sender` then `selector` is either null or does not |
| 1287 | // belong to the PeerConnection (in Plan B, senders can be removed from the |
| 1288 | // PeerConnection). This means that "all the stats objects representing the |
| 1289 | // selector" is an empty set. Invoking GetStatsReport() with a null selector |
| 1290 | // produces an empty stats report. |
| 1291 | stats_collector_->GetStatsReport(internal_sender, callback); |
| 1292 | RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(2); |
| 1293 | } |
| 1294 |
| 1295 | void PeerConnection::GetStats( |
| 1296 | rtc::scoped_refptr<RtpReceiverInterface> selector, |
| 1297 | rtc::scoped_refptr<RTCStatsCollectorCallback> callback) { |
| 1298 | TRACE_EVENT0("webrtc", "PeerConnection::GetStats"); |
| 1299 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1300 | RTC_DCHECK(callback); |
| 1301 | RTC_DCHECK(stats_collector_); |
| 1302 | RTC_LOG_THREAD_BLOCK_COUNT(); |
| 1303 | rtc::scoped_refptr<RtpReceiverInternal> internal_receiver; |
| 1304 | if (selector) { |
| 1305 | for (const auto& proxy_transceiver : |
| 1306 | rtp_manager()->transceivers()->List()) { |
| 1307 | for (const auto& proxy_receiver : |
| 1308 | proxy_transceiver->internal()->receivers()) { |
| 1309 | if (proxy_receiver == selector) { |
| 1310 | internal_receiver = proxy_receiver->internal(); |
| 1311 | break; |
| 1312 | } |
| 1313 | } |
| 1314 | if (internal_receiver) |
| 1315 | break; |
| 1316 | } |
| 1317 | } |
| 1318 | // If there is no `internal_receiver` then `selector` is either null or does |
| 1319 | // not belong to the PeerConnection (in Plan B, receivers can be removed from |
| 1320 | // the PeerConnection). This means that "all the stats objects representing |
| 1321 | // the selector" is an empty set. Invoking GetStatsReport() with a null |
| 1322 | // selector produces an empty stats report. |
| 1323 | stats_collector_->GetStatsReport(internal_receiver, callback); |
| 1324 | RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(2); |
| 1325 | } |
| 1326 |
| 1327 | PeerConnectionInterface::SignalingState PeerConnection::signaling_state() { |
| 1328 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1329 | return sdp_handler_->signaling_state(); |
| 1330 | } |
| 1331 |
| 1332 | PeerConnectionInterface::IceConnectionState |
| 1333 | PeerConnection::ice_connection_state() { |
| 1334 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1335 | return ice_connection_state_; |
| 1336 | } |
| 1337 |
| 1338 | PeerConnectionInterface::IceConnectionState |
| 1339 | PeerConnection::standardized_ice_connection_state() { |
| 1340 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1341 | return standardized_ice_connection_state_; |
| 1342 | } |
| 1343 |
| 1344 | PeerConnectionInterface::PeerConnectionState |
| 1345 | PeerConnection::peer_connection_state() { |
| 1346 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1347 | return connection_state_; |
| 1348 | } |
| 1349 |
| 1350 | PeerConnectionInterface::IceGatheringState |
| 1351 | PeerConnection::ice_gathering_state() { |
| 1352 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1353 | return ice_gathering_state_; |
| 1354 | } |
| 1355 |
| 1356 | absl::optional<bool> PeerConnection::can_trickle_ice_candidates() { |
| 1357 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1358 | const SessionDescriptionInterface* description = current_remote_description(); |
| 1359 | if (!description) { |
| 1360 | description = pending_remote_description(); |
| 1361 | } |
| 1362 | if (!description) { |
| 1363 | return absl::nullopt; |
| 1364 | } |
| 1365 | // TODO(bugs.webrtc.org/7443): Change to retrieve from session-level option. |
| 1366 | if (description->description()->transport_infos().size() < 1) { |
| 1367 | return absl::nullopt; |
| 1368 | } |
| 1369 | return description->description()->transport_infos()[0].description.HasOption( |
| 1370 | "trickle"); |
| 1371 | } |
| 1372 |
| 1373 | RTCErrorOr<rtc::scoped_refptr<DataChannelInterface>> |
| 1374 | PeerConnection::CreateDataChannelOrError(const std::string& label, |
| 1375 | const DataChannelInit* config) { |
| 1376 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1377 | TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel"); |
| 1378 |
| 1379 | bool first_datachannel = !data_channel_controller_.HasDataChannels(); |
| 1380 |
| 1381 | std::unique_ptr<InternalDataChannelInit> internal_config; |
| 1382 | if (config) { |
| 1383 | internal_config.reset(new InternalDataChannelInit(*config)); |
| 1384 | } |
| 1385 | // TODO(bugs.webrtc.org/12796): Return a more specific error. |
| 1386 | rtc::scoped_refptr<DataChannelInterface> channel( |
| 1387 | data_channel_controller_.InternalCreateDataChannelWithProxy( |
| 1388 | label, internal_config.get())); |
| 1389 | if (!channel.get()) { |
| 1390 | return RTCError(RTCErrorType::INTERNAL_ERROR, |
| 1391 | "Data channel creation failed"); |
| 1392 | } |
| 1393 |
| 1394 | // Trigger the onRenegotiationNeeded event for |
| 1395 | // the first SCTP DataChannel. |
| 1396 | if (first_datachannel) { |
| 1397 | sdp_handler_->UpdateNegotiationNeeded(); |
| 1398 | } |
| 1399 | NoteUsageEvent(UsageEvent::DATA_ADDED); |
| 1400 | return channel; |
| 1401 | } |
| 1402 |
| 1403 | void PeerConnection::RestartIce() { |
| 1404 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1405 | sdp_handler_->RestartIce(); |
| 1406 | } |
| 1407 |
| 1408 | void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer, |
| 1409 | const RTCOfferAnswerOptions& options) { |
| 1410 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1411 | sdp_handler_->CreateOffer(observer, options); |
| 1412 | } |
| 1413 |
| 1414 | void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer, |
| 1415 | const RTCOfferAnswerOptions& options) { |
| 1416 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1417 | sdp_handler_->CreateAnswer(observer, options); |
| 1418 | } |
| 1419 |
| 1420 | void PeerConnection::SetLocalDescription( |
| 1421 | SetSessionDescriptionObserver* observer, |
| 1422 | SessionDescriptionInterface* desc_ptr) { |
| 1423 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1424 | sdp_handler_->SetLocalDescription(observer, desc_ptr); |
| 1425 | } |
| 1426 |
| 1427 | void PeerConnection::SetLocalDescription( |
| 1428 | std::unique_ptr<SessionDescriptionInterface> desc, |
| 1429 | rtc::scoped_refptr<SetLocalDescriptionObserverInterface> observer) { |
| 1430 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1431 | sdp_handler_->SetLocalDescription(std::move(desc), observer); |
| 1432 | } |
| 1433 |
| 1434 | void PeerConnection::SetLocalDescription( |
| 1435 | SetSessionDescriptionObserver* observer) { |
| 1436 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1437 | sdp_handler_->SetLocalDescription(observer); |
| 1438 | } |
| 1439 |
| 1440 | void PeerConnection::SetLocalDescription( |
| 1441 | rtc::scoped_refptr<SetLocalDescriptionObserverInterface> observer) { |
| 1442 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1443 | sdp_handler_->SetLocalDescription(observer); |
| 1444 | } |
| 1445 |
| 1446 | void PeerConnection::SetRemoteDescription( |
| 1447 | SetSessionDescriptionObserver* observer, |
| 1448 | SessionDescriptionInterface* desc_ptr) { |
| 1449 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1450 | sdp_handler_->SetRemoteDescription(observer, desc_ptr); |
| 1451 | } |
| 1452 |
| 1453 | void PeerConnection::SetRemoteDescription( |
| 1454 | std::unique_ptr<SessionDescriptionInterface> desc, |
| 1455 | rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) { |
| 1456 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1457 | sdp_handler_->SetRemoteDescription(std::move(desc), observer); |
| 1458 | } |
| 1459 |
| 1460 | PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() { |
| 1461 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1462 | return configuration_; |
| 1463 | } |
| 1464 |
| 1465 | RTCError PeerConnection::SetConfiguration( |
| 1466 | const RTCConfiguration& configuration) { |
| 1467 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1468 | TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration"); |
| 1469 | if (IsClosed()) { |
| 1470 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE, |
| 1471 | "SetConfiguration: PeerConnection is closed."); |
| 1472 | } |
| 1473 |
| 1474 | // According to JSEP, after setLocalDescription, changing the candidate pool |
| 1475 | // size is not allowed, and changing the set of ICE servers will not result |
| 1476 | // in new candidates being gathered. |
| 1477 | if (local_description() && configuration.ice_candidate_pool_size != |
| 1478 | configuration_.ice_candidate_pool_size) { |
| 1479 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION, |
| 1480 | "Can't change candidate pool size after calling " |
| 1481 | "SetLocalDescription."); |
| 1482 | } |
| 1483 |
| 1484 | if (local_description() && |
| 1485 | configuration.crypto_options != configuration_.crypto_options) { |
| 1486 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION, |
| 1487 | "Can't change crypto_options after calling " |
| 1488 | "SetLocalDescription."); |
| 1489 | } |
| 1490 |
| 1491 | // The simplest (and most future-compatible) way to tell if the config was |
| 1492 | // modified in an invalid way is to copy each property we do support |
| 1493 | // modifying, then use operator==. There are far more properties we don't |
| 1494 | // support modifying than those we do, and more could be added. |
| 1495 | RTCConfiguration modified_config = configuration_; |
| 1496 | modified_config.servers = configuration.servers; |
| 1497 | modified_config.type = configuration.type; |
| 1498 | modified_config.ice_candidate_pool_size = |
| 1499 | configuration.ice_candidate_pool_size; |
| 1500 | modified_config.prune_turn_ports = configuration.prune_turn_ports; |
| 1501 | modified_config.turn_port_prune_policy = configuration.turn_port_prune_policy; |
| 1502 | modified_config.surface_ice_candidates_on_ice_transport_type_changed = |
| 1503 | configuration.surface_ice_candidates_on_ice_transport_type_changed; |
| 1504 | modified_config.ice_check_min_interval = configuration.ice_check_min_interval; |
| 1505 | modified_config.ice_check_interval_strong_connectivity = |
| 1506 | configuration.ice_check_interval_strong_connectivity; |
| 1507 | modified_config.ice_check_interval_weak_connectivity = |
| 1508 | configuration.ice_check_interval_weak_connectivity; |
| 1509 | modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout; |
| 1510 | modified_config.ice_unwritable_min_checks = |
| 1511 | configuration.ice_unwritable_min_checks; |
| 1512 | modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout; |
| 1513 | modified_config.stun_candidate_keepalive_interval = |
| 1514 | configuration.stun_candidate_keepalive_interval; |
| 1515 | modified_config.turn_customizer = configuration.turn_customizer; |
| 1516 | modified_config.network_preference = configuration.network_preference; |
| 1517 | modified_config.active_reset_srtp_params = |
| 1518 | configuration.active_reset_srtp_params; |
| 1519 | modified_config.turn_logging_id = configuration.turn_logging_id; |
| 1520 | modified_config.allow_codec_switching = configuration.allow_codec_switching; |
| 1521 | modified_config.stable_writable_connection_ping_interval_ms = |
| 1522 | configuration.stable_writable_connection_ping_interval_ms; |
| 1523 | if (configuration != modified_config) { |
| 1524 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION, |
| 1525 | "Modifying the configuration in an unsupported way."); |
| 1526 | } |
| 1527 |
| 1528 | // Validate the modified configuration. |
| 1529 | RTCError validate_error = ValidateConfiguration(modified_config); |
| 1530 | if (!validate_error.ok()) { |
| 1531 | return validate_error; |
| 1532 | } |
| 1533 |
| 1534 | // Note that this isn't possible through chromium, since it's an unsigned |
| 1535 | // short in WebIDL. |
| 1536 | if (configuration.ice_candidate_pool_size < 0 || |
| 1537 | configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) { |
| 1538 | return RTCError(RTCErrorType::INVALID_RANGE); |
| 1539 | } |
| 1540 |
| 1541 | // Parse ICE servers before hopping to network thread. |
| 1542 | cricket::ServerAddresses stun_servers; |
| 1543 | std::vector<cricket::RelayServerConfig> turn_servers; |
| 1544 | RTCError parse_error = ParseIceServersOrError(configuration.servers, |
| 1545 | &stun_servers, &turn_servers); |
| 1546 | if (!parse_error.ok()) { |
| 1547 | return parse_error; |
| 1548 | } |
| 1549 | // Add the turn logging id to all turn servers |
| 1550 | for (cricket::RelayServerConfig& turn_server : turn_servers) { |
| 1551 | turn_server.turn_logging_id = configuration.turn_logging_id; |
| 1552 | } |
| 1553 |
| 1554 | // Note if STUN or TURN servers were supplied. |
| 1555 | if (!stun_servers.empty()) { |
| 1556 | NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED); |
| 1557 | } |
| 1558 | if (!turn_servers.empty()) { |
| 1559 | NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED); |
| 1560 | } |
| 1561 |
| 1562 | const bool has_local_description = local_description() != nullptr; |
| 1563 |
| 1564 | const bool needs_ice_restart = |
| 1565 | modified_config.servers != configuration_.servers || |
| 1566 | NeedIceRestart( |
| 1567 | configuration_.surface_ice_candidates_on_ice_transport_type_changed, |
| 1568 | configuration_.type, modified_config.type) || |
| 1569 | modified_config.GetTurnPortPrunePolicy() != |
| 1570 | configuration_.GetTurnPortPrunePolicy(); |
| 1571 | cricket::IceConfig ice_config = ParseIceConfig(modified_config); |
| 1572 |
| 1573 | // Apply part of the configuration on the network thread. In theory this |
| 1574 | // shouldn't fail. |
| 1575 | if (!network_thread()->BlockingCall( |
| 1576 | [this, needs_ice_restart, &ice_config, &stun_servers, &turn_servers, |
| 1577 | &modified_config, has_local_description] { |
| 1578 | RTC_DCHECK_RUN_ON(network_thread()); |
| 1579 | // As described in JSEP, calling setConfiguration with new ICE |
| 1580 | // servers or candidate policy must set a "needs-ice-restart" bit so |
| 1581 | // that the next offer triggers an ICE restart which will pick up |
| 1582 | // the changes. |
| 1583 | if (needs_ice_restart) |
| 1584 | transport_controller_->SetNeedsIceRestartFlag(); |
| 1585 |
| 1586 | transport_controller_->SetIceConfig(ice_config); |
| 1587 | return ReconfigurePortAllocator_n( |
| 1588 | stun_servers, turn_servers, modified_config.type, |
| 1589 | modified_config.ice_candidate_pool_size, |
| 1590 | modified_config.GetTurnPortPrunePolicy(), |
| 1591 | modified_config.turn_customizer, |
| 1592 | modified_config.stun_candidate_keepalive_interval, |
| 1593 | has_local_description); |
| 1594 | })) { |
| 1595 | LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, |
| 1596 | "Failed to apply configuration to PortAllocator."); |
| 1597 | } |
| 1598 |
| 1599 | if (configuration_.active_reset_srtp_params != |
| 1600 | modified_config.active_reset_srtp_params) { |
| 1601 | // TODO(tommi): merge BlockingCalls |
| 1602 | network_thread()->BlockingCall([this, &modified_config] { |
| 1603 | RTC_DCHECK_RUN_ON(network_thread()); |
| 1604 | transport_controller_->SetActiveResetSrtpParams( |
| 1605 | modified_config.active_reset_srtp_params); |
| 1606 | }); |
| 1607 | } |
| 1608 |
| 1609 | if (modified_config.allow_codec_switching.has_value()) { |
| 1610 | std::vector<cricket::VideoMediaChannel*> channels; |
| 1611 | for (const auto& transceiver : rtp_manager()->transceivers()->List()) { |
| 1612 | if (transceiver->media_type() != cricket::MEDIA_TYPE_VIDEO) |
| 1613 | continue; |
| 1614 |
| 1615 | auto* video_channel = transceiver->internal()->channel(); |
| 1616 | if (video_channel) |
| 1617 | channels.push_back(static_cast<cricket::VideoMediaChannel*>( |
| 1618 | video_channel->media_channel())); |
| 1619 | } |
| 1620 |
| 1621 | worker_thread()->BlockingCall( |
| 1622 | [channels = std::move(channels), |
| 1623 | allow_codec_switching = *modified_config.allow_codec_switching]() { |
| 1624 | for (auto* ch : channels) |
| 1625 | ch->SetVideoCodecSwitchingEnabled(allow_codec_switching); |
| 1626 | }); |
| 1627 | } |
| 1628 |
| 1629 | configuration_ = modified_config; |
| 1630 | return RTCError::OK(); |
| 1631 | } |
| 1632 |
| 1633 | bool PeerConnection::AddIceCandidate( |
| 1634 | const IceCandidateInterface* ice_candidate) { |
| 1635 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1636 | ClearStatsCache(); |
| 1637 | return sdp_handler_->AddIceCandidate(ice_candidate); |
| 1638 | } |
| 1639 |
| 1640 | void PeerConnection::AddIceCandidate( |
| 1641 | std::unique_ptr<IceCandidateInterface> candidate, |
| 1642 | std::function<void(RTCError)> callback) { |
| 1643 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1644 | sdp_handler_->AddIceCandidate(std::move(candidate), |
| 1645 | [this, callback](webrtc::RTCError result) { |
| 1646 | ClearStatsCache(); |
| 1647 | callback(result); |
| 1648 | }); |
| 1649 | } |
| 1650 |
| 1651 | bool PeerConnection::RemoveIceCandidates( |
| 1652 | const std::vector<cricket::Candidate>& candidates) { |
| 1653 | TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates"); |
| 1654 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1655 | return sdp_handler_->RemoveIceCandidates(candidates); |
| 1656 | } |
| 1657 |
| 1658 | RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) { |
| 1659 | if (!worker_thread()->IsCurrent()) { |
| 1660 | return worker_thread()->BlockingCall([&]() { return SetBitrate(bitrate); }); |
| 1661 | } |
| 1662 | RTC_DCHECK_RUN_ON(worker_thread()); |
| 1663 |
| 1664 | const bool has_min = bitrate.min_bitrate_bps.has_value(); |
| 1665 | const bool has_start = bitrate.start_bitrate_bps.has_value(); |
| 1666 | const bool has_max = bitrate.max_bitrate_bps.has_value(); |
| 1667 | if (has_min && *bitrate.min_bitrate_bps < 0) { |
| 1668 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 1669 | "min_bitrate_bps <= 0"); |
| 1670 | } |
| 1671 | if (has_start) { |
| 1672 | if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) { |
| 1673 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 1674 | "start_bitrate_bps < min_bitrate_bps"); |
| 1675 | } else if (*bitrate.start_bitrate_bps < 0) { |
| 1676 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 1677 | "curent_bitrate_bps < 0"); |
| 1678 | } |
| 1679 | } |
| 1680 | if (has_max) { |
| 1681 | if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) { |
| 1682 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 1683 | "max_bitrate_bps < start_bitrate_bps"); |
| 1684 | } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) { |
| 1685 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 1686 | "max_bitrate_bps < min_bitrate_bps"); |
| 1687 | } else if (*bitrate.max_bitrate_bps < 0) { |
| 1688 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 1689 | "max_bitrate_bps < 0"); |
| 1690 | } |
| 1691 | } |
| 1692 |
| 1693 | RTC_DCHECK(call_.get()); |
| 1694 | call_->SetClientBitratePreferences(bitrate); |
| 1695 |
| 1696 | return RTCError::OK(); |
| 1697 | } |
| 1698 |
| 1699 | void PeerConnection::SetAudioPlayout(bool playout) { |
| 1700 | if (!worker_thread()->IsCurrent()) { |
| 1701 | worker_thread()->BlockingCall( |
| 1702 | [this, playout] { SetAudioPlayout(playout); }); |
| 1703 | return; |
| 1704 | } |
| 1705 | auto audio_state = context_->media_engine()->voice().GetAudioState(); |
| 1706 | audio_state->SetPlayout(playout); |
| 1707 | } |
| 1708 |
| 1709 | void PeerConnection::SetAudioRecording(bool recording) { |
| 1710 | if (!worker_thread()->IsCurrent()) { |
| 1711 | worker_thread()->BlockingCall( |
| 1712 | [this, recording] { SetAudioRecording(recording); }); |
| 1713 | return; |
| 1714 | } |
| 1715 | auto audio_state = context_->media_engine()->voice().GetAudioState(); |
| 1716 | audio_state->SetRecording(recording); |
| 1717 | } |
| 1718 |
| 1719 | void PeerConnection::AddAdaptationResource( |
| 1720 | rtc::scoped_refptr<Resource> resource) { |
| 1721 | if (!worker_thread()->IsCurrent()) { |
| 1722 | return worker_thread()->BlockingCall( |
| 1723 | [this, resource]() { return AddAdaptationResource(resource); }); |
| 1724 | } |
| 1725 | RTC_DCHECK_RUN_ON(worker_thread()); |
| 1726 | if (!call_) { |
| 1727 | // The PeerConnection has been closed. |
| 1728 | return; |
| 1729 | } |
| 1730 | call_->AddAdaptationResource(resource); |
| 1731 | } |
| 1732 |
| 1733 | bool PeerConnection::ConfiguredForMedia() const { |
| 1734 | return context_->media_engine(); |
| 1735 | } |
| 1736 |
| 1737 | bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output, |
| 1738 | int64_t output_period_ms) { |
| 1739 | return worker_thread()->BlockingCall( |
| 1740 | [this, output = std::move(output), output_period_ms]() mutable { |
| 1741 | return StartRtcEventLog_w(std::move(output), output_period_ms); |
| 1742 | }); |
| 1743 | } |
| 1744 |
| 1745 | bool PeerConnection::StartRtcEventLog( |
| 1746 | std::unique_ptr<RtcEventLogOutput> output) { |
| 1747 | int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput; |
| 1748 | if (trials().IsEnabled("WebRTC-RtcEventLogNewFormat")) { |
| 1749 | output_period_ms = 5000; |
| 1750 | } |
| 1751 | return StartRtcEventLog(std::move(output), output_period_ms); |
| 1752 | } |
| 1753 |
| 1754 | void PeerConnection::StopRtcEventLog() { |
| 1755 | worker_thread()->BlockingCall([this] { StopRtcEventLog_w(); }); |
| 1756 | } |
| 1757 |
| 1758 | rtc::scoped_refptr<DtlsTransportInterface> |
| 1759 | PeerConnection::LookupDtlsTransportByMid(const std::string& mid) { |
| 1760 | RTC_DCHECK_RUN_ON(network_thread()); |
| 1761 | return transport_controller_->LookupDtlsTransportByMid(mid); |
| 1762 | } |
| 1763 |
| 1764 | rtc::scoped_refptr<DtlsTransport> |
| 1765 | PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) { |
| 1766 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1767 | // TODO(bugs.webrtc.org/9987): Avoid the thread jump. |
| 1768 | // This might be done by caching the value on the signaling thread. |
| 1769 | return network_thread()->BlockingCall([this, mid]() { |
| 1770 | RTC_DCHECK_RUN_ON(network_thread()); |
| 1771 | return transport_controller_->LookupDtlsTransportByMid(mid); |
| 1772 | }); |
| 1773 | } |
| 1774 |
| 1775 | rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport() |
| 1776 | const { |
| 1777 | RTC_DCHECK_RUN_ON(network_thread()); |
| 1778 | if (!sctp_mid_n_) |
| 1779 | return nullptr; |
| 1780 |
| 1781 | return transport_controller_->GetSctpTransport(*sctp_mid_n_); |
| 1782 | } |
| 1783 |
| 1784 | const SessionDescriptionInterface* PeerConnection::local_description() const { |
| 1785 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1786 | return sdp_handler_->local_description(); |
| 1787 | } |
| 1788 |
| 1789 | const SessionDescriptionInterface* PeerConnection::remote_description() const { |
| 1790 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1791 | return sdp_handler_->remote_description(); |
| 1792 | } |
| 1793 |
| 1794 | const SessionDescriptionInterface* PeerConnection::current_local_description() |
| 1795 | const { |
| 1796 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1797 | return sdp_handler_->current_local_description(); |
| 1798 | } |
| 1799 |
| 1800 | const SessionDescriptionInterface* PeerConnection::current_remote_description() |
| 1801 | const { |
| 1802 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1803 | return sdp_handler_->current_remote_description(); |
| 1804 | } |
| 1805 |
| 1806 | const SessionDescriptionInterface* PeerConnection::pending_local_description() |
| 1807 | const { |
| 1808 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1809 | return sdp_handler_->pending_local_description(); |
| 1810 | } |
| 1811 |
| 1812 | const SessionDescriptionInterface* PeerConnection::pending_remote_description() |
| 1813 | const { |
| 1814 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1815 | return sdp_handler_->pending_remote_description(); |
| 1816 | } |
| 1817 |
| 1818 | void PeerConnection::Close() { |
| 1819 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1820 | TRACE_EVENT0("webrtc", "PeerConnection::Close"); |
| 1821 |
| 1822 | RTC_LOG_THREAD_BLOCK_COUNT(); |
| 1823 |
| 1824 | if (IsClosed()) { |
| 1825 | return; |
| 1826 | } |
| 1827 | // Update stats here so that we have the most recent stats for tracks and |
| 1828 | // streams before the channels are closed. |
| 1829 | legacy_stats_->UpdateStats(kStatsOutputLevelStandard); |
| 1830 |
| 1831 | ice_connection_state_ = PeerConnectionInterface::kIceConnectionClosed; |
| 1832 | Observer()->OnIceConnectionChange(ice_connection_state_); |
| 1833 | standardized_ice_connection_state_ = |
| 1834 | PeerConnectionInterface::IceConnectionState::kIceConnectionClosed; |
| 1835 | connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed; |
| 1836 | Observer()->OnConnectionChange(connection_state_); |
| 1837 |
| 1838 | sdp_handler_->Close(); |
| 1839 |
| 1840 | NoteUsageEvent(UsageEvent::CLOSE_CALLED); |
| 1841 |
| 1842 | if (ConfiguredForMedia()) { |
| 1843 | for (const auto& transceiver : rtp_manager()->transceivers()->List()) { |
| 1844 | transceiver->internal()->SetPeerConnectionClosed(); |
| 1845 | if (!transceiver->stopped()) |
| 1846 | transceiver->StopInternal(); |
| 1847 | } |
| 1848 | } |
| 1849 | // Ensure that all asynchronous stats requests are completed before destroying |
| 1850 | // the transport controller below. |
| 1851 | if (stats_collector_) { |
| 1852 | stats_collector_->WaitForPendingRequest(); |
| 1853 | } |
| 1854 |
| 1855 | // Don't destroy BaseChannels until after stats has been cleaned up so that |
| 1856 | // the last stats request can still read from the channels. |
| 1857 | sdp_handler_->DestroyAllChannels(); |
| 1858 |
| 1859 | // The event log is used in the transport controller, which must be outlived |
| 1860 | // by the former. CreateOffer by the peer connection is implemented |
| 1861 | // asynchronously and if the peer connection is closed without resetting the |
| 1862 | // WebRTC session description factory, the session description factory would |
| 1863 | // call the transport controller. |
| 1864 | sdp_handler_->ResetSessionDescFactory(); |
| 1865 | if (ConfiguredForMedia()) { |
| 1866 | rtp_manager_->Close(); |
| 1867 | } |
| 1868 |
| 1869 | network_thread()->BlockingCall([this] { |
| 1870 | // Data channels will already have been unset via the DestroyAllChannels() |
| 1871 | // call above, which triggers a call to TeardownDataChannelTransport_n(). |
| 1872 | // TODO(tommi): ^^ That's not exactly optimal since this is yet another |
| 1873 | // blocking hop to the network thread during Close(). Further still, the |
| 1874 | // voice/video/data channels will be cleared on the worker thread. |
| 1875 | RTC_DCHECK_RUN_ON(network_thread()); |
| 1876 | transport_controller_.reset(); |
| 1877 | port_allocator_->DiscardCandidatePool(); |
| 1878 | if (network_thread_safety_) { |
| 1879 | network_thread_safety_->SetNotAlive(); |
| 1880 | } |
| 1881 | }); |
| 1882 |
| 1883 | worker_thread()->BlockingCall([this] { |
| 1884 | RTC_DCHECK_RUN_ON(worker_thread()); |
| 1885 | worker_thread_safety_->SetNotAlive(); |
| 1886 | call_.reset(); |
| 1887 | // The event log must outlive call (and any other object that uses it). |
| 1888 | event_log_.reset(); |
| 1889 | }); |
| 1890 | ReportUsagePattern(); |
| 1891 | // The .h file says that observer can be discarded after close() returns. |
| 1892 | // Make sure this is true. |
| 1893 | observer_ = nullptr; |
| 1894 |
| 1895 | // Signal shutdown to the sdp handler. This invalidates weak pointers for |
| 1896 | // internal pending callbacks. |
| 1897 | sdp_handler_->PrepareForShutdown(); |
| 1898 | } |
| 1899 |
| 1900 | void PeerConnection::SetIceConnectionState(IceConnectionState new_state) { |
| 1901 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1902 | if (ice_connection_state_ == new_state) { |
| 1903 | return; |
| 1904 | } |
| 1905 |
| 1906 | // After transitioning to "closed", ignore any additional states from |
| 1907 | // TransportController (such as "disconnected"). |
| 1908 | if (IsClosed()) { |
| 1909 | return; |
| 1910 | } |
| 1911 |
| 1912 | RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_ |
| 1913 | << " => " << new_state; |
| 1914 | RTC_DCHECK(ice_connection_state_ != |
| 1915 | PeerConnectionInterface::kIceConnectionClosed); |
| 1916 |
| 1917 | ice_connection_state_ = new_state; |
| 1918 | Observer()->OnIceConnectionChange(ice_connection_state_); |
| 1919 | } |
| 1920 |
| 1921 | void PeerConnection::SetStandardizedIceConnectionState( |
| 1922 | PeerConnectionInterface::IceConnectionState new_state) { |
| 1923 | if (standardized_ice_connection_state_ == new_state) { |
| 1924 | return; |
| 1925 | } |
| 1926 |
| 1927 | if (IsClosed()) { |
| 1928 | return; |
| 1929 | } |
| 1930 |
| 1931 | RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState " |
| 1932 | << standardized_ice_connection_state_ << " => " << new_state; |
| 1933 |
| 1934 | standardized_ice_connection_state_ = new_state; |
| 1935 | Observer()->OnStandardizedIceConnectionChange(new_state); |
| 1936 | } |
| 1937 |
| 1938 | void PeerConnection::SetConnectionState( |
| 1939 | PeerConnectionInterface::PeerConnectionState new_state) { |
| 1940 | if (connection_state_ == new_state) |
| 1941 | return; |
| 1942 | if (IsClosed()) |
| 1943 | return; |
| 1944 | connection_state_ = new_state; |
| 1945 | Observer()->OnConnectionChange(new_state); |
| 1946 |
| 1947 | // The first connection state change to connected happens once per |
| 1948 | // connection which makes it a good point to report metrics. |
| 1949 | if (new_state == PeerConnectionState::kConnected && !was_ever_connected_) { |
| 1950 | was_ever_connected_ = true; |
| 1951 | ReportFirstConnectUsageMetrics(); |
| 1952 | } |
| 1953 | } |
| 1954 |
| 1955 | void PeerConnection::ReportFirstConnectUsageMetrics() { |
| 1956 | // Record bundle-policy from configuration. Done here from |
| 1957 | // connectionStateChange to limit to actually established connections. |
| 1958 | BundlePolicyUsage policy = kBundlePolicyUsageMax; |
| 1959 | switch (configuration_.bundle_policy) { |
| 1960 | case kBundlePolicyBalanced: |
| 1961 | policy = kBundlePolicyUsageBalanced; |
| 1962 | break; |
| 1963 | case kBundlePolicyMaxBundle: |
| 1964 | policy = kBundlePolicyUsageMaxBundle; |
| 1965 | break; |
| 1966 | case kBundlePolicyMaxCompat: |
| 1967 | policy = kBundlePolicyUsageMaxCompat; |
| 1968 | break; |
| 1969 | } |
| 1970 | RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.BundlePolicy", policy, |
| 1971 | kBundlePolicyUsageMax); |
| 1972 |
| 1973 | // Record whether there was a local or remote provisional answer. |
| 1974 | ProvisionalAnswerUsage pranswer = kProvisionalAnswerNotUsed; |
| 1975 | if (local_description()->GetType() == SdpType::kPrAnswer) { |
| 1976 | pranswer = kProvisionalAnswerLocal; |
| 1977 | } else if (remote_description()->GetType() == SdpType::kPrAnswer) { |
| 1978 | pranswer = kProvisionalAnswerRemote; |
| 1979 | } |
| 1980 | RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.ProvisionalAnswer", pranswer, |
| 1981 | kProvisionalAnswerMax); |
| 1982 |
| 1983 | // Record the number of valid / invalid ice-ufrag. We do allow certain |
| 1984 | // non-spec ice-char for backward-compat reasons. At this point we know |
| 1985 | // that the ufrag/pwd consists of a valid ice-char or one of the four |
| 1986 | // not allowed characters since we have passed the IsIceChar check done |
| 1987 | // by the p2p transport description on setRemoteDescription calls. |
| 1988 | auto transport_infos = remote_description()->description()->transport_infos(); |
| 1989 | if (transport_infos.size() > 0) { |
| 1990 | auto ice_parameters = transport_infos[0].description.GetIceParameters(); |
| 1991 | auto is_invalid_char = [](char c) { |
| 1992 | return c == '-' || c == '=' || c == '#' || c == '_'; |
| 1993 | }; |
| 1994 | bool isUsingInvalidIceCharInUfrag = |
| 1995 | absl::c_any_of(ice_parameters.ufrag, is_invalid_char); |
| 1996 | bool isUsingInvalidIceCharInPwd = |
| 1997 | absl::c_any_of(ice_parameters.pwd, is_invalid_char); |
| 1998 | RTC_HISTOGRAM_BOOLEAN( |
| 1999 | "WebRTC.PeerConnection.ValidIceChars", |
| 2000 | !(isUsingInvalidIceCharInUfrag || isUsingInvalidIceCharInPwd)); |
| 2001 | } |
| 2002 | } |
| 2003 |
| 2004 | void PeerConnection::OnIceGatheringChange( |
| 2005 | PeerConnectionInterface::IceGatheringState new_state) { |
| 2006 | if (IsClosed()) { |
| 2007 | return; |
| 2008 | } |
| 2009 | ice_gathering_state_ = new_state; |
| 2010 | Observer()->OnIceGatheringChange(ice_gathering_state_); |
| 2011 | } |
| 2012 |
| 2013 | void PeerConnection::OnIceCandidate( |
| 2014 | std::unique_ptr<IceCandidateInterface> candidate) { |
| 2015 | if (IsClosed()) { |
| 2016 | return; |
| 2017 | } |
| 2018 | ReportIceCandidateCollected(candidate->candidate()); |
| 2019 | ClearStatsCache(); |
| 2020 | Observer()->OnIceCandidate(candidate.get()); |
| 2021 | } |
| 2022 |
| 2023 | void PeerConnection::OnIceCandidateError(const std::string& address, |
| 2024 | int port, |
| 2025 | const std::string& url, |
| 2026 | int error_code, |
| 2027 | const std::string& error_text) { |
| 2028 | if (IsClosed()) { |
| 2029 | return; |
| 2030 | } |
| 2031 | Observer()->OnIceCandidateError(address, port, url, error_code, error_text); |
| 2032 | } |
| 2033 |
| 2034 | void PeerConnection::OnIceCandidatesRemoved( |
| 2035 | const std::vector<cricket::Candidate>& candidates) { |
| 2036 | if (IsClosed()) { |
| 2037 | return; |
| 2038 | } |
| 2039 | Observer()->OnIceCandidatesRemoved(candidates); |
| 2040 | } |
| 2041 |
| 2042 | void PeerConnection::OnSelectedCandidatePairChanged( |
| 2043 | const cricket::CandidatePairChangeEvent& event) { |
| 2044 | if (IsClosed()) { |
| 2045 | return; |
| 2046 | } |
| 2047 |
| 2048 | if (event.selected_candidate_pair.local_candidate().type() == |
| 2049 | LOCAL_PORT_TYPE && |
| 2050 | event.selected_candidate_pair.remote_candidate().type() == |
| 2051 | LOCAL_PORT_TYPE) { |
| 2052 | NoteUsageEvent(UsageEvent::DIRECT_CONNECTION_SELECTED); |
| 2053 | } |
| 2054 |
| 2055 | Observer()->OnIceSelectedCandidatePairChanged(event); |
| 2056 | } |
| 2057 |
| 2058 | absl::optional<std::string> PeerConnection::GetDataMid() const { |
| 2059 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2060 | return sctp_mid_s_; |
| 2061 | } |
| 2062 |
| 2063 | void PeerConnection::SetSctpDataMid(const std::string& mid) { |
| 2064 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2065 | sctp_mid_s_ = mid; |
| 2066 | } |
| 2067 |
| 2068 | void PeerConnection::ResetSctpDataMid() { |
| 2069 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2070 | sctp_mid_s_.reset(); |
| 2071 | sctp_transport_name_s_.clear(); |
| 2072 | } |
| 2073 |
| 2074 | void PeerConnection::OnSctpDataChannelClosed(DataChannelInterface* channel) { |
| 2075 | // Since data_channel_controller doesn't do signals, this |
| 2076 | // signal is relayed here. |
| 2077 | data_channel_controller_.OnSctpDataChannelClosed( |
| 2078 | static_cast<SctpDataChannel*>(channel)); |
| 2079 | } |
| 2080 |
| 2081 | PeerConnection::InitializePortAllocatorResult |
| 2082 | PeerConnection::InitializePortAllocator_n( |
| 2083 | const cricket::ServerAddresses& stun_servers, |
| 2084 | const std::vector<cricket::RelayServerConfig>& turn_servers, |
| 2085 | const RTCConfiguration& configuration) { |
| 2086 | RTC_DCHECK_RUN_ON(network_thread()); |
| 2087 |
| 2088 | port_allocator_->Initialize(); |
| 2089 | // To handle both internal and externally created port allocator, we will |
| 2090 | // enable BUNDLE here. |
| 2091 | int port_allocator_flags = port_allocator_->flags(); |
| 2092 | port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET | |
| 2093 | cricket::PORTALLOCATOR_ENABLE_IPV6 | |
| 2094 | cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI; |
| 2095 | // If the disable-IPv6 flag was specified, we'll not override it |
| 2096 | // by experiment. |
| 2097 | if (configuration.disable_ipv6) { |
| 2098 | port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6); |
| 2099 | } else if (trials().IsDisabled("WebRTC-IPv6Default")) { |
| 2100 | port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6); |
| 2101 | } |
| 2102 | if (configuration.disable_ipv6_on_wifi) { |
| 2103 | port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI); |
| 2104 | RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled."; |
| 2105 | } |
| 2106 |
| 2107 | if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) { |
| 2108 | port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP; |
| 2109 | RTC_LOG(LS_INFO) << "TCP candidates are disabled."; |
| 2110 | } |
| 2111 |
| 2112 | if (configuration.candidate_network_policy == |
| 2113 | kCandidateNetworkPolicyLowCost) { |
| 2114 | port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS; |
| 2115 | RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks"; |
| 2116 | } |
| 2117 |
| 2118 | if (configuration.disable_link_local_networks) { |
| 2119 | port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS; |
| 2120 | RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces."; |
| 2121 | } |
| 2122 |
| 2123 | port_allocator_->set_flags(port_allocator_flags); |
| 2124 | // No step delay is used while allocating ports. |
| 2125 | port_allocator_->set_step_delay(cricket::kMinimumStepDelay); |
| 2126 | port_allocator_->SetCandidateFilter( |
| 2127 | ConvertIceTransportTypeToCandidateFilter(configuration.type)); |
| 2128 | port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks); |
| 2129 |
| 2130 | auto turn_servers_copy = turn_servers; |
| 2131 | for (auto& turn_server : turn_servers_copy) { |
| 2132 | turn_server.tls_cert_verifier = tls_cert_verifier_.get(); |
| 2133 | } |
| 2134 | // Call this last since it may create pooled allocator sessions using the |
| 2135 | // properties set above. |
| 2136 | port_allocator_->SetConfiguration( |
| 2137 | stun_servers, std::move(turn_servers_copy), |
| 2138 | configuration.ice_candidate_pool_size, |
| 2139 | configuration.GetTurnPortPrunePolicy(), configuration.turn_customizer, |
| 2140 | configuration.stun_candidate_keepalive_interval); |
| 2141 |
| 2142 | InitializePortAllocatorResult res; |
| 2143 | res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6; |
| 2144 | return res; |
| 2145 | } |
| 2146 |
| 2147 | bool PeerConnection::ReconfigurePortAllocator_n( |
| 2148 | const cricket::ServerAddresses& stun_servers, |
| 2149 | const std::vector<cricket::RelayServerConfig>& turn_servers, |
| 2150 | IceTransportsType type, |
| 2151 | int candidate_pool_size, |
| 2152 | PortPrunePolicy turn_port_prune_policy, |
| 2153 | webrtc::TurnCustomizer* turn_customizer, |
| 2154 | absl::optional<int> stun_candidate_keepalive_interval, |
| 2155 | bool have_local_description) { |
| 2156 | RTC_DCHECK_RUN_ON(network_thread()); |
| 2157 | port_allocator_->SetCandidateFilter( |
| 2158 | ConvertIceTransportTypeToCandidateFilter(type)); |
| 2159 | // According to JSEP, after setLocalDescription, changing the candidate pool |
| 2160 | // size is not allowed, and changing the set of ICE servers will not result |
| 2161 | // in new candidates being gathered. |
| 2162 | if (have_local_description) { |
| 2163 | port_allocator_->FreezeCandidatePool(); |
| 2164 | } |
| 2165 | // Add the custom tls turn servers if they exist. |
| 2166 | auto turn_servers_copy = turn_servers; |
| 2167 | for (auto& turn_server : turn_servers_copy) { |
| 2168 | turn_server.tls_cert_verifier = tls_cert_verifier_.get(); |
| 2169 | } |
| 2170 | // Call this last since it may create pooled allocator sessions using the |
| 2171 | // candidate filter set above. |
| 2172 | return port_allocator_->SetConfiguration( |
| 2173 | stun_servers, std::move(turn_servers_copy), candidate_pool_size, |
| 2174 | turn_port_prune_policy, turn_customizer, |
| 2175 | stun_candidate_keepalive_interval); |
| 2176 | } |
| 2177 |
| 2178 | bool PeerConnection::StartRtcEventLog_w( |
| 2179 | std::unique_ptr<RtcEventLogOutput> output, |
| 2180 | int64_t output_period_ms) { |
| 2181 | RTC_DCHECK_RUN_ON(worker_thread()); |
| 2182 | if (!event_log_) { |
| 2183 | return false; |
| 2184 | } |
| 2185 | return event_log_->StartLogging(std::move(output), output_period_ms); |
| 2186 | } |
| 2187 |
| 2188 | void PeerConnection::StopRtcEventLog_w() { |
| 2189 | RTC_DCHECK_RUN_ON(worker_thread()); |
| 2190 | if (event_log_) { |
| 2191 | event_log_->StopLogging(); |
| 2192 | } |
| 2193 | } |
| 2194 |
| 2195 | bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) { |
| 2196 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2197 | if (!local_description() || !remote_description()) { |
| 2198 | RTC_LOG(LS_VERBOSE) |
| 2199 | << "Local and Remote descriptions must be applied to get the " |
| 2200 | "SSL Role of the SCTP transport."; |
| 2201 | return false; |
| 2202 | } |
| 2203 | if (!data_channel_controller_.data_channel_transport()) { |
| 2204 | RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the " |
| 2205 | "SSL Role of the SCTP transport."; |
| 2206 | return false; |
| 2207 | } |
| 2208 |
| 2209 | absl::optional<rtc::SSLRole> dtls_role; |
| 2210 | if (sctp_mid_s_) { |
| 2211 | dtls_role = network_thread()->BlockingCall([this] { |
| 2212 | RTC_DCHECK_RUN_ON(network_thread()); |
| 2213 | return transport_controller_->GetDtlsRole(*sctp_mid_n_); |
| 2214 | }); |
| 2215 | if (!dtls_role && sdp_handler_->is_caller().has_value()) { |
| 2216 | // This works fine if we are the offerer, but can be a mistake if |
| 2217 | // we are the answerer and the remote offer is ACTIVE. In that |
| 2218 | // case, we will guess the role wrong. |
| 2219 | // TODO(bugs.webrtc.org/13668): Check if this actually happens. |
| 2220 | RTC_LOG(LS_ERROR) |
| 2221 | << "Possible risk: DTLS role guesser is active, is_caller is " |
| 2222 | << *sdp_handler_->is_caller(); |
| 2223 | dtls_role = |
| 2224 | *sdp_handler_->is_caller() ? rtc::SSL_SERVER : rtc::SSL_CLIENT; |
| 2225 | } |
| 2226 | if (dtls_role) { |
| 2227 | *role = *dtls_role; |
| 2228 | return true; |
| 2229 | } |
| 2230 | } |
| 2231 | return false; |
| 2232 | } |
| 2233 |
| 2234 | bool PeerConnection::GetSslRole(const std::string& content_name, |
| 2235 | rtc::SSLRole* role) { |
| 2236 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2237 | if (!local_description() || !remote_description()) { |
| 2238 | RTC_LOG(LS_INFO) |
| 2239 | << "Local and Remote descriptions must be applied to get the " |
| 2240 | "SSL Role of the session."; |
| 2241 | return false; |
| 2242 | } |
| 2243 |
| 2244 | auto dtls_role = network_thread()->BlockingCall([this, content_name]() { |
| 2245 | RTC_DCHECK_RUN_ON(network_thread()); |
| 2246 | return transport_controller_->GetDtlsRole(content_name); |
| 2247 | }); |
| 2248 | if (dtls_role) { |
| 2249 | *role = *dtls_role; |
| 2250 | return true; |
| 2251 | } |
| 2252 | return false; |
| 2253 | } |
| 2254 |
| 2255 | bool PeerConnection::GetTransportDescription( |
| 2256 | const SessionDescription* description, |
| 2257 | const std::string& content_name, |
| 2258 | cricket::TransportDescription* tdesc) { |
| 2259 | if (!description || !tdesc) { |
| 2260 | return false; |
| 2261 | } |
| 2262 | const TransportInfo* transport_info = |
| 2263 | description->GetTransportInfoByName(content_name); |
| 2264 | if (!transport_info) { |
| 2265 | return false; |
| 2266 | } |
| 2267 | *tdesc = transport_info->description; |
| 2268 | return true; |
| 2269 | } |
| 2270 |
| 2271 | std::vector<DataChannelStats> PeerConnection::GetDataChannelStats() const { |
| 2272 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2273 | return data_channel_controller_.GetDataChannelStats(); |
| 2274 | } |
| 2275 |
| 2276 | absl::optional<std::string> PeerConnection::sctp_transport_name() const { |
| 2277 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2278 | if (sctp_mid_s_ && transport_controller_copy_) |
| 2279 | return sctp_transport_name_s_; |
| 2280 | return absl::optional<std::string>(); |
| 2281 | } |
| 2282 |
| 2283 | absl::optional<std::string> PeerConnection::sctp_mid() const { |
| 2284 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2285 | return sctp_mid_s_; |
| 2286 | } |
| 2287 |
| 2288 | cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const { |
| 2289 | RTC_DCHECK_RUN_ON(network_thread()); |
| 2290 | if (!network_thread_safety_->alive()) |
| 2291 | return {}; |
| 2292 | cricket::CandidateStatsList candidate_stats_list; |
| 2293 | port_allocator_->GetCandidateStatsFromPooledSessions(&candidate_stats_list); |
| 2294 | return candidate_stats_list; |
| 2295 | } |
| 2296 |
| 2297 | std::map<std::string, cricket::TransportStats> |
| 2298 | PeerConnection::GetTransportStatsByNames( |
| 2299 | const std::set<std::string>& transport_names) { |
| 2300 | TRACE_EVENT0("webrtc", "PeerConnection::GetTransportStatsByNames"); |
| 2301 | RTC_DCHECK_RUN_ON(network_thread()); |
| 2302 | if (!network_thread_safety_->alive()) |
| 2303 | return {}; |
| 2304 |
| 2305 | rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls; |
| 2306 | std::map<std::string, cricket::TransportStats> transport_stats_by_name; |
| 2307 | for (const std::string& transport_name : transport_names) { |
| 2308 | cricket::TransportStats transport_stats; |
| 2309 | bool success = |
| 2310 | transport_controller_->GetStats(transport_name, &transport_stats); |
| 2311 | if (success) { |
| 2312 | transport_stats_by_name[transport_name] = std::move(transport_stats); |
| 2313 | } else { |
| 2314 | RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name=" |
| 2315 | << transport_name; |
| 2316 | } |
| 2317 | } |
| 2318 | return transport_stats_by_name; |
| 2319 | } |
| 2320 |
| 2321 | bool PeerConnection::GetLocalCertificate( |
| 2322 | const std::string& transport_name, |
| 2323 | rtc::scoped_refptr<rtc::RTCCertificate>* certificate) { |
| 2324 | RTC_DCHECK_RUN_ON(network_thread()); |
| 2325 | if (!network_thread_safety_->alive() || !certificate) { |
| 2326 | return false; |
| 2327 | } |
| 2328 | *certificate = transport_controller_->GetLocalCertificate(transport_name); |
| 2329 | return *certificate != nullptr; |
| 2330 | } |
| 2331 |
| 2332 | std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain( |
| 2333 | const std::string& transport_name) { |
| 2334 | RTC_DCHECK_RUN_ON(network_thread()); |
| 2335 | return transport_controller_->GetRemoteSSLCertChain(transport_name); |
| 2336 | } |
| 2337 |
| 2338 | bool PeerConnection::IceRestartPending(const std::string& content_name) const { |
| 2339 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2340 | return sdp_handler_->IceRestartPending(content_name); |
| 2341 | } |
| 2342 |
| 2343 | bool PeerConnection::NeedsIceRestart(const std::string& content_name) const { |
| 2344 | return network_thread()->BlockingCall([this, &content_name] { |
| 2345 | RTC_DCHECK_RUN_ON(network_thread()); |
| 2346 | return transport_controller_->NeedsIceRestart(content_name); |
| 2347 | }); |
| 2348 | } |
| 2349 |
| 2350 | void PeerConnection::OnTransportControllerConnectionState( |
| 2351 | cricket::IceConnectionState state) { |
| 2352 | switch (state) { |
| 2353 | case cricket::kIceConnectionConnecting: |
| 2354 | // If the current state is Connected or Completed, then there were |
| 2355 | // writable channels but now there are not, so the next state must |
| 2356 | // be Disconnected. |
| 2357 | // kIceConnectionConnecting is currently used as the default, |
| 2358 | // un-connected state by the TransportController, so its only use is |
| 2359 | // detecting disconnections. |
| 2360 | if (ice_connection_state_ == |
| 2361 | PeerConnectionInterface::kIceConnectionConnected || |
| 2362 | ice_connection_state_ == |
| 2363 | PeerConnectionInterface::kIceConnectionCompleted) { |
| 2364 | SetIceConnectionState( |
| 2365 | PeerConnectionInterface::kIceConnectionDisconnected); |
| 2366 | } |
| 2367 | break; |
| 2368 | case cricket::kIceConnectionFailed: |
| 2369 | SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed); |
| 2370 | break; |
| 2371 | case cricket::kIceConnectionConnected: |
| 2372 | RTC_LOG(LS_INFO) << "Changing to ICE connected state because " |
| 2373 | "all transports are writable."; |
| 2374 | SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected); |
| 2375 | NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED); |
| 2376 | break; |
| 2377 | case cricket::kIceConnectionCompleted: |
| 2378 | RTC_LOG(LS_INFO) << "Changing to ICE completed state because " |
| 2379 | "all transports are complete."; |
| 2380 | if (ice_connection_state_ != |
| 2381 | PeerConnectionInterface::kIceConnectionConnected) { |
| 2382 | // If jumping directly from "checking" to "connected", |
| 2383 | // signal "connected" first. |
| 2384 | SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected); |
| 2385 | } |
| 2386 | SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted); |
| 2387 |
| 2388 | NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED); |
| 2389 | break; |
| 2390 | default: |
| 2391 | RTC_DCHECK_NOTREACHED(); |
| 2392 | } |
| 2393 | } |
| 2394 |
| 2395 | void PeerConnection::OnTransportControllerCandidatesGathered( |
| 2396 | const std::string& transport_name, |
| 2397 | const cricket::Candidates& candidates) { |
| 2398 | // TODO(bugs.webrtc.org/12427): Expect this to come in on the network thread |
| 2399 | // (not signaling as it currently does), handle appropriately. |
| 2400 | int sdp_mline_index; |
| 2401 | if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) { |
| 2402 | RTC_LOG(LS_ERROR) |
| 2403 | << "OnTransportControllerCandidatesGathered: content name " |
| 2404 | << transport_name << " not found"; |
| 2405 | return; |
| 2406 | } |
| 2407 |
| 2408 | for (cricket::Candidates::const_iterator citer = candidates.begin(); |
| 2409 | citer != candidates.end(); ++citer) { |
| 2410 | // Use transport_name as the candidate media id. |
| 2411 | std::unique_ptr<JsepIceCandidate> candidate( |
| 2412 | new JsepIceCandidate(transport_name, sdp_mline_index, *citer)); |
| 2413 | sdp_handler_->AddLocalIceCandidate(candidate.get()); |
| 2414 | OnIceCandidate(std::move(candidate)); |
| 2415 | } |
| 2416 | } |
| 2417 |
| 2418 | void PeerConnection::OnTransportControllerCandidateError( |
| 2419 | const cricket::IceCandidateErrorEvent& event) { |
| 2420 | OnIceCandidateError(event.address, event.port, event.url, event.error_code, |
| 2421 | event.error_text); |
| 2422 | } |
| 2423 |
| 2424 | void PeerConnection::OnTransportControllerCandidatesRemoved( |
| 2425 | const std::vector<cricket::Candidate>& candidates) { |
| 2426 | // Sanity check. |
| 2427 | for (const cricket::Candidate& candidate : candidates) { |
| 2428 | if (candidate.transport_name().empty()) { |
| 2429 | RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: " |
| 2430 | "empty content name in candidate " |
| 2431 | << candidate.ToString(); |
| 2432 | return; |
| 2433 | } |
| 2434 | } |
| 2435 | sdp_handler_->RemoveLocalIceCandidates(candidates); |
| 2436 | OnIceCandidatesRemoved(candidates); |
| 2437 | } |
| 2438 |
| 2439 | void PeerConnection::OnTransportControllerCandidateChanged( |
| 2440 | const cricket::CandidatePairChangeEvent& event) { |
| 2441 | OnSelectedCandidatePairChanged(event); |
| 2442 | } |
| 2443 |
| 2444 | void PeerConnection::OnTransportControllerDtlsHandshakeError( |
| 2445 | rtc::SSLHandshakeError error) { |
| 2446 | RTC_HISTOGRAM_ENUMERATION( |
| 2447 | "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error), |
| 2448 | static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE)); |
| 2449 | } |
| 2450 |
| 2451 | // Returns the media index for a local ice candidate given the content name. |
| 2452 | bool PeerConnection::GetLocalCandidateMediaIndex( |
| 2453 | const std::string& content_name, |
| 2454 | int* sdp_mline_index) { |
| 2455 | if (!local_description() || !sdp_mline_index) { |
| 2456 | return false; |
| 2457 | } |
| 2458 |
| 2459 | bool content_found = false; |
| 2460 | const ContentInfos& contents = local_description()->description()->contents(); |
| 2461 | for (size_t index = 0; index < contents.size(); ++index) { |
| 2462 | if (contents[index].name == content_name) { |
| 2463 | *sdp_mline_index = static_cast<int>(index); |
| 2464 | content_found = true; |
| 2465 | break; |
| 2466 | } |
| 2467 | } |
| 2468 | return content_found; |
| 2469 | } |
| 2470 |
| 2471 | Call::Stats PeerConnection::GetCallStats() { |
| 2472 | if (!worker_thread()->IsCurrent()) { |
| 2473 | return worker_thread()->BlockingCall([this] { return GetCallStats(); }); |
| 2474 | } |
| 2475 | RTC_DCHECK_RUN_ON(worker_thread()); |
| 2476 | rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls; |
| 2477 | if (call_) { |
| 2478 | return call_->GetStats(); |
| 2479 | } else { |
| 2480 | return Call::Stats(); |
| 2481 | } |
| 2482 | } |
| 2483 |
| 2484 | bool PeerConnection::SetupDataChannelTransport_n(const std::string& mid) { |
| 2485 | DataChannelTransportInterface* transport = |
| 2486 | transport_controller_->GetDataChannelTransport(mid); |
| 2487 | if (!transport) { |
| 2488 | RTC_LOG(LS_ERROR) |
| 2489 | << "Data channel transport is not available for data channels, mid=" |
| 2490 | << mid; |
| 2491 | return false; |
| 2492 | } |
| 2493 | RTC_LOG(LS_INFO) << "Setting up data channel transport for mid=" << mid; |
| 2494 |
| 2495 | data_channel_controller_.set_data_channel_transport(transport); |
| 2496 | data_channel_controller_.SetupDataChannelTransport_n(); |
| 2497 | sctp_mid_n_ = mid; |
| 2498 | cricket::DtlsTransportInternal* dtls_transport = |
| 2499 | transport_controller_->GetDtlsTransport(mid); |
| 2500 | if (dtls_transport) { |
| 2501 | signaling_thread()->PostTask( |
| 2502 | SafeTask(signaling_thread_safety_.flag(), |
| 2503 | [this, name = dtls_transport->transport_name()] { |
| 2504 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2505 | sctp_transport_name_s_ = std::move(name); |
| 2506 | })); |
| 2507 | } |
| 2508 |
| 2509 | // Note: setting the data sink and checking initial state must be done last, |
| 2510 | // after setting up the data channel. Setting the data sink may trigger |
| 2511 | // callbacks to PeerConnection which require the transport to be completely |
| 2512 | // set up (eg. OnReadyToSend()). |
| 2513 | transport->SetDataSink(&data_channel_controller_); |
| 2514 | return true; |
| 2515 | } |
| 2516 |
| 2517 | void PeerConnection::TeardownDataChannelTransport_n() { |
| 2518 | if (sctp_mid_n_) { |
| 2519 | // `sctp_mid_` may still be active through an SCTP transport. If not, unset |
| 2520 | // it. |
| 2521 | RTC_LOG(LS_INFO) << "Tearing down data channel transport for mid=" |
| 2522 | << *sctp_mid_n_; |
| 2523 | sctp_mid_n_.reset(); |
| 2524 | } |
| 2525 |
| 2526 | data_channel_controller_.TeardownDataChannelTransport_n(); |
| 2527 | } |
| 2528 |
| 2529 | // Returns false if bundle is enabled and rtcp_mux is disabled. |
| 2530 | bool PeerConnection::ValidateBundleSettings( |
| 2531 | const SessionDescription* desc, |
| 2532 | const std::map<std::string, const cricket::ContentGroup*>& |
| 2533 | bundle_groups_by_mid) { |
| 2534 | if (bundle_groups_by_mid.empty()) |
| 2535 | return true; |
| 2536 |
| 2537 | const cricket::ContentInfos& contents = desc->contents(); |
| 2538 | for (cricket::ContentInfos::const_iterator citer = contents.begin(); |
| 2539 | citer != contents.end(); ++citer) { |
| 2540 | const cricket::ContentInfo* content = (&*citer); |
| 2541 | RTC_DCHECK(content != NULL); |
| 2542 | auto it = bundle_groups_by_mid.find(content->name); |
| 2543 | if (it != bundle_groups_by_mid.end() && !content->rejected && |
| 2544 | content->type == MediaProtocolType::kRtp) { |
| 2545 | if (!HasRtcpMuxEnabled(content)) |
| 2546 | return false; |
| 2547 | } |
| 2548 | } |
| 2549 | // RTCP-MUX is enabled in all the contents. |
| 2550 | return true; |
| 2551 | } |
| 2552 |
| 2553 | void PeerConnection::ReportSdpBundleUsage( |
| 2554 | const SessionDescriptionInterface& remote_description) { |
| 2555 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2556 |
| 2557 | bool using_bundle = |
| 2558 | remote_description.description()->HasGroup(cricket::GROUP_TYPE_BUNDLE); |
| 2559 | int num_audio_mlines = 0; |
| 2560 | int num_video_mlines = 0; |
| 2561 | int num_data_mlines = 0; |
| 2562 | for (const ContentInfo& content : |
| 2563 | remote_description.description()->contents()) { |
| 2564 | cricket::MediaType media_type = content.media_description()->type(); |
| 2565 | if (media_type == cricket::MEDIA_TYPE_AUDIO) { |
| 2566 | num_audio_mlines += 1; |
| 2567 | } else if (media_type == cricket::MEDIA_TYPE_VIDEO) { |
| 2568 | num_video_mlines += 1; |
| 2569 | } else if (media_type == cricket::MEDIA_TYPE_DATA) { |
| 2570 | num_data_mlines += 1; |
| 2571 | } |
| 2572 | } |
| 2573 | bool simple = num_audio_mlines <= 1 && num_video_mlines <= 1; |
| 2574 | BundleUsage usage = kBundleUsageMax; |
| 2575 | if (num_audio_mlines == 0 && num_video_mlines == 0) { |
| 2576 | if (num_data_mlines > 0) { |
| 2577 | usage = using_bundle ? kBundleUsageBundleDatachannelOnly |
| 2578 | : kBundleUsageNoBundleDatachannelOnly; |
| 2579 | } else { |
| 2580 | usage = kBundleUsageEmpty; |
| 2581 | } |
| 2582 | } else if (configuration_.sdp_semantics == SdpSemantics::kPlanB_DEPRECATED) { |
| 2583 | // In plan-b, simple/complex usage will not show up in the number of |
| 2584 | // m-lines or BUNDLE. |
| 2585 | usage = using_bundle ? kBundleUsageBundlePlanB : kBundleUsageNoBundlePlanB; |
| 2586 | } else { |
| 2587 | if (simple) { |
| 2588 | usage = |
| 2589 | using_bundle ? kBundleUsageBundleSimple : kBundleUsageNoBundleSimple; |
| 2590 | } else { |
| 2591 | usage = using_bundle ? kBundleUsageBundleComplex |
| 2592 | : kBundleUsageNoBundleComplex; |
| 2593 | } |
| 2594 | } |
| 2595 | RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.BundleUsage", usage, |
| 2596 | kBundleUsageMax); |
| 2597 | } |
| 2598 |
| 2599 | void PeerConnection::ReportIceCandidateCollected( |
| 2600 | const cricket::Candidate& candidate) { |
| 2601 | NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED); |
| 2602 | if (candidate.address().IsPrivateIP()) { |
| 2603 | NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED); |
| 2604 | } |
| 2605 | if (candidate.address().IsUnresolvedIP()) { |
| 2606 | NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED); |
| 2607 | } |
| 2608 | if (candidate.address().family() == AF_INET6) { |
| 2609 | NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED); |
| 2610 | } |
| 2611 | } |
| 2612 |
| 2613 | void PeerConnection::NoteUsageEvent(UsageEvent event) { |
| 2614 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2615 | usage_pattern_.NoteUsageEvent(event); |
| 2616 | } |
| 2617 |
| 2618 | // Asynchronously adds remote candidates on the network thread. |
| 2619 | void PeerConnection::AddRemoteCandidate(const std::string& mid, |
| 2620 | const cricket::Candidate& candidate) { |
| 2621 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2622 |
| 2623 | if (candidate.network_type() != rtc::ADAPTER_TYPE_UNKNOWN) { |
| 2624 | RTC_DLOG(LS_WARNING) << "Using candidate with adapter type set - this " |
| 2625 | "should only happen in test"; |
| 2626 | } |
| 2627 |
| 2628 | // Clear fields that do not make sense as remote candidates. |
| 2629 | cricket::Candidate new_candidate(candidate); |
| 2630 | new_candidate.set_network_type(rtc::ADAPTER_TYPE_UNKNOWN); |
| 2631 | new_candidate.set_relay_protocol(""); |
| 2632 | new_candidate.set_underlying_type_for_vpn(rtc::ADAPTER_TYPE_UNKNOWN); |
| 2633 |
| 2634 | network_thread()->PostTask(SafeTask( |
| 2635 | network_thread_safety_, [this, mid = mid, candidate = new_candidate] { |
| 2636 | RTC_DCHECK_RUN_ON(network_thread()); |
| 2637 | std::vector<cricket::Candidate> candidates = {candidate}; |
| 2638 | RTCError error = |
| 2639 | transport_controller_->AddRemoteCandidates(mid, candidates); |
| 2640 | if (error.ok()) { |
| 2641 | signaling_thread()->PostTask(SafeTask( |
| 2642 | signaling_thread_safety_.flag(), |
| 2643 | [this, candidate = std::move(candidate)] { |
| 2644 | ReportRemoteIceCandidateAdded(candidate); |
| 2645 | // Candidates successfully submitted for checking. |
| 2646 | if (ice_connection_state() == |
| 2647 | PeerConnectionInterface::kIceConnectionNew || |
| 2648 | ice_connection_state() == |
| 2649 | PeerConnectionInterface::kIceConnectionDisconnected) { |
| 2650 | // If state is New, then the session has just gotten its first |
| 2651 | // remote ICE candidates, so go to Checking. If state is |
| 2652 | // Disconnected, the session is re-using old candidates or |
| 2653 | // receiving additional ones, so go to Checking. If state is |
| 2654 | // Connected, stay Connected. |
| 2655 | // TODO(bemasc): If state is Connected, and the new candidates |
| 2656 | // are for a newly added transport, then the state actually |
| 2657 | // _should_ move to checking. Add a way to distinguish that |
| 2658 | // case. |
| 2659 | SetIceConnectionState( |
| 2660 | PeerConnectionInterface::kIceConnectionChecking); |
| 2661 | } |
| 2662 | // TODO(bemasc): If state is Completed, go back to Connected. |
| 2663 | })); |
| 2664 | } else { |
| 2665 | RTC_LOG(LS_WARNING) << error.message(); |
| 2666 | } |
| 2667 | })); |
| 2668 | } |
| 2669 |
| 2670 | void PeerConnection::ReportUsagePattern() const { |
| 2671 | usage_pattern_.ReportUsagePattern(observer_); |
| 2672 | } |
| 2673 |
| 2674 | void PeerConnection::ReportRemoteIceCandidateAdded( |
| 2675 | const cricket::Candidate& candidate) { |
| 2676 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2677 |
| 2678 | NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED); |
| 2679 |
| 2680 | if (candidate.address().IsPrivateIP()) { |
| 2681 | NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED); |
| 2682 | } |
| 2683 | if (candidate.address().IsUnresolvedIP()) { |
| 2684 | NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED); |
| 2685 | } |
| 2686 | if (candidate.address().family() == AF_INET6) { |
| 2687 | NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED); |
| 2688 | } |
| 2689 | } |
| 2690 |
| 2691 | bool PeerConnection::SrtpRequired() const { |
| 2692 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2693 | return (dtls_enabled_ || |
| 2694 | sdp_handler_->webrtc_session_desc_factory()->SdesPolicy() == |
| 2695 | cricket::SEC_REQUIRED); |
| 2696 | } |
| 2697 |
| 2698 | void PeerConnection::OnTransportControllerGatheringState( |
| 2699 | cricket::IceGatheringState state) { |
| 2700 | RTC_DCHECK(signaling_thread()->IsCurrent()); |
| 2701 | if (state == cricket::kIceGatheringGathering) { |
| 2702 | OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering); |
| 2703 | } else if (state == cricket::kIceGatheringComplete) { |
| 2704 | OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete); |
| 2705 | } else if (state == cricket::kIceGatheringNew) { |
| 2706 | OnIceGatheringChange(PeerConnectionInterface::kIceGatheringNew); |
| 2707 | } else { |
| 2708 | RTC_LOG(LS_ERROR) << "Unknown state received: " << state; |
| 2709 | RTC_DCHECK_NOTREACHED(); |
| 2710 | } |
| 2711 | } |
| 2712 |
| 2713 | // Runs on network_thread(). |
| 2714 | void PeerConnection::ReportTransportStats() { |
| 2715 | TRACE_EVENT0("webrtc", "PeerConnection::ReportTransportStats"); |
| 2716 | rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls; |
| 2717 | std::map<std::string, std::set<cricket::MediaType>> |
| 2718 | media_types_by_transport_name; |
| 2719 | if (ConfiguredForMedia()) { |
| 2720 | for (const auto& transceiver : |
| 2721 | rtp_manager()->transceivers()->UnsafeList()) { |
| 2722 | if (transceiver->internal()->channel()) { |
| 2723 | std::string transport_name( |
| 2724 | transceiver->internal()->channel()->transport_name()); |
| 2725 | media_types_by_transport_name[transport_name].insert( |
| 2726 | transceiver->media_type()); |
| 2727 | } |
| 2728 | } |
| 2729 | } |
| 2730 |
| 2731 | if (sctp_mid_n_) { |
| 2732 | cricket::DtlsTransportInternal* dtls_transport = |
| 2733 | transport_controller_->GetDtlsTransport(*sctp_mid_n_); |
| 2734 | if (dtls_transport) { |
| 2735 | media_types_by_transport_name[dtls_transport->transport_name()].insert( |
| 2736 | cricket::MEDIA_TYPE_DATA); |
| 2737 | } |
| 2738 | } |
| 2739 |
| 2740 | for (const auto& entry : media_types_by_transport_name) { |
| 2741 | const std::string& transport_name = entry.first; |
| 2742 | const std::set<cricket::MediaType> media_types = entry.second; |
| 2743 | cricket::TransportStats stats; |
| 2744 | if (transport_controller_->GetStats(transport_name, &stats)) { |
| 2745 | ReportBestConnectionState(stats); |
| 2746 | ReportNegotiatedCiphers(dtls_enabled_, stats, media_types); |
| 2747 | } |
| 2748 | } |
| 2749 | } |
| 2750 |
| 2751 | // Walk through the ConnectionInfos to gather best connection usage |
| 2752 | // for IPv4 and IPv6. |
| 2753 | // static (no member state required) |
| 2754 | void PeerConnection::ReportBestConnectionState( |
| 2755 | const cricket::TransportStats& stats) { |
| 2756 | for (const cricket::TransportChannelStats& channel_stats : |
| 2757 | stats.channel_stats) { |
| 2758 | for (const cricket::ConnectionInfo& connection_info : |
| 2759 | channel_stats.ice_transport_stats.connection_infos) { |
| 2760 | if (!connection_info.best_connection) { |
| 2761 | continue; |
| 2762 | } |
| 2763 |
| 2764 | const cricket::Candidate& local = connection_info.local_candidate; |
| 2765 | const cricket::Candidate& remote = connection_info.remote_candidate; |
| 2766 |
| 2767 | // Increment the counter for IceCandidatePairType. |
| 2768 | if (local.protocol() == cricket::TCP_PROTOCOL_NAME || |
| 2769 | (local.type() == RELAY_PORT_TYPE && |
| 2770 | local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) { |
| 2771 | RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP", |
| 2772 | GetIceCandidatePairCounter(local, remote), |
| 2773 | kIceCandidatePairMax); |
| 2774 | } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) { |
| 2775 | RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP", |
| 2776 | GetIceCandidatePairCounter(local, remote), |
| 2777 | kIceCandidatePairMax); |
| 2778 | } else { |
| 2779 | RTC_CHECK_NOTREACHED(); |
| 2780 | } |
| 2781 |
| 2782 | // Increment the counter for IP type. |
| 2783 | if (local.address().family() == AF_INET) { |
| 2784 | RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", |
| 2785 | kBestConnections_IPv4, |
| 2786 | kPeerConnectionAddressFamilyCounter_Max); |
| 2787 | } else if (local.address().family() == AF_INET6) { |
| 2788 | RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", |
| 2789 | kBestConnections_IPv6, |
| 2790 | kPeerConnectionAddressFamilyCounter_Max); |
| 2791 | } else { |
| 2792 | RTC_CHECK(!local.address().hostname().empty() && |
| 2793 | local.address().IsUnresolvedIP()); |
| 2794 | } |
| 2795 |
| 2796 | return; |
| 2797 | } |
| 2798 | } |
| 2799 | } |
| 2800 |
| 2801 | // static |
| 2802 | void PeerConnection::ReportNegotiatedCiphers( |
| 2803 | bool dtls_enabled, |
| 2804 | const cricket::TransportStats& stats, |
| 2805 | const std::set<cricket::MediaType>& media_types) { |
| 2806 | if (!dtls_enabled || stats.channel_stats.empty()) { |
| 2807 | return; |
| 2808 | } |
| 2809 |
| 2810 | int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite; |
| 2811 | int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite; |
| 2812 | if (srtp_crypto_suite == rtc::kSrtpInvalidCryptoSuite && |
| 2813 | ssl_cipher_suite == rtc::kTlsNullWithNullNull) { |
| 2814 | return; |
| 2815 | } |
| 2816 |
| 2817 | if (srtp_crypto_suite != rtc::kSrtpInvalidCryptoSuite) { |
| 2818 | for (cricket::MediaType media_type : media_types) { |
| 2819 | switch (media_type) { |
| 2820 | case cricket::MEDIA_TYPE_AUDIO: |
| 2821 | RTC_HISTOGRAM_ENUMERATION_SPARSE( |
| 2822 | "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite, |
| 2823 | rtc::kSrtpCryptoSuiteMaxValue); |
| 2824 | break; |
| 2825 | case cricket::MEDIA_TYPE_VIDEO: |
| 2826 | RTC_HISTOGRAM_ENUMERATION_SPARSE( |
| 2827 | "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite, |
| 2828 | rtc::kSrtpCryptoSuiteMaxValue); |
| 2829 | break; |
| 2830 | case cricket::MEDIA_TYPE_DATA: |
| 2831 | RTC_HISTOGRAM_ENUMERATION_SPARSE( |
| 2832 | "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite, |
| 2833 | rtc::kSrtpCryptoSuiteMaxValue); |
| 2834 | break; |
| 2835 | default: |
| 2836 | RTC_DCHECK_NOTREACHED(); |
| 2837 | continue; |
| 2838 | } |
| 2839 | } |
| 2840 | } |
| 2841 |
| 2842 | if (ssl_cipher_suite != rtc::kTlsNullWithNullNull) { |
| 2843 | for (cricket::MediaType media_type : media_types) { |
| 2844 | switch (media_type) { |
| 2845 | case cricket::MEDIA_TYPE_AUDIO: |
| 2846 | RTC_HISTOGRAM_ENUMERATION_SPARSE( |
| 2847 | "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite, |
| 2848 | rtc::kSslCipherSuiteMaxValue); |
| 2849 | break; |
| 2850 | case cricket::MEDIA_TYPE_VIDEO: |
| 2851 | RTC_HISTOGRAM_ENUMERATION_SPARSE( |
| 2852 | "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite, |
| 2853 | rtc::kSslCipherSuiteMaxValue); |
| 2854 | break; |
| 2855 | case cricket::MEDIA_TYPE_DATA: |
| 2856 | RTC_HISTOGRAM_ENUMERATION_SPARSE( |
| 2857 | "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite, |
| 2858 | rtc::kSslCipherSuiteMaxValue); |
| 2859 | break; |
| 2860 | default: |
| 2861 | RTC_DCHECK_NOTREACHED(); |
| 2862 | continue; |
| 2863 | } |
| 2864 | } |
| 2865 | } |
| 2866 | } |
| 2867 |
| 2868 | bool PeerConnection::OnTransportChanged( |
| 2869 | const std::string& mid, |
| 2870 | RtpTransportInternal* rtp_transport, |
| 2871 | rtc::scoped_refptr<DtlsTransport> dtls_transport, |
| 2872 | DataChannelTransportInterface* data_channel_transport) { |
| 2873 | RTC_DCHECK_RUN_ON(network_thread()); |
| 2874 | bool ret = true; |
| 2875 | if (ConfiguredForMedia()) { |
| 2876 | for (const auto& transceiver : |
| 2877 | rtp_manager()->transceivers()->UnsafeList()) { |
| 2878 | cricket::ChannelInterface* channel = transceiver->internal()->channel(); |
| 2879 | if (channel && channel->mid() == mid) { |
| 2880 | ret = channel->SetRtpTransport(rtp_transport); |
| 2881 | } |
| 2882 | } |
| 2883 | } |
| 2884 |
| 2885 | if (mid == sctp_mid_n_) { |
| 2886 | data_channel_controller_.OnTransportChanged(data_channel_transport); |
| 2887 | if (dtls_transport) { |
| 2888 | signaling_thread()->PostTask(SafeTask( |
| 2889 | signaling_thread_safety_.flag(), |
| 2890 | [this, |
| 2891 | name = std::string(dtls_transport->internal()->transport_name())] { |
| 2892 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2893 | sctp_transport_name_s_ = std::move(name); |
| 2894 | })); |
| 2895 | } |
| 2896 | } |
| 2897 |
| 2898 | return ret; |
| 2899 | } |
| 2900 |
| 2901 | PeerConnectionObserver* PeerConnection::Observer() const { |
| 2902 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2903 | RTC_DCHECK(observer_); |
| 2904 | return observer_; |
| 2905 | } |
| 2906 |
| 2907 | void PeerConnection::StartSctpTransport(int local_port, |
| 2908 | int remote_port, |
| 2909 | int max_message_size) { |
| 2910 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2911 | if (!sctp_mid_s_) |
| 2912 | return; |
| 2913 |
| 2914 | network_thread()->PostTask(SafeTask( |
| 2915 | network_thread_safety_, |
| 2916 | [this, mid = *sctp_mid_s_, local_port, remote_port, max_message_size] { |
| 2917 | rtc::scoped_refptr<SctpTransport> sctp_transport = |
| 2918 | transport_controller_n()->GetSctpTransport(mid); |
| 2919 | if (sctp_transport) |
| 2920 | sctp_transport->Start(local_port, remote_port, max_message_size); |
| 2921 | })); |
| 2922 | } |
| 2923 |
| 2924 | CryptoOptions PeerConnection::GetCryptoOptions() { |
| 2925 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2926 | // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions |
| 2927 | // after it has been removed. |
| 2928 | return configuration_.crypto_options.has_value() |
| 2929 | ? *configuration_.crypto_options |
| 2930 | : options_.crypto_options; |
| 2931 | } |
| 2932 |
| 2933 | void PeerConnection::ClearStatsCache() { |
| 2934 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2935 | if (legacy_stats_) { |
| 2936 | legacy_stats_->InvalidateCache(); |
| 2937 | } |
| 2938 | if (stats_collector_) { |
| 2939 | stats_collector_->ClearCachedStatsReport(); |
| 2940 | } |
| 2941 | } |
| 2942 |
| 2943 | bool PeerConnection::ShouldFireNegotiationNeededEvent(uint32_t event_id) { |
| 2944 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2945 | return sdp_handler_->ShouldFireNegotiationNeededEvent(event_id); |
| 2946 | } |
| 2947 |
| 2948 | void PeerConnection::RequestUsagePatternReportForTesting() { |
| 2949 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2950 | message_handler_.RequestUsagePatternReport( |
| 2951 | [this]() { |
| 2952 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2953 | ReportUsagePattern(); |
| 2954 | }, |
| 2955 | /* delay_ms= */ 0); |
| 2956 | } |
| 2957 |
| 2958 | std::function<void(const rtc::CopyOnWriteBuffer& packet, |
| 2959 | int64_t packet_time_us)> |
| 2960 | PeerConnection::InitializeRtcpCallback() { |
| 2961 | RTC_DCHECK_RUN_ON(network_thread()); |
| 2962 | return [this](const rtc::CopyOnWriteBuffer& packet, int64_t packet_time_us) { |
| 2963 | RTC_DCHECK_RUN_ON(network_thread()); |
| 2964 | call_ptr_->Receiver()->DeliverPacket(MediaType::ANY, packet, |
| 2965 | packet_time_us); |
| 2966 | }; |
| 2967 | } |
| 2968 |
| 2969 | } // namespace webrtc |
| 2970 |