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