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