| 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/sdp_offer_answer.h" |
| 12 |
| 13 | #include <algorithm> |
| 14 | #include <iterator> |
| 15 | #include <map> |
| 16 | #include <memory> |
| 17 | #include <queue> |
| 18 | #include <type_traits> |
| 19 | #include <utility> |
| 20 |
| 21 | #include "absl/algorithm/container.h" |
| 22 | #include "absl/memory/memory.h" |
| 23 | #include "absl/strings/string_view.h" |
| 24 | #include "api/array_view.h" |
| 25 | #include "api/crypto/crypto_options.h" |
| 26 | #include "api/dtls_transport_interface.h" |
| 27 | #include "api/rtp_parameters.h" |
| 28 | #include "api/rtp_receiver_interface.h" |
| 29 | #include "api/rtp_sender_interface.h" |
| 30 | #include "api/video/builtin_video_bitrate_allocator_factory.h" |
| 31 | #include "media/base/codec.h" |
| 32 | #include "media/base/media_engine.h" |
| 33 | #include "media/base/rid_description.h" |
| 34 | #include "p2p/base/ice_transport_internal.h" |
| 35 | #include "p2p/base/p2p_constants.h" |
| 36 | #include "p2p/base/p2p_transport_channel.h" |
| 37 | #include "p2p/base/port.h" |
| 38 | #include "p2p/base/transport_description.h" |
| 39 | #include "p2p/base/transport_description_factory.h" |
| 40 | #include "p2p/base/transport_info.h" |
| 41 | #include "pc/data_channel_utils.h" |
| 42 | #include "pc/dtls_transport.h" |
| 43 | #include "pc/media_stream.h" |
| 44 | #include "pc/media_stream_proxy.h" |
| 45 | #include "pc/peer_connection.h" |
| 46 | #include "pc/peer_connection_message_handler.h" |
| 47 | #include "pc/rtp_media_utils.h" |
| 48 | #include "pc/rtp_sender.h" |
| 49 | #include "pc/rtp_transport_internal.h" |
| 50 | #include "pc/simulcast_description.h" |
| 51 | #include "pc/stats_collector.h" |
| 52 | #include "pc/usage_pattern.h" |
| 53 | #include "pc/webrtc_session_description_factory.h" |
| 54 | #include "rtc_base/helpers.h" |
| 55 | #include "rtc_base/location.h" |
| 56 | #include "rtc_base/logging.h" |
| 57 | #include "rtc_base/ref_counted_object.h" |
| 58 | #include "rtc_base/rtc_certificate.h" |
| 59 | #include "rtc_base/ssl_stream_adapter.h" |
| 60 | #include "rtc_base/string_encode.h" |
| 61 | #include "rtc_base/strings/string_builder.h" |
| 62 | #include "rtc_base/third_party/sigslot/sigslot.h" |
| 63 | #include "rtc_base/trace_event.h" |
| 64 | #include "system_wrappers/include/field_trial.h" |
| 65 | #include "system_wrappers/include/metrics.h" |
| 66 |
| 67 | using cricket::ContentInfo; |
| 68 | using cricket::ContentInfos; |
| 69 | using cricket::MediaContentDescription; |
| 70 | using cricket::MediaProtocolType; |
| 71 | using cricket::RidDescription; |
| 72 | using cricket::RidDirection; |
| 73 | using cricket::SessionDescription; |
| 74 | using cricket::SimulcastDescription; |
| 75 | using cricket::SimulcastLayer; |
| 76 | using cricket::SimulcastLayerList; |
| 77 | using cricket::StreamParams; |
| 78 | using cricket::TransportInfo; |
| 79 |
| 80 | using cricket::LOCAL_PORT_TYPE; |
| 81 | using cricket::PRFLX_PORT_TYPE; |
| 82 | using cricket::RELAY_PORT_TYPE; |
| 83 | using cricket::STUN_PORT_TYPE; |
| 84 |
| 85 | namespace webrtc { |
| 86 |
| 87 | namespace { |
| 88 |
| 89 | typedef webrtc::PeerConnectionInterface::RTCOfferAnswerOptions |
| 90 | RTCOfferAnswerOptions; |
| 91 |
| 92 | constexpr const char* kAlwaysAllowPayloadTypeDemuxingFieldTrialName = |
| 93 | "WebRTC-AlwaysAllowPayloadTypeDemuxing"; |
| 94 |
| 95 | // Error messages |
| 96 | const char kInvalidSdp[] = "Invalid session description."; |
| 97 | const char kInvalidCandidates[] = "Description contains invalid candidates."; |
| 98 | const char kBundleWithoutRtcpMux[] = |
| 99 | "rtcp-mux must be enabled when BUNDLE " |
| 100 | "is enabled."; |
| 101 | const char kMlineMismatchInAnswer[] = |
| 102 | "The order of m-lines in answer doesn't match order in offer. Rejecting " |
| 103 | "answer."; |
| 104 | const char kMlineMismatchInSubsequentOffer[] = |
| 105 | "The order of m-lines in subsequent offer doesn't match order from " |
| 106 | "previous offer/answer."; |
| 107 | const char kSdpWithoutIceUfragPwd[] = |
| 108 | "Called with SDP without ice-ufrag and ice-pwd."; |
| 109 | const char kSdpWithoutDtlsFingerprint[] = |
| 110 | "Called with SDP without DTLS fingerprint."; |
| 111 | const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto."; |
| 112 |
| 113 | const char kSessionError[] = "Session error code: "; |
| 114 | const char kSessionErrorDesc[] = "Session error description: "; |
| 115 |
| 116 | // UMA metric names. |
| 117 | const char kSimulcastVersionApplyLocalDescription[] = |
| 118 | "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription"; |
| 119 | const char kSimulcastVersionApplyRemoteDescription[] = |
| 120 | "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription"; |
| 121 | const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled"; |
| 122 |
| 123 | // The length of RTCP CNAMEs. |
| 124 | static const int kRtcpCnameLength = 16; |
| 125 |
| 126 | // The maximum length of the MID attribute. |
| 127 | // TODO(bugs.webrtc.org/12517) - reduce to 16 again. |
| 128 | static constexpr size_t kMidMaxSize = 32; |
| 129 |
| 130 | const char kDefaultStreamId[] = "default"; |
| 131 | // NOTE: Duplicated in peer_connection.cc: |
| 132 | static const char kDefaultAudioSenderId[] = "defaulta0"; |
| 133 | static const char kDefaultVideoSenderId[] = "defaultv0"; |
| 134 |
| 135 | void NoteAddIceCandidateResult(int result) { |
| 136 | RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result, |
| 137 | kAddIceCandidateMax); |
| 138 | } |
| 139 |
| 140 | void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type, |
| 141 | cricket::MediaType media_type) { |
| 142 | // Array of structs needed to map {KeyExchangeProtocolType, |
| 143 | // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in |
| 144 | // order to avoid -Wglobal-constructors and -Wexit-time-destructors. |
| 145 | static constexpr struct { |
| 146 | KeyExchangeProtocolType protocol_type; |
| 147 | cricket::MediaType media_type; |
| 148 | KeyExchangeProtocolMedia protocol_media; |
| 149 | } kEnumCounterKeyProtocolMediaMap[] = { |
| 150 | {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO, |
| 151 | kEnumCounterKeyProtocolMediaTypeDtlsAudio}, |
| 152 | {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO, |
| 153 | kEnumCounterKeyProtocolMediaTypeDtlsVideo}, |
| 154 | {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA, |
| 155 | kEnumCounterKeyProtocolMediaTypeDtlsData}, |
| 156 | {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO, |
| 157 | kEnumCounterKeyProtocolMediaTypeSdesAudio}, |
| 158 | {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO, |
| 159 | kEnumCounterKeyProtocolMediaTypeSdesVideo}, |
| 160 | {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA, |
| 161 | kEnumCounterKeyProtocolMediaTypeSdesData}, |
| 162 | }; |
| 163 |
| 164 | RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type, |
| 165 | kEnumCounterKeyProtocolMax); |
| 166 |
| 167 | for (const auto& i : kEnumCounterKeyProtocolMediaMap) { |
| 168 | if (i.protocol_type == protocol_type && i.media_type == media_type) { |
| 169 | RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia", |
| 170 | i.protocol_media, |
| 171 | kEnumCounterKeyProtocolMediaTypeMax); |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 |
| 176 | std::map<std::string, const cricket::ContentGroup*> GetBundleGroupsByMid( |
| 177 | const SessionDescription* desc) { |
| 178 | std::vector<const cricket::ContentGroup*> bundle_groups = |
| 179 | desc->GetGroupsByName(cricket::GROUP_TYPE_BUNDLE); |
| 180 | std::map<std::string, const cricket::ContentGroup*> bundle_groups_by_mid; |
| 181 | for (const cricket::ContentGroup* bundle_group : bundle_groups) { |
| 182 | for (const std::string& content_name : bundle_group->content_names()) { |
| 183 | bundle_groups_by_mid[content_name] = bundle_group; |
| 184 | } |
| 185 | } |
| 186 | return bundle_groups_by_mid; |
| 187 | } |
| 188 |
| 189 | // Returns true if `new_desc` requests an ICE restart (i.e., new ufrag/pwd). |
| 190 | bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc, |
| 191 | const SessionDescriptionInterface* new_desc, |
| 192 | const std::string& content_name) { |
| 193 | if (!old_desc) { |
| 194 | return false; |
| 195 | } |
| 196 | const SessionDescription* new_sd = new_desc->description(); |
| 197 | const SessionDescription* old_sd = old_desc->description(); |
| 198 | const ContentInfo* cinfo = new_sd->GetContentByName(content_name); |
| 199 | if (!cinfo || cinfo->rejected) { |
| 200 | return false; |
| 201 | } |
| 202 | // If the content isn't rejected, check if ufrag and password has changed. |
| 203 | const cricket::TransportDescription* new_transport_desc = |
| 204 | new_sd->GetTransportDescriptionByName(content_name); |
| 205 | const cricket::TransportDescription* old_transport_desc = |
| 206 | old_sd->GetTransportDescriptionByName(content_name); |
| 207 | if (!new_transport_desc || !old_transport_desc) { |
| 208 | // No transport description exists. This is not an ICE restart. |
| 209 | return false; |
| 210 | } |
| 211 | if (cricket::IceCredentialsChanged( |
| 212 | old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd, |
| 213 | new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) { |
| 214 | RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name |
| 215 | << "."; |
| 216 | return true; |
| 217 | } |
| 218 | return false; |
| 219 | } |
| 220 |
| 221 | // Generates a string error message for SetLocalDescription/SetRemoteDescription |
| 222 | // from an RTCError. |
| 223 | std::string GetSetDescriptionErrorMessage(cricket::ContentSource source, |
| 224 | SdpType type, |
| 225 | const RTCError& error) { |
| 226 | rtc::StringBuilder oss; |
| 227 | oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote") |
| 228 | << " " << SdpTypeToString(type) << " sdp: " << error.message(); |
| 229 | return oss.Release(); |
| 230 | } |
| 231 |
| 232 | std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) { |
| 233 | std::string output = "streams=["; |
| 234 | const char* separator = ""; |
| 235 | for (const auto& stream_id : stream_ids) { |
| 236 | output.append(separator).append(stream_id); |
| 237 | separator = ", "; |
| 238 | } |
| 239 | output.append("]"); |
| 240 | return output; |
| 241 | } |
| 242 |
| 243 | void ReportSimulcastApiVersion(const char* name, |
| 244 | const SessionDescription& session) { |
| 245 | bool has_legacy = false; |
| 246 | bool has_spec_compliant = false; |
| 247 | for (const ContentInfo& content : session.contents()) { |
| 248 | if (!content.media_description()) { |
| 249 | continue; |
| 250 | } |
| 251 | has_spec_compliant |= content.media_description()->HasSimulcast(); |
| 252 | for (const StreamParams& sp : content.media_description()->streams()) { |
| 253 | has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics); |
| 254 | } |
| 255 | } |
| 256 |
| 257 | if (has_legacy) { |
| 258 | RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy, |
| 259 | kSimulcastApiVersionMax); |
| 260 | } |
| 261 | if (has_spec_compliant) { |
| 262 | RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant, |
| 263 | kSimulcastApiVersionMax); |
| 264 | } |
| 265 | if (!has_legacy && !has_spec_compliant) { |
| 266 | RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone, |
| 267 | kSimulcastApiVersionMax); |
| 268 | } |
| 269 | } |
| 270 |
| 271 | const ContentInfo* FindTransceiverMSection( |
| 272 | RtpTransceiver* transceiver, |
| 273 | const SessionDescriptionInterface* session_description) { |
| 274 | return transceiver->mid() |
| 275 | ? session_description->description()->GetContentByName( |
| 276 | *transceiver->mid()) |
| 277 | : nullptr; |
| 278 | } |
| 279 |
| 280 | // If the direction is "recvonly" or "inactive", treat the description |
| 281 | // as containing no streams. |
| 282 | // See: https://code.google.com/p/webrtc/issues/detail?id=5054 |
| 283 | std::vector<cricket::StreamParams> GetActiveStreams( |
| 284 | const cricket::MediaContentDescription* desc) { |
| 285 | return RtpTransceiverDirectionHasSend(desc->direction()) |
| 286 | ? desc->streams() |
| 287 | : std::vector<cricket::StreamParams>(); |
| 288 | } |
| 289 |
| 290 | // Logic to decide if an m= section can be recycled. This means that the new |
| 291 | // m= section is not rejected, but the old local or remote m= section is |
| 292 | // rejected. `old_content_one` and `old_content_two` refer to the m= section |
| 293 | // of the old remote and old local descriptions in no particular order. |
| 294 | // We need to check both the old local and remote because either |
| 295 | // could be the most current from the latest negotation. |
| 296 | bool IsMediaSectionBeingRecycled(SdpType type, |
| 297 | const ContentInfo& content, |
| 298 | const ContentInfo* old_content_one, |
| 299 | const ContentInfo* old_content_two) { |
| 300 | return type == SdpType::kOffer && !content.rejected && |
| 301 | ((old_content_one && old_content_one->rejected) || |
| 302 | (old_content_two && old_content_two->rejected)); |
| 303 | } |
| 304 |
| 305 | // Verify that the order of media sections in `new_desc` matches |
| 306 | // `current_desc`. The number of m= sections in `new_desc` should be no |
| 307 | // less than `current_desc`. In the case of checking an answer's |
| 308 | // `new_desc`, the `current_desc` is the last offer that was set as the |
| 309 | // local or remote. In the case of checking an offer's `new_desc` we |
| 310 | // check against the local and remote descriptions stored from the last |
| 311 | // negotiation, because either of these could be the most up to date for |
| 312 | // possible rejected m sections. These are the `current_desc` and |
| 313 | // `secondary_current_desc`. |
| 314 | bool MediaSectionsInSameOrder(const SessionDescription& current_desc, |
| 315 | const SessionDescription* secondary_current_desc, |
| 316 | const SessionDescription& new_desc, |
| 317 | const SdpType type) { |
| 318 | if (current_desc.contents().size() > new_desc.contents().size()) { |
| 319 | return false; |
| 320 | } |
| 321 |
| 322 | for (size_t i = 0; i < current_desc.contents().size(); ++i) { |
| 323 | const cricket::ContentInfo* secondary_content_info = nullptr; |
| 324 | if (secondary_current_desc && |
| 325 | i < secondary_current_desc->contents().size()) { |
| 326 | secondary_content_info = &secondary_current_desc->contents()[i]; |
| 327 | } |
| 328 | if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i], |
| 329 | ¤t_desc.contents()[i], |
| 330 | secondary_content_info)) { |
| 331 | // For new offer descriptions, if the media section can be recycled, it's |
| 332 | // valid for the MID and media type to change. |
| 333 | continue; |
| 334 | } |
| 335 | if (new_desc.contents()[i].name != current_desc.contents()[i].name) { |
| 336 | return false; |
| 337 | } |
| 338 | const MediaContentDescription* new_desc_mdesc = |
| 339 | new_desc.contents()[i].media_description(); |
| 340 | const MediaContentDescription* current_desc_mdesc = |
| 341 | current_desc.contents()[i].media_description(); |
| 342 | if (new_desc_mdesc->type() != current_desc_mdesc->type()) { |
| 343 | return false; |
| 344 | } |
| 345 | } |
| 346 | return true; |
| 347 | } |
| 348 |
| 349 | bool MediaSectionsHaveSameCount(const SessionDescription& desc1, |
| 350 | const SessionDescription& desc2) { |
| 351 | return desc1.contents().size() == desc2.contents().size(); |
| 352 | } |
| 353 | // Checks that each non-rejected content has SDES crypto keys or a DTLS |
| 354 | // fingerprint, unless it's in a BUNDLE group, in which case only the |
| 355 | // BUNDLE-tag section (first media section/description in the BUNDLE group) |
| 356 | // needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint |
| 357 | // to SDES keys, will be caught in JsepTransport negotiation, and backstopped |
| 358 | // by Channel's `srtp_required` check. |
| 359 | RTCError VerifyCrypto(const SessionDescription* desc, |
| 360 | bool dtls_enabled, |
| 361 | const std::map<std::string, const cricket::ContentGroup*>& |
| 362 | bundle_groups_by_mid) { |
| 363 | for (const cricket::ContentInfo& content_info : desc->contents()) { |
| 364 | if (content_info.rejected) { |
| 365 | continue; |
| 366 | } |
| 367 | // Note what media is used with each crypto protocol, for all sections. |
| 368 | NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls |
| 369 | : webrtc::kEnumCounterKeyProtocolSdes, |
| 370 | content_info.media_description()->type()); |
| 371 | const std::string& mid = content_info.name; |
| 372 | auto it = bundle_groups_by_mid.find(mid); |
| 373 | const cricket::ContentGroup* bundle = |
| 374 | it != bundle_groups_by_mid.end() ? it->second : nullptr; |
| 375 | if (bundle && mid != *(bundle->FirstContentName())) { |
| 376 | // This isn't the first media section in the BUNDLE group, so it's not |
| 377 | // required to have crypto attributes, since only the crypto attributes |
| 378 | // from the first section actually get used. |
| 379 | continue; |
| 380 | } |
| 381 |
| 382 | // If the content isn't rejected or bundled into another m= section, crypto |
| 383 | // must be present. |
| 384 | const MediaContentDescription* media = content_info.media_description(); |
| 385 | const TransportInfo* tinfo = desc->GetTransportInfoByName(mid); |
| 386 | if (!media || !tinfo) { |
| 387 | // Something is not right. |
| 388 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp); |
| 389 | } |
| 390 | if (dtls_enabled) { |
| 391 | if (!tinfo->description.identity_fingerprint) { |
| 392 | RTC_LOG(LS_WARNING) |
| 393 | << "Session description must have DTLS fingerprint if " |
| 394 | "DTLS enabled."; |
| 395 | return RTCError(RTCErrorType::INVALID_PARAMETER, |
| 396 | kSdpWithoutDtlsFingerprint); |
| 397 | } |
| 398 | } else { |
| 399 | if (media->cryptos().empty()) { |
| 400 | RTC_LOG(LS_WARNING) |
| 401 | << "Session description must have SDES when DTLS disabled."; |
| 402 | return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto); |
| 403 | } |
| 404 | } |
| 405 | } |
| 406 | return RTCError::OK(); |
| 407 | } |
| 408 |
| 409 | // Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless |
| 410 | // it's in a BUNDLE group, in which case only the BUNDLE-tag section (first |
| 411 | // media section/description in the BUNDLE group) needs a ufrag and pwd. |
| 412 | bool VerifyIceUfragPwdPresent( |
| 413 | const SessionDescription* desc, |
| 414 | const std::map<std::string, const cricket::ContentGroup*>& |
| 415 | bundle_groups_by_mid) { |
| 416 | for (const cricket::ContentInfo& content_info : desc->contents()) { |
| 417 | if (content_info.rejected) { |
| 418 | continue; |
| 419 | } |
| 420 | const std::string& mid = content_info.name; |
| 421 | auto it = bundle_groups_by_mid.find(mid); |
| 422 | const cricket::ContentGroup* bundle = |
| 423 | it != bundle_groups_by_mid.end() ? it->second : nullptr; |
| 424 | if (bundle && mid != *(bundle->FirstContentName())) { |
| 425 | // This isn't the first media section in the BUNDLE group, so it's not |
| 426 | // required to have ufrag/password, since only the ufrag/password from |
| 427 | // the first section actually get used. |
| 428 | continue; |
| 429 | } |
| 430 |
| 431 | // If the content isn't rejected or bundled into another m= section, |
| 432 | // ice-ufrag and ice-pwd must be present. |
| 433 | const TransportInfo* tinfo = desc->GetTransportInfoByName(mid); |
| 434 | if (!tinfo) { |
| 435 | // Something is not right. |
| 436 | RTC_LOG(LS_ERROR) << kInvalidSdp; |
| 437 | return false; |
| 438 | } |
| 439 | if (tinfo->description.ice_ufrag.empty() || |
| 440 | tinfo->description.ice_pwd.empty()) { |
| 441 | RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd."; |
| 442 | return false; |
| 443 | } |
| 444 | } |
| 445 | return true; |
| 446 | } |
| 447 |
| 448 | RTCError ValidateMids(const cricket::SessionDescription& description) { |
| 449 | std::set<std::string> mids; |
| 450 | size_t max_length = 0; |
| 451 | for (const cricket::ContentInfo& content : description.contents()) { |
| 452 | if (content.name.empty()) { |
| 453 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 454 | "A media section is missing a MID attribute."); |
| 455 | } |
| 456 | max_length = std::max(max_length, content.name.size()); |
| 457 | if (content.name.size() > kMidMaxSize) { |
| 458 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 459 | "The MID attribute exceeds the maximum supported " |
| 460 | "length of 32 characters."); |
| 461 | } |
| 462 | if (!mids.insert(content.name).second) { |
| 463 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 464 | "Duplicate a=mid value '" + content.name + "'."); |
| 465 | } |
| 466 | } |
| 467 | RTC_HISTOGRAM_COUNTS_LINEAR("WebRTC.PeerConnection.Mid.Size", max_length, 0, |
| 468 | 31, 32); |
| 469 | return RTCError::OK(); |
| 470 | } |
| 471 |
| 472 | bool IsValidOfferToReceiveMedia(int value) { |
| 473 | typedef PeerConnectionInterface::RTCOfferAnswerOptions Options; |
| 474 | return (value >= Options::kUndefined) && |
| 475 | (value <= Options::kMaxOfferToReceiveMedia); |
| 476 | } |
| 477 |
| 478 | bool ValidateOfferAnswerOptions( |
| 479 | const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) { |
| 480 | return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) && |
| 481 | IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video); |
| 482 | } |
| 483 |
| 484 | // This method will extract any send encodings that were sent by the remote |
| 485 | // connection. This is currently only relevant for Simulcast scenario (where |
| 486 | // the number of layers may be communicated by the server). |
| 487 | std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription( |
| 488 | const MediaContentDescription& desc) { |
| 489 | if (!desc.HasSimulcast()) { |
| 490 | return {}; |
| 491 | } |
| 492 | std::vector<RtpEncodingParameters> result; |
| 493 | const SimulcastDescription& simulcast = desc.simulcast_description(); |
| 494 |
| 495 | // This is a remote description, the parameters we are after should appear |
| 496 | // as receive streams. |
| 497 | for (const auto& alternatives : simulcast.receive_layers()) { |
| 498 | RTC_DCHECK(!alternatives.empty()); |
| 499 | // There is currently no way to specify or choose from alternatives. |
| 500 | // We will always use the first alternative, which is the most preferred. |
| 501 | const SimulcastLayer& layer = alternatives[0]; |
| 502 | RtpEncodingParameters parameters; |
| 503 | parameters.rid = layer.rid; |
| 504 | parameters.active = !layer.is_paused; |
| 505 | result.push_back(parameters); |
| 506 | } |
| 507 |
| 508 | return result; |
| 509 | } |
| 510 |
| 511 | RTCError UpdateSimulcastLayerStatusInSender( |
| 512 | const std::vector<SimulcastLayer>& layers, |
| 513 | rtc::scoped_refptr<RtpSenderInternal> sender) { |
| 514 | RTC_DCHECK(sender); |
| 515 | RtpParameters parameters = sender->GetParametersInternal(); |
| 516 | std::vector<std::string> disabled_layers; |
| 517 |
| 518 | // The simulcast envelope cannot be changed, only the status of the streams. |
| 519 | // So we will iterate over the send encodings rather than the layers. |
| 520 | for (RtpEncodingParameters& encoding : parameters.encodings) { |
| 521 | auto iter = std::find_if(layers.begin(), layers.end(), |
| 522 | [&encoding](const SimulcastLayer& layer) { |
| 523 | return layer.rid == encoding.rid; |
| 524 | }); |
| 525 | // A layer that cannot be found may have been removed by the remote party. |
| 526 | if (iter == layers.end()) { |
| 527 | disabled_layers.push_back(encoding.rid); |
| 528 | continue; |
| 529 | } |
| 530 |
| 531 | encoding.active = !iter->is_paused; |
| 532 | } |
| 533 |
| 534 | RTCError result = sender->SetParametersInternal(parameters); |
| 535 | if (result.ok()) { |
| 536 | result = sender->DisableEncodingLayers(disabled_layers); |
| 537 | } |
| 538 |
| 539 | return result; |
| 540 | } |
| 541 |
| 542 | bool SimulcastIsRejected(const ContentInfo* local_content, |
| 543 | const MediaContentDescription& answer_media_desc, |
| 544 | bool enable_encrypted_rtp_header_extensions) { |
| 545 | bool simulcast_offered = local_content && |
| 546 | local_content->media_description() && |
| 547 | local_content->media_description()->HasSimulcast(); |
| 548 | bool simulcast_answered = answer_media_desc.HasSimulcast(); |
| 549 | bool rids_supported = RtpExtension::FindHeaderExtensionByUri( |
| 550 | answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri, |
| 551 | enable_encrypted_rtp_header_extensions |
| 552 | ? RtpExtension::Filter::kPreferEncryptedExtension |
| 553 | : RtpExtension::Filter::kDiscardEncryptedExtension); |
| 554 | return simulcast_offered && (!simulcast_answered || !rids_supported); |
| 555 | } |
| 556 |
| 557 | RTCError DisableSimulcastInSender( |
| 558 | rtc::scoped_refptr<RtpSenderInternal> sender) { |
| 559 | RTC_DCHECK(sender); |
| 560 | RtpParameters parameters = sender->GetParametersInternal(); |
| 561 | if (parameters.encodings.size() <= 1) { |
| 562 | return RTCError::OK(); |
| 563 | } |
| 564 |
| 565 | std::vector<std::string> disabled_layers; |
| 566 | std::transform( |
| 567 | parameters.encodings.begin() + 1, parameters.encodings.end(), |
| 568 | std::back_inserter(disabled_layers), |
| 569 | [](const RtpEncodingParameters& encoding) { return encoding.rid; }); |
| 570 | return sender->DisableEncodingLayers(disabled_layers); |
| 571 | } |
| 572 |
| 573 | // The SDP parser used to populate these values by default for the 'content |
| 574 | // name' if an a=mid line was absent. |
| 575 | absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) { |
| 576 | switch (media_type) { |
| 577 | case cricket::MEDIA_TYPE_AUDIO: |
| 578 | return cricket::CN_AUDIO; |
| 579 | case cricket::MEDIA_TYPE_VIDEO: |
| 580 | return cricket::CN_VIDEO; |
| 581 | case cricket::MEDIA_TYPE_DATA: |
| 582 | return cricket::CN_DATA; |
| 583 | case cricket::MEDIA_TYPE_UNSUPPORTED: |
| 584 | return "not supported"; |
| 585 | } |
| 586 | RTC_DCHECK_NOTREACHED(); |
| 587 | return ""; |
| 588 | } |
| 589 |
| 590 | // Add options to |[audio/video]_media_description_options| from `senders`. |
| 591 | void AddPlanBRtpSenderOptions( |
| 592 | const std::vector<rtc::scoped_refptr< |
| 593 | RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders, |
| 594 | cricket::MediaDescriptionOptions* audio_media_description_options, |
| 595 | cricket::MediaDescriptionOptions* video_media_description_options, |
| 596 | int num_sim_layers) { |
| 597 | for (const auto& sender : senders) { |
| 598 | if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) { |
| 599 | if (audio_media_description_options) { |
| 600 | audio_media_description_options->AddAudioSender( |
| 601 | sender->id(), sender->internal()->stream_ids()); |
| 602 | } |
| 603 | } else { |
| 604 | RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO); |
| 605 | if (video_media_description_options) { |
| 606 | video_media_description_options->AddVideoSender( |
| 607 | sender->id(), sender->internal()->stream_ids(), {}, |
| 608 | SimulcastLayerList(), num_sim_layers); |
| 609 | } |
| 610 | } |
| 611 | } |
| 612 | } |
| 613 |
| 614 | cricket::MediaDescriptionOptions GetMediaDescriptionOptionsForTransceiver( |
| 615 | RtpTransceiver* transceiver, |
| 616 | const std::string& mid, |
| 617 | bool is_create_offer) { |
| 618 | // NOTE: a stopping transceiver should be treated as a stopped one in |
| 619 | // createOffer as specified in |
| 620 | // https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-createoffer. |
| 621 | bool stopped = |
| 622 | is_create_offer ? transceiver->stopping() : transceiver->stopped(); |
| 623 | cricket::MediaDescriptionOptions media_description_options( |
| 624 | transceiver->media_type(), mid, transceiver->direction(), stopped); |
| 625 | media_description_options.codec_preferences = |
| 626 | transceiver->codec_preferences(); |
| 627 | media_description_options.header_extensions = |
| 628 | transceiver->HeaderExtensionsToOffer(); |
| 629 | // This behavior is specified in JSEP. The gist is that: |
| 630 | // 1. The MSID is included if the RtpTransceiver's direction is sendonly or |
| 631 | // sendrecv. |
| 632 | // 2. If the MSID is included, then it must be included in any subsequent |
| 633 | // offer/answer exactly the same until the RtpTransceiver is stopped. |
| 634 | if (stopped || (!RtpTransceiverDirectionHasSend(transceiver->direction()) && |
| 635 | !transceiver->has_ever_been_used_to_send())) { |
| 636 | return media_description_options; |
| 637 | } |
| 638 |
| 639 | cricket::SenderOptions sender_options; |
| 640 | sender_options.track_id = transceiver->sender()->id(); |
| 641 | sender_options.stream_ids = transceiver->sender()->stream_ids(); |
| 642 |
| 643 | // The following sets up RIDs and Simulcast. |
| 644 | // RIDs are included if Simulcast is requested or if any RID was specified. |
| 645 | RtpParameters send_parameters = |
| 646 | transceiver->sender_internal()->GetParametersInternal(); |
| 647 | bool has_rids = std::any_of(send_parameters.encodings.begin(), |
| 648 | send_parameters.encodings.end(), |
| 649 | [](const RtpEncodingParameters& encoding) { |
| 650 | return !encoding.rid.empty(); |
| 651 | }); |
| 652 |
| 653 | std::vector<RidDescription> send_rids; |
| 654 | SimulcastLayerList send_layers; |
| 655 | for (const RtpEncodingParameters& encoding : send_parameters.encodings) { |
| 656 | if (encoding.rid.empty()) { |
| 657 | continue; |
| 658 | } |
| 659 | send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend)); |
| 660 | send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active)); |
| 661 | } |
| 662 |
| 663 | if (has_rids) { |
| 664 | sender_options.rids = send_rids; |
| 665 | } |
| 666 |
| 667 | sender_options.simulcast_layers = send_layers; |
| 668 | // When RIDs are configured, we must set num_sim_layers to 0 to. |
| 669 | // Otherwise, num_sim_layers must be 1 because either there is no |
| 670 | // simulcast, or simulcast is acheived by munging the SDP. |
| 671 | sender_options.num_sim_layers = has_rids ? 0 : 1; |
| 672 | media_description_options.sender_options.push_back(sender_options); |
| 673 |
| 674 | return media_description_options; |
| 675 | } |
| 676 |
| 677 | // Returns the ContentInfo at mline index `i`, or null if none exists. |
| 678 | const ContentInfo* GetContentByIndex(const SessionDescriptionInterface* sdesc, |
| 679 | size_t i) { |
| 680 | if (!sdesc) { |
| 681 | return nullptr; |
| 682 | } |
| 683 | const ContentInfos& contents = sdesc->description()->contents(); |
| 684 | return (i < contents.size() ? &contents[i] : nullptr); |
| 685 | } |
| 686 |
| 687 | // From `rtc_options`, fill parts of `session_options` shared by all generated |
| 688 | // m= sectionss (in other words, nothing that involves a map/array). |
| 689 | void ExtractSharedMediaSessionOptions( |
| 690 | const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options, |
| 691 | cricket::MediaSessionOptions* session_options) { |
| 692 | session_options->vad_enabled = rtc_options.voice_activity_detection; |
| 693 | session_options->bundle_enabled = rtc_options.use_rtp_mux; |
| 694 | session_options->raw_packetization_for_video = |
| 695 | rtc_options.raw_packetization_for_video; |
| 696 | } |
| 697 |
| 698 | // Generate a RTCP CNAME when a PeerConnection is created. |
| 699 | std::string GenerateRtcpCname() { |
| 700 | std::string cname; |
| 701 | if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) { |
| 702 | RTC_LOG(LS_ERROR) << "Failed to generate CNAME."; |
| 703 | RTC_DCHECK_NOTREACHED(); |
| 704 | } |
| 705 | return cname; |
| 706 | } |
| 707 |
| 708 | // Check if we can send `new_stream` on a PeerConnection. |
| 709 | bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams, |
| 710 | webrtc::MediaStreamInterface* new_stream) { |
| 711 | if (!new_stream || !current_streams) { |
| 712 | return false; |
| 713 | } |
| 714 | if (current_streams->find(new_stream->id()) != nullptr) { |
| 715 | RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id() |
| 716 | << " is already added."; |
| 717 | return false; |
| 718 | } |
| 719 | return true; |
| 720 | } |
| 721 |
| 722 | rtc::scoped_refptr<webrtc::DtlsTransport> LookupDtlsTransportByMid( |
| 723 | rtc::Thread* network_thread, |
| 724 | JsepTransportController* controller, |
| 725 | const std::string& mid) { |
| 726 | // TODO(tommi): Can we post this (and associated operations where this |
| 727 | // function is called) to the network thread and avoid this Invoke? |
| 728 | // We might be able to simplify a few things if we set the transport on |
| 729 | // the network thread and then update the implementation to check that |
| 730 | // the set_ and relevant get methods are always called on the network |
| 731 | // thread (we'll need to update proxy maps). |
| 732 | return network_thread->Invoke<rtc::scoped_refptr<webrtc::DtlsTransport>>( |
| 733 | RTC_FROM_HERE, |
| 734 | [controller, &mid] { return controller->LookupDtlsTransportByMid(mid); }); |
| 735 | } |
| 736 |
| 737 | bool ContentHasHeaderExtension(const cricket::ContentInfo& content_info, |
| 738 | absl::string_view header_extension_uri) { |
| 739 | for (const RtpExtension& rtp_header_extension : |
| 740 | content_info.media_description()->rtp_header_extensions()) { |
| 741 | if (rtp_header_extension.uri == header_extension_uri) { |
| 742 | return true; |
| 743 | } |
| 744 | } |
| 745 | return false; |
| 746 | } |
| 747 |
| 748 | } // namespace |
| 749 |
| 750 | // Used by parameterless SetLocalDescription() to create an offer or answer. |
| 751 | // Upon completion of creating the session description, SetLocalDescription() is |
| 752 | // invoked with the result. |
| 753 | class SdpOfferAnswerHandler::ImplicitCreateSessionDescriptionObserver |
| 754 | : public CreateSessionDescriptionObserver { |
| 755 | public: |
| 756 | ImplicitCreateSessionDescriptionObserver( |
| 757 | rtc::WeakPtr<SdpOfferAnswerHandler> sdp_handler, |
| 758 | rtc::scoped_refptr<SetLocalDescriptionObserverInterface> |
| 759 | set_local_description_observer) |
| 760 | : sdp_handler_(std::move(sdp_handler)), |
| 761 | set_local_description_observer_( |
| 762 | std::move(set_local_description_observer)) {} |
| 763 | ~ImplicitCreateSessionDescriptionObserver() override { |
| 764 | RTC_DCHECK(was_called_); |
| 765 | } |
| 766 |
| 767 | void SetOperationCompleteCallback( |
| 768 | std::function<void()> operation_complete_callback) { |
| 769 | operation_complete_callback_ = std::move(operation_complete_callback); |
| 770 | } |
| 771 |
| 772 | bool was_called() const { return was_called_; } |
| 773 |
| 774 | void OnSuccess(SessionDescriptionInterface* desc_ptr) override { |
| 775 | RTC_DCHECK(!was_called_); |
| 776 | std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr); |
| 777 | was_called_ = true; |
| 778 |
| 779 | // Abort early if `pc_` is no longer valid. |
| 780 | if (!sdp_handler_) { |
| 781 | operation_complete_callback_(); |
| 782 | return; |
| 783 | } |
| 784 | // DoSetLocalDescription() is a synchronous operation that invokes |
| 785 | // `set_local_description_observer_` with the result. |
| 786 | sdp_handler_->DoSetLocalDescription( |
| 787 | std::move(desc), std::move(set_local_description_observer_)); |
| 788 | operation_complete_callback_(); |
| 789 | } |
| 790 |
| 791 | void OnFailure(RTCError error) override { |
| 792 | RTC_DCHECK(!was_called_); |
| 793 | was_called_ = true; |
| 794 | set_local_description_observer_->OnSetLocalDescriptionComplete(RTCError( |
| 795 | error.type(), std::string("SetLocalDescription failed to create " |
| 796 | "session description - ") + |
| 797 | error.message())); |
| 798 | operation_complete_callback_(); |
| 799 | } |
| 800 |
| 801 | private: |
| 802 | bool was_called_ = false; |
| 803 | rtc::WeakPtr<SdpOfferAnswerHandler> sdp_handler_; |
| 804 | rtc::scoped_refptr<SetLocalDescriptionObserverInterface> |
| 805 | set_local_description_observer_; |
| 806 | std::function<void()> operation_complete_callback_; |
| 807 | }; |
| 808 |
| 809 | // Wraps a CreateSessionDescriptionObserver and an OperationsChain operation |
| 810 | // complete callback. When the observer is invoked, the wrapped observer is |
| 811 | // invoked followed by invoking the completion callback. |
| 812 | class CreateSessionDescriptionObserverOperationWrapper |
| 813 | : public CreateSessionDescriptionObserver { |
| 814 | public: |
| 815 | CreateSessionDescriptionObserverOperationWrapper( |
| 816 | rtc::scoped_refptr<CreateSessionDescriptionObserver> observer, |
| 817 | std::function<void()> operation_complete_callback) |
| 818 | : observer_(std::move(observer)), |
| 819 | operation_complete_callback_(std::move(operation_complete_callback)) { |
| 820 | RTC_DCHECK(observer_); |
| 821 | } |
| 822 | ~CreateSessionDescriptionObserverOperationWrapper() override { |
| 823 | #if RTC_DCHECK_IS_ON |
| 824 | RTC_DCHECK(was_called_); |
| 825 | #endif |
| 826 | } |
| 827 |
| 828 | void OnSuccess(SessionDescriptionInterface* desc) override { |
| 829 | #if RTC_DCHECK_IS_ON |
| 830 | RTC_DCHECK(!was_called_); |
| 831 | was_called_ = true; |
| 832 | #endif // RTC_DCHECK_IS_ON |
| 833 | // Completing the operation before invoking the observer allows the observer |
| 834 | // to execute SetLocalDescription() without delay. |
| 835 | operation_complete_callback_(); |
| 836 | observer_->OnSuccess(desc); |
| 837 | } |
| 838 |
| 839 | void OnFailure(RTCError error) override { |
| 840 | #if RTC_DCHECK_IS_ON |
| 841 | RTC_DCHECK(!was_called_); |
| 842 | was_called_ = true; |
| 843 | #endif // RTC_DCHECK_IS_ON |
| 844 | operation_complete_callback_(); |
| 845 | observer_->OnFailure(std::move(error)); |
| 846 | } |
| 847 |
| 848 | private: |
| 849 | #if RTC_DCHECK_IS_ON |
| 850 | bool was_called_ = false; |
| 851 | #endif // RTC_DCHECK_IS_ON |
| 852 | rtc::scoped_refptr<CreateSessionDescriptionObserver> observer_; |
| 853 | std::function<void()> operation_complete_callback_; |
| 854 | }; |
| 855 |
| 856 | // Wrapper for SetSessionDescriptionObserver that invokes the success or failure |
| 857 | // callback in a posted message handled by the peer connection. This introduces |
| 858 | // a delay that prevents recursive API calls by the observer, but this also |
| 859 | // means that the PeerConnection can be modified before the observer sees the |
| 860 | // result of the operation. This is ill-advised for synchronizing states. |
| 861 | // |
| 862 | // Implements both the SetLocalDescriptionObserverInterface and the |
| 863 | // SetRemoteDescriptionObserverInterface. |
| 864 | class SdpOfferAnswerHandler::SetSessionDescriptionObserverAdapter |
| 865 | : public SetLocalDescriptionObserverInterface, |
| 866 | public SetRemoteDescriptionObserverInterface { |
| 867 | public: |
| 868 | SetSessionDescriptionObserverAdapter( |
| 869 | rtc::WeakPtr<SdpOfferAnswerHandler> handler, |
| 870 | rtc::scoped_refptr<SetSessionDescriptionObserver> inner_observer) |
| 871 | : handler_(std::move(handler)), |
| 872 | inner_observer_(std::move(inner_observer)) {} |
| 873 |
| 874 | // SetLocalDescriptionObserverInterface implementation. |
| 875 | void OnSetLocalDescriptionComplete(RTCError error) override { |
| 876 | OnSetDescriptionComplete(std::move(error)); |
| 877 | } |
| 878 | // SetRemoteDescriptionObserverInterface implementation. |
| 879 | void OnSetRemoteDescriptionComplete(RTCError error) override { |
| 880 | OnSetDescriptionComplete(std::move(error)); |
| 881 | } |
| 882 |
| 883 | private: |
| 884 | void OnSetDescriptionComplete(RTCError error) { |
| 885 | if (!handler_) |
| 886 | return; |
| 887 | if (error.ok()) { |
| 888 | handler_->pc_->message_handler()->PostSetSessionDescriptionSuccess( |
| 889 | inner_observer_); |
| 890 | } else { |
| 891 | handler_->pc_->message_handler()->PostSetSessionDescriptionFailure( |
| 892 | inner_observer_, std::move(error)); |
| 893 | } |
| 894 | } |
| 895 |
| 896 | rtc::WeakPtr<SdpOfferAnswerHandler> handler_; |
| 897 | rtc::scoped_refptr<SetSessionDescriptionObserver> inner_observer_; |
| 898 | }; |
| 899 |
| 900 | class SdpOfferAnswerHandler::LocalIceCredentialsToReplace { |
| 901 | public: |
| 902 | // Sets the ICE credentials that need restarting to the ICE credentials of |
| 903 | // the current and pending descriptions. |
| 904 | void SetIceCredentialsFromLocalDescriptions( |
| 905 | const SessionDescriptionInterface* current_local_description, |
| 906 | const SessionDescriptionInterface* pending_local_description) { |
| 907 | ice_credentials_.clear(); |
| 908 | if (current_local_description) { |
| 909 | AppendIceCredentialsFromSessionDescription(*current_local_description); |
| 910 | } |
| 911 | if (pending_local_description) { |
| 912 | AppendIceCredentialsFromSessionDescription(*pending_local_description); |
| 913 | } |
| 914 | } |
| 915 |
| 916 | void ClearIceCredentials() { ice_credentials_.clear(); } |
| 917 |
| 918 | // Returns true if we have ICE credentials that need restarting. |
| 919 | bool HasIceCredentials() const { return !ice_credentials_.empty(); } |
| 920 |
| 921 | // Returns true if `local_description` shares no ICE credentials with the |
| 922 | // ICE credentials that need restarting. |
| 923 | bool SatisfiesIceRestart( |
| 924 | const SessionDescriptionInterface& local_description) const { |
| 925 | for (const auto& transport_info : |
| 926 | local_description.description()->transport_infos()) { |
| 927 | if (ice_credentials_.find(std::make_pair( |
| 928 | transport_info.description.ice_ufrag, |
| 929 | transport_info.description.ice_pwd)) != ice_credentials_.end()) { |
| 930 | return false; |
| 931 | } |
| 932 | } |
| 933 | return true; |
| 934 | } |
| 935 |
| 936 | private: |
| 937 | void AppendIceCredentialsFromSessionDescription( |
| 938 | const SessionDescriptionInterface& desc) { |
| 939 | for (const auto& transport_info : desc.description()->transport_infos()) { |
| 940 | ice_credentials_.insert( |
| 941 | std::make_pair(transport_info.description.ice_ufrag, |
| 942 | transport_info.description.ice_pwd)); |
| 943 | } |
| 944 | } |
| 945 |
| 946 | std::set<std::pair<std::string, std::string>> ice_credentials_; |
| 947 | }; |
| 948 |
| 949 | SdpOfferAnswerHandler::SdpOfferAnswerHandler(PeerConnection* pc) |
| 950 | : pc_(pc), |
| 951 | local_streams_(StreamCollection::Create()), |
| 952 | remote_streams_(StreamCollection::Create()), |
| 953 | operations_chain_(rtc::OperationsChain::Create()), |
| 954 | rtcp_cname_(GenerateRtcpCname()), |
| 955 | local_ice_credentials_to_replace_(new LocalIceCredentialsToReplace()), |
| 956 | weak_ptr_factory_(this) { |
| 957 | operations_chain_->SetOnChainEmptyCallback( |
| 958 | [this_weak_ptr = weak_ptr_factory_.GetWeakPtr()]() { |
| 959 | if (!this_weak_ptr) |
| 960 | return; |
| 961 | this_weak_ptr->OnOperationsChainEmpty(); |
| 962 | }); |
| 963 | } |
| 964 |
| 965 | SdpOfferAnswerHandler::~SdpOfferAnswerHandler() {} |
| 966 |
| 967 | // Static |
| 968 | std::unique_ptr<SdpOfferAnswerHandler> SdpOfferAnswerHandler::Create( |
| 969 | PeerConnection* pc, |
| 970 | const PeerConnectionInterface::RTCConfiguration& configuration, |
| 971 | PeerConnectionDependencies& dependencies) { |
| 972 | auto handler = absl::WrapUnique(new SdpOfferAnswerHandler(pc)); |
| 973 | handler->Initialize(configuration, dependencies); |
| 974 | return handler; |
| 975 | } |
| 976 |
| 977 | void SdpOfferAnswerHandler::Initialize( |
| 978 | const PeerConnectionInterface::RTCConfiguration& configuration, |
| 979 | PeerConnectionDependencies& dependencies) { |
| 980 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 981 | video_options_.screencast_min_bitrate_kbps = |
| 982 | configuration.screencast_min_bitrate; |
| 983 | audio_options_.combined_audio_video_bwe = |
| 984 | configuration.combined_audio_video_bwe; |
| 985 |
| 986 | audio_options_.audio_jitter_buffer_max_packets = |
| 987 | configuration.audio_jitter_buffer_max_packets; |
| 988 |
| 989 | audio_options_.audio_jitter_buffer_fast_accelerate = |
| 990 | configuration.audio_jitter_buffer_fast_accelerate; |
| 991 |
| 992 | audio_options_.audio_jitter_buffer_min_delay_ms = |
| 993 | configuration.audio_jitter_buffer_min_delay_ms; |
| 994 |
| 995 | audio_options_.audio_jitter_buffer_enable_rtx_handling = |
| 996 | configuration.audio_jitter_buffer_enable_rtx_handling; |
| 997 |
| 998 | // Obtain a certificate from RTCConfiguration if any were provided (optional). |
| 999 | rtc::scoped_refptr<rtc::RTCCertificate> certificate; |
| 1000 | if (!configuration.certificates.empty()) { |
| 1001 | // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of |
| 1002 | // just picking the first one. The decision should be made based on the DTLS |
| 1003 | // handshake. The DTLS negotiations need to know about all certificates. |
| 1004 | certificate = configuration.certificates[0]; |
| 1005 | } |
| 1006 |
| 1007 | webrtc_session_desc_factory_ = |
| 1008 | std::make_unique<WebRtcSessionDescriptionFactory>( |
| 1009 | signaling_thread(), channel_manager(), this, pc_->session_id(), |
| 1010 | pc_->dtls_enabled(), std::move(dependencies.cert_generator), |
| 1011 | certificate, &ssrc_generator_, |
| 1012 | [this](const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) { |
| 1013 | transport_controller()->SetLocalCertificate(certificate); |
| 1014 | }); |
| 1015 |
| 1016 | if (pc_->options()->disable_encryption) { |
| 1017 | webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED); |
| 1018 | } |
| 1019 |
| 1020 | webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions( |
| 1021 | pc_->GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions); |
| 1022 | webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan()); |
| 1023 |
| 1024 | if (dependencies.video_bitrate_allocator_factory) { |
| 1025 | video_bitrate_allocator_factory_ = |
| 1026 | std::move(dependencies.video_bitrate_allocator_factory); |
| 1027 | } else { |
| 1028 | video_bitrate_allocator_factory_ = |
| 1029 | CreateBuiltinVideoBitrateAllocatorFactory(); |
| 1030 | } |
| 1031 | } |
| 1032 |
| 1033 | // ================================================================== |
| 1034 | // Access to pc_ variables |
| 1035 | cricket::ChannelManager* SdpOfferAnswerHandler::channel_manager() const { |
| 1036 | return pc_->channel_manager(); |
| 1037 | } |
| 1038 | TransceiverList* SdpOfferAnswerHandler::transceivers() { |
| 1039 | if (!pc_->rtp_manager()) { |
| 1040 | return nullptr; |
| 1041 | } |
| 1042 | return pc_->rtp_manager()->transceivers(); |
| 1043 | } |
| 1044 | const TransceiverList* SdpOfferAnswerHandler::transceivers() const { |
| 1045 | if (!pc_->rtp_manager()) { |
| 1046 | return nullptr; |
| 1047 | } |
| 1048 | return pc_->rtp_manager()->transceivers(); |
| 1049 | } |
| 1050 | JsepTransportController* SdpOfferAnswerHandler::transport_controller() { |
| 1051 | return pc_->transport_controller(); |
| 1052 | } |
| 1053 | const JsepTransportController* SdpOfferAnswerHandler::transport_controller() |
| 1054 | const { |
| 1055 | return pc_->transport_controller(); |
| 1056 | } |
| 1057 | DataChannelController* SdpOfferAnswerHandler::data_channel_controller() { |
| 1058 | return pc_->data_channel_controller(); |
| 1059 | } |
| 1060 | const DataChannelController* SdpOfferAnswerHandler::data_channel_controller() |
| 1061 | const { |
| 1062 | return pc_->data_channel_controller(); |
| 1063 | } |
| 1064 | cricket::PortAllocator* SdpOfferAnswerHandler::port_allocator() { |
| 1065 | return pc_->port_allocator(); |
| 1066 | } |
| 1067 | const cricket::PortAllocator* SdpOfferAnswerHandler::port_allocator() const { |
| 1068 | return pc_->port_allocator(); |
| 1069 | } |
| 1070 | RtpTransmissionManager* SdpOfferAnswerHandler::rtp_manager() { |
| 1071 | return pc_->rtp_manager(); |
| 1072 | } |
| 1073 | const RtpTransmissionManager* SdpOfferAnswerHandler::rtp_manager() const { |
| 1074 | return pc_->rtp_manager(); |
| 1075 | } |
| 1076 |
| 1077 | // =================================================================== |
| 1078 |
| 1079 | void SdpOfferAnswerHandler::PrepareForShutdown() { |
| 1080 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1081 | weak_ptr_factory_.InvalidateWeakPtrs(); |
| 1082 | } |
| 1083 |
| 1084 | void SdpOfferAnswerHandler::Close() { |
| 1085 | ChangeSignalingState(PeerConnectionInterface::kClosed); |
| 1086 | } |
| 1087 |
| 1088 | void SdpOfferAnswerHandler::RestartIce() { |
| 1089 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1090 | local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions( |
| 1091 | current_local_description(), pending_local_description()); |
| 1092 | UpdateNegotiationNeeded(); |
| 1093 | } |
| 1094 |
| 1095 | rtc::Thread* SdpOfferAnswerHandler::signaling_thread() const { |
| 1096 | return pc_->signaling_thread(); |
| 1097 | } |
| 1098 |
| 1099 | void SdpOfferAnswerHandler::CreateOffer( |
| 1100 | CreateSessionDescriptionObserver* observer, |
| 1101 | const PeerConnectionInterface::RTCOfferAnswerOptions& options) { |
| 1102 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1103 | // Chain this operation. If asynchronous operations are pending on the chain, |
| 1104 | // this operation will be queued to be invoked, otherwise the contents of the |
| 1105 | // lambda will execute immediately. |
| 1106 | operations_chain_->ChainOperation( |
| 1107 | [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(), |
| 1108 | observer_refptr = |
| 1109 | rtc::scoped_refptr<CreateSessionDescriptionObserver>(observer), |
| 1110 | options](std::function<void()> operations_chain_callback) { |
| 1111 | // Abort early if `this_weak_ptr` is no longer valid. |
| 1112 | if (!this_weak_ptr) { |
| 1113 | observer_refptr->OnFailure( |
| 1114 | RTCError(RTCErrorType::INTERNAL_ERROR, |
| 1115 | "CreateOffer failed because the session was shut down")); |
| 1116 | operations_chain_callback(); |
| 1117 | return; |
| 1118 | } |
| 1119 | // The operation completes asynchronously when the wrapper is invoked. |
| 1120 | auto observer_wrapper = rtc::make_ref_counted< |
| 1121 | CreateSessionDescriptionObserverOperationWrapper>( |
| 1122 | std::move(observer_refptr), std::move(operations_chain_callback)); |
| 1123 | this_weak_ptr->DoCreateOffer(options, observer_wrapper); |
| 1124 | }); |
| 1125 | } |
| 1126 |
| 1127 | void SdpOfferAnswerHandler::SetLocalDescription( |
| 1128 | SetSessionDescriptionObserver* observer, |
| 1129 | SessionDescriptionInterface* desc_ptr) { |
| 1130 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1131 | // Chain this operation. If asynchronous operations are pending on the chain, |
| 1132 | // this operation will be queued to be invoked, otherwise the contents of the |
| 1133 | // lambda will execute immediately. |
| 1134 | operations_chain_->ChainOperation( |
| 1135 | [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(), |
| 1136 | observer_refptr = |
| 1137 | rtc::scoped_refptr<SetSessionDescriptionObserver>(observer), |
| 1138 | desc = std::unique_ptr<SessionDescriptionInterface>(desc_ptr)]( |
| 1139 | std::function<void()> operations_chain_callback) mutable { |
| 1140 | // Abort early if `this_weak_ptr` is no longer valid. |
| 1141 | if (!this_weak_ptr) { |
| 1142 | // For consistency with SetSessionDescriptionObserverAdapter whose |
| 1143 | // posted messages doesn't get processed when the PC is destroyed, we |
| 1144 | // do not inform `observer_refptr` that the operation failed. |
| 1145 | operations_chain_callback(); |
| 1146 | return; |
| 1147 | } |
| 1148 | // SetSessionDescriptionObserverAdapter takes care of making sure the |
| 1149 | // `observer_refptr` is invoked in a posted message. |
| 1150 | this_weak_ptr->DoSetLocalDescription( |
| 1151 | std::move(desc), |
| 1152 | rtc::make_ref_counted<SetSessionDescriptionObserverAdapter>( |
| 1153 | this_weak_ptr, observer_refptr)); |
| 1154 | // For backwards-compatability reasons, we declare the operation as |
| 1155 | // completed here (rather than in a post), so that the operation chain |
| 1156 | // is not blocked by this operation when the observer is invoked. This |
| 1157 | // allows the observer to trigger subsequent offer/answer operations |
| 1158 | // synchronously if the operation chain is now empty. |
| 1159 | operations_chain_callback(); |
| 1160 | }); |
| 1161 | } |
| 1162 |
| 1163 | void SdpOfferAnswerHandler::SetLocalDescription( |
| 1164 | std::unique_ptr<SessionDescriptionInterface> desc, |
| 1165 | rtc::scoped_refptr<SetLocalDescriptionObserverInterface> observer) { |
| 1166 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1167 | // Chain this operation. If asynchronous operations are pending on the chain, |
| 1168 | // this operation will be queued to be invoked, otherwise the contents of the |
| 1169 | // lambda will execute immediately. |
| 1170 | operations_chain_->ChainOperation( |
| 1171 | [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(), observer, |
| 1172 | desc = std::move(desc)]( |
| 1173 | std::function<void()> operations_chain_callback) mutable { |
| 1174 | // Abort early if `this_weak_ptr` is no longer valid. |
| 1175 | if (!this_weak_ptr) { |
| 1176 | observer->OnSetLocalDescriptionComplete(RTCError( |
| 1177 | RTCErrorType::INTERNAL_ERROR, |
| 1178 | "SetLocalDescription failed because the session was shut down")); |
| 1179 | operations_chain_callback(); |
| 1180 | return; |
| 1181 | } |
| 1182 | this_weak_ptr->DoSetLocalDescription(std::move(desc), observer); |
| 1183 | // DoSetLocalDescription() is implemented as a synchronous operation. |
| 1184 | // The `observer` will already have been informed that it completed, and |
| 1185 | // we can mark this operation as complete without any loose ends. |
| 1186 | operations_chain_callback(); |
| 1187 | }); |
| 1188 | } |
| 1189 |
| 1190 | void SdpOfferAnswerHandler::SetLocalDescription( |
| 1191 | SetSessionDescriptionObserver* observer) { |
| 1192 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1193 | SetLocalDescription( |
| 1194 | rtc::make_ref_counted<SetSessionDescriptionObserverAdapter>( |
| 1195 | weak_ptr_factory_.GetWeakPtr(), observer)); |
| 1196 | } |
| 1197 |
| 1198 | void SdpOfferAnswerHandler::SetLocalDescription( |
| 1199 | rtc::scoped_refptr<SetLocalDescriptionObserverInterface> observer) { |
| 1200 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1201 | // The `create_sdp_observer` handles performing DoSetLocalDescription() with |
| 1202 | // the resulting description as well as completing the operation. |
| 1203 | auto create_sdp_observer = |
| 1204 | rtc::make_ref_counted<ImplicitCreateSessionDescriptionObserver>( |
| 1205 | weak_ptr_factory_.GetWeakPtr(), observer); |
| 1206 | // Chain this operation. If asynchronous operations are pending on the chain, |
| 1207 | // this operation will be queued to be invoked, otherwise the contents of the |
| 1208 | // lambda will execute immediately. |
| 1209 | operations_chain_->ChainOperation( |
| 1210 | [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(), |
| 1211 | create_sdp_observer](std::function<void()> operations_chain_callback) { |
| 1212 | // The `create_sdp_observer` is responsible for completing the |
| 1213 | // operation. |
| 1214 | create_sdp_observer->SetOperationCompleteCallback( |
| 1215 | std::move(operations_chain_callback)); |
| 1216 | // Abort early if `this_weak_ptr` is no longer valid. This triggers the |
| 1217 | // same code path as if DoCreateOffer() or DoCreateAnswer() failed. |
| 1218 | if (!this_weak_ptr) { |
| 1219 | create_sdp_observer->OnFailure(RTCError( |
| 1220 | RTCErrorType::INTERNAL_ERROR, |
| 1221 | "SetLocalDescription failed because the session was shut down")); |
| 1222 | return; |
| 1223 | } |
| 1224 | switch (this_weak_ptr->signaling_state()) { |
| 1225 | case PeerConnectionInterface::kStable: |
| 1226 | case PeerConnectionInterface::kHaveLocalOffer: |
| 1227 | case PeerConnectionInterface::kHaveRemotePrAnswer: |
| 1228 | // TODO(hbos): If [LastCreatedOffer] exists and still represents the |
| 1229 | // current state of the system, use that instead of creating another |
| 1230 | // offer. |
| 1231 | this_weak_ptr->DoCreateOffer( |
| 1232 | PeerConnectionInterface::RTCOfferAnswerOptions(), |
| 1233 | create_sdp_observer); |
| 1234 | break; |
| 1235 | case PeerConnectionInterface::kHaveLocalPrAnswer: |
| 1236 | case PeerConnectionInterface::kHaveRemoteOffer: |
| 1237 | // TODO(hbos): If [LastCreatedAnswer] exists and still represents |
| 1238 | // the current state of the system, use that instead of creating |
| 1239 | // another answer. |
| 1240 | this_weak_ptr->DoCreateAnswer( |
| 1241 | PeerConnectionInterface::RTCOfferAnswerOptions(), |
| 1242 | create_sdp_observer); |
| 1243 | break; |
| 1244 | case PeerConnectionInterface::kClosed: |
| 1245 | create_sdp_observer->OnFailure(RTCError( |
| 1246 | RTCErrorType::INVALID_STATE, |
| 1247 | "SetLocalDescription called when PeerConnection is closed.")); |
| 1248 | break; |
| 1249 | } |
| 1250 | }); |
| 1251 | } |
| 1252 |
| 1253 | RTCError SdpOfferAnswerHandler::ApplyLocalDescription( |
| 1254 | std::unique_ptr<SessionDescriptionInterface> desc, |
| 1255 | const std::map<std::string, const cricket::ContentGroup*>& |
| 1256 | bundle_groups_by_mid) { |
| 1257 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::ApplyLocalDescription"); |
| 1258 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1259 | RTC_DCHECK(desc); |
| 1260 |
| 1261 | // Update stats here so that we have the most recent stats for tracks and |
| 1262 | // streams that might be removed by updating the session description. |
| 1263 | pc_->stats()->UpdateStats(PeerConnectionInterface::kStatsOutputLevelStandard); |
| 1264 |
| 1265 | // Take a reference to the old local description since it's used below to |
| 1266 | // compare against the new local description. When setting the new local |
| 1267 | // description, grab ownership of the replaced session description in case it |
| 1268 | // is the same as `old_local_description`, to keep it alive for the duration |
| 1269 | // of the method. |
| 1270 | const SessionDescriptionInterface* old_local_description = |
| 1271 | local_description(); |
| 1272 | std::unique_ptr<SessionDescriptionInterface> replaced_local_description; |
| 1273 | SdpType type = desc->GetType(); |
| 1274 | if (type == SdpType::kAnswer) { |
| 1275 | replaced_local_description = pending_local_description_ |
| 1276 | ? std::move(pending_local_description_) |
| 1277 | : std::move(current_local_description_); |
| 1278 | current_local_description_ = std::move(desc); |
| 1279 | pending_local_description_ = nullptr; |
| 1280 | current_remote_description_ = std::move(pending_remote_description_); |
| 1281 | } else { |
| 1282 | replaced_local_description = std::move(pending_local_description_); |
| 1283 | pending_local_description_ = std::move(desc); |
| 1284 | } |
| 1285 | // The session description to apply now must be accessed by |
| 1286 | // `local_description()`. |
| 1287 | RTC_DCHECK(local_description()); |
| 1288 |
| 1289 | // Report statistics about any use of simulcast. |
| 1290 | ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription, |
| 1291 | *local_description()->description()); |
| 1292 |
| 1293 | if (!is_caller_) { |
| 1294 | if (remote_description()) { |
| 1295 | // Remote description was applied first, so this PC is the callee. |
| 1296 | is_caller_ = false; |
| 1297 | } else { |
| 1298 | // Local description is applied first, so this PC is the caller. |
| 1299 | is_caller_ = true; |
| 1300 | } |
| 1301 | } |
| 1302 |
| 1303 | RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type); |
| 1304 | if (!error.ok()) { |
| 1305 | return error; |
| 1306 | } |
| 1307 |
| 1308 | if (IsUnifiedPlan()) { |
| 1309 | RTCError error = UpdateTransceiversAndDataChannels( |
| 1310 | cricket::CS_LOCAL, *local_description(), old_local_description, |
| 1311 | remote_description(), bundle_groups_by_mid); |
| 1312 | if (!error.ok()) { |
| 1313 | return error; |
| 1314 | } |
| 1315 | std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list; |
| 1316 | std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams; |
| 1317 | for (const auto& transceiver_ext : transceivers()->List()) { |
| 1318 | auto transceiver = transceiver_ext->internal(); |
| 1319 | if (transceiver->stopped()) { |
| 1320 | continue; |
| 1321 | } |
| 1322 |
| 1323 | // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots. |
| 1324 | // Note that code paths that don't set MID won't be able to use |
| 1325 | // information about DTLS transports. |
| 1326 | if (transceiver->mid()) { |
| 1327 | auto dtls_transport = LookupDtlsTransportByMid( |
| 1328 | pc_->network_thread(), transport_controller(), *transceiver->mid()); |
| 1329 | transceiver->sender_internal()->set_transport(dtls_transport); |
| 1330 | transceiver->receiver_internal()->set_transport(dtls_transport); |
| 1331 | } |
| 1332 |
| 1333 | const ContentInfo* content = |
| 1334 | FindMediaSectionForTransceiver(transceiver, local_description()); |
| 1335 | if (!content) { |
| 1336 | continue; |
| 1337 | } |
| 1338 | const MediaContentDescription* media_desc = content->media_description(); |
| 1339 | // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run |
| 1340 | // the following steps: |
| 1341 | if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) { |
| 1342 | // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and |
| 1343 | // transceiver's [[FiredDirection]] slot is either "sendrecv" or |
| 1344 | // "recvonly", process the removal of a remote track for the media |
| 1345 | // description, given transceiver, removeList, and muteTracks. |
| 1346 | if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) && |
| 1347 | (transceiver->fired_direction() && |
| 1348 | RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) { |
| 1349 | ProcessRemovalOfRemoteTrack(transceiver_ext, &remove_list, |
| 1350 | &removed_streams); |
| 1351 | } |
| 1352 | // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and |
| 1353 | // [[FiredDirection]] slots to direction. |
| 1354 | transceiver->set_current_direction(media_desc->direction()); |
| 1355 | transceiver->set_fired_direction(media_desc->direction()); |
| 1356 | } |
| 1357 | } |
| 1358 | auto observer = pc_->Observer(); |
| 1359 | for (const auto& transceiver : remove_list) { |
| 1360 | observer->OnRemoveTrack(transceiver->receiver()); |
| 1361 | } |
| 1362 | for (const auto& stream : removed_streams) { |
| 1363 | observer->OnRemoveStream(stream); |
| 1364 | } |
| 1365 | } else { |
| 1366 | // Media channels will be created only when offer is set. These may use new |
| 1367 | // transports just created by PushdownTransportDescription. |
| 1368 | if (type == SdpType::kOffer) { |
| 1369 | // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local |
| 1370 | // description is applied. Restore back to old description. |
| 1371 | RTCError error = CreateChannels(*local_description()->description()); |
| 1372 | if (!error.ok()) { |
| 1373 | return error; |
| 1374 | } |
| 1375 | } |
| 1376 | // Remove unused channels if MediaContentDescription is rejected. |
| 1377 | RemoveUnusedChannels(local_description()->description()); |
| 1378 | } |
| 1379 |
| 1380 | error = UpdateSessionState(type, cricket::CS_LOCAL, |
| 1381 | local_description()->description(), |
| 1382 | bundle_groups_by_mid); |
| 1383 | if (!error.ok()) { |
| 1384 | return error; |
| 1385 | } |
| 1386 |
| 1387 | if (remote_description()) { |
| 1388 | // Now that we have a local description, we can push down remote candidates. |
| 1389 | UseCandidatesInSessionDescription(remote_description()); |
| 1390 | } |
| 1391 |
| 1392 | pending_ice_restarts_.clear(); |
| 1393 | if (session_error() != SessionError::kNone) { |
| 1394 | LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg()); |
| 1395 | } |
| 1396 |
| 1397 | // If setting the description decided our SSL role, allocate any necessary |
| 1398 | // SCTP sids. |
| 1399 | rtc::SSLRole role; |
| 1400 | if (pc_->GetSctpSslRole(&role)) { |
| 1401 | data_channel_controller()->AllocateSctpSids(role); |
| 1402 | } |
| 1403 |
| 1404 | if (IsUnifiedPlan()) { |
| 1405 | // We must use List and not ListInternal here because |
| 1406 | // transceivers()->StableState() is indexed by the non-internal refptr. |
| 1407 | for (const auto& transceiver_ext : transceivers()->List()) { |
| 1408 | auto transceiver = transceiver_ext->internal(); |
| 1409 | if (transceiver->stopped()) { |
| 1410 | continue; |
| 1411 | } |
| 1412 | const ContentInfo* content = |
| 1413 | FindMediaSectionForTransceiver(transceiver, local_description()); |
| 1414 | if (!content) { |
| 1415 | continue; |
| 1416 | } |
| 1417 | cricket::ChannelInterface* channel = transceiver->channel(); |
| 1418 | if (content->rejected || !channel || channel->local_streams().empty()) { |
| 1419 | // 0 is a special value meaning "this sender has no associated send |
| 1420 | // stream". Need to call this so the sender won't attempt to configure |
| 1421 | // a no longer existing stream and run into DCHECKs in the lower |
| 1422 | // layers. |
| 1423 | transceiver->sender_internal()->SetSsrc(0); |
| 1424 | } else { |
| 1425 | // Get the StreamParams from the channel which could generate SSRCs. |
| 1426 | const std::vector<StreamParams>& streams = channel->local_streams(); |
| 1427 | transceiver->sender_internal()->set_stream_ids(streams[0].stream_ids()); |
| 1428 | auto encodings = transceiver->sender_internal()->init_send_encodings(); |
| 1429 | transceiver->sender_internal()->SetSsrc(streams[0].first_ssrc()); |
| 1430 | if (!encodings.empty()) { |
| 1431 | transceivers() |
| 1432 | ->StableState(transceiver_ext) |
| 1433 | ->SetInitSendEncodings(encodings); |
| 1434 | } |
| 1435 | } |
| 1436 | } |
| 1437 | } else { |
| 1438 | // Plan B semantics. |
| 1439 |
| 1440 | // Update state and SSRC of local MediaStreams and DataChannels based on the |
| 1441 | // local session description. |
| 1442 | const cricket::ContentInfo* audio_content = |
| 1443 | GetFirstAudioContent(local_description()->description()); |
| 1444 | if (audio_content) { |
| 1445 | if (audio_content->rejected) { |
| 1446 | RemoveSenders(cricket::MEDIA_TYPE_AUDIO); |
| 1447 | } else { |
| 1448 | const cricket::AudioContentDescription* audio_desc = |
| 1449 | audio_content->media_description()->as_audio(); |
| 1450 | UpdateLocalSenders(audio_desc->streams(), audio_desc->type()); |
| 1451 | } |
| 1452 | } |
| 1453 |
| 1454 | const cricket::ContentInfo* video_content = |
| 1455 | GetFirstVideoContent(local_description()->description()); |
| 1456 | if (video_content) { |
| 1457 | if (video_content->rejected) { |
| 1458 | RemoveSenders(cricket::MEDIA_TYPE_VIDEO); |
| 1459 | } else { |
| 1460 | const cricket::VideoContentDescription* video_desc = |
| 1461 | video_content->media_description()->as_video(); |
| 1462 | UpdateLocalSenders(video_desc->streams(), video_desc->type()); |
| 1463 | } |
| 1464 | } |
| 1465 | } |
| 1466 |
| 1467 | // This function does nothing with data content. |
| 1468 |
| 1469 | if (type == SdpType::kAnswer && |
| 1470 | local_ice_credentials_to_replace_->SatisfiesIceRestart( |
| 1471 | *current_local_description_)) { |
| 1472 | local_ice_credentials_to_replace_->ClearIceCredentials(); |
| 1473 | } |
| 1474 |
| 1475 | return RTCError::OK(); |
| 1476 | } |
| 1477 |
| 1478 | void SdpOfferAnswerHandler::SetRemoteDescription( |
| 1479 | SetSessionDescriptionObserver* observer, |
| 1480 | SessionDescriptionInterface* desc_ptr) { |
| 1481 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1482 | // Chain this operation. If asynchronous operations are pending on the chain, |
| 1483 | // this operation will be queued to be invoked, otherwise the contents of the |
| 1484 | // lambda will execute immediately. |
| 1485 | operations_chain_->ChainOperation( |
| 1486 | [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(), |
| 1487 | observer_refptr = |
| 1488 | rtc::scoped_refptr<SetSessionDescriptionObserver>(observer), |
| 1489 | desc = std::unique_ptr<SessionDescriptionInterface>(desc_ptr)]( |
| 1490 | std::function<void()> operations_chain_callback) mutable { |
| 1491 | // Abort early if `this_weak_ptr` is no longer valid. |
| 1492 | if (!this_weak_ptr) { |
| 1493 | // For consistency with SetSessionDescriptionObserverAdapter whose |
| 1494 | // posted messages doesn't get processed when the PC is destroyed, we |
| 1495 | // do not inform `observer_refptr` that the operation failed. |
| 1496 | operations_chain_callback(); |
| 1497 | return; |
| 1498 | } |
| 1499 | // SetSessionDescriptionObserverAdapter takes care of making sure the |
| 1500 | // `observer_refptr` is invoked in a posted message. |
| 1501 | this_weak_ptr->DoSetRemoteDescription( |
| 1502 | std::move(desc), |
| 1503 | rtc::make_ref_counted<SetSessionDescriptionObserverAdapter>( |
| 1504 | this_weak_ptr, observer_refptr)); |
| 1505 | // For backwards-compatability reasons, we declare the operation as |
| 1506 | // completed here (rather than in a post), so that the operation chain |
| 1507 | // is not blocked by this operation when the observer is invoked. This |
| 1508 | // allows the observer to trigger subsequent offer/answer operations |
| 1509 | // synchronously if the operation chain is now empty. |
| 1510 | operations_chain_callback(); |
| 1511 | }); |
| 1512 | } |
| 1513 |
| 1514 | void SdpOfferAnswerHandler::SetRemoteDescription( |
| 1515 | std::unique_ptr<SessionDescriptionInterface> desc, |
| 1516 | rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) { |
| 1517 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1518 | // Chain this operation. If asynchronous operations are pending on the chain, |
| 1519 | // this operation will be queued to be invoked, otherwise the contents of the |
| 1520 | // lambda will execute immediately. |
| 1521 | operations_chain_->ChainOperation( |
| 1522 | [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(), observer, |
| 1523 | desc = std::move(desc)]( |
| 1524 | std::function<void()> operations_chain_callback) mutable { |
| 1525 | // Abort early if `this_weak_ptr` is no longer valid. |
| 1526 | if (!this_weak_ptr) { |
| 1527 | observer->OnSetRemoteDescriptionComplete(RTCError( |
| 1528 | RTCErrorType::INTERNAL_ERROR, |
| 1529 | "SetRemoteDescription failed because the session was shut down")); |
| 1530 | operations_chain_callback(); |
| 1531 | return; |
| 1532 | } |
| 1533 | this_weak_ptr->DoSetRemoteDescription(std::move(desc), |
| 1534 | std::move(observer)); |
| 1535 | // DoSetRemoteDescription() is implemented as a synchronous operation. |
| 1536 | // The `observer` will already have been informed that it completed, and |
| 1537 | // we can mark this operation as complete without any loose ends. |
| 1538 | operations_chain_callback(); |
| 1539 | }); |
| 1540 | } |
| 1541 |
| 1542 | RTCError SdpOfferAnswerHandler::ApplyRemoteDescription( |
| 1543 | std::unique_ptr<SessionDescriptionInterface> desc, |
| 1544 | const std::map<std::string, const cricket::ContentGroup*>& |
| 1545 | bundle_groups_by_mid) { |
| 1546 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::ApplyRemoteDescription"); |
| 1547 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1548 | RTC_DCHECK(desc); |
| 1549 |
| 1550 | // Update stats here so that we have the most recent stats for tracks and |
| 1551 | // streams that might be removed by updating the session description. |
| 1552 | pc_->stats()->UpdateStats(PeerConnectionInterface::kStatsOutputLevelStandard); |
| 1553 |
| 1554 | // Take a reference to the old remote description since it's used below to |
| 1555 | // compare against the new remote description. When setting the new remote |
| 1556 | // description, grab ownership of the replaced session description in case it |
| 1557 | // is the same as `old_remote_description`, to keep it alive for the duration |
| 1558 | // of the method. |
| 1559 | const SessionDescriptionInterface* old_remote_description = |
| 1560 | remote_description(); |
| 1561 | std::unique_ptr<SessionDescriptionInterface> replaced_remote_description; |
| 1562 | SdpType type = desc->GetType(); |
| 1563 | if (type == SdpType::kAnswer) { |
| 1564 | replaced_remote_description = pending_remote_description_ |
| 1565 | ? std::move(pending_remote_description_) |
| 1566 | : std::move(current_remote_description_); |
| 1567 | current_remote_description_ = std::move(desc); |
| 1568 | pending_remote_description_ = nullptr; |
| 1569 | current_local_description_ = std::move(pending_local_description_); |
| 1570 | } else { |
| 1571 | replaced_remote_description = std::move(pending_remote_description_); |
| 1572 | pending_remote_description_ = std::move(desc); |
| 1573 | } |
| 1574 | // The session description to apply now must be accessed by |
| 1575 | // `remote_description()`. |
| 1576 | RTC_DCHECK(remote_description()); |
| 1577 |
| 1578 | // Report statistics about any use of simulcast. |
| 1579 | ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription, |
| 1580 | *remote_description()->description()); |
| 1581 |
| 1582 | RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type); |
| 1583 | if (!error.ok()) { |
| 1584 | return error; |
| 1585 | } |
| 1586 | // Transport and Media channels will be created only when offer is set. |
| 1587 | if (IsUnifiedPlan()) { |
| 1588 | RTCError error = UpdateTransceiversAndDataChannels( |
| 1589 | cricket::CS_REMOTE, *remote_description(), local_description(), |
| 1590 | old_remote_description, bundle_groups_by_mid); |
| 1591 | if (!error.ok()) { |
| 1592 | return error; |
| 1593 | } |
| 1594 | } else { |
| 1595 | // Media channels will be created only when offer is set. These may use new |
| 1596 | // transports just created by PushdownTransportDescription. |
| 1597 | if (type == SdpType::kOffer) { |
| 1598 | // TODO(mallinath) - Handle CreateChannel failure, as new local |
| 1599 | // description is applied. Restore back to old description. |
| 1600 | RTCError error = CreateChannels(*remote_description()->description()); |
| 1601 | if (!error.ok()) { |
| 1602 | return error; |
| 1603 | } |
| 1604 | } |
| 1605 | // Remove unused channels if MediaContentDescription is rejected. |
| 1606 | RemoveUnusedChannels(remote_description()->description()); |
| 1607 | } |
| 1608 |
| 1609 | // NOTE: Candidates allocation will be initiated only when |
| 1610 | // SetLocalDescription is called. |
| 1611 | error = UpdateSessionState(type, cricket::CS_REMOTE, |
| 1612 | remote_description()->description(), |
| 1613 | bundle_groups_by_mid); |
| 1614 | if (!error.ok()) { |
| 1615 | return error; |
| 1616 | } |
| 1617 |
| 1618 | if (local_description() && |
| 1619 | !UseCandidatesInSessionDescription(remote_description())) { |
| 1620 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates); |
| 1621 | } |
| 1622 |
| 1623 | if (old_remote_description) { |
| 1624 | for (const cricket::ContentInfo& content : |
| 1625 | old_remote_description->description()->contents()) { |
| 1626 | // Check if this new SessionDescription contains new ICE ufrag and |
| 1627 | // password that indicates the remote peer requests an ICE restart. |
| 1628 | // TODO(deadbeef): When we start storing both the current and pending |
| 1629 | // remote description, this should reset pending_ice_restarts and compare |
| 1630 | // against the current description. |
| 1631 | if (CheckForRemoteIceRestart(old_remote_description, remote_description(), |
| 1632 | content.name)) { |
| 1633 | if (type == SdpType::kOffer) { |
| 1634 | pending_ice_restarts_.insert(content.name); |
| 1635 | } |
| 1636 | } else { |
| 1637 | // We retain all received candidates only if ICE is not restarted. |
| 1638 | // When ICE is restarted, all previous candidates belong to an old |
| 1639 | // generation and should not be kept. |
| 1640 | // TODO(deadbeef): This goes against the W3C spec which says the remote |
| 1641 | // description should only contain candidates from the last set remote |
| 1642 | // description plus any candidates added since then. We should remove |
| 1643 | // this once we're sure it won't break anything. |
| 1644 | WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription( |
| 1645 | old_remote_description, content.name, mutable_remote_description()); |
| 1646 | } |
| 1647 | } |
| 1648 | } |
| 1649 |
| 1650 | if (session_error() != SessionError::kNone) { |
| 1651 | LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg()); |
| 1652 | } |
| 1653 |
| 1654 | // Set the the ICE connection state to connecting since the connection may |
| 1655 | // become writable with peer reflexive candidates before any remote candidate |
| 1656 | // is signaled. |
| 1657 | // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix |
| 1658 | // is to have a new signal the indicates a change in checking state from the |
| 1659 | // transport and expose a new checking() member from transport that can be |
| 1660 | // read to determine the current checking state. The existing SignalConnecting |
| 1661 | // actually means "gathering candidates", so cannot be be used here. |
| 1662 | if (remote_description()->GetType() != SdpType::kOffer && |
| 1663 | remote_description()->number_of_mediasections() > 0u && |
| 1664 | pc_->ice_connection_state() == |
| 1665 | PeerConnectionInterface::kIceConnectionNew) { |
| 1666 | pc_->SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking); |
| 1667 | } |
| 1668 |
| 1669 | // If setting the description decided our SSL role, allocate any necessary |
| 1670 | // SCTP sids. |
| 1671 | rtc::SSLRole role; |
| 1672 | if (pc_->GetSctpSslRole(&role)) { |
| 1673 | data_channel_controller()->AllocateSctpSids(role); |
| 1674 | } |
| 1675 |
| 1676 | if (IsUnifiedPlan()) { |
| 1677 | std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> |
| 1678 | now_receiving_transceivers; |
| 1679 | std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list; |
| 1680 | std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams; |
| 1681 | std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams; |
| 1682 | for (const auto& transceiver_ext : transceivers()->List()) { |
| 1683 | const auto transceiver = transceiver_ext->internal(); |
| 1684 | const ContentInfo* content = |
| 1685 | FindMediaSectionForTransceiver(transceiver, remote_description()); |
| 1686 | if (!content) { |
| 1687 | continue; |
| 1688 | } |
| 1689 | const MediaContentDescription* media_desc = content->media_description(); |
| 1690 | RtpTransceiverDirection local_direction = |
| 1691 | RtpTransceiverDirectionReversed(media_desc->direction()); |
| 1692 | // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the |
| 1693 | // RTCSessionDescription: Set the associated remote streams given |
| 1694 | // transceiver.[[Receiver]], msids, addList, and removeList". |
| 1695 | // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription |
| 1696 | if (RtpTransceiverDirectionHasRecv(local_direction)) { |
| 1697 | std::vector<std::string> stream_ids; |
| 1698 | if (!media_desc->streams().empty()) { |
| 1699 | // The remote description has signaled the stream IDs. |
| 1700 | stream_ids = media_desc->streams()[0].stream_ids(); |
| 1701 | } |
| 1702 | transceivers() |
| 1703 | ->StableState(transceiver_ext) |
| 1704 | ->SetRemoteStreamIdsIfUnset(transceiver->receiver()->stream_ids()); |
| 1705 |
| 1706 | RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name |
| 1707 | << " (" << GetStreamIdsString(stream_ids) << ")."; |
| 1708 | SetAssociatedRemoteStreams(transceiver->receiver_internal(), stream_ids, |
| 1709 | &added_streams, &removed_streams); |
| 1710 | // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 |
| 1711 | // "Set the RTCSessionDescription: If direction is sendrecv or recvonly, |
| 1712 | // and transceiver's current direction is neither sendrecv nor recvonly, |
| 1713 | // process the addition of a remote track for the media description. |
| 1714 | if (!transceiver->fired_direction() || |
| 1715 | !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) { |
| 1716 | RTC_LOG(LS_INFO) |
| 1717 | << "Processing the addition of a remote track for MID=" |
| 1718 | << content->name << "."; |
| 1719 | // Since the transceiver is passed to the user in an |
| 1720 | // OnTrack event, we must use the proxied transceiver. |
| 1721 | now_receiving_transceivers.push_back(transceiver_ext); |
| 1722 | } |
| 1723 | } |
| 1724 | // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's |
| 1725 | // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the |
| 1726 | // removal of a remote track for the media description, given transceiver, |
| 1727 | // removeList, and muteTracks. |
| 1728 | if (!RtpTransceiverDirectionHasRecv(local_direction) && |
| 1729 | (transceiver->fired_direction() && |
| 1730 | RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) { |
| 1731 | ProcessRemovalOfRemoteTrack(transceiver_ext, &remove_list, |
| 1732 | &removed_streams); |
| 1733 | } |
| 1734 | // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction. |
| 1735 | transceiver->set_fired_direction(local_direction); |
| 1736 | // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run |
| 1737 | // the following steps: |
| 1738 | if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) { |
| 1739 | // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to |
| 1740 | // direction. |
| 1741 | transceiver->set_current_direction(local_direction); |
| 1742 | // 2.2.8.1.11.[3-6]: Set the transport internal slots. |
| 1743 | if (transceiver->mid()) { |
| 1744 | auto dtls_transport = LookupDtlsTransportByMid(pc_->network_thread(), |
| 1745 | transport_controller(), |
| 1746 | *transceiver->mid()); |
| 1747 | transceiver->sender_internal()->set_transport(dtls_transport); |
| 1748 | transceiver->receiver_internal()->set_transport(dtls_transport); |
| 1749 | } |
| 1750 | } |
| 1751 | // 2.2.8.1.12: If the media description is rejected, and transceiver is |
| 1752 | // not already stopped, stop the RTCRtpTransceiver transceiver. |
| 1753 | if (content->rejected && !transceiver->stopped()) { |
| 1754 | RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name |
| 1755 | << " since the media section was rejected."; |
| 1756 | transceiver->StopTransceiverProcedure(); |
| 1757 | } |
| 1758 | if (!content->rejected && |
| 1759 | RtpTransceiverDirectionHasRecv(local_direction)) { |
| 1760 | if (!media_desc->streams().empty() && |
| 1761 | media_desc->streams()[0].has_ssrcs()) { |
| 1762 | uint32_t ssrc = media_desc->streams()[0].first_ssrc(); |
| 1763 | transceiver->receiver_internal()->SetupMediaChannel(ssrc); |
| 1764 | } else { |
| 1765 | transceiver->receiver_internal()->SetupUnsignaledMediaChannel(); |
| 1766 | } |
| 1767 | } |
| 1768 | } |
| 1769 | // Once all processing has finished, fire off callbacks. |
| 1770 | auto observer = pc_->Observer(); |
| 1771 | for (const auto& transceiver : now_receiving_transceivers) { |
| 1772 | pc_->stats()->AddTrack(transceiver->receiver()->track()); |
| 1773 | observer->OnTrack(transceiver); |
| 1774 | observer->OnAddTrack(transceiver->receiver(), |
| 1775 | transceiver->receiver()->streams()); |
| 1776 | } |
| 1777 | for (const auto& stream : added_streams) { |
| 1778 | observer->OnAddStream(stream); |
| 1779 | } |
| 1780 | for (const auto& transceiver : remove_list) { |
| 1781 | observer->OnRemoveTrack(transceiver->receiver()); |
| 1782 | } |
| 1783 | for (const auto& stream : removed_streams) { |
| 1784 | observer->OnRemoveStream(stream); |
| 1785 | } |
| 1786 | } |
| 1787 |
| 1788 | const cricket::ContentInfo* audio_content = |
| 1789 | GetFirstAudioContent(remote_description()->description()); |
| 1790 | const cricket::ContentInfo* video_content = |
| 1791 | GetFirstVideoContent(remote_description()->description()); |
| 1792 | const cricket::AudioContentDescription* audio_desc = |
| 1793 | GetFirstAudioContentDescription(remote_description()->description()); |
| 1794 | const cricket::VideoContentDescription* video_desc = |
| 1795 | GetFirstVideoContentDescription(remote_description()->description()); |
| 1796 |
| 1797 | // Check if the descriptions include streams, just in case the peer supports |
| 1798 | // MSID, but doesn't indicate so with "a=msid-semantic". |
| 1799 | if (remote_description()->description()->msid_supported() || |
| 1800 | (audio_desc && !audio_desc->streams().empty()) || |
| 1801 | (video_desc && !video_desc->streams().empty())) { |
| 1802 | remote_peer_supports_msid_ = true; |
| 1803 | } |
| 1804 |
| 1805 | // We wait to signal new streams until we finish processing the description, |
| 1806 | // since only at that point will new streams have all their tracks. |
| 1807 | rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create()); |
| 1808 |
| 1809 | if (!IsUnifiedPlan()) { |
| 1810 | // TODO(steveanton): When removing RTP senders/receivers in response to a |
| 1811 | // rejected media section, there is some cleanup logic that expects the |
| 1812 | // voice/ video channel to still be set. But in this method the voice/video |
| 1813 | // channel would have been destroyed by the SetRemoteDescription caller |
| 1814 | // above so the cleanup that relies on them fails to run. The RemoveSenders |
| 1815 | // calls should be moved to right before the DestroyChannel calls to fix |
| 1816 | // this. |
| 1817 |
| 1818 | // Find all audio rtp streams and create corresponding remote AudioTracks |
| 1819 | // and MediaStreams. |
| 1820 | if (audio_content) { |
| 1821 | if (audio_content->rejected) { |
| 1822 | RemoveSenders(cricket::MEDIA_TYPE_AUDIO); |
| 1823 | } else { |
| 1824 | bool default_audio_track_needed = |
| 1825 | !remote_peer_supports_msid_ && |
| 1826 | RtpTransceiverDirectionHasSend(audio_desc->direction()); |
| 1827 | UpdateRemoteSendersList(GetActiveStreams(audio_desc), |
| 1828 | default_audio_track_needed, audio_desc->type(), |
| 1829 | new_streams); |
| 1830 | } |
| 1831 | } |
| 1832 |
| 1833 | // Find all video rtp streams and create corresponding remote VideoTracks |
| 1834 | // and MediaStreams. |
| 1835 | if (video_content) { |
| 1836 | if (video_content->rejected) { |
| 1837 | RemoveSenders(cricket::MEDIA_TYPE_VIDEO); |
| 1838 | } else { |
| 1839 | bool default_video_track_needed = |
| 1840 | !remote_peer_supports_msid_ && |
| 1841 | RtpTransceiverDirectionHasSend(video_desc->direction()); |
| 1842 | UpdateRemoteSendersList(GetActiveStreams(video_desc), |
| 1843 | default_video_track_needed, video_desc->type(), |
| 1844 | new_streams); |
| 1845 | } |
| 1846 | } |
| 1847 |
| 1848 | // Iterate new_streams and notify the observer about new MediaStreams. |
| 1849 | auto observer = pc_->Observer(); |
| 1850 | for (size_t i = 0; i < new_streams->count(); ++i) { |
| 1851 | MediaStreamInterface* new_stream = new_streams->at(i); |
| 1852 | pc_->stats()->AddStream(new_stream); |
| 1853 | observer->OnAddStream( |
| 1854 | rtc::scoped_refptr<MediaStreamInterface>(new_stream)); |
| 1855 | } |
| 1856 |
| 1857 | UpdateEndedRemoteMediaStreams(); |
| 1858 | } |
| 1859 |
| 1860 | if (type == SdpType::kAnswer && |
| 1861 | local_ice_credentials_to_replace_->SatisfiesIceRestart( |
| 1862 | *current_local_description_)) { |
| 1863 | local_ice_credentials_to_replace_->ClearIceCredentials(); |
| 1864 | } |
| 1865 |
| 1866 | return RTCError::OK(); |
| 1867 | } |
| 1868 |
| 1869 | void SdpOfferAnswerHandler::DoSetLocalDescription( |
| 1870 | std::unique_ptr<SessionDescriptionInterface> desc, |
| 1871 | rtc::scoped_refptr<SetLocalDescriptionObserverInterface> observer) { |
| 1872 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1873 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::DoSetLocalDescription"); |
| 1874 |
| 1875 | if (!observer) { |
| 1876 | RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL."; |
| 1877 | return; |
| 1878 | } |
| 1879 |
| 1880 | if (!desc) { |
| 1881 | observer->OnSetLocalDescriptionComplete( |
| 1882 | RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL.")); |
| 1883 | return; |
| 1884 | } |
| 1885 |
| 1886 | // If a session error has occurred the PeerConnection is in a possibly |
| 1887 | // inconsistent state so fail right away. |
| 1888 | if (session_error() != SessionError::kNone) { |
| 1889 | std::string error_message = GetSessionErrorMsg(); |
| 1890 | RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message; |
| 1891 | observer->OnSetLocalDescriptionComplete( |
| 1892 | RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message))); |
| 1893 | return; |
| 1894 | } |
| 1895 |
| 1896 | // For SLD we support only explicit rollback. |
| 1897 | if (desc->GetType() == SdpType::kRollback) { |
| 1898 | if (IsUnifiedPlan()) { |
| 1899 | observer->OnSetLocalDescriptionComplete(Rollback(desc->GetType())); |
| 1900 | } else { |
| 1901 | observer->OnSetLocalDescriptionComplete( |
| 1902 | RTCError(RTCErrorType::UNSUPPORTED_OPERATION, |
| 1903 | "Rollback not supported in Plan B")); |
| 1904 | } |
| 1905 | return; |
| 1906 | } |
| 1907 |
| 1908 | std::map<std::string, const cricket::ContentGroup*> bundle_groups_by_mid = |
| 1909 | GetBundleGroupsByMid(desc->description()); |
| 1910 | RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL, |
| 1911 | bundle_groups_by_mid); |
| 1912 | if (!error.ok()) { |
| 1913 | std::string error_message = GetSetDescriptionErrorMessage( |
| 1914 | cricket::CS_LOCAL, desc->GetType(), error); |
| 1915 | RTC_LOG(LS_ERROR) << error_message; |
| 1916 | observer->OnSetLocalDescriptionComplete( |
| 1917 | RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message))); |
| 1918 | return; |
| 1919 | } |
| 1920 |
| 1921 | // Grab the description type before moving ownership to ApplyLocalDescription, |
| 1922 | // which may destroy it before returning. |
| 1923 | const SdpType type = desc->GetType(); |
| 1924 |
| 1925 | error = ApplyLocalDescription(std::move(desc), bundle_groups_by_mid); |
| 1926 | // `desc` may be destroyed at this point. |
| 1927 |
| 1928 | if (!error.ok()) { |
| 1929 | // If ApplyLocalDescription fails, the PeerConnection could be in an |
| 1930 | // inconsistent state, so act conservatively here and set the session error |
| 1931 | // so that future calls to SetLocalDescription/SetRemoteDescription fail. |
| 1932 | SetSessionError(SessionError::kContent, error.message()); |
| 1933 | std::string error_message = |
| 1934 | GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error); |
| 1935 | RTC_LOG(LS_ERROR) << error_message; |
| 1936 | observer->OnSetLocalDescriptionComplete( |
| 1937 | RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message))); |
| 1938 | return; |
| 1939 | } |
| 1940 | RTC_DCHECK(local_description()); |
| 1941 |
| 1942 | if (local_description()->GetType() == SdpType::kAnswer) { |
| 1943 | RemoveStoppedTransceivers(); |
| 1944 |
| 1945 | // TODO(deadbeef): We already had to hop to the network thread for |
| 1946 | // MaybeStartGathering... |
| 1947 | pc_->network_thread()->Invoke<void>( |
| 1948 | RTC_FROM_HERE, [this] { port_allocator()->DiscardCandidatePool(); }); |
| 1949 | // Make UMA notes about what was agreed to. |
| 1950 | ReportNegotiatedSdpSemantics(*local_description()); |
| 1951 | } |
| 1952 |
| 1953 | observer->OnSetLocalDescriptionComplete(RTCError::OK()); |
| 1954 | pc_->NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED); |
| 1955 |
| 1956 | // Check if negotiation is needed. We must do this after informing the |
| 1957 | // observer that SetLocalDescription() has completed to ensure negotiation is |
| 1958 | // not needed prior to the promise resolving. |
| 1959 | if (IsUnifiedPlan()) { |
| 1960 | bool was_negotiation_needed = is_negotiation_needed_; |
| 1961 | UpdateNegotiationNeeded(); |
| 1962 | if (signaling_state() == PeerConnectionInterface::kStable && |
| 1963 | was_negotiation_needed && is_negotiation_needed_) { |
| 1964 | // Legacy version. |
| 1965 | pc_->Observer()->OnRenegotiationNeeded(); |
| 1966 | // Spec-compliant version; the event may get invalidated before firing. |
| 1967 | GenerateNegotiationNeededEvent(); |
| 1968 | } |
| 1969 | } |
| 1970 |
| 1971 | // MaybeStartGathering needs to be called after informing the observer so that |
| 1972 | // we don't signal any candidates before signaling that SetLocalDescription |
| 1973 | // completed. |
| 1974 | transport_controller()->MaybeStartGathering(); |
| 1975 | } |
| 1976 |
| 1977 | void SdpOfferAnswerHandler::DoCreateOffer( |
| 1978 | const PeerConnectionInterface::RTCOfferAnswerOptions& options, |
| 1979 | rtc::scoped_refptr<CreateSessionDescriptionObserver> observer) { |
| 1980 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 1981 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::DoCreateOffer"); |
| 1982 |
| 1983 | if (!observer) { |
| 1984 | RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL."; |
| 1985 | return; |
| 1986 | } |
| 1987 |
| 1988 | if (pc_->IsClosed()) { |
| 1989 | std::string error = "CreateOffer called when PeerConnection is closed."; |
| 1990 | RTC_LOG(LS_ERROR) << error; |
| 1991 | pc_->message_handler()->PostCreateSessionDescriptionFailure( |
| 1992 | observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error))); |
| 1993 | return; |
| 1994 | } |
| 1995 |
| 1996 | // If a session error has occurred the PeerConnection is in a possibly |
| 1997 | // inconsistent state so fail right away. |
| 1998 | if (session_error() != SessionError::kNone) { |
| 1999 | std::string error_message = GetSessionErrorMsg(); |
| 2000 | RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message; |
| 2001 | pc_->message_handler()->PostCreateSessionDescriptionFailure( |
| 2002 | observer, |
| 2003 | RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message))); |
| 2004 | return; |
| 2005 | } |
| 2006 |
| 2007 | if (!ValidateOfferAnswerOptions(options)) { |
| 2008 | std::string error = "CreateOffer called with invalid options."; |
| 2009 | RTC_LOG(LS_ERROR) << error; |
| 2010 | pc_->message_handler()->PostCreateSessionDescriptionFailure( |
| 2011 | observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error))); |
| 2012 | return; |
| 2013 | } |
| 2014 |
| 2015 | // Legacy handling for offer_to_receive_audio and offer_to_receive_video. |
| 2016 | // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions". |
| 2017 | if (IsUnifiedPlan()) { |
| 2018 | RTCError error = HandleLegacyOfferOptions(options); |
| 2019 | if (!error.ok()) { |
| 2020 | pc_->message_handler()->PostCreateSessionDescriptionFailure( |
| 2021 | observer, std::move(error)); |
| 2022 | return; |
| 2023 | } |
| 2024 | } |
| 2025 |
| 2026 | cricket::MediaSessionOptions session_options; |
| 2027 | GetOptionsForOffer(options, &session_options); |
| 2028 | webrtc_session_desc_factory_->CreateOffer(observer, options, session_options); |
| 2029 | } |
| 2030 |
| 2031 | void SdpOfferAnswerHandler::CreateAnswer( |
| 2032 | CreateSessionDescriptionObserver* observer, |
| 2033 | const PeerConnectionInterface::RTCOfferAnswerOptions& options) { |
| 2034 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::CreateAnswer"); |
| 2035 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2036 | // Chain this operation. If asynchronous operations are pending on the chain, |
| 2037 | // this operation will be queued to be invoked, otherwise the contents of the |
| 2038 | // lambda will execute immediately. |
| 2039 | operations_chain_->ChainOperation( |
| 2040 | [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(), |
| 2041 | observer_refptr = |
| 2042 | rtc::scoped_refptr<CreateSessionDescriptionObserver>(observer), |
| 2043 | options](std::function<void()> operations_chain_callback) { |
| 2044 | // Abort early if `this_weak_ptr` is no longer valid. |
| 2045 | if (!this_weak_ptr) { |
| 2046 | observer_refptr->OnFailure(RTCError( |
| 2047 | RTCErrorType::INTERNAL_ERROR, |
| 2048 | "CreateAnswer failed because the session was shut down")); |
| 2049 | operations_chain_callback(); |
| 2050 | return; |
| 2051 | } |
| 2052 | // The operation completes asynchronously when the wrapper is invoked. |
| 2053 | auto observer_wrapper = rtc::make_ref_counted< |
| 2054 | CreateSessionDescriptionObserverOperationWrapper>( |
| 2055 | std::move(observer_refptr), std::move(operations_chain_callback)); |
| 2056 | this_weak_ptr->DoCreateAnswer(options, observer_wrapper); |
| 2057 | }); |
| 2058 | } |
| 2059 |
| 2060 | void SdpOfferAnswerHandler::DoCreateAnswer( |
| 2061 | const PeerConnectionInterface::RTCOfferAnswerOptions& options, |
| 2062 | rtc::scoped_refptr<CreateSessionDescriptionObserver> observer) { |
| 2063 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2064 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::DoCreateAnswer"); |
| 2065 | if (!observer) { |
| 2066 | RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL."; |
| 2067 | return; |
| 2068 | } |
| 2069 |
| 2070 | // If a session error has occurred the PeerConnection is in a possibly |
| 2071 | // inconsistent state so fail right away. |
| 2072 | if (session_error() != SessionError::kNone) { |
| 2073 | std::string error_message = GetSessionErrorMsg(); |
| 2074 | RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message; |
| 2075 | pc_->message_handler()->PostCreateSessionDescriptionFailure( |
| 2076 | observer, |
| 2077 | RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message))); |
| 2078 | return; |
| 2079 | } |
| 2080 |
| 2081 | if (!(signaling_state_ == PeerConnectionInterface::kHaveRemoteOffer || |
| 2082 | signaling_state_ == PeerConnectionInterface::kHaveLocalPrAnswer)) { |
| 2083 | std::string error = |
| 2084 | "PeerConnection cannot create an answer in a state other than " |
| 2085 | "have-remote-offer or have-local-pranswer."; |
| 2086 | RTC_LOG(LS_ERROR) << error; |
| 2087 | pc_->message_handler()->PostCreateSessionDescriptionFailure( |
| 2088 | observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error))); |
| 2089 | return; |
| 2090 | } |
| 2091 |
| 2092 | // The remote description should be set if we're in the right state. |
| 2093 | RTC_DCHECK(remote_description()); |
| 2094 |
| 2095 | if (IsUnifiedPlan()) { |
| 2096 | if (options.offer_to_receive_audio != |
| 2097 | PeerConnectionInterface::RTCOfferAnswerOptions::kUndefined) { |
| 2098 | RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not " |
| 2099 | "supported with Unified Plan semantics. Use the " |
| 2100 | "RtpTransceiver API instead."; |
| 2101 | } |
| 2102 | if (options.offer_to_receive_video != |
| 2103 | PeerConnectionInterface::RTCOfferAnswerOptions::kUndefined) { |
| 2104 | RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not " |
| 2105 | "supported with Unified Plan semantics. Use the " |
| 2106 | "RtpTransceiver API instead."; |
| 2107 | } |
| 2108 | } |
| 2109 |
| 2110 | cricket::MediaSessionOptions session_options; |
| 2111 | GetOptionsForAnswer(options, &session_options); |
| 2112 | webrtc_session_desc_factory_->CreateAnswer(observer, session_options); |
| 2113 | } |
| 2114 |
| 2115 | void SdpOfferAnswerHandler::DoSetRemoteDescription( |
| 2116 | std::unique_ptr<SessionDescriptionInterface> desc, |
| 2117 | rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) { |
| 2118 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2119 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::DoSetRemoteDescription"); |
| 2120 |
| 2121 | if (!observer) { |
| 2122 | RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL."; |
| 2123 | return; |
| 2124 | } |
| 2125 |
| 2126 | if (!desc) { |
| 2127 | observer->OnSetRemoteDescriptionComplete(RTCError( |
| 2128 | RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL.")); |
| 2129 | return; |
| 2130 | } |
| 2131 |
| 2132 | // If a session error has occurred the PeerConnection is in a possibly |
| 2133 | // inconsistent state so fail right away. |
| 2134 | if (session_error() != SessionError::kNone) { |
| 2135 | std::string error_message = GetSessionErrorMsg(); |
| 2136 | RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message; |
| 2137 | observer->OnSetRemoteDescriptionComplete( |
| 2138 | RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message))); |
| 2139 | return; |
| 2140 | } |
| 2141 | if (IsUnifiedPlan()) { |
| 2142 | if (pc_->configuration()->enable_implicit_rollback) { |
| 2143 | if (desc->GetType() == SdpType::kOffer && |
| 2144 | signaling_state() == PeerConnectionInterface::kHaveLocalOffer) { |
| 2145 | Rollback(desc->GetType()); |
| 2146 | } |
| 2147 | } |
| 2148 | // Explicit rollback. |
| 2149 | if (desc->GetType() == SdpType::kRollback) { |
| 2150 | observer->OnSetRemoteDescriptionComplete(Rollback(desc->GetType())); |
| 2151 | return; |
| 2152 | } |
| 2153 | } else if (desc->GetType() == SdpType::kRollback) { |
| 2154 | observer->OnSetRemoteDescriptionComplete( |
| 2155 | RTCError(RTCErrorType::UNSUPPORTED_OPERATION, |
| 2156 | "Rollback not supported in Plan B")); |
| 2157 | return; |
| 2158 | } |
| 2159 | if (desc->GetType() == SdpType::kOffer || |
| 2160 | desc->GetType() == SdpType::kAnswer) { |
| 2161 | // Report to UMA the format of the received offer or answer. |
| 2162 | pc_->ReportSdpFormatReceived(*desc); |
| 2163 | pc_->ReportSdpBundleUsage(*desc); |
| 2164 | } |
| 2165 |
| 2166 | // Handle remote descriptions missing a=mid lines for interop with legacy end |
| 2167 | // points. |
| 2168 | FillInMissingRemoteMids(desc->description()); |
| 2169 |
| 2170 | std::map<std::string, const cricket::ContentGroup*> bundle_groups_by_mid = |
| 2171 | GetBundleGroupsByMid(desc->description()); |
| 2172 | RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE, |
| 2173 | bundle_groups_by_mid); |
| 2174 | if (!error.ok()) { |
| 2175 | std::string error_message = GetSetDescriptionErrorMessage( |
| 2176 | cricket::CS_REMOTE, desc->GetType(), error); |
| 2177 | RTC_LOG(LS_ERROR) << error_message; |
| 2178 | observer->OnSetRemoteDescriptionComplete( |
| 2179 | RTCError(error.type(), std::move(error_message))); |
| 2180 | return; |
| 2181 | } |
| 2182 |
| 2183 | // Grab the description type before moving ownership to |
| 2184 | // ApplyRemoteDescription, which may destroy it before returning. |
| 2185 | const SdpType type = desc->GetType(); |
| 2186 |
| 2187 | error = ApplyRemoteDescription(std::move(desc), bundle_groups_by_mid); |
| 2188 | // `desc` may be destroyed at this point. |
| 2189 |
| 2190 | if (!error.ok()) { |
| 2191 | // If ApplyRemoteDescription fails, the PeerConnection could be in an |
| 2192 | // inconsistent state, so act conservatively here and set the session error |
| 2193 | // so that future calls to SetLocalDescription/SetRemoteDescription fail. |
| 2194 | SetSessionError(SessionError::kContent, error.message()); |
| 2195 | std::string error_message = |
| 2196 | GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error); |
| 2197 | RTC_LOG(LS_ERROR) << error_message; |
| 2198 | observer->OnSetRemoteDescriptionComplete( |
| 2199 | RTCError(error.type(), std::move(error_message))); |
| 2200 | return; |
| 2201 | } |
| 2202 | RTC_DCHECK(remote_description()); |
| 2203 |
| 2204 | if (type == SdpType::kAnswer) { |
| 2205 | RemoveStoppedTransceivers(); |
| 2206 | // TODO(deadbeef): We already had to hop to the network thread for |
| 2207 | // MaybeStartGathering... |
| 2208 | pc_->network_thread()->Invoke<void>( |
| 2209 | RTC_FROM_HERE, [this] { port_allocator()->DiscardCandidatePool(); }); |
| 2210 | // Make UMA notes about what was agreed to. |
| 2211 | ReportNegotiatedSdpSemantics(*remote_description()); |
| 2212 | } |
| 2213 |
| 2214 | observer->OnSetRemoteDescriptionComplete(RTCError::OK()); |
| 2215 | pc_->NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED); |
| 2216 |
| 2217 | // Check if negotiation is needed. We must do this after informing the |
| 2218 | // observer that SetRemoteDescription() has completed to ensure negotiation is |
| 2219 | // not needed prior to the promise resolving. |
| 2220 | if (IsUnifiedPlan()) { |
| 2221 | bool was_negotiation_needed = is_negotiation_needed_; |
| 2222 | UpdateNegotiationNeeded(); |
| 2223 | if (signaling_state() == PeerConnectionInterface::kStable && |
| 2224 | was_negotiation_needed && is_negotiation_needed_) { |
| 2225 | // Legacy version. |
| 2226 | pc_->Observer()->OnRenegotiationNeeded(); |
| 2227 | // Spec-compliant version; the event may get invalidated before firing. |
| 2228 | GenerateNegotiationNeededEvent(); |
| 2229 | } |
| 2230 | } |
| 2231 | } |
| 2232 |
| 2233 | void SdpOfferAnswerHandler::SetAssociatedRemoteStreams( |
| 2234 | rtc::scoped_refptr<RtpReceiverInternal> receiver, |
| 2235 | const std::vector<std::string>& stream_ids, |
| 2236 | std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams, |
| 2237 | std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) { |
| 2238 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2239 | std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams; |
| 2240 | for (const std::string& stream_id : stream_ids) { |
| 2241 | rtc::scoped_refptr<MediaStreamInterface> stream = |
| 2242 | remote_streams_->find(stream_id); |
| 2243 | if (!stream) { |
| 2244 | stream = MediaStreamProxy::Create(rtc::Thread::Current(), |
| 2245 | MediaStream::Create(stream_id)); |
| 2246 | remote_streams_->AddStream(stream); |
| 2247 | added_streams->push_back(stream); |
| 2248 | } |
| 2249 | media_streams.push_back(stream); |
| 2250 | } |
| 2251 | // Special case: "a=msid" missing, use random stream ID. |
| 2252 | if (media_streams.empty() && |
| 2253 | !(remote_description()->description()->msid_signaling() & |
| 2254 | cricket::kMsidSignalingMediaSection)) { |
| 2255 | if (!missing_msid_default_stream_) { |
| 2256 | missing_msid_default_stream_ = MediaStreamProxy::Create( |
| 2257 | rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid())); |
| 2258 | added_streams->push_back(missing_msid_default_stream_); |
| 2259 | } |
| 2260 | media_streams.push_back(missing_msid_default_stream_); |
| 2261 | } |
| 2262 | std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams = |
| 2263 | receiver->streams(); |
| 2264 | // SetStreams() will add/remove the receiver's track to/from the streams. This |
| 2265 | // differs from the spec - the spec uses an "addList" and "removeList" to |
| 2266 | // update the stream-track relationships in a later step. We do this earlier, |
| 2267 | // changing the order of things, but the end-result is the same. |
| 2268 | // TODO(hbos): When we remove remote_streams(), use set_stream_ids() |
| 2269 | // instead. https://crbug.com/webrtc/9480 |
| 2270 | receiver->SetStreams(media_streams); |
| 2271 | RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams); |
| 2272 | } |
| 2273 |
| 2274 | bool SdpOfferAnswerHandler::AddIceCandidate( |
| 2275 | const IceCandidateInterface* ice_candidate) { |
| 2276 | const AddIceCandidateResult result = AddIceCandidateInternal(ice_candidate); |
| 2277 | NoteAddIceCandidateResult(result); |
| 2278 | // If the return value is kAddIceCandidateFailNotReady, the candidate has been |
| 2279 | // added, although not 'ready', but that's a success. |
| 2280 | return result == kAddIceCandidateSuccess || |
| 2281 | result == kAddIceCandidateFailNotReady; |
| 2282 | } |
| 2283 |
| 2284 | AddIceCandidateResult SdpOfferAnswerHandler::AddIceCandidateInternal( |
| 2285 | const IceCandidateInterface* ice_candidate) { |
| 2286 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2287 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::AddIceCandidate"); |
| 2288 | if (pc_->IsClosed()) { |
| 2289 | RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed."; |
| 2290 | return kAddIceCandidateFailClosed; |
| 2291 | } |
| 2292 |
| 2293 | if (!remote_description()) { |
| 2294 | RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added " |
| 2295 | "without any remote session description."; |
| 2296 | return kAddIceCandidateFailNoRemoteDescription; |
| 2297 | } |
| 2298 |
| 2299 | if (!ice_candidate) { |
| 2300 | RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null."; |
| 2301 | return kAddIceCandidateFailNullCandidate; |
| 2302 | } |
| 2303 |
| 2304 | bool valid = false; |
| 2305 | bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid); |
| 2306 | if (!valid) { |
| 2307 | return kAddIceCandidateFailNotValid; |
| 2308 | } |
| 2309 |
| 2310 | // Add this candidate to the remote session description. |
| 2311 | if (!mutable_remote_description()->AddCandidate(ice_candidate)) { |
| 2312 | RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used."; |
| 2313 | return kAddIceCandidateFailInAddition; |
| 2314 | } |
| 2315 |
| 2316 | if (!ready) { |
| 2317 | RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate."; |
| 2318 | return kAddIceCandidateFailNotReady; |
| 2319 | } |
| 2320 |
| 2321 | if (!UseCandidate(ice_candidate)) { |
| 2322 | return kAddIceCandidateFailNotUsable; |
| 2323 | } |
| 2324 |
| 2325 | pc_->NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED); |
| 2326 |
| 2327 | return kAddIceCandidateSuccess; |
| 2328 | } |
| 2329 |
| 2330 | void SdpOfferAnswerHandler::AddIceCandidate( |
| 2331 | std::unique_ptr<IceCandidateInterface> candidate, |
| 2332 | std::function<void(RTCError)> callback) { |
| 2333 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::AddIceCandidate"); |
| 2334 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2335 | // Chain this operation. If asynchronous operations are pending on the chain, |
| 2336 | // this operation will be queued to be invoked, otherwise the contents of the |
| 2337 | // lambda will execute immediately. |
| 2338 | operations_chain_->ChainOperation( |
| 2339 | [this_weak_ptr = weak_ptr_factory_.GetWeakPtr(), |
| 2340 | candidate = std::move(candidate), callback = std::move(callback)]( |
| 2341 | std::function<void()> operations_chain_callback) { |
| 2342 | auto result = |
| 2343 | this_weak_ptr |
| 2344 | ? this_weak_ptr->AddIceCandidateInternal(candidate.get()) |
| 2345 | : kAddIceCandidateFailClosed; |
| 2346 | NoteAddIceCandidateResult(result); |
| 2347 | operations_chain_callback(); |
| 2348 | if (result == kAddIceCandidateFailClosed) { |
| 2349 | callback(RTCError( |
| 2350 | RTCErrorType::INVALID_STATE, |
| 2351 | "AddIceCandidate failed because the session was shut down")); |
| 2352 | } else if (result != kAddIceCandidateSuccess && |
| 2353 | result != kAddIceCandidateFailNotReady) { |
| 2354 | // Fail with an error type and message consistent with Chromium. |
| 2355 | // TODO(hbos): Fail with error types according to spec. |
| 2356 | callback(RTCError(RTCErrorType::UNSUPPORTED_OPERATION, |
| 2357 | "Error processing ICE candidate")); |
| 2358 | } else { |
| 2359 | callback(RTCError::OK()); |
| 2360 | } |
| 2361 | }); |
| 2362 | } |
| 2363 |
| 2364 | bool SdpOfferAnswerHandler::RemoveIceCandidates( |
| 2365 | const std::vector<cricket::Candidate>& candidates) { |
| 2366 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::RemoveIceCandidates"); |
| 2367 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2368 | if (pc_->IsClosed()) { |
| 2369 | RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed."; |
| 2370 | return false; |
| 2371 | } |
| 2372 |
| 2373 | if (!remote_description()) { |
| 2374 | RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed " |
| 2375 | "without any remote session description."; |
| 2376 | return false; |
| 2377 | } |
| 2378 |
| 2379 | if (candidates.empty()) { |
| 2380 | RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty."; |
| 2381 | return false; |
| 2382 | } |
| 2383 |
| 2384 | size_t number_removed = |
| 2385 | mutable_remote_description()->RemoveCandidates(candidates); |
| 2386 | if (number_removed != candidates.size()) { |
| 2387 | RTC_LOG(LS_ERROR) |
| 2388 | << "RemoveIceCandidates: Failed to remove candidates. Requested " |
| 2389 | << candidates.size() << " but only " << number_removed |
| 2390 | << " are removed."; |
| 2391 | } |
| 2392 |
| 2393 | // Remove the candidates from the transport controller. |
| 2394 | RTCError error = transport_controller()->RemoveRemoteCandidates(candidates); |
| 2395 | if (!error.ok()) { |
| 2396 | RTC_LOG(LS_ERROR) |
| 2397 | << "RemoveIceCandidates: Error when removing remote candidates: " |
| 2398 | << error.message(); |
| 2399 | } |
| 2400 | return true; |
| 2401 | } |
| 2402 |
| 2403 | void SdpOfferAnswerHandler::AddLocalIceCandidate( |
| 2404 | const JsepIceCandidate* candidate) { |
| 2405 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2406 | if (local_description()) { |
| 2407 | mutable_local_description()->AddCandidate(candidate); |
| 2408 | } |
| 2409 | } |
| 2410 |
| 2411 | void SdpOfferAnswerHandler::RemoveLocalIceCandidates( |
| 2412 | const std::vector<cricket::Candidate>& candidates) { |
| 2413 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2414 | if (local_description()) { |
| 2415 | mutable_local_description()->RemoveCandidates(candidates); |
| 2416 | } |
| 2417 | } |
| 2418 |
| 2419 | const SessionDescriptionInterface* SdpOfferAnswerHandler::local_description() |
| 2420 | const { |
| 2421 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2422 | return pending_local_description_ ? pending_local_description_.get() |
| 2423 | : current_local_description_.get(); |
| 2424 | } |
| 2425 |
| 2426 | const SessionDescriptionInterface* SdpOfferAnswerHandler::remote_description() |
| 2427 | const { |
| 2428 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2429 | return pending_remote_description_ ? pending_remote_description_.get() |
| 2430 | : current_remote_description_.get(); |
| 2431 | } |
| 2432 |
| 2433 | const SessionDescriptionInterface* |
| 2434 | SdpOfferAnswerHandler::current_local_description() const { |
| 2435 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2436 | return current_local_description_.get(); |
| 2437 | } |
| 2438 |
| 2439 | const SessionDescriptionInterface* |
| 2440 | SdpOfferAnswerHandler::current_remote_description() const { |
| 2441 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2442 | return current_remote_description_.get(); |
| 2443 | } |
| 2444 |
| 2445 | const SessionDescriptionInterface* |
| 2446 | SdpOfferAnswerHandler::pending_local_description() const { |
| 2447 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2448 | return pending_local_description_.get(); |
| 2449 | } |
| 2450 |
| 2451 | const SessionDescriptionInterface* |
| 2452 | SdpOfferAnswerHandler::pending_remote_description() const { |
| 2453 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2454 | return pending_remote_description_.get(); |
| 2455 | } |
| 2456 |
| 2457 | PeerConnectionInterface::SignalingState SdpOfferAnswerHandler::signaling_state() |
| 2458 | const { |
| 2459 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2460 | return signaling_state_; |
| 2461 | } |
| 2462 |
| 2463 | void SdpOfferAnswerHandler::ChangeSignalingState( |
| 2464 | PeerConnectionInterface::SignalingState signaling_state) { |
| 2465 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::ChangeSignalingState"); |
| 2466 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2467 | if (signaling_state_ == signaling_state) { |
| 2468 | return; |
| 2469 | } |
| 2470 | RTC_LOG(LS_INFO) << "Session: " << pc_->session_id() << " Old state: " |
| 2471 | << PeerConnectionInterface::AsString(signaling_state_) |
| 2472 | << " New state: " |
| 2473 | << PeerConnectionInterface::AsString(signaling_state); |
| 2474 | signaling_state_ = signaling_state; |
| 2475 | pc_->Observer()->OnSignalingChange(signaling_state_); |
| 2476 | } |
| 2477 |
| 2478 | RTCError SdpOfferAnswerHandler::UpdateSessionState( |
| 2479 | SdpType type, |
| 2480 | cricket::ContentSource source, |
| 2481 | const cricket::SessionDescription* description, |
| 2482 | const std::map<std::string, const cricket::ContentGroup*>& |
| 2483 | bundle_groups_by_mid) { |
| 2484 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2485 |
| 2486 | // If there's already a pending error then no state transition should happen. |
| 2487 | // But all call-sites should be verifying this before calling us! |
| 2488 | RTC_DCHECK(session_error() == SessionError::kNone); |
| 2489 |
| 2490 | // If this is answer-ish we're ready to let media flow. |
| 2491 | if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) { |
| 2492 | EnableSending(); |
| 2493 | } |
| 2494 |
| 2495 | // Update the signaling state according to the specified state machine (see |
| 2496 | // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum). |
| 2497 | if (type == SdpType::kOffer) { |
| 2498 | ChangeSignalingState(source == cricket::CS_LOCAL |
| 2499 | ? PeerConnectionInterface::kHaveLocalOffer |
| 2500 | : PeerConnectionInterface::kHaveRemoteOffer); |
| 2501 | } else if (type == SdpType::kPrAnswer) { |
| 2502 | ChangeSignalingState(source == cricket::CS_LOCAL |
| 2503 | ? PeerConnectionInterface::kHaveLocalPrAnswer |
| 2504 | : PeerConnectionInterface::kHaveRemotePrAnswer); |
| 2505 | } else { |
| 2506 | RTC_DCHECK(type == SdpType::kAnswer); |
| 2507 | ChangeSignalingState(PeerConnectionInterface::kStable); |
| 2508 | transceivers()->DiscardStableStates(); |
| 2509 | } |
| 2510 |
| 2511 | // Update internal objects according to the session description's media |
| 2512 | // descriptions. |
| 2513 | return PushdownMediaDescription(type, source, bundle_groups_by_mid); |
| 2514 | } |
| 2515 |
| 2516 | bool SdpOfferAnswerHandler::ShouldFireNegotiationNeededEvent( |
| 2517 | uint32_t event_id) { |
| 2518 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2519 | // Plan B? Always fire to conform with useless legacy behavior. |
| 2520 | if (!IsUnifiedPlan()) { |
| 2521 | return true; |
| 2522 | } |
| 2523 | // The event ID has been invalidated. Either negotiation is no longer needed |
| 2524 | // or a newer negotiation needed event has been generated. |
| 2525 | if (event_id != negotiation_needed_event_id_) { |
| 2526 | return false; |
| 2527 | } |
| 2528 | // The chain is no longer empty, update negotiation needed when it becomes |
| 2529 | // empty. This should generate a newer negotiation needed event, making this |
| 2530 | // one obsolete. |
| 2531 | if (!operations_chain_->IsEmpty()) { |
| 2532 | // Since we just suppressed an event that would have been fired, if |
| 2533 | // negotiation is still needed by the time the chain becomes empty again, we |
| 2534 | // must make sure to generate another event if negotiation is needed then. |
| 2535 | // This happens when `is_negotiation_needed_` goes from false to true, so we |
| 2536 | // set it to false until UpdateNegotiationNeeded() is called. |
| 2537 | is_negotiation_needed_ = false; |
| 2538 | update_negotiation_needed_on_empty_chain_ = true; |
| 2539 | return false; |
| 2540 | } |
| 2541 | // We must not fire if the signaling state is no longer "stable". If |
| 2542 | // negotiation is still needed when we return to "stable", a new negotiation |
| 2543 | // needed event will be generated, so this one can safely be suppressed. |
| 2544 | if (signaling_state_ != PeerConnectionInterface::kStable) { |
| 2545 | return false; |
| 2546 | } |
| 2547 | // All checks have passed - please fire "negotiationneeded" now! |
| 2548 | return true; |
| 2549 | } |
| 2550 |
| 2551 | rtc::scoped_refptr<StreamCollectionInterface> |
| 2552 | SdpOfferAnswerHandler::local_streams() { |
| 2553 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2554 | RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified " |
| 2555 | "Plan SdpSemantics. Please use GetSenders " |
| 2556 | "instead."; |
| 2557 | return local_streams_; |
| 2558 | } |
| 2559 |
| 2560 | rtc::scoped_refptr<StreamCollectionInterface> |
| 2561 | SdpOfferAnswerHandler::remote_streams() { |
| 2562 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2563 | RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified " |
| 2564 | "Plan SdpSemantics. Please use GetReceivers " |
| 2565 | "instead."; |
| 2566 | return remote_streams_; |
| 2567 | } |
| 2568 |
| 2569 | bool SdpOfferAnswerHandler::AddStream(MediaStreamInterface* local_stream) { |
| 2570 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2571 | RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan " |
| 2572 | "SdpSemantics. Please use AddTrack instead."; |
| 2573 | if (pc_->IsClosed()) { |
| 2574 | return false; |
| 2575 | } |
| 2576 | if (!CanAddLocalMediaStream(local_streams_, local_stream)) { |
| 2577 | return false; |
| 2578 | } |
| 2579 |
| 2580 | local_streams_->AddStream(local_stream); |
| 2581 | auto observer = std::make_unique<MediaStreamObserver>( |
| 2582 | local_stream, |
| 2583 | [this](AudioTrackInterface* audio_track, |
| 2584 | MediaStreamInterface* media_stream) { |
| 2585 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2586 | OnAudioTrackAdded(audio_track, media_stream); |
| 2587 | }, |
| 2588 | [this](AudioTrackInterface* audio_track, |
| 2589 | MediaStreamInterface* media_stream) { |
| 2590 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2591 | OnAudioTrackRemoved(audio_track, media_stream); |
| 2592 | }, |
| 2593 | [this](VideoTrackInterface* video_track, |
| 2594 | MediaStreamInterface* media_stream) { |
| 2595 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2596 | OnVideoTrackAdded(video_track, media_stream); |
| 2597 | }, |
| 2598 | [this](VideoTrackInterface* video_track, |
| 2599 | MediaStreamInterface* media_stream) { |
| 2600 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2601 | OnVideoTrackRemoved(video_track, media_stream); |
| 2602 | }); |
| 2603 | stream_observers_.push_back(std::move(observer)); |
| 2604 |
| 2605 | for (const auto& track : local_stream->GetAudioTracks()) { |
| 2606 | rtp_manager()->AddAudioTrack(track.get(), local_stream); |
| 2607 | } |
| 2608 | for (const auto& track : local_stream->GetVideoTracks()) { |
| 2609 | rtp_manager()->AddVideoTrack(track.get(), local_stream); |
| 2610 | } |
| 2611 |
| 2612 | pc_->stats()->AddStream(local_stream); |
| 2613 | UpdateNegotiationNeeded(); |
| 2614 | return true; |
| 2615 | } |
| 2616 |
| 2617 | void SdpOfferAnswerHandler::RemoveStream(MediaStreamInterface* local_stream) { |
| 2618 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2619 | RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified " |
| 2620 | "Plan SdpSemantics. Please use RemoveTrack " |
| 2621 | "instead."; |
| 2622 | TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream"); |
| 2623 | if (!pc_->IsClosed()) { |
| 2624 | for (const auto& track : local_stream->GetAudioTracks()) { |
| 2625 | rtp_manager()->RemoveAudioTrack(track.get(), local_stream); |
| 2626 | } |
| 2627 | for (const auto& track : local_stream->GetVideoTracks()) { |
| 2628 | rtp_manager()->RemoveVideoTrack(track.get(), local_stream); |
| 2629 | } |
| 2630 | } |
| 2631 | local_streams_->RemoveStream(local_stream); |
| 2632 | stream_observers_.erase( |
| 2633 | std::remove_if( |
| 2634 | stream_observers_.begin(), stream_observers_.end(), |
| 2635 | [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) { |
| 2636 | return observer->stream()->id().compare(local_stream->id()) == 0; |
| 2637 | }), |
| 2638 | stream_observers_.end()); |
| 2639 |
| 2640 | if (pc_->IsClosed()) { |
| 2641 | return; |
| 2642 | } |
| 2643 | UpdateNegotiationNeeded(); |
| 2644 | } |
| 2645 |
| 2646 | void SdpOfferAnswerHandler::OnAudioTrackAdded(AudioTrackInterface* track, |
| 2647 | MediaStreamInterface* stream) { |
| 2648 | if (pc_->IsClosed()) { |
| 2649 | return; |
| 2650 | } |
| 2651 | rtp_manager()->AddAudioTrack(track, stream); |
| 2652 | UpdateNegotiationNeeded(); |
| 2653 | } |
| 2654 |
| 2655 | void SdpOfferAnswerHandler::OnAudioTrackRemoved(AudioTrackInterface* track, |
| 2656 | MediaStreamInterface* stream) { |
| 2657 | if (pc_->IsClosed()) { |
| 2658 | return; |
| 2659 | } |
| 2660 | rtp_manager()->RemoveAudioTrack(track, stream); |
| 2661 | UpdateNegotiationNeeded(); |
| 2662 | } |
| 2663 |
| 2664 | void SdpOfferAnswerHandler::OnVideoTrackAdded(VideoTrackInterface* track, |
| 2665 | MediaStreamInterface* stream) { |
| 2666 | if (pc_->IsClosed()) { |
| 2667 | return; |
| 2668 | } |
| 2669 | rtp_manager()->AddVideoTrack(track, stream); |
| 2670 | UpdateNegotiationNeeded(); |
| 2671 | } |
| 2672 |
| 2673 | void SdpOfferAnswerHandler::OnVideoTrackRemoved(VideoTrackInterface* track, |
| 2674 | MediaStreamInterface* stream) { |
| 2675 | if (pc_->IsClosed()) { |
| 2676 | return; |
| 2677 | } |
| 2678 | rtp_manager()->RemoveVideoTrack(track, stream); |
| 2679 | UpdateNegotiationNeeded(); |
| 2680 | } |
| 2681 |
| 2682 | RTCError SdpOfferAnswerHandler::Rollback(SdpType desc_type) { |
| 2683 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::Rollback"); |
| 2684 | auto state = signaling_state(); |
| 2685 | if (state != PeerConnectionInterface::kHaveLocalOffer && |
| 2686 | state != PeerConnectionInterface::kHaveRemoteOffer) { |
| 2687 | return RTCError(RTCErrorType::INVALID_STATE, |
| 2688 | (rtc::StringBuilder("Called in wrong signalingState: ") |
| 2689 | << (PeerConnectionInterface::AsString(signaling_state()))) |
| 2690 | .Release()); |
| 2691 | } |
| 2692 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2693 | RTC_DCHECK(IsUnifiedPlan()); |
| 2694 | std::vector<rtc::scoped_refptr<MediaStreamInterface>> all_added_streams; |
| 2695 | std::vector<rtc::scoped_refptr<MediaStreamInterface>> all_removed_streams; |
| 2696 | std::vector<rtc::scoped_refptr<RtpReceiverInterface>> removed_receivers; |
| 2697 |
| 2698 | for (auto&& transceivers_stable_state_pair : transceivers()->StableStates()) { |
| 2699 | auto transceiver = transceivers_stable_state_pair.first; |
| 2700 | auto state = transceivers_stable_state_pair.second; |
| 2701 |
| 2702 | if (state.remote_stream_ids()) { |
| 2703 | std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams; |
| 2704 | std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams; |
| 2705 | SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(), |
| 2706 | state.remote_stream_ids().value(), |
| 2707 | &added_streams, &removed_streams); |
| 2708 | all_added_streams.insert(all_added_streams.end(), added_streams.begin(), |
| 2709 | added_streams.end()); |
| 2710 | all_removed_streams.insert(all_removed_streams.end(), |
| 2711 | removed_streams.begin(), |
| 2712 | removed_streams.end()); |
| 2713 | if (!state.has_m_section() && !state.newly_created()) { |
| 2714 | continue; |
| 2715 | } |
| 2716 | } |
| 2717 |
| 2718 | RTC_DCHECK(transceiver->internal()->mid().has_value()); |
| 2719 | DestroyTransceiverChannel(transceiver); |
| 2720 |
| 2721 | if (signaling_state() == PeerConnectionInterface::kHaveRemoteOffer && |
| 2722 | transceiver->receiver()) { |
| 2723 | removed_receivers.push_back(transceiver->receiver()); |
| 2724 | } |
| 2725 | if (state.newly_created()) { |
| 2726 | if (transceiver->internal()->reused_for_addtrack()) { |
| 2727 | transceiver->internal()->set_created_by_addtrack(true); |
| 2728 | } else { |
| 2729 | transceivers()->Remove(transceiver); |
| 2730 | } |
| 2731 | } |
| 2732 | if (state.init_send_encodings()) { |
| 2733 | transceiver->internal()->sender_internal()->set_init_send_encodings( |
| 2734 | state.init_send_encodings().value()); |
| 2735 | } |
| 2736 | transceiver->internal()->sender_internal()->set_transport(nullptr); |
| 2737 | transceiver->internal()->receiver_internal()->set_transport(nullptr); |
| 2738 | transceiver->internal()->set_mid(state.mid()); |
| 2739 | transceiver->internal()->set_mline_index(state.mline_index()); |
| 2740 | } |
| 2741 | RTCError e = transport_controller()->RollbackTransports(); |
| 2742 | if (!e.ok()) { |
| 2743 | return e; |
| 2744 | } |
| 2745 | transceivers()->DiscardStableStates(); |
| 2746 | pending_local_description_.reset(); |
| 2747 | pending_remote_description_.reset(); |
| 2748 | ChangeSignalingState(PeerConnectionInterface::kStable); |
| 2749 |
| 2750 | // Once all processing has finished, fire off callbacks. |
| 2751 | for (const auto& receiver : removed_receivers) { |
| 2752 | pc_->Observer()->OnRemoveTrack(receiver); |
| 2753 | } |
| 2754 | for (const auto& stream : all_added_streams) { |
| 2755 | pc_->Observer()->OnAddStream(stream); |
| 2756 | } |
| 2757 | for (const auto& stream : all_removed_streams) { |
| 2758 | pc_->Observer()->OnRemoveStream(stream); |
| 2759 | } |
| 2760 |
| 2761 | // The assumption is that in case of implicit rollback UpdateNegotiationNeeded |
| 2762 | // gets called in SetRemoteDescription. |
| 2763 | if (desc_type == SdpType::kRollback) { |
| 2764 | UpdateNegotiationNeeded(); |
| 2765 | if (is_negotiation_needed_) { |
| 2766 | // Legacy version. |
| 2767 | pc_->Observer()->OnRenegotiationNeeded(); |
| 2768 | // Spec-compliant version; the event may get invalidated before firing. |
| 2769 | GenerateNegotiationNeededEvent(); |
| 2770 | } |
| 2771 | } |
| 2772 | return RTCError::OK(); |
| 2773 | } |
| 2774 |
| 2775 | bool SdpOfferAnswerHandler::IsUnifiedPlan() const { |
| 2776 | return pc_->IsUnifiedPlan(); |
| 2777 | } |
| 2778 |
| 2779 | void SdpOfferAnswerHandler::OnOperationsChainEmpty() { |
| 2780 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2781 | if (pc_->IsClosed() || !update_negotiation_needed_on_empty_chain_) |
| 2782 | return; |
| 2783 | update_negotiation_needed_on_empty_chain_ = false; |
| 2784 | // Firing when chain is empty is only supported in Unified Plan to avoid Plan |
| 2785 | // B regressions. (In Plan B, onnegotiationneeded is already broken anyway, so |
| 2786 | // firing it even more might just be confusing.) |
| 2787 | if (IsUnifiedPlan()) { |
| 2788 | UpdateNegotiationNeeded(); |
| 2789 | } |
| 2790 | } |
| 2791 |
| 2792 | absl::optional<bool> SdpOfferAnswerHandler::is_caller() { |
| 2793 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2794 | return is_caller_; |
| 2795 | } |
| 2796 |
| 2797 | bool SdpOfferAnswerHandler::HasNewIceCredentials() { |
| 2798 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2799 | return local_ice_credentials_to_replace_->HasIceCredentials(); |
| 2800 | } |
| 2801 |
| 2802 | bool SdpOfferAnswerHandler::IceRestartPending( |
| 2803 | const std::string& content_name) const { |
| 2804 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2805 | return pending_ice_restarts_.find(content_name) != |
| 2806 | pending_ice_restarts_.end(); |
| 2807 | } |
| 2808 |
| 2809 | bool SdpOfferAnswerHandler::NeedsIceRestart( |
| 2810 | const std::string& content_name) const { |
| 2811 | return pc_->NeedsIceRestart(content_name); |
| 2812 | } |
| 2813 |
| 2814 | absl::optional<rtc::SSLRole> SdpOfferAnswerHandler::GetDtlsRole( |
| 2815 | const std::string& mid) const { |
| 2816 | return transport_controller()->GetDtlsRole(mid); |
| 2817 | } |
| 2818 |
| 2819 | void SdpOfferAnswerHandler::UpdateNegotiationNeeded() { |
| 2820 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2821 | if (!IsUnifiedPlan()) { |
| 2822 | pc_->Observer()->OnRenegotiationNeeded(); |
| 2823 | GenerateNegotiationNeededEvent(); |
| 2824 | return; |
| 2825 | } |
| 2826 |
| 2827 | // In the spec, a task is queued here to run the following steps - this is |
| 2828 | // meant to ensure we do not fire onnegotiationneeded prematurely if multiple |
| 2829 | // changes are being made at once. In order to support Chromium's |
| 2830 | // implementation where the JavaScript representation of the PeerConnection |
| 2831 | // lives on a separate thread though, the queuing of a task is instead |
| 2832 | // performed by the PeerConnectionObserver posting from the signaling thread |
| 2833 | // to the JavaScript main thread that negotiation is needed. And because the |
| 2834 | // Operations Chain lives on the WebRTC signaling thread, |
| 2835 | // ShouldFireNegotiationNeededEvent() must be called before firing the event |
| 2836 | // to ensure the Operations Chain is still empty and the event has not been |
| 2837 | // invalidated. |
| 2838 |
| 2839 | // If connection's [[IsClosed]] slot is true, abort these steps. |
| 2840 | if (pc_->IsClosed()) |
| 2841 | return; |
| 2842 |
| 2843 | // If connection's signaling state is not "stable", abort these steps. |
| 2844 | if (signaling_state() != PeerConnectionInterface::kStable) |
| 2845 | return; |
| 2846 |
| 2847 | // NOTE |
| 2848 | // The negotiation-needed flag will be updated once the state transitions to |
| 2849 | // "stable", as part of the steps for setting an RTCSessionDescription. |
| 2850 |
| 2851 | // If the result of checking if negotiation is needed is false, clear the |
| 2852 | // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot |
| 2853 | // to false, and abort these steps. |
| 2854 | bool is_negotiation_needed = CheckIfNegotiationIsNeeded(); |
| 2855 | if (!is_negotiation_needed) { |
| 2856 | is_negotiation_needed_ = false; |
| 2857 | // Invalidate any negotiation needed event that may previosuly have been |
| 2858 | // generated. |
| 2859 | ++negotiation_needed_event_id_; |
| 2860 | return; |
| 2861 | } |
| 2862 |
| 2863 | // If connection's [[NegotiationNeeded]] slot is already true, abort these |
| 2864 | // steps. |
| 2865 | if (is_negotiation_needed_) |
| 2866 | return; |
| 2867 |
| 2868 | // Set connection's [[NegotiationNeeded]] slot to true. |
| 2869 | is_negotiation_needed_ = true; |
| 2870 |
| 2871 | // Queue a task that runs the following steps: |
| 2872 | // If connection's [[IsClosed]] slot is true, abort these steps. |
| 2873 | // If connection's [[NegotiationNeeded]] slot is false, abort these steps. |
| 2874 | // Fire an event named negotiationneeded at connection. |
| 2875 | pc_->Observer()->OnRenegotiationNeeded(); |
| 2876 | // Fire the spec-compliant version; when ShouldFireNegotiationNeededEvent() is |
| 2877 | // used in the task queued by the observer, this event will only fire when the |
| 2878 | // chain is empty. |
| 2879 | GenerateNegotiationNeededEvent(); |
| 2880 | } |
| 2881 |
| 2882 | bool SdpOfferAnswerHandler::CheckIfNegotiationIsNeeded() { |
| 2883 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 2884 | // 1. If any implementation-specific negotiation is required, as described at |
| 2885 | // the start of this section, return true. |
| 2886 |
| 2887 | // 2. If connection.[[LocalIceCredentialsToReplace]] is not empty, return |
| 2888 | // true. |
| 2889 | if (local_ice_credentials_to_replace_->HasIceCredentials()) { |
| 2890 | return true; |
| 2891 | } |
| 2892 |
| 2893 | // 3. Let description be connection.[[CurrentLocalDescription]]. |
| 2894 | const SessionDescriptionInterface* description = current_local_description(); |
| 2895 | if (!description) |
| 2896 | return true; |
| 2897 |
| 2898 | // 4. If connection has created any RTCDataChannels, and no m= section in |
| 2899 | // description has been negotiated yet for data, return true. |
| 2900 | if (data_channel_controller()->HasSctpDataChannels()) { |
| 2901 | if (!cricket::GetFirstDataContent(description->description()->contents())) |
| 2902 | return true; |
| 2903 | } |
| 2904 |
| 2905 | // 5. For each transceiver in connection's set of transceivers, perform the |
| 2906 | // following checks: |
| 2907 | for (const auto& transceiver : transceivers()->ListInternal()) { |
| 2908 | const ContentInfo* current_local_msection = |
| 2909 | FindTransceiverMSection(transceiver, description); |
| 2910 |
| 2911 | const ContentInfo* current_remote_msection = |
| 2912 | FindTransceiverMSection(transceiver, current_remote_description()); |
| 2913 |
| 2914 | // 5.4 If transceiver is stopped and is associated with an m= section, |
| 2915 | // but the associated m= section is not yet rejected in |
| 2916 | // connection.[[CurrentLocalDescription]] or |
| 2917 | // connection.[[CurrentRemoteDescription]], return true. |
| 2918 | if (transceiver->stopped()) { |
| 2919 | RTC_DCHECK(transceiver->stopping()); |
| 2920 | if (current_local_msection && !current_local_msection->rejected && |
| 2921 | ((current_remote_msection && !current_remote_msection->rejected) || |
| 2922 | !current_remote_msection)) { |
| 2923 | return true; |
| 2924 | } |
| 2925 | continue; |
| 2926 | } |
| 2927 |
| 2928 | // 5.1 If transceiver.[[Stopping]] is true and transceiver.[[Stopped]] is |
| 2929 | // false, return true. |
| 2930 | if (transceiver->stopping() && !transceiver->stopped()) |
| 2931 | return true; |
| 2932 |
| 2933 | // 5.2 If transceiver isn't stopped and isn't yet associated with an m= |
| 2934 | // section in description, return true. |
| 2935 | if (!current_local_msection) |
| 2936 | return true; |
| 2937 |
| 2938 | const MediaContentDescription* current_local_media_description = |
| 2939 | current_local_msection->media_description(); |
| 2940 | // 5.3 If transceiver isn't stopped and is associated with an m= section |
| 2941 | // in description then perform the following checks: |
| 2942 |
| 2943 | // 5.3.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the |
| 2944 | // associated m= section in description either doesn't contain a single |
| 2945 | // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this |
| 2946 | // m= section, or the MSID values themselves, differ from what is in |
| 2947 | // transceiver.sender.[[AssociatedMediaStreamIds]], return true. |
| 2948 | if (RtpTransceiverDirectionHasSend(transceiver->direction())) { |
| 2949 | if (current_local_media_description->streams().size() == 0) |
| 2950 | return true; |
| 2951 |
| 2952 | std::vector<std::string> msection_msids; |
| 2953 | for (const auto& stream : current_local_media_description->streams()) { |
| 2954 | for (const std::string& msid : stream.stream_ids()) |
| 2955 | msection_msids.push_back(msid); |
| 2956 | } |
| 2957 |
| 2958 | std::vector<std::string> transceiver_msids = |
| 2959 | transceiver->sender()->stream_ids(); |
| 2960 | if (msection_msids.size() != transceiver_msids.size()) |
| 2961 | return true; |
| 2962 |
| 2963 | absl::c_sort(transceiver_msids); |
| 2964 | absl::c_sort(msection_msids); |
| 2965 | if (transceiver_msids != msection_msids) |
| 2966 | return true; |
| 2967 | } |
| 2968 |
| 2969 | // 5.3.2 If description is of type "offer", and the direction of the |
| 2970 | // associated m= section in neither connection.[[CurrentLocalDescription]] |
| 2971 | // nor connection.[[CurrentRemoteDescription]] matches |
| 2972 | // transceiver.[[Direction]], return true. |
| 2973 | if (description->GetType() == SdpType::kOffer) { |
| 2974 | if (!current_remote_description()) |
| 2975 | return true; |
| 2976 |
| 2977 | if (!current_remote_msection) |
| 2978 | return true; |
| 2979 |
| 2980 | RtpTransceiverDirection current_local_direction = |
| 2981 | current_local_media_description->direction(); |
| 2982 | RtpTransceiverDirection current_remote_direction = |
| 2983 | current_remote_msection->media_description()->direction(); |
| 2984 | if (transceiver->direction() != current_local_direction && |
| 2985 | transceiver->direction() != |
| 2986 | RtpTransceiverDirectionReversed(current_remote_direction)) { |
| 2987 | return true; |
| 2988 | } |
| 2989 | } |
| 2990 |
| 2991 | // 5.3.3 If description is of type "answer", and the direction of the |
| 2992 | // associated m= section in the description does not match |
| 2993 | // transceiver.[[Direction]] intersected with the offered direction (as |
| 2994 | // described in [JSEP] (section 5.3.1.)), return true. |
| 2995 | if (description->GetType() == SdpType::kAnswer) { |
| 2996 | if (!remote_description()) |
| 2997 | return true; |
| 2998 |
| 2999 | const ContentInfo* offered_remote_msection = |
| 3000 | FindTransceiverMSection(transceiver, remote_description()); |
| 3001 |
| 3002 | RtpTransceiverDirection offered_direction = |
| 3003 | offered_remote_msection |
| 3004 | ? offered_remote_msection->media_description()->direction() |
| 3005 | : RtpTransceiverDirection::kInactive; |
| 3006 |
| 3007 | if (current_local_media_description->direction() != |
| 3008 | (RtpTransceiverDirectionIntersection( |
| 3009 | transceiver->direction(), |
| 3010 | RtpTransceiverDirectionReversed(offered_direction)))) { |
| 3011 | return true; |
| 3012 | } |
| 3013 | } |
| 3014 | } |
| 3015 |
| 3016 | // If all the preceding checks were performed and true was not returned, |
| 3017 | // nothing remains to be negotiated; return false. |
| 3018 | return false; |
| 3019 | } |
| 3020 |
| 3021 | void SdpOfferAnswerHandler::GenerateNegotiationNeededEvent() { |
| 3022 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 3023 | ++negotiation_needed_event_id_; |
| 3024 | pc_->Observer()->OnNegotiationNeededEvent(negotiation_needed_event_id_); |
| 3025 | } |
| 3026 |
| 3027 | RTCError SdpOfferAnswerHandler::ValidateSessionDescription( |
| 3028 | const SessionDescriptionInterface* sdesc, |
| 3029 | cricket::ContentSource source, |
| 3030 | const std::map<std::string, const cricket::ContentGroup*>& |
| 3031 | bundle_groups_by_mid) { |
| 3032 | if (session_error() != SessionError::kNone) { |
| 3033 | LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg()); |
| 3034 | } |
| 3035 |
| 3036 | if (!sdesc || !sdesc->description()) { |
| 3037 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp); |
| 3038 | } |
| 3039 |
| 3040 | SdpType type = sdesc->GetType(); |
| 3041 | if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) || |
| 3042 | (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) { |
| 3043 | LOG_AND_RETURN_ERROR( |
| 3044 | RTCErrorType::INVALID_STATE, |
| 3045 | (rtc::StringBuilder("Called in wrong state: ") |
| 3046 | << PeerConnectionInterface::AsString(signaling_state())) |
| 3047 | .Release()); |
| 3048 | } |
| 3049 |
| 3050 | RTCError error = ValidateMids(*sdesc->description()); |
| 3051 | if (!error.ok()) { |
| 3052 | return error; |
| 3053 | } |
| 3054 |
| 3055 | // Verify crypto settings. |
| 3056 | std::string crypto_error; |
| 3057 | if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED || |
| 3058 | pc_->dtls_enabled()) { |
| 3059 | RTCError crypto_error = VerifyCrypto( |
| 3060 | sdesc->description(), pc_->dtls_enabled(), bundle_groups_by_mid); |
| 3061 | if (!crypto_error.ok()) { |
| 3062 | return crypto_error; |
| 3063 | } |
| 3064 | } |
| 3065 |
| 3066 | // Verify ice-ufrag and ice-pwd. |
| 3067 | if (!VerifyIceUfragPwdPresent(sdesc->description(), bundle_groups_by_mid)) { |
| 3068 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 3069 | kSdpWithoutIceUfragPwd); |
| 3070 | } |
| 3071 |
| 3072 | if (!pc_->ValidateBundleSettings(sdesc->description(), |
| 3073 | bundle_groups_by_mid)) { |
| 3074 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 3075 | kBundleWithoutRtcpMux); |
| 3076 | } |
| 3077 |
| 3078 | // TODO(skvlad): When the local rtcp-mux policy is Require, reject any |
| 3079 | // m-lines that do not rtcp-mux enabled. |
| 3080 |
| 3081 | // Verify m-lines in Answer when compared against Offer. |
| 3082 | if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) { |
| 3083 | // With an answer we want to compare the new answer session description with |
| 3084 | // the offer's session description from the current negotiation. |
| 3085 | const cricket::SessionDescription* offer_desc = |
| 3086 | (source == cricket::CS_LOCAL) ? remote_description()->description() |
| 3087 | : local_description()->description(); |
| 3088 | if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) || |
| 3089 | !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(), |
| 3090 | type)) { |
| 3091 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 3092 | kMlineMismatchInAnswer); |
| 3093 | } |
| 3094 | } else { |
| 3095 | // The re-offers should respect the order of m= sections in current |
| 3096 | // description. See RFC3264 Section 8 paragraph 4 for more details. |
| 3097 | // With a re-offer, either the current local or current remote descriptions |
| 3098 | // could be the most up to date, so we would like to check against both of |
| 3099 | // them if they exist. It could be the case that one of them has a 0 port |
| 3100 | // for a media section, but the other does not. This is important to check |
| 3101 | // against in the case that we are recycling an m= section. |
| 3102 | const cricket::SessionDescription* current_desc = nullptr; |
| 3103 | const cricket::SessionDescription* secondary_current_desc = nullptr; |
| 3104 | if (local_description()) { |
| 3105 | current_desc = local_description()->description(); |
| 3106 | if (remote_description()) { |
| 3107 | secondary_current_desc = remote_description()->description(); |
| 3108 | } |
| 3109 | } else if (remote_description()) { |
| 3110 | current_desc = remote_description()->description(); |
| 3111 | } |
| 3112 | if (current_desc && |
| 3113 | !MediaSectionsInSameOrder(*current_desc, secondary_current_desc, |
| 3114 | *sdesc->description(), type)) { |
| 3115 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 3116 | kMlineMismatchInSubsequentOffer); |
| 3117 | } |
| 3118 | } |
| 3119 |
| 3120 | if (IsUnifiedPlan()) { |
| 3121 | // Ensure that each audio and video media section has at most one |
| 3122 | // "StreamParams". This will return an error if receiving a session |
| 3123 | // description from a "Plan B" endpoint which adds multiple tracks of the |
| 3124 | // same type. With Unified Plan, there can only be at most one track per |
| 3125 | // media section. |
| 3126 | for (const ContentInfo& content : sdesc->description()->contents()) { |
| 3127 | const MediaContentDescription& desc = *content.media_description(); |
| 3128 | if ((desc.type() == cricket::MEDIA_TYPE_AUDIO || |
| 3129 | desc.type() == cricket::MEDIA_TYPE_VIDEO) && |
| 3130 | desc.streams().size() > 1u) { |
| 3131 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 3132 | "Media section has more than one track specified " |
| 3133 | "with a=ssrc lines which is not supported with " |
| 3134 | "Unified Plan."); |
| 3135 | } |
| 3136 | } |
| 3137 | } |
| 3138 |
| 3139 | return RTCError::OK(); |
| 3140 | } |
| 3141 |
| 3142 | RTCError SdpOfferAnswerHandler::UpdateTransceiversAndDataChannels( |
| 3143 | cricket::ContentSource source, |
| 3144 | const SessionDescriptionInterface& new_session, |
| 3145 | const SessionDescriptionInterface* old_local_description, |
| 3146 | const SessionDescriptionInterface* old_remote_description, |
| 3147 | const std::map<std::string, const cricket::ContentGroup*>& |
| 3148 | bundle_groups_by_mid) { |
| 3149 | TRACE_EVENT0("webrtc", |
| 3150 | "SdpOfferAnswerHandler::UpdateTransceiversAndDataChannels"); |
| 3151 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 3152 | RTC_DCHECK(IsUnifiedPlan()); |
| 3153 |
| 3154 | if (new_session.GetType() == SdpType::kOffer) { |
| 3155 | // If the BUNDLE policy is max-bundle, then we know for sure that all |
| 3156 | // transports will be bundled from the start. Return an error if max-bundle |
| 3157 | // is specified but the session description does not have a BUNDLE group. |
| 3158 | if (pc_->configuration()->bundle_policy == |
| 3159 | PeerConnectionInterface::kBundlePolicyMaxBundle && |
| 3160 | bundle_groups_by_mid.empty()) { |
| 3161 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 3162 | "max-bundle configured but session description " |
| 3163 | "has no BUNDLE group"); |
| 3164 | } |
| 3165 | } |
| 3166 |
| 3167 | const ContentInfos& new_contents = new_session.description()->contents(); |
| 3168 | for (size_t i = 0; i < new_contents.size(); ++i) { |
| 3169 | const cricket::ContentInfo& new_content = new_contents[i]; |
| 3170 | cricket::MediaType media_type = new_content.media_description()->type(); |
| 3171 | mid_generator_.AddKnownId(new_content.name); |
| 3172 | auto it = bundle_groups_by_mid.find(new_content.name); |
| 3173 | const cricket::ContentGroup* bundle_group = |
| 3174 | it != bundle_groups_by_mid.end() ? it->second : nullptr; |
| 3175 | if (media_type == cricket::MEDIA_TYPE_AUDIO || |
| 3176 | media_type == cricket::MEDIA_TYPE_VIDEO) { |
| 3177 | const cricket::ContentInfo* old_local_content = nullptr; |
| 3178 | if (old_local_description && |
| 3179 | i < old_local_description->description()->contents().size()) { |
| 3180 | old_local_content = |
| 3181 | &old_local_description->description()->contents()[i]; |
| 3182 | } |
| 3183 | const cricket::ContentInfo* old_remote_content = nullptr; |
| 3184 | if (old_remote_description && |
| 3185 | i < old_remote_description->description()->contents().size()) { |
| 3186 | old_remote_content = |
| 3187 | &old_remote_description->description()->contents()[i]; |
| 3188 | } |
| 3189 | auto transceiver_or_error = |
| 3190 | AssociateTransceiver(source, new_session.GetType(), i, new_content, |
| 3191 | old_local_content, old_remote_content); |
| 3192 | if (!transceiver_or_error.ok()) { |
| 3193 | // In the case where a transceiver is rejected locally, we don't |
| 3194 | // expect to find a transceiver, but might find it in the case |
| 3195 | // where state is still "stopping", not "stopped". |
| 3196 | if (new_content.rejected) { |
| 3197 | continue; |
| 3198 | } |
| 3199 | return transceiver_or_error.MoveError(); |
| 3200 | } |
| 3201 | auto transceiver = transceiver_or_error.MoveValue(); |
| 3202 | RTCError error = |
| 3203 | UpdateTransceiverChannel(transceiver, new_content, bundle_group); |
| 3204 | if (!error.ok()) { |
| 3205 | return error; |
| 3206 | } |
| 3207 | } else if (media_type == cricket::MEDIA_TYPE_DATA) { |
| 3208 | if (pc_->GetDataMid() && new_content.name != *(pc_->GetDataMid())) { |
| 3209 | // Ignore all but the first data section. |
| 3210 | RTC_LOG(LS_INFO) << "Ignoring data media section with MID=" |
| 3211 | << new_content.name; |
| 3212 | continue; |
| 3213 | } |
| 3214 | RTCError error = UpdateDataChannel(source, new_content, bundle_group); |
| 3215 | if (!error.ok()) { |
| 3216 | return error; |
| 3217 | } |
| 3218 | } else if (media_type == cricket::MEDIA_TYPE_UNSUPPORTED) { |
| 3219 | RTC_LOG(LS_INFO) << "Ignoring unsupported media type"; |
| 3220 | } else { |
| 3221 | LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, |
| 3222 | "Unknown section type."); |
| 3223 | } |
| 3224 | } |
| 3225 |
| 3226 | return RTCError::OK(); |
| 3227 | } |
| 3228 |
| 3229 | RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>> |
| 3230 | SdpOfferAnswerHandler::AssociateTransceiver( |
| 3231 | cricket::ContentSource source, |
| 3232 | SdpType type, |
| 3233 | size_t mline_index, |
| 3234 | const ContentInfo& content, |
| 3235 | const ContentInfo* old_local_content, |
| 3236 | const ContentInfo* old_remote_content) { |
| 3237 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::AssociateTransceiver"); |
| 3238 | RTC_DCHECK(IsUnifiedPlan()); |
| 3239 | #if RTC_DCHECK_IS_ON |
| 3240 | // If this is an offer then the m= section might be recycled. If the m= |
| 3241 | // section is being recycled (defined as: rejected in the current local or |
| 3242 | // remote description and not rejected in new description), the transceiver |
| 3243 | // should have been removed by RemoveStoppedtransceivers()-> |
| 3244 | if (IsMediaSectionBeingRecycled(type, content, old_local_content, |
| 3245 | old_remote_content)) { |
| 3246 | const std::string& old_mid = |
| 3247 | (old_local_content && old_local_content->rejected) |
| 3248 | ? old_local_content->name |
| 3249 | : old_remote_content->name; |
| 3250 | auto old_transceiver = transceivers()->FindByMid(old_mid); |
| 3251 | // The transceiver should be disassociated in RemoveStoppedTransceivers() |
| 3252 | RTC_DCHECK(!old_transceiver); |
| 3253 | } |
| 3254 | #endif |
| 3255 |
| 3256 | const MediaContentDescription* media_desc = content.media_description(); |
| 3257 | auto transceiver = transceivers()->FindByMid(content.name); |
| 3258 | if (source == cricket::CS_LOCAL) { |
| 3259 | // Find the RtpTransceiver that corresponds to this m= section, using the |
| 3260 | // mapping between transceivers and m= section indices established when |
| 3261 | // creating the offer. |
| 3262 | if (!transceiver) { |
| 3263 | transceiver = transceivers()->FindByMLineIndex(mline_index); |
| 3264 | } |
| 3265 | if (!transceiver) { |
| 3266 | // This may happen normally when media sections are rejected. |
| 3267 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, |
| 3268 | "Transceiver not found based on m-line index"); |
| 3269 | } |
| 3270 | } else { |
| 3271 | RTC_DCHECK_EQ(source, cricket::CS_REMOTE); |
| 3272 | // If the m= section is sendrecv or recvonly, and there are RtpTransceivers |
| 3273 | // of the same type... |
| 3274 | // When simulcast is requested, a transceiver cannot be associated because |
| 3275 | // AddTrack cannot be called to initialize it. |
| 3276 | if (!transceiver && |
| 3277 | RtpTransceiverDirectionHasRecv(media_desc->direction()) && |
| 3278 | !media_desc->HasSimulcast()) { |
| 3279 | transceiver = FindAvailableTransceiverToReceive(media_desc->type()); |
| 3280 | } |
| 3281 | // If no RtpTransceiver was found in the previous step, create one with a |
| 3282 | // recvonly direction. |
| 3283 | if (!transceiver) { |
| 3284 | RTC_LOG(LS_INFO) << "Adding " |
| 3285 | << cricket::MediaTypeToString(media_desc->type()) |
| 3286 | << " transceiver for MID=" << content.name |
| 3287 | << " at i=" << mline_index |
| 3288 | << " in response to the remote description."; |
| 3289 | std::string sender_id = rtc::CreateRandomUuid(); |
| 3290 | std::vector<RtpEncodingParameters> send_encodings = |
| 3291 | GetSendEncodingsFromRemoteDescription(*media_desc); |
| 3292 | auto sender = rtp_manager()->CreateSender(media_desc->type(), sender_id, |
| 3293 | nullptr, {}, send_encodings); |
| 3294 | std::string receiver_id; |
| 3295 | if (!media_desc->streams().empty()) { |
| 3296 | receiver_id = media_desc->streams()[0].id; |
| 3297 | } else { |
| 3298 | receiver_id = rtc::CreateRandomUuid(); |
| 3299 | } |
| 3300 | auto receiver = |
| 3301 | rtp_manager()->CreateReceiver(media_desc->type(), receiver_id); |
| 3302 | transceiver = rtp_manager()->CreateAndAddTransceiver(sender, receiver); |
| 3303 | transceiver->internal()->set_direction( |
| 3304 | RtpTransceiverDirection::kRecvOnly); |
| 3305 | if (type == SdpType::kOffer) { |
| 3306 | transceivers()->StableState(transceiver)->set_newly_created(); |
| 3307 | } |
| 3308 | } |
| 3309 |
| 3310 | RTC_DCHECK(transceiver); |
| 3311 |
| 3312 | // Check if the offer indicated simulcast but the answer rejected it. |
| 3313 | // This can happen when simulcast is not supported on the remote party. |
| 3314 | if (SimulcastIsRejected(old_local_content, *media_desc, |
| 3315 | pc_->GetCryptoOptions() |
| 3316 | .srtp.enable_encrypted_rtp_header_extensions)) { |
| 3317 | RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true); |
| 3318 | RTCError error = |
| 3319 | DisableSimulcastInSender(transceiver->internal()->sender_internal()); |
| 3320 | if (!error.ok()) { |
| 3321 | RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast."; |
| 3322 | return std::move(error); |
| 3323 | } |
| 3324 | } |
| 3325 | } |
| 3326 |
| 3327 | if (transceiver->media_type() != media_desc->type()) { |
| 3328 | LOG_AND_RETURN_ERROR( |
| 3329 | RTCErrorType::INVALID_PARAMETER, |
| 3330 | "Transceiver type does not match media description type."); |
| 3331 | } |
| 3332 |
| 3333 | if (media_desc->HasSimulcast()) { |
| 3334 | std::vector<SimulcastLayer> layers = |
| 3335 | source == cricket::CS_LOCAL |
| 3336 | ? media_desc->simulcast_description().send_layers().GetAllLayers() |
| 3337 | : media_desc->simulcast_description() |
| 3338 | .receive_layers() |
| 3339 | .GetAllLayers(); |
| 3340 | RTCError error = UpdateSimulcastLayerStatusInSender( |
| 3341 | layers, transceiver->internal()->sender_internal()); |
| 3342 | if (!error.ok()) { |
| 3343 | RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers."; |
| 3344 | return std::move(error); |
| 3345 | } |
| 3346 | } |
| 3347 | if (type == SdpType::kOffer) { |
| 3348 | bool state_changes = transceiver->internal()->mid() != content.name || |
| 3349 | transceiver->internal()->mline_index() != mline_index; |
| 3350 | if (state_changes) { |
| 3351 | transceivers() |
| 3352 | ->StableState(transceiver) |
| 3353 | ->SetMSectionIfUnset(transceiver->internal()->mid(), |
| 3354 | transceiver->internal()->mline_index()); |
| 3355 | } |
| 3356 | } |
| 3357 | // Associate the found or created RtpTransceiver with the m= section by |
| 3358 | // setting the value of the RtpTransceiver's mid property to the MID of the m= |
| 3359 | // section, and establish a mapping between the transceiver and the index of |
| 3360 | // the m= section. |
| 3361 | transceiver->internal()->set_mid(content.name); |
| 3362 | transceiver->internal()->set_mline_index(mline_index); |
| 3363 | return std::move(transceiver); |
| 3364 | } |
| 3365 |
| 3366 | RTCError SdpOfferAnswerHandler::UpdateTransceiverChannel( |
| 3367 | rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>> |
| 3368 | transceiver, |
| 3369 | const cricket::ContentInfo& content, |
| 3370 | const cricket::ContentGroup* bundle_group) { |
| 3371 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::UpdateTransceiverChannel"); |
| 3372 | RTC_DCHECK(IsUnifiedPlan()); |
| 3373 | RTC_DCHECK(transceiver); |
| 3374 | cricket::ChannelInterface* channel = transceiver->internal()->channel(); |
| 3375 | if (content.rejected) { |
| 3376 | if (channel) { |
| 3377 | transceiver->internal()->SetChannel(nullptr); |
| 3378 | DestroyChannelInterface(channel); |
| 3379 | } |
| 3380 | } else { |
| 3381 | if (!channel) { |
| 3382 | if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) { |
| 3383 | channel = CreateVoiceChannel(content.name); |
| 3384 | } else { |
| 3385 | RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type()); |
| 3386 | channel = CreateVideoChannel(content.name); |
| 3387 | } |
| 3388 | if (!channel) { |
| 3389 | LOG_AND_RETURN_ERROR( |
| 3390 | RTCErrorType::INTERNAL_ERROR, |
| 3391 | "Failed to create channel for mid=" + content.name); |
| 3392 | } |
| 3393 | transceiver->internal()->SetChannel(channel); |
| 3394 | } |
| 3395 | } |
| 3396 | return RTCError::OK(); |
| 3397 | } |
| 3398 |
| 3399 | RTCError SdpOfferAnswerHandler::UpdateDataChannel( |
| 3400 | cricket::ContentSource source, |
| 3401 | const cricket::ContentInfo& content, |
| 3402 | const cricket::ContentGroup* bundle_group) { |
| 3403 | if (content.rejected) { |
| 3404 | RTC_LOG(LS_INFO) << "Rejected data channel transport with mid=" |
| 3405 | << content.mid(); |
| 3406 |
| 3407 | rtc::StringBuilder sb; |
| 3408 | sb << "Rejected data channel transport with mid=" << content.mid(); |
| 3409 | RTCError error(RTCErrorType::OPERATION_ERROR_WITH_DATA, sb.Release()); |
| 3410 | error.set_error_detail(RTCErrorDetailType::DATA_CHANNEL_FAILURE); |
| 3411 | DestroyDataChannelTransport(error); |
| 3412 | } else { |
| 3413 | if (!data_channel_controller()->data_channel_transport()) { |
| 3414 | RTC_LOG(LS_INFO) << "Creating data channel, mid=" << content.mid(); |
| 3415 | if (!CreateDataChannel(content.name)) { |
| 3416 | LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, |
| 3417 | "Failed to create data channel."); |
| 3418 | } |
| 3419 | } |
| 3420 | } |
| 3421 | return RTCError::OK(); |
| 3422 | } |
| 3423 |
| 3424 | bool SdpOfferAnswerHandler::ExpectSetLocalDescription(SdpType type) { |
| 3425 | PeerConnectionInterface::SignalingState state = signaling_state(); |
| 3426 | if (type == SdpType::kOffer) { |
| 3427 | return (state == PeerConnectionInterface::kStable) || |
| 3428 | (state == PeerConnectionInterface::kHaveLocalOffer); |
| 3429 | } else { |
| 3430 | RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer); |
| 3431 | return (state == PeerConnectionInterface::kHaveRemoteOffer) || |
| 3432 | (state == PeerConnectionInterface::kHaveLocalPrAnswer); |
| 3433 | } |
| 3434 | } |
| 3435 |
| 3436 | bool SdpOfferAnswerHandler::ExpectSetRemoteDescription(SdpType type) { |
| 3437 | PeerConnectionInterface::SignalingState state = signaling_state(); |
| 3438 | if (type == SdpType::kOffer) { |
| 3439 | return (state == PeerConnectionInterface::kStable) || |
| 3440 | (state == PeerConnectionInterface::kHaveRemoteOffer); |
| 3441 | } else { |
| 3442 | RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer); |
| 3443 | return (state == PeerConnectionInterface::kHaveLocalOffer) || |
| 3444 | (state == PeerConnectionInterface::kHaveRemotePrAnswer); |
| 3445 | } |
| 3446 | } |
| 3447 |
| 3448 | void SdpOfferAnswerHandler::FillInMissingRemoteMids( |
| 3449 | cricket::SessionDescription* new_remote_description) { |
| 3450 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 3451 | RTC_DCHECK(new_remote_description); |
| 3452 | const cricket::ContentInfos no_infos; |
| 3453 | const cricket::ContentInfos& local_contents = |
| 3454 | (local_description() ? local_description()->description()->contents() |
| 3455 | : no_infos); |
| 3456 | const cricket::ContentInfos& remote_contents = |
| 3457 | (remote_description() ? remote_description()->description()->contents() |
| 3458 | : no_infos); |
| 3459 | for (size_t i = 0; i < new_remote_description->contents().size(); ++i) { |
| 3460 | cricket::ContentInfo& content = new_remote_description->contents()[i]; |
| 3461 | if (!content.name.empty()) { |
| 3462 | continue; |
| 3463 | } |
| 3464 | std::string new_mid; |
| 3465 | absl::string_view source_explanation; |
| 3466 | if (IsUnifiedPlan()) { |
| 3467 | if (i < local_contents.size()) { |
| 3468 | new_mid = local_contents[i].name; |
| 3469 | source_explanation = "from the matching local media section"; |
| 3470 | } else if (i < remote_contents.size()) { |
| 3471 | new_mid = remote_contents[i].name; |
| 3472 | source_explanation = "from the matching previous remote media section"; |
| 3473 | } else { |
| 3474 | new_mid = mid_generator_.GenerateString(); |
| 3475 | source_explanation = "generated just now"; |
| 3476 | } |
| 3477 | } else { |
| 3478 | new_mid = std::string( |
| 3479 | GetDefaultMidForPlanB(content.media_description()->type())); |
| 3480 | source_explanation = "to match pre-existing behavior"; |
| 3481 | } |
| 3482 | RTC_DCHECK(!new_mid.empty()); |
| 3483 | content.name = new_mid; |
| 3484 | new_remote_description->transport_infos()[i].content_name = new_mid; |
| 3485 | RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i |
| 3486 | << " is missing an a=mid line. Filling in the value '" |
| 3487 | << new_mid << "' " << source_explanation << "."; |
| 3488 | } |
| 3489 | } |
| 3490 |
| 3491 | rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>> |
| 3492 | SdpOfferAnswerHandler::FindAvailableTransceiverToReceive( |
| 3493 | cricket::MediaType media_type) const { |
| 3494 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 3495 | RTC_DCHECK(IsUnifiedPlan()); |
| 3496 | // From JSEP section 5.10 (Applying a Remote Description): |
| 3497 | // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of |
| 3498 | // the same type that were added to the PeerConnection by addTrack and are not |
| 3499 | // associated with any m= section and are not stopped, find the first such |
| 3500 | // RtpTransceiver. |
| 3501 | for (auto transceiver : transceivers()->List()) { |
| 3502 | if (transceiver->media_type() == media_type && |
| 3503 | transceiver->internal()->created_by_addtrack() && !transceiver->mid() && |
| 3504 | !transceiver->stopped()) { |
| 3505 | return transceiver; |
| 3506 | } |
| 3507 | } |
| 3508 | return nullptr; |
| 3509 | } |
| 3510 |
| 3511 | const cricket::ContentInfo* |
| 3512 | SdpOfferAnswerHandler::FindMediaSectionForTransceiver( |
| 3513 | const RtpTransceiver* transceiver, |
| 3514 | const SessionDescriptionInterface* sdesc) const { |
| 3515 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 3516 | RTC_DCHECK(transceiver); |
| 3517 | RTC_DCHECK(sdesc); |
| 3518 | if (IsUnifiedPlan()) { |
| 3519 | if (!transceiver->mid()) { |
| 3520 | // This transceiver is not associated with a media section yet. |
| 3521 | return nullptr; |
| 3522 | } |
| 3523 | return sdesc->description()->GetContentByName(*transceiver->mid()); |
| 3524 | } else { |
| 3525 | // Plan B only allows at most one audio and one video section, so use the |
| 3526 | // first media section of that type. |
| 3527 | return cricket::GetFirstMediaContent(sdesc->description()->contents(), |
| 3528 | transceiver->media_type()); |
| 3529 | } |
| 3530 | } |
| 3531 |
| 3532 | void SdpOfferAnswerHandler::GetOptionsForOffer( |
| 3533 | const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options, |
| 3534 | cricket::MediaSessionOptions* session_options) { |
| 3535 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 3536 | ExtractSharedMediaSessionOptions(offer_answer_options, session_options); |
| 3537 |
| 3538 | if (IsUnifiedPlan()) { |
| 3539 | GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options); |
| 3540 | } else { |
| 3541 | GetOptionsForPlanBOffer(offer_answer_options, session_options); |
| 3542 | } |
| 3543 |
| 3544 | // Apply ICE restart flag and renomination flag. |
| 3545 | bool ice_restart = offer_answer_options.ice_restart || HasNewIceCredentials(); |
| 3546 | for (auto& options : session_options->media_description_options) { |
| 3547 | options.transport_options.ice_restart = ice_restart; |
| 3548 | options.transport_options.enable_ice_renomination = |
| 3549 | pc_->configuration()->enable_ice_renomination; |
| 3550 | } |
| 3551 |
| 3552 | session_options->rtcp_cname = rtcp_cname_; |
| 3553 | session_options->crypto_options = pc_->GetCryptoOptions(); |
| 3554 | session_options->pooled_ice_credentials = |
| 3555 | pc_->network_thread()->Invoke<std::vector<cricket::IceParameters>>( |
| 3556 | RTC_FROM_HERE, |
| 3557 | [this] { return port_allocator()->GetPooledIceCredentials(); }); |
| 3558 | session_options->offer_extmap_allow_mixed = |
| 3559 | pc_->configuration()->offer_extmap_allow_mixed; |
| 3560 |
| 3561 | // Allow fallback for using obsolete SCTP syntax. |
| 3562 | // Note that the default in `session_options` is true, while |
| 3563 | // the default in `options` is false. |
| 3564 | session_options->use_obsolete_sctp_sdp = |
| 3565 | offer_answer_options.use_obsolete_sctp_sdp; |
| 3566 | } |
| 3567 |
| 3568 | void SdpOfferAnswerHandler::GetOptionsForPlanBOffer( |
| 3569 | const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options, |
| 3570 | cricket::MediaSessionOptions* session_options) { |
| 3571 | // Figure out transceiver directional preferences. |
| 3572 | bool send_audio = |
| 3573 | !rtp_manager()->GetAudioTransceiver()->internal()->senders().empty(); |
| 3574 | bool send_video = |
| 3575 | !rtp_manager()->GetVideoTransceiver()->internal()->senders().empty(); |
| 3576 |
| 3577 | // By default, generate sendrecv/recvonly m= sections. |
| 3578 | bool recv_audio = true; |
| 3579 | bool recv_video = true; |
| 3580 |
| 3581 | // By default, only offer a new m= section if we have media to send with it. |
| 3582 | bool offer_new_audio_description = send_audio; |
| 3583 | bool offer_new_video_description = send_video; |
| 3584 | bool offer_new_data_description = |
| 3585 | data_channel_controller()->HasDataChannels(); |
| 3586 |
| 3587 | // The "offer_to_receive_X" options allow those defaults to be overridden. |
| 3588 | if (offer_answer_options.offer_to_receive_audio != |
| 3589 | PeerConnectionInterface::RTCOfferAnswerOptions::kUndefined) { |
| 3590 | recv_audio = (offer_answer_options.offer_to_receive_audio > 0); |
| 3591 | offer_new_audio_description = |
| 3592 | offer_new_audio_description || |
| 3593 | (offer_answer_options.offer_to_receive_audio > 0); |
| 3594 | } |
| 3595 | if (offer_answer_options.offer_to_receive_video != |
| 3596 | RTCOfferAnswerOptions::kUndefined) { |
| 3597 | recv_video = (offer_answer_options.offer_to_receive_video > 0); |
| 3598 | offer_new_video_description = |
| 3599 | offer_new_video_description || |
| 3600 | (offer_answer_options.offer_to_receive_video > 0); |
| 3601 | } |
| 3602 |
| 3603 | absl::optional<size_t> audio_index; |
| 3604 | absl::optional<size_t> video_index; |
| 3605 | absl::optional<size_t> data_index; |
| 3606 | // If a current description exists, generate m= sections in the same order, |
| 3607 | // using the first audio/video/data section that appears and rejecting |
| 3608 | // extraneous ones. |
| 3609 | if (local_description()) { |
| 3610 | GenerateMediaDescriptionOptions( |
| 3611 | local_description(), |
| 3612 | RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio), |
| 3613 | RtpTransceiverDirectionFromSendRecv(send_video, recv_video), |
| 3614 | &audio_index, &video_index, &data_index, session_options); |
| 3615 | } |
| 3616 |
| 3617 | // Add audio/video/data m= sections to the end if needed. |
| 3618 | if (!audio_index && offer_new_audio_description) { |
| 3619 | cricket::MediaDescriptionOptions options( |
| 3620 | cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO, |
| 3621 | RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio), false); |
| 3622 | options.header_extensions = |
| 3623 | channel_manager()->GetSupportedAudioRtpHeaderExtensions(); |
| 3624 | session_options->media_description_options.push_back(options); |
| 3625 | audio_index = session_options->media_description_options.size() - 1; |
| 3626 | } |
| 3627 | if (!video_index && offer_new_video_description) { |
| 3628 | cricket::MediaDescriptionOptions options( |
| 3629 | cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO, |
| 3630 | RtpTransceiverDirectionFromSendRecv(send_video, recv_video), false); |
| 3631 | options.header_extensions = |
| 3632 | channel_manager()->GetSupportedVideoRtpHeaderExtensions(); |
| 3633 | session_options->media_description_options.push_back(options); |
| 3634 | video_index = session_options->media_description_options.size() - 1; |
| 3635 | } |
| 3636 | if (!data_index && offer_new_data_description) { |
| 3637 | session_options->media_description_options.push_back( |
| 3638 | GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA)); |
| 3639 | data_index = session_options->media_description_options.size() - 1; |
| 3640 | } |
| 3641 |
| 3642 | cricket::MediaDescriptionOptions* audio_media_description_options = |
| 3643 | !audio_index ? nullptr |
| 3644 | : &session_options->media_description_options[*audio_index]; |
| 3645 | cricket::MediaDescriptionOptions* video_media_description_options = |
| 3646 | !video_index ? nullptr |
| 3647 | : &session_options->media_description_options[*video_index]; |
| 3648 |
| 3649 | AddPlanBRtpSenderOptions(rtp_manager()->GetSendersInternal(), |
| 3650 | audio_media_description_options, |
| 3651 | video_media_description_options, |
| 3652 | offer_answer_options.num_simulcast_layers); |
| 3653 | } |
| 3654 |
| 3655 | void SdpOfferAnswerHandler::GetOptionsForUnifiedPlanOffer( |
| 3656 | const RTCOfferAnswerOptions& offer_answer_options, |
| 3657 | cricket::MediaSessionOptions* session_options) { |
| 3658 | // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial |
| 3659 | // Offers) and 5.2.2 (Subsequent Offers). |
| 3660 | RTC_DCHECK_EQ(session_options->media_description_options.size(), 0); |
| 3661 | const ContentInfos no_infos; |
| 3662 | const ContentInfos& local_contents = |
| 3663 | (local_description() ? local_description()->description()->contents() |
| 3664 | : no_infos); |
| 3665 | const ContentInfos& remote_contents = |
| 3666 | (remote_description() ? remote_description()->description()->contents() |
| 3667 | : no_infos); |
| 3668 | // The mline indices that can be recycled. New transceivers should reuse these |
| 3669 | // slots first. |
| 3670 | std::queue<size_t> recycleable_mline_indices; |
| 3671 | // First, go through each media section that exists in either the local or |
| 3672 | // remote description and generate a media section in this offer for the |
| 3673 | // associated transceiver. If a media section can be recycled, generate a |
| 3674 | // default, rejected media section here that can be later overwritten. |
| 3675 | for (size_t i = 0; |
| 3676 | i < std::max(local_contents.size(), remote_contents.size()); ++i) { |
| 3677 | // Either `local_content` or `remote_content` is non-null. |
| 3678 | const ContentInfo* local_content = |
| 3679 | (i < local_contents.size() ? &local_contents[i] : nullptr); |
| 3680 | const ContentInfo* current_local_content = |
| 3681 | GetContentByIndex(current_local_description(), i); |
| 3682 | const ContentInfo* remote_content = |
| 3683 | (i < remote_contents.size() ? &remote_contents[i] : nullptr); |
| 3684 | const ContentInfo* current_remote_content = |
| 3685 | GetContentByIndex(current_remote_description(), i); |
| 3686 | bool had_been_rejected = |
| 3687 | (current_local_content && current_local_content->rejected) || |
| 3688 | (current_remote_content && current_remote_content->rejected); |
| 3689 | const std::string& mid = |
| 3690 | (local_content ? local_content->name : remote_content->name); |
| 3691 | cricket::MediaType media_type = |
| 3692 | (local_content ? local_content->media_description()->type() |
| 3693 | : remote_content->media_description()->type()); |
| 3694 | if (media_type == cricket::MEDIA_TYPE_AUDIO || |
| 3695 | media_type == cricket::MEDIA_TYPE_VIDEO) { |
| 3696 | // A media section is considered eligible for recycling if it is marked as |
| 3697 | // rejected in either the current local or current remote description. |
| 3698 | auto transceiver = transceivers()->FindByMid(mid); |
| 3699 | if (!transceiver) { |
| 3700 | // No associated transceiver. The media section has been stopped. |
| 3701 | recycleable_mline_indices.push(i); |
| 3702 | session_options->media_description_options.push_back( |
| 3703 | cricket::MediaDescriptionOptions(media_type, mid, |
| 3704 | RtpTransceiverDirection::kInactive, |
| 3705 | /*stopped=*/true)); |
| 3706 | } else { |
| 3707 | // NOTE: a stopping transceiver should be treated as a stopped one in |
| 3708 | // createOffer as specified in |
| 3709 | // https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-createoffer. |
| 3710 | if (had_been_rejected && transceiver->stopping()) { |
| 3711 | session_options->media_description_options.push_back( |
| 3712 | cricket::MediaDescriptionOptions( |
| 3713 | transceiver->media_type(), mid, |
| 3714 | RtpTransceiverDirection::kInactive, |
| 3715 | /*stopped=*/true)); |
| 3716 | recycleable_mline_indices.push(i); |
| 3717 | } else { |
| 3718 | session_options->media_description_options.push_back( |
| 3719 | GetMediaDescriptionOptionsForTransceiver( |
| 3720 | transceiver->internal(), mid, |
| 3721 | /*is_create_offer=*/true)); |
| 3722 | // CreateOffer shouldn't really cause any state changes in |
| 3723 | // PeerConnection, but we need a way to match new transceivers to new |
| 3724 | // media sections in SetLocalDescription and JSEP specifies this is |
| 3725 | // done by recording the index of the media section generated for the |
| 3726 | // transceiver in the offer. |
| 3727 | transceiver->internal()->set_mline_index(i); |
| 3728 | } |
| 3729 | } |
| 3730 | } else if (media_type == cricket::MEDIA_TYPE_UNSUPPORTED) { |
| 3731 | RTC_DCHECK(local_content->rejected); |
| 3732 | session_options->media_description_options.push_back( |
| 3733 | cricket::MediaDescriptionOptions(media_type, mid, |
| 3734 | RtpTransceiverDirection::kInactive, |
| 3735 | /*stopped=*/true)); |
| 3736 | } else { |
| 3737 | RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type); |
| 3738 | if (had_been_rejected) { |
| 3739 | session_options->media_description_options.push_back( |
| 3740 | GetMediaDescriptionOptionsForRejectedData(mid)); |
| 3741 | } else { |
| 3742 | RTC_CHECK(pc_->GetDataMid()); |
| 3743 | if (mid == *(pc_->GetDataMid())) { |
| 3744 | session_options->media_description_options.push_back( |
| 3745 | GetMediaDescriptionOptionsForActiveData(mid)); |
| 3746 | } else { |
| 3747 | session_options->media_description_options.push_back( |
| 3748 | GetMediaDescriptionOptionsForRejectedData(mid)); |
| 3749 | } |
| 3750 | } |
| 3751 | } |
| 3752 | } |
| 3753 |
| 3754 | // Next, look for transceivers that are newly added (that is, are not stopped |
| 3755 | // and not associated). Reuse media sections marked as recyclable first, |
| 3756 | // otherwise append to the end of the offer. New media sections should be |
| 3757 | // added in the order they were added to the PeerConnection. |
| 3758 | for (const auto& transceiver : transceivers()->ListInternal()) { |
| 3759 | if (transceiver->mid() || transceiver->stopping()) { |
| 3760 | continue; |
| 3761 | } |
| 3762 | size_t mline_index; |
| 3763 | if (!recycleable_mline_indices.empty()) { |
| 3764 | mline_index = recycleable_mline_indices.front(); |
| 3765 | recycleable_mline_indices.pop(); |
| 3766 | session_options->media_description_options[mline_index] = |
| 3767 | GetMediaDescriptionOptionsForTransceiver( |
| 3768 | transceiver, mid_generator_.GenerateString(), |
| 3769 | /*is_create_offer=*/true); |
| 3770 | } else { |
| 3771 | mline_index = session_options->media_description_options.size(); |
| 3772 | session_options->media_description_options.push_back( |
| 3773 | GetMediaDescriptionOptionsForTransceiver( |
| 3774 | transceiver, mid_generator_.GenerateString(), |
| 3775 | /*is_create_offer=*/true)); |
| 3776 | } |
| 3777 | // See comment above for why CreateOffer changes the transceiver's state. |
| 3778 | transceiver->set_mline_index(mline_index); |
| 3779 | } |
| 3780 | // Lastly, add a m-section if we have local data channels and an m section |
| 3781 | // does not already exist. |
| 3782 | if (!pc_->GetDataMid() && data_channel_controller()->HasDataChannels()) { |
| 3783 | session_options->media_description_options.push_back( |
| 3784 | GetMediaDescriptionOptionsForActiveData( |
| 3785 | mid_generator_.GenerateString())); |
| 3786 | } |
| 3787 | } |
| 3788 |
| 3789 | void SdpOfferAnswerHandler::GetOptionsForAnswer( |
| 3790 | const RTCOfferAnswerOptions& offer_answer_options, |
| 3791 | cricket::MediaSessionOptions* session_options) { |
| 3792 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 3793 | ExtractSharedMediaSessionOptions(offer_answer_options, session_options); |
| 3794 |
| 3795 | if (IsUnifiedPlan()) { |
| 3796 | GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options); |
| 3797 | } else { |
| 3798 | GetOptionsForPlanBAnswer(offer_answer_options, session_options); |
| 3799 | } |
| 3800 |
| 3801 | // Apply ICE renomination flag. |
| 3802 | for (auto& options : session_options->media_description_options) { |
| 3803 | options.transport_options.enable_ice_renomination = |
| 3804 | pc_->configuration()->enable_ice_renomination; |
| 3805 | } |
| 3806 |
| 3807 | session_options->rtcp_cname = rtcp_cname_; |
| 3808 | session_options->crypto_options = pc_->GetCryptoOptions(); |
| 3809 | session_options->pooled_ice_credentials = |
| 3810 | pc_->network_thread()->Invoke<std::vector<cricket::IceParameters>>( |
| 3811 | RTC_FROM_HERE, |
| 3812 | [this] { return port_allocator()->GetPooledIceCredentials(); }); |
| 3813 | } |
| 3814 |
| 3815 | void SdpOfferAnswerHandler::GetOptionsForPlanBAnswer( |
| 3816 | const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options, |
| 3817 | cricket::MediaSessionOptions* session_options) { |
| 3818 | // Figure out transceiver directional preferences. |
| 3819 | bool send_audio = |
| 3820 | !rtp_manager()->GetAudioTransceiver()->internal()->senders().empty(); |
| 3821 | bool send_video = |
| 3822 | !rtp_manager()->GetVideoTransceiver()->internal()->senders().empty(); |
| 3823 |
| 3824 | // By default, generate sendrecv/recvonly m= sections. The direction is also |
| 3825 | // restricted by the direction in the offer. |
| 3826 | bool recv_audio = true; |
| 3827 | bool recv_video = true; |
| 3828 |
| 3829 | // The "offer_to_receive_X" options allow those defaults to be overridden. |
| 3830 | if (offer_answer_options.offer_to_receive_audio != |
| 3831 | RTCOfferAnswerOptions::kUndefined) { |
| 3832 | recv_audio = (offer_answer_options.offer_to_receive_audio > 0); |
| 3833 | } |
| 3834 | if (offer_answer_options.offer_to_receive_video != |
| 3835 | RTCOfferAnswerOptions::kUndefined) { |
| 3836 | recv_video = (offer_answer_options.offer_to_receive_video > 0); |
| 3837 | } |
| 3838 |
| 3839 | absl::optional<size_t> audio_index; |
| 3840 | absl::optional<size_t> video_index; |
| 3841 | absl::optional<size_t> data_index; |
| 3842 |
| 3843 | // Generate m= sections that match those in the offer. |
| 3844 | // Note that mediasession.cc will handle intersection our preferred |
| 3845 | // direction with the offered direction. |
| 3846 | GenerateMediaDescriptionOptions( |
| 3847 | remote_description(), |
| 3848 | RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio), |
| 3849 | RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index, |
| 3850 | &video_index, &data_index, session_options); |
| 3851 |
| 3852 | cricket::MediaDescriptionOptions* audio_media_description_options = |
| 3853 | !audio_index ? nullptr |
| 3854 | : &session_options->media_description_options[*audio_index]; |
| 3855 | cricket::MediaDescriptionOptions* video_media_description_options = |
| 3856 | !video_index ? nullptr |
| 3857 | : &session_options->media_description_options[*video_index]; |
| 3858 |
| 3859 | AddPlanBRtpSenderOptions(rtp_manager()->GetSendersInternal(), |
| 3860 | audio_media_description_options, |
| 3861 | video_media_description_options, |
| 3862 | offer_answer_options.num_simulcast_layers); |
| 3863 | } |
| 3864 |
| 3865 | void SdpOfferAnswerHandler::GetOptionsForUnifiedPlanAnswer( |
| 3866 | const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options, |
| 3867 | cricket::MediaSessionOptions* session_options) { |
| 3868 | // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial |
| 3869 | // Answers) and 5.3.2 (Subsequent Answers). |
| 3870 | RTC_DCHECK(remote_description()); |
| 3871 | RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer); |
| 3872 | for (const ContentInfo& content : |
| 3873 | remote_description()->description()->contents()) { |
| 3874 | cricket::MediaType media_type = content.media_description()->type(); |
| 3875 | if (media_type == cricket::MEDIA_TYPE_AUDIO || |
| 3876 | media_type == cricket::MEDIA_TYPE_VIDEO) { |
| 3877 | auto transceiver = transceivers()->FindByMid(content.name); |
| 3878 | if (transceiver) { |
| 3879 | session_options->media_description_options.push_back( |
| 3880 | GetMediaDescriptionOptionsForTransceiver( |
| 3881 | transceiver->internal(), content.name, |
| 3882 | /*is_create_offer=*/false)); |
| 3883 | } else { |
| 3884 | // This should only happen with rejected transceivers. |
| 3885 | RTC_DCHECK(content.rejected); |
| 3886 | session_options->media_description_options.push_back( |
| 3887 | cricket::MediaDescriptionOptions(media_type, content.name, |
| 3888 | RtpTransceiverDirection::kInactive, |
| 3889 | /*stopped=*/true)); |
| 3890 | } |
| 3891 | } else if (media_type == cricket::MEDIA_TYPE_UNSUPPORTED) { |
| 3892 | RTC_DCHECK(content.rejected); |
| 3893 | session_options->media_description_options.push_back( |
| 3894 | cricket::MediaDescriptionOptions(media_type, content.name, |
| 3895 | RtpTransceiverDirection::kInactive, |
| 3896 | /*stopped=*/true)); |
| 3897 | } else { |
| 3898 | RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type); |
| 3899 | // Reject all data sections if data channels are disabled. |
| 3900 | // Reject a data section if it has already been rejected. |
| 3901 | // Reject all data sections except for the first one. |
| 3902 | if (content.rejected || content.name != *(pc_->GetDataMid())) { |
| 3903 | session_options->media_description_options.push_back( |
| 3904 | GetMediaDescriptionOptionsForRejectedData(content.name)); |
| 3905 | } else { |
| 3906 | session_options->media_description_options.push_back( |
| 3907 | GetMediaDescriptionOptionsForActiveData(content.name)); |
| 3908 | } |
| 3909 | } |
| 3910 | } |
| 3911 | } |
| 3912 |
| 3913 | const char* SdpOfferAnswerHandler::SessionErrorToString( |
| 3914 | SessionError error) const { |
| 3915 | switch (error) { |
| 3916 | case SessionError::kNone: |
| 3917 | return "ERROR_NONE"; |
| 3918 | case SessionError::kContent: |
| 3919 | return "ERROR_CONTENT"; |
| 3920 | case SessionError::kTransport: |
| 3921 | return "ERROR_TRANSPORT"; |
| 3922 | } |
| 3923 | RTC_DCHECK_NOTREACHED(); |
| 3924 | return ""; |
| 3925 | } |
| 3926 |
| 3927 | std::string SdpOfferAnswerHandler::GetSessionErrorMsg() { |
| 3928 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 3929 | rtc::StringBuilder desc; |
| 3930 | desc << kSessionError << SessionErrorToString(session_error()) << ". "; |
| 3931 | desc << kSessionErrorDesc << session_error_desc() << "."; |
| 3932 | return desc.Release(); |
| 3933 | } |
| 3934 |
| 3935 | void SdpOfferAnswerHandler::SetSessionError(SessionError error, |
| 3936 | const std::string& error_desc) { |
| 3937 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 3938 | if (error != session_error_) { |
| 3939 | session_error_ = error; |
| 3940 | session_error_desc_ = error_desc; |
| 3941 | } |
| 3942 | } |
| 3943 |
| 3944 | RTCError SdpOfferAnswerHandler::HandleLegacyOfferOptions( |
| 3945 | const PeerConnectionInterface::RTCOfferAnswerOptions& options) { |
| 3946 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 3947 | RTC_DCHECK(IsUnifiedPlan()); |
| 3948 |
| 3949 | if (options.offer_to_receive_audio == 0) { |
| 3950 | RemoveRecvDirectionFromReceivingTransceiversOfType( |
| 3951 | cricket::MEDIA_TYPE_AUDIO); |
| 3952 | } else if (options.offer_to_receive_audio == 1) { |
| 3953 | AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO); |
| 3954 | } else if (options.offer_to_receive_audio > 1) { |
| 3955 | LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER, |
| 3956 | "offer_to_receive_audio > 1 is not supported."); |
| 3957 | } |
| 3958 |
| 3959 | if (options.offer_to_receive_video == 0) { |
| 3960 | RemoveRecvDirectionFromReceivingTransceiversOfType( |
| 3961 | cricket::MEDIA_TYPE_VIDEO); |
| 3962 | } else if (options.offer_to_receive_video == 1) { |
| 3963 | AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO); |
| 3964 | } else if (options.offer_to_receive_video > 1) { |
| 3965 | LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER, |
| 3966 | "offer_to_receive_video > 1 is not supported."); |
| 3967 | } |
| 3968 |
| 3969 | return RTCError::OK(); |
| 3970 | } |
| 3971 |
| 3972 | void SdpOfferAnswerHandler::RemoveRecvDirectionFromReceivingTransceiversOfType( |
| 3973 | cricket::MediaType media_type) { |
| 3974 | for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) { |
| 3975 | RtpTransceiverDirection new_direction = |
| 3976 | RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false); |
| 3977 | if (new_direction != transceiver->direction()) { |
| 3978 | RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type) |
| 3979 | << " transceiver (MID=" |
| 3980 | << transceiver->mid().value_or("<not set>") << ") from " |
| 3981 | << RtpTransceiverDirectionToString( |
| 3982 | transceiver->direction()) |
| 3983 | << " to " |
| 3984 | << RtpTransceiverDirectionToString(new_direction) |
| 3985 | << " since CreateOffer specified offer_to_receive=0"; |
| 3986 | transceiver->internal()->set_direction(new_direction); |
| 3987 | } |
| 3988 | } |
| 3989 | } |
| 3990 |
| 3991 | void SdpOfferAnswerHandler::AddUpToOneReceivingTransceiverOfType( |
| 3992 | cricket::MediaType media_type) { |
| 3993 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 3994 | if (GetReceivingTransceiversOfType(media_type).empty()) { |
| 3995 | RTC_LOG(LS_INFO) |
| 3996 | << "Adding one recvonly " << cricket::MediaTypeToString(media_type) |
| 3997 | << " transceiver since CreateOffer specified offer_to_receive=1"; |
| 3998 | RtpTransceiverInit init; |
| 3999 | init.direction = RtpTransceiverDirection::kRecvOnly; |
| 4000 | pc_->AddTransceiver(media_type, nullptr, init, |
| 4001 | /*update_negotiation_needed=*/false); |
| 4002 | } |
| 4003 | } |
| 4004 |
| 4005 | std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>> |
| 4006 | SdpOfferAnswerHandler::GetReceivingTransceiversOfType( |
| 4007 | cricket::MediaType media_type) { |
| 4008 | std::vector< |
| 4009 | rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>> |
| 4010 | receiving_transceivers; |
| 4011 | for (const auto& transceiver : transceivers()->List()) { |
| 4012 | if (!transceiver->stopped() && transceiver->media_type() == media_type && |
| 4013 | RtpTransceiverDirectionHasRecv(transceiver->direction())) { |
| 4014 | receiving_transceivers.push_back(transceiver); |
| 4015 | } |
| 4016 | } |
| 4017 | return receiving_transceivers; |
| 4018 | } |
| 4019 |
| 4020 | void SdpOfferAnswerHandler::ProcessRemovalOfRemoteTrack( |
| 4021 | rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>> |
| 4022 | transceiver, |
| 4023 | std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list, |
| 4024 | std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) { |
| 4025 | RTC_DCHECK(transceiver->mid()); |
| 4026 | RTC_LOG(LS_INFO) << "Processing the removal of a track for MID=" |
| 4027 | << *transceiver->mid(); |
| 4028 | std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams = |
| 4029 | transceiver->internal()->receiver_internal()->streams(); |
| 4030 | // This will remove the remote track from the streams. |
| 4031 | transceiver->internal()->receiver_internal()->set_stream_ids({}); |
| 4032 | remove_list->push_back(transceiver); |
| 4033 | RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams); |
| 4034 | } |
| 4035 |
| 4036 | void SdpOfferAnswerHandler::RemoveRemoteStreamsIfEmpty( |
| 4037 | const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams, |
| 4038 | std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) { |
| 4039 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4040 | // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of |
| 4041 | // streams, see if the stream was removed by checking if this was the last |
| 4042 | // receiver with that stream ID. |
| 4043 | for (const auto& remote_stream : remote_streams) { |
| 4044 | if (remote_stream->GetAudioTracks().empty() && |
| 4045 | remote_stream->GetVideoTracks().empty()) { |
| 4046 | remote_streams_->RemoveStream(remote_stream); |
| 4047 | removed_streams->push_back(remote_stream); |
| 4048 | } |
| 4049 | } |
| 4050 | } |
| 4051 |
| 4052 | void SdpOfferAnswerHandler::RemoveSenders(cricket::MediaType media_type) { |
| 4053 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4054 | UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type); |
| 4055 | UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false, |
| 4056 | media_type, nullptr); |
| 4057 | } |
| 4058 |
| 4059 | void SdpOfferAnswerHandler::UpdateLocalSenders( |
| 4060 | const std::vector<cricket::StreamParams>& streams, |
| 4061 | cricket::MediaType media_type) { |
| 4062 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::UpdateLocalSenders"); |
| 4063 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4064 | std::vector<RtpSenderInfo>* current_senders = |
| 4065 | rtp_manager()->GetLocalSenderInfos(media_type); |
| 4066 |
| 4067 | // Find removed tracks. I.e., tracks where the track id, stream id or ssrc |
| 4068 | // don't match the new StreamParam. |
| 4069 | for (auto sender_it = current_senders->begin(); |
| 4070 | sender_it != current_senders->end(); |
| 4071 | /* incremented manually */) { |
| 4072 | const RtpSenderInfo& info = *sender_it; |
| 4073 | const cricket::StreamParams* params = |
| 4074 | cricket::GetStreamBySsrc(streams, info.first_ssrc); |
| 4075 | if (!params || params->id != info.sender_id || |
| 4076 | params->first_stream_id() != info.stream_id) { |
| 4077 | rtp_manager()->OnLocalSenderRemoved(info, media_type); |
| 4078 | sender_it = current_senders->erase(sender_it); |
| 4079 | } else { |
| 4080 | ++sender_it; |
| 4081 | } |
| 4082 | } |
| 4083 |
| 4084 | // Find new and active senders. |
| 4085 | for (const cricket::StreamParams& params : streams) { |
| 4086 | // The sync_label is the MediaStream label and the `stream.id` is the |
| 4087 | // sender id. |
| 4088 | const std::string& stream_id = params.first_stream_id(); |
| 4089 | const std::string& sender_id = params.id; |
| 4090 | uint32_t ssrc = params.first_ssrc(); |
| 4091 | const RtpSenderInfo* sender_info = |
| 4092 | rtp_manager()->FindSenderInfo(*current_senders, stream_id, sender_id); |
| 4093 | if (!sender_info) { |
| 4094 | current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc)); |
| 4095 | rtp_manager()->OnLocalSenderAdded(current_senders->back(), media_type); |
| 4096 | } |
| 4097 | } |
| 4098 | } |
| 4099 |
| 4100 | void SdpOfferAnswerHandler::UpdateRemoteSendersList( |
| 4101 | const cricket::StreamParamsVec& streams, |
| 4102 | bool default_sender_needed, |
| 4103 | cricket::MediaType media_type, |
| 4104 | StreamCollection* new_streams) { |
| 4105 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::UpdateRemoteSendersList"); |
| 4106 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4107 | RTC_DCHECK(!IsUnifiedPlan()); |
| 4108 |
| 4109 | std::vector<RtpSenderInfo>* current_senders = |
| 4110 | rtp_manager()->GetRemoteSenderInfos(media_type); |
| 4111 |
| 4112 | // Find removed senders. I.e., senders where the sender id or ssrc don't match |
| 4113 | // the new StreamParam. |
| 4114 | for (auto sender_it = current_senders->begin(); |
| 4115 | sender_it != current_senders->end(); |
| 4116 | /* incremented manually */) { |
| 4117 | const RtpSenderInfo& info = *sender_it; |
| 4118 | const cricket::StreamParams* params = |
| 4119 | cricket::GetStreamBySsrc(streams, info.first_ssrc); |
| 4120 | std::string params_stream_id; |
| 4121 | if (params) { |
| 4122 | params_stream_id = |
| 4123 | (!params->first_stream_id().empty() ? params->first_stream_id() |
| 4124 | : kDefaultStreamId); |
| 4125 | } |
| 4126 | bool sender_exists = params && params->id == info.sender_id && |
| 4127 | params_stream_id == info.stream_id; |
| 4128 | // If this is a default track, and we still need it, don't remove it. |
| 4129 | if ((info.stream_id == kDefaultStreamId && default_sender_needed) || |
| 4130 | sender_exists) { |
| 4131 | ++sender_it; |
| 4132 | } else { |
| 4133 | rtp_manager()->OnRemoteSenderRemoved( |
| 4134 | info, remote_streams_->find(info.stream_id), media_type); |
| 4135 | sender_it = current_senders->erase(sender_it); |
| 4136 | } |
| 4137 | } |
| 4138 |
| 4139 | // Find new and active senders. |
| 4140 | for (const cricket::StreamParams& params : streams) { |
| 4141 | if (!params.has_ssrcs()) { |
| 4142 | // The remote endpoint has streams, but didn't signal ssrcs. For an active |
| 4143 | // sender, this means it is coming from a Unified Plan endpoint,so we just |
| 4144 | // create a default. |
| 4145 | default_sender_needed = true; |
| 4146 | break; |
| 4147 | } |
| 4148 |
| 4149 | // `params.id` is the sender id and the stream id uses the first of |
| 4150 | // `params.stream_ids`. The remote description could come from a Unified |
| 4151 | // Plan endpoint, with multiple or no stream_ids() signaled. Since this is |
| 4152 | // not supported in Plan B, we just take the first here and create the |
| 4153 | // default stream ID if none is specified. |
| 4154 | const std::string& stream_id = |
| 4155 | (!params.first_stream_id().empty() ? params.first_stream_id() |
| 4156 | : kDefaultStreamId); |
| 4157 | const std::string& sender_id = params.id; |
| 4158 | uint32_t ssrc = params.first_ssrc(); |
| 4159 |
| 4160 | rtc::scoped_refptr<MediaStreamInterface> stream = |
| 4161 | remote_streams_->find(stream_id); |
| 4162 | if (!stream) { |
| 4163 | // This is a new MediaStream. Create a new remote MediaStream. |
| 4164 | stream = MediaStreamProxy::Create(rtc::Thread::Current(), |
| 4165 | MediaStream::Create(stream_id)); |
| 4166 | remote_streams_->AddStream(stream); |
| 4167 | new_streams->AddStream(stream); |
| 4168 | } |
| 4169 |
| 4170 | const RtpSenderInfo* sender_info = |
| 4171 | rtp_manager()->FindSenderInfo(*current_senders, stream_id, sender_id); |
| 4172 | if (!sender_info) { |
| 4173 | current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc)); |
| 4174 | rtp_manager()->OnRemoteSenderAdded(current_senders->back(), stream, |
| 4175 | media_type); |
| 4176 | } |
| 4177 | } |
| 4178 |
| 4179 | // Add default sender if necessary. |
| 4180 | if (default_sender_needed) { |
| 4181 | rtc::scoped_refptr<MediaStreamInterface> default_stream = |
| 4182 | remote_streams_->find(kDefaultStreamId); |
| 4183 | if (!default_stream) { |
| 4184 | // Create the new default MediaStream. |
| 4185 | default_stream = MediaStreamProxy::Create( |
| 4186 | rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId)); |
| 4187 | remote_streams_->AddStream(default_stream); |
| 4188 | new_streams->AddStream(default_stream); |
| 4189 | } |
| 4190 | std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO) |
| 4191 | ? kDefaultAudioSenderId |
| 4192 | : kDefaultVideoSenderId; |
| 4193 | const RtpSenderInfo* default_sender_info = rtp_manager()->FindSenderInfo( |
| 4194 | *current_senders, kDefaultStreamId, default_sender_id); |
| 4195 | if (!default_sender_info) { |
| 4196 | current_senders->push_back( |
| 4197 | RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0)); |
| 4198 | rtp_manager()->OnRemoteSenderAdded(current_senders->back(), |
| 4199 | default_stream, media_type); |
| 4200 | } |
| 4201 | } |
| 4202 | } |
| 4203 |
| 4204 | void SdpOfferAnswerHandler::EnableSending() { |
| 4205 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::EnableSending"); |
| 4206 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4207 | for (const auto& transceiver : transceivers()->ListInternal()) { |
| 4208 | cricket::ChannelInterface* channel = transceiver->channel(); |
| 4209 | if (channel) { |
| 4210 | channel->Enable(true); |
| 4211 | } |
| 4212 | } |
| 4213 | } |
| 4214 |
| 4215 | RTCError SdpOfferAnswerHandler::PushdownMediaDescription( |
| 4216 | SdpType type, |
| 4217 | cricket::ContentSource source, |
| 4218 | const std::map<std::string, const cricket::ContentGroup*>& |
| 4219 | bundle_groups_by_mid) { |
| 4220 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::PushdownMediaDescription"); |
| 4221 | const SessionDescriptionInterface* sdesc = |
| 4222 | (source == cricket::CS_LOCAL ? local_description() |
| 4223 | : remote_description()); |
| 4224 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4225 | RTC_DCHECK(sdesc); |
| 4226 |
| 4227 | if (!UpdatePayloadTypeDemuxingState(source, bundle_groups_by_mid)) { |
| 4228 | // Note that this is never expected to fail, since RtpDemuxer doesn't return |
| 4229 | // an error when changing payload type demux criteria, which is all this |
| 4230 | // does. |
| 4231 | LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, |
| 4232 | "Failed to update payload type demuxing state."); |
| 4233 | } |
| 4234 |
| 4235 | // Push down the new SDP media section for each audio/video transceiver. |
| 4236 | auto rtp_transceivers = transceivers()->ListInternal(); |
| 4237 | std::vector< |
| 4238 | std::pair<cricket::ChannelInterface*, const MediaContentDescription*>> |
| 4239 | channels; |
| 4240 | for (const auto& transceiver : rtp_transceivers) { |
| 4241 | const ContentInfo* content_info = |
| 4242 | FindMediaSectionForTransceiver(transceiver, sdesc); |
| 4243 | cricket::ChannelInterface* channel = transceiver->channel(); |
| 4244 | if (!channel || !content_info || content_info->rejected) { |
| 4245 | continue; |
| 4246 | } |
| 4247 | const MediaContentDescription* content_desc = |
| 4248 | content_info->media_description(); |
| 4249 | if (!content_desc) { |
| 4250 | continue; |
| 4251 | } |
| 4252 |
| 4253 | transceiver->OnNegotiationUpdate(type, content_desc); |
| 4254 | channels.push_back(std::make_pair(channel, content_desc)); |
| 4255 | } |
| 4256 |
| 4257 | // This for-loop of invokes helps audio impairment during re-negotiations. |
| 4258 | // One of the causes is that downstairs decoder creation is synchronous at the |
| 4259 | // moment, and that a decoder is created for each codec listed in the SDP. |
| 4260 | // |
| 4261 | // TODO(bugs.webrtc.org/12840): consider merging the invokes again after |
| 4262 | // these projects have shipped: |
| 4263 | // - bugs.webrtc.org/12462 |
| 4264 | // - crbug.com/1157227 |
| 4265 | // - crbug.com/1187289 |
| 4266 | for (const auto& entry : channels) { |
| 4267 | RTCError error = |
| 4268 | pc_->worker_thread()->Invoke<RTCError>(RTC_FROM_HERE, [&]() { |
| 4269 | std::string error; |
| 4270 | bool success = |
| 4271 | (source == cricket::CS_LOCAL) |
| 4272 | ? entry.first->SetLocalContent(entry.second, type, &error) |
| 4273 | : entry.first->SetRemoteContent(entry.second, type, &error); |
| 4274 | if (!success) { |
| 4275 | LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error); |
| 4276 | } |
| 4277 | return RTCError::OK(); |
| 4278 | }); |
| 4279 | if (!error.ok()) { |
| 4280 | return error; |
| 4281 | } |
| 4282 | } |
| 4283 |
| 4284 | // Need complete offer/answer with an SCTP m= section before starting SCTP, |
| 4285 | // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19 |
| 4286 | if (pc_->sctp_mid() && local_description() && remote_description()) { |
| 4287 | auto local_sctp_description = cricket::GetFirstSctpDataContentDescription( |
| 4288 | local_description()->description()); |
| 4289 | auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription( |
| 4290 | remote_description()->description()); |
| 4291 | if (local_sctp_description && remote_sctp_description) { |
| 4292 | int max_message_size; |
| 4293 | // A remote max message size of zero means "any size supported". |
| 4294 | // We configure the connection with our own max message size. |
| 4295 | if (remote_sctp_description->max_message_size() == 0) { |
| 4296 | max_message_size = local_sctp_description->max_message_size(); |
| 4297 | } else { |
| 4298 | max_message_size = |
| 4299 | std::min(local_sctp_description->max_message_size(), |
| 4300 | remote_sctp_description->max_message_size()); |
| 4301 | } |
| 4302 | pc_->StartSctpTransport(local_sctp_description->port(), |
| 4303 | remote_sctp_description->port(), |
| 4304 | max_message_size); |
| 4305 | } |
| 4306 | } |
| 4307 |
| 4308 | return RTCError::OK(); |
| 4309 | } |
| 4310 |
| 4311 | RTCError SdpOfferAnswerHandler::PushdownTransportDescription( |
| 4312 | cricket::ContentSource source, |
| 4313 | SdpType type) { |
| 4314 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::PushdownTransportDescription"); |
| 4315 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4316 |
| 4317 | if (source == cricket::CS_LOCAL) { |
| 4318 | const SessionDescriptionInterface* sdesc = local_description(); |
| 4319 | RTC_DCHECK(sdesc); |
| 4320 | return transport_controller()->SetLocalDescription(type, |
| 4321 | sdesc->description()); |
| 4322 | } else { |
| 4323 | const SessionDescriptionInterface* sdesc = remote_description(); |
| 4324 | RTC_DCHECK(sdesc); |
| 4325 | return transport_controller()->SetRemoteDescription(type, |
| 4326 | sdesc->description()); |
| 4327 | } |
| 4328 | } |
| 4329 |
| 4330 | void SdpOfferAnswerHandler::RemoveStoppedTransceivers() { |
| 4331 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::RemoveStoppedTransceivers"); |
| 4332 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4333 | // 3.2.10.1: For each transceiver in the connection's set of transceivers |
| 4334 | // run the following steps: |
| 4335 | if (!IsUnifiedPlan()) |
| 4336 | return; |
| 4337 | // Traverse a copy of the transceiver list. |
| 4338 | auto transceiver_list = transceivers()->List(); |
| 4339 | for (auto transceiver : transceiver_list) { |
| 4340 | // 3.2.10.1.1: If transceiver is stopped, associated with an m= section |
| 4341 | // and the associated m= section is rejected in |
| 4342 | // connection.[[CurrentLocalDescription]] or |
| 4343 | // connection.[[CurrentRemoteDescription]], remove the |
| 4344 | // transceiver from the connection's set of transceivers. |
| 4345 | if (!transceiver->stopped()) { |
| 4346 | continue; |
| 4347 | } |
| 4348 | const ContentInfo* local_content = FindMediaSectionForTransceiver( |
| 4349 | transceiver->internal(), local_description()); |
| 4350 | const ContentInfo* remote_content = FindMediaSectionForTransceiver( |
| 4351 | transceiver->internal(), remote_description()); |
| 4352 | if ((local_content && local_content->rejected) || |
| 4353 | (remote_content && remote_content->rejected)) { |
| 4354 | RTC_LOG(LS_INFO) << "Dissociating transceiver" |
| 4355 | " since the media section is being recycled."; |
| 4356 | transceiver->internal()->set_mid(absl::nullopt); |
| 4357 | transceiver->internal()->set_mline_index(absl::nullopt); |
| 4358 | } else if (!local_content && !remote_content) { |
| 4359 | // TODO(bugs.webrtc.org/11973): Consider if this should be removed already |
| 4360 | // See https://github.com/w3c/webrtc-pc/issues/2576 |
| 4361 | RTC_LOG(LS_INFO) |
| 4362 | << "Dropping stopped transceiver that was never associated"; |
| 4363 | } |
| 4364 | transceivers()->Remove(transceiver); |
| 4365 | } |
| 4366 | } |
| 4367 |
| 4368 | void SdpOfferAnswerHandler::RemoveUnusedChannels( |
| 4369 | const SessionDescription* desc) { |
| 4370 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4371 | // Destroy video channel first since it may have a pointer to the |
| 4372 | // voice channel. |
| 4373 | const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc); |
| 4374 | if (!video_info || video_info->rejected) { |
| 4375 | DestroyTransceiverChannel(rtp_manager()->GetVideoTransceiver()); |
| 4376 | } |
| 4377 |
| 4378 | const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc); |
| 4379 | if (!audio_info || audio_info->rejected) { |
| 4380 | DestroyTransceiverChannel(rtp_manager()->GetAudioTransceiver()); |
| 4381 | } |
| 4382 |
| 4383 | const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc); |
| 4384 | if (!data_info) { |
| 4385 | RTCError error(RTCErrorType::OPERATION_ERROR_WITH_DATA, |
| 4386 | "No data channel section in the description."); |
| 4387 | error.set_error_detail(RTCErrorDetailType::DATA_CHANNEL_FAILURE); |
| 4388 | DestroyDataChannelTransport(error); |
| 4389 | } else if (data_info->rejected) { |
| 4390 | rtc::StringBuilder sb; |
| 4391 | sb << "Rejected data channel with mid=" << data_info->name << "."; |
| 4392 |
| 4393 | RTCError error(RTCErrorType::OPERATION_ERROR_WITH_DATA, sb.Release()); |
| 4394 | error.set_error_detail(RTCErrorDetailType::DATA_CHANNEL_FAILURE); |
| 4395 | DestroyDataChannelTransport(error); |
| 4396 | } |
| 4397 | } |
| 4398 |
| 4399 | void SdpOfferAnswerHandler::ReportNegotiatedSdpSemantics( |
| 4400 | const SessionDescriptionInterface& answer) { |
| 4401 | SdpSemanticNegotiated semantics_negotiated; |
| 4402 | switch (answer.description()->msid_signaling()) { |
| 4403 | case 0: |
| 4404 | semantics_negotiated = kSdpSemanticNegotiatedNone; |
| 4405 | break; |
| 4406 | case cricket::kMsidSignalingMediaSection: |
| 4407 | semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan; |
| 4408 | break; |
| 4409 | case cricket::kMsidSignalingSsrcAttribute: |
| 4410 | semantics_negotiated = kSdpSemanticNegotiatedPlanB; |
| 4411 | break; |
| 4412 | case cricket::kMsidSignalingMediaSection | |
| 4413 | cricket::kMsidSignalingSsrcAttribute: |
| 4414 | semantics_negotiated = kSdpSemanticNegotiatedMixed; |
| 4415 | break; |
| 4416 | default: |
| 4417 | RTC_DCHECK_NOTREACHED(); |
| 4418 | } |
| 4419 | RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated", |
| 4420 | semantics_negotiated, kSdpSemanticNegotiatedMax); |
| 4421 | } |
| 4422 |
| 4423 | void SdpOfferAnswerHandler::UpdateEndedRemoteMediaStreams() { |
| 4424 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4425 | std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove; |
| 4426 | for (size_t i = 0; i < remote_streams_->count(); ++i) { |
| 4427 | MediaStreamInterface* stream = remote_streams_->at(i); |
| 4428 | if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) { |
| 4429 | streams_to_remove.push_back(stream); |
| 4430 | } |
| 4431 | } |
| 4432 |
| 4433 | for (auto& stream : streams_to_remove) { |
| 4434 | remote_streams_->RemoveStream(stream); |
| 4435 | pc_->Observer()->OnRemoveStream(std::move(stream)); |
| 4436 | } |
| 4437 | } |
| 4438 |
| 4439 | bool SdpOfferAnswerHandler::UseCandidatesInSessionDescription( |
| 4440 | const SessionDescriptionInterface* remote_desc) { |
| 4441 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4442 | if (!remote_desc) { |
| 4443 | return true; |
| 4444 | } |
| 4445 | bool ret = true; |
| 4446 |
| 4447 | for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) { |
| 4448 | const IceCandidateCollection* candidates = remote_desc->candidates(m); |
| 4449 | for (size_t n = 0; n < candidates->count(); ++n) { |
| 4450 | const IceCandidateInterface* candidate = candidates->at(n); |
| 4451 | bool valid = false; |
| 4452 | if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) { |
| 4453 | if (valid) { |
| 4454 | RTC_LOG(LS_INFO) |
| 4455 | << "UseCandidatesInSessionDescription: Not ready to use " |
| 4456 | "candidate."; |
| 4457 | } |
| 4458 | continue; |
| 4459 | } |
| 4460 | ret = UseCandidate(candidate); |
| 4461 | if (!ret) { |
| 4462 | break; |
| 4463 | } |
| 4464 | } |
| 4465 | } |
| 4466 | return ret; |
| 4467 | } |
| 4468 |
| 4469 | bool SdpOfferAnswerHandler::UseCandidate( |
| 4470 | const IceCandidateInterface* candidate) { |
| 4471 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4472 |
| 4473 | rtc::Thread::ScopedDisallowBlockingCalls no_blocking_calls; |
| 4474 |
| 4475 | RTCErrorOr<const cricket::ContentInfo*> result = |
| 4476 | FindContentInfo(remote_description(), candidate); |
| 4477 | if (!result.ok()) |
| 4478 | return false; |
| 4479 |
| 4480 | const cricket::Candidate& c = candidate->candidate(); |
| 4481 | RTCError error = cricket::VerifyCandidate(c); |
| 4482 | if (!error.ok()) { |
| 4483 | RTC_LOG(LS_WARNING) << "Invalid candidate: " << c.ToString(); |
| 4484 | return true; |
| 4485 | } |
| 4486 |
| 4487 | pc_->AddRemoteCandidate(result.value()->name, c); |
| 4488 |
| 4489 | return true; |
| 4490 | } |
| 4491 |
| 4492 | // We need to check the local/remote description for the Transport instead of |
| 4493 | // the session, because a new Transport added during renegotiation may have |
| 4494 | // them unset while the session has them set from the previous negotiation. |
| 4495 | // Not doing so may trigger the auto generation of transport description and |
| 4496 | // mess up DTLS identity information, ICE credential, etc. |
| 4497 | bool SdpOfferAnswerHandler::ReadyToUseRemoteCandidate( |
| 4498 | const IceCandidateInterface* candidate, |
| 4499 | const SessionDescriptionInterface* remote_desc, |
| 4500 | bool* valid) { |
| 4501 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4502 | *valid = true; |
| 4503 |
| 4504 | const SessionDescriptionInterface* current_remote_desc = |
| 4505 | remote_desc ? remote_desc : remote_description(); |
| 4506 |
| 4507 | if (!current_remote_desc) { |
| 4508 | return false; |
| 4509 | } |
| 4510 |
| 4511 | RTCErrorOr<const cricket::ContentInfo*> result = |
| 4512 | FindContentInfo(current_remote_desc, candidate); |
| 4513 | if (!result.ok()) { |
| 4514 | RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. " |
| 4515 | << result.error().message(); |
| 4516 |
| 4517 | *valid = false; |
| 4518 | return false; |
| 4519 | } |
| 4520 |
| 4521 | return true; |
| 4522 | } |
| 4523 |
| 4524 | RTCErrorOr<const cricket::ContentInfo*> SdpOfferAnswerHandler::FindContentInfo( |
| 4525 | const SessionDescriptionInterface* description, |
| 4526 | const IceCandidateInterface* candidate) { |
| 4527 | if (!candidate->sdp_mid().empty()) { |
| 4528 | auto& contents = description->description()->contents(); |
| 4529 | auto it = absl::c_find_if( |
| 4530 | contents, [candidate](const cricket::ContentInfo& content_info) { |
| 4531 | return content_info.mid() == candidate->sdp_mid(); |
| 4532 | }); |
| 4533 | if (it == contents.end()) { |
| 4534 | return RTCError( |
| 4535 | RTCErrorType::INVALID_PARAMETER, |
| 4536 | "Mid " + candidate->sdp_mid() + |
| 4537 | " specified but no media section with that mid found."); |
| 4538 | } else { |
| 4539 | return &*it; |
| 4540 | } |
| 4541 | } else if (candidate->sdp_mline_index() >= 0) { |
| 4542 | size_t mediacontent_index = |
| 4543 | static_cast<size_t>(candidate->sdp_mline_index()); |
| 4544 | size_t content_size = description->description()->contents().size(); |
| 4545 | if (mediacontent_index < content_size) { |
| 4546 | return &description->description()->contents()[mediacontent_index]; |
| 4547 | } else { |
| 4548 | return RTCError(RTCErrorType::INVALID_RANGE, |
| 4549 | "Media line index (" + |
| 4550 | rtc::ToString(candidate->sdp_mline_index()) + |
| 4551 | ") out of range (number of mlines: " + |
| 4552 | rtc::ToString(content_size) + ")."); |
| 4553 | } |
| 4554 | } |
| 4555 |
| 4556 | return RTCError(RTCErrorType::INVALID_PARAMETER, |
| 4557 | "Neither sdp_mline_index nor sdp_mid specified."); |
| 4558 | } |
| 4559 |
| 4560 | RTCError SdpOfferAnswerHandler::CreateChannels(const SessionDescription& desc) { |
| 4561 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::CreateChannels"); |
| 4562 | // Creating the media channels. Transports should already have been created |
| 4563 | // at this point. |
| 4564 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4565 | const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc); |
| 4566 | if (voice && !voice->rejected && |
| 4567 | !rtp_manager()->GetAudioTransceiver()->internal()->channel()) { |
| 4568 | cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name); |
| 4569 | if (!voice_channel) { |
| 4570 | LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, |
| 4571 | "Failed to create voice channel."); |
| 4572 | } |
| 4573 | rtp_manager()->GetAudioTransceiver()->internal()->SetChannel(voice_channel); |
| 4574 | } |
| 4575 |
| 4576 | const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc); |
| 4577 | if (video && !video->rejected && |
| 4578 | !rtp_manager()->GetVideoTransceiver()->internal()->channel()) { |
| 4579 | cricket::VideoChannel* video_channel = CreateVideoChannel(video->name); |
| 4580 | if (!video_channel) { |
| 4581 | LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, |
| 4582 | "Failed to create video channel."); |
| 4583 | } |
| 4584 | rtp_manager()->GetVideoTransceiver()->internal()->SetChannel(video_channel); |
| 4585 | } |
| 4586 |
| 4587 | const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc); |
| 4588 | if (data && !data->rejected && |
| 4589 | !data_channel_controller()->data_channel_transport()) { |
| 4590 | if (!CreateDataChannel(data->name)) { |
| 4591 | LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, |
| 4592 | "Failed to create data channel."); |
| 4593 | } |
| 4594 | } |
| 4595 |
| 4596 | return RTCError::OK(); |
| 4597 | } |
| 4598 |
| 4599 | // TODO(steveanton): Perhaps this should be managed by the RtpTransceiver. |
| 4600 | cricket::VoiceChannel* SdpOfferAnswerHandler::CreateVoiceChannel( |
| 4601 | const std::string& mid) { |
| 4602 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::CreateVoiceChannel"); |
| 4603 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4604 | if (!channel_manager()->media_engine()) |
| 4605 | return nullptr; |
| 4606 |
| 4607 | RtpTransportInternal* rtp_transport = pc_->GetRtpTransport(mid); |
| 4608 |
| 4609 | // TODO(bugs.webrtc.org/11992): CreateVoiceChannel internally switches to the |
| 4610 | // worker thread. We shouldn't be using the `call_ptr_` hack here but simply |
| 4611 | // be on the worker thread and use `call_` (update upstream code). |
| 4612 | return channel_manager()->CreateVoiceChannel( |
| 4613 | pc_->call_ptr(), pc_->configuration()->media_config, rtp_transport, |
| 4614 | signaling_thread(), mid, pc_->SrtpRequired(), pc_->GetCryptoOptions(), |
| 4615 | &ssrc_generator_, audio_options()); |
| 4616 | } |
| 4617 |
| 4618 | // TODO(steveanton): Perhaps this should be managed by the RtpTransceiver. |
| 4619 | cricket::VideoChannel* SdpOfferAnswerHandler::CreateVideoChannel( |
| 4620 | const std::string& mid) { |
| 4621 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::CreateVideoChannel"); |
| 4622 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4623 | if (!channel_manager()->media_engine()) |
| 4624 | return nullptr; |
| 4625 |
| 4626 | // NOTE: This involves a non-ideal hop (Invoke) over to the network thread. |
| 4627 | RtpTransportInternal* rtp_transport = pc_->GetRtpTransport(mid); |
| 4628 |
| 4629 | // TODO(bugs.webrtc.org/11992): CreateVideoChannel internally switches to the |
| 4630 | // worker thread. We shouldn't be using the `call_ptr_` hack here but simply |
| 4631 | // be on the worker thread and use `call_` (update upstream code). |
| 4632 | return channel_manager()->CreateVideoChannel( |
| 4633 | pc_->call_ptr(), pc_->configuration()->media_config, rtp_transport, |
| 4634 | signaling_thread(), mid, pc_->SrtpRequired(), pc_->GetCryptoOptions(), |
| 4635 | &ssrc_generator_, video_options(), |
| 4636 | video_bitrate_allocator_factory_.get()); |
| 4637 | } |
| 4638 |
| 4639 | bool SdpOfferAnswerHandler::CreateDataChannel(const std::string& mid) { |
| 4640 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4641 | if (!pc_->network_thread()->Invoke<bool>(RTC_FROM_HERE, [this, &mid] { |
| 4642 | RTC_DCHECK_RUN_ON(pc_->network_thread()); |
| 4643 | return pc_->SetupDataChannelTransport_n(mid); |
| 4644 | })) { |
| 4645 | return false; |
| 4646 | } |
| 4647 | // TODO(tommi): Is this necessary? SetupDataChannelTransport_n() above |
| 4648 | // will have queued up updating the transport name on the signaling thread |
| 4649 | // and could update the mid at the same time. This here is synchronous |
| 4650 | // though, but it changes the state of PeerConnection and makes it be |
| 4651 | // out of sync (transport name not set while the mid is set). |
| 4652 | pc_->SetSctpDataMid(mid); |
| 4653 | return true; |
| 4654 | } |
| 4655 |
| 4656 | void SdpOfferAnswerHandler::DestroyTransceiverChannel( |
| 4657 | rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>> |
| 4658 | transceiver) { |
| 4659 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::DestroyTransceiverChannel"); |
| 4660 | RTC_DCHECK(transceiver); |
| 4661 | RTC_LOG_THREAD_BLOCK_COUNT(); |
| 4662 |
| 4663 | // TODO(tommi): We're currently on the signaling thread. |
| 4664 | // There are multiple hops to the worker ahead. |
| 4665 | // Consider if we can make the call to SetChannel() on the worker thread |
| 4666 | // (and require that to be the context it's always called in) and also |
| 4667 | // call DestroyChannelInterface there, since it also needs to hop to the |
| 4668 | // worker. |
| 4669 |
| 4670 | cricket::ChannelInterface* channel = transceiver->internal()->channel(); |
| 4671 | RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(0); |
| 4672 | if (channel) { |
| 4673 | // TODO(tommi): VideoRtpReceiver::SetMediaChannel blocks and jumps to the |
| 4674 | // worker thread. When being set to nullptr, there are additional |
| 4675 | // blocking calls to e.g. ClearRecordableEncodedFrameCallback which triggers |
| 4676 | // another blocking call or Stop() for video channels. |
| 4677 | // The channel object also needs to be de-initialized on the network thread |
| 4678 | // so if ownership of the channel object lies with the transceiver, we could |
| 4679 | // un-set the channel pointer and uninitialize/destruct the channel object |
| 4680 | // at the same time, rather than in separate steps. |
| 4681 | transceiver->internal()->SetChannel(nullptr); |
| 4682 | // TODO(tommi): All channel objects end up getting deleted on the |
| 4683 | // worker thread (ideally should be on the network thread but the |
| 4684 | // MediaChannel objects are tied to the worker. Can the teardown be done |
| 4685 | // asynchronously across the threads rather than blocking? |
| 4686 | DestroyChannelInterface(channel); |
| 4687 | } |
| 4688 | } |
| 4689 |
| 4690 | void SdpOfferAnswerHandler::DestroyDataChannelTransport(RTCError error) { |
| 4691 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4692 | const bool has_sctp = pc_->sctp_mid().has_value(); |
| 4693 |
| 4694 | if (has_sctp) |
| 4695 | data_channel_controller()->OnTransportChannelClosed(error); |
| 4696 |
| 4697 | pc_->network_thread()->Invoke<void>(RTC_FROM_HERE, [this] { |
| 4698 | RTC_DCHECK_RUN_ON(pc_->network_thread()); |
| 4699 | pc_->TeardownDataChannelTransport_n(); |
| 4700 | }); |
| 4701 |
| 4702 | if (has_sctp) |
| 4703 | pc_->ResetSctpDataMid(); |
| 4704 | } |
| 4705 |
| 4706 | void SdpOfferAnswerHandler::DestroyChannelInterface( |
| 4707 | cricket::ChannelInterface* channel) { |
| 4708 | TRACE_EVENT0("webrtc", "SdpOfferAnswerHandler::DestroyChannelInterface"); |
| 4709 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4710 | RTC_DCHECK(channel_manager()->media_engine()); |
| 4711 | RTC_DCHECK(channel); |
| 4712 |
| 4713 | // TODO(bugs.webrtc.org/11992): All the below methods should be called on the |
| 4714 | // worker thread. (they switch internally anyway). Change |
| 4715 | // DestroyChannelInterface to either be called on the worker thread, or do |
| 4716 | // this asynchronously on the worker. |
| 4717 | RTC_LOG_THREAD_BLOCK_COUNT(); |
| 4718 |
| 4719 | switch (channel->media_type()) { |
| 4720 | case cricket::MEDIA_TYPE_AUDIO: |
| 4721 | channel_manager()->DestroyVoiceChannel( |
| 4722 | static_cast<cricket::VoiceChannel*>(channel)); |
| 4723 | break; |
| 4724 | case cricket::MEDIA_TYPE_VIDEO: |
| 4725 | channel_manager()->DestroyVideoChannel( |
| 4726 | static_cast<cricket::VideoChannel*>(channel)); |
| 4727 | break; |
| 4728 | case cricket::MEDIA_TYPE_DATA: |
| 4729 | RTC_DCHECK_NOTREACHED() |
| 4730 | << "Trying to destroy datachannel through DestroyChannelInterface"; |
| 4731 | break; |
| 4732 | default: |
| 4733 | RTC_DCHECK_NOTREACHED() |
| 4734 | << "Unknown media type: " << channel->media_type(); |
| 4735 | break; |
| 4736 | } |
| 4737 |
| 4738 | // TODO(tommi): Figure out why we can get 2 blocking calls when running |
| 4739 | // PeerConnectionCryptoTest.CreateAnswerWithDifferentSslRoles. |
| 4740 | // and 3 when running |
| 4741 | // PeerConnectionCryptoTest.CreateAnswerWithDifferentSslRoles |
| 4742 | // RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(1); |
| 4743 | } |
| 4744 |
| 4745 | void SdpOfferAnswerHandler::DestroyAllChannels() { |
| 4746 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4747 | if (!transceivers()) { |
| 4748 | return; |
| 4749 | } |
| 4750 |
| 4751 | RTC_LOG_THREAD_BLOCK_COUNT(); |
| 4752 |
| 4753 | // Destroy video channels first since they may have a pointer to a voice |
| 4754 | // channel. |
| 4755 | auto list = transceivers()->List(); |
| 4756 | RTC_DCHECK_BLOCK_COUNT_NO_MORE_THAN(0); |
| 4757 |
| 4758 | for (const auto& transceiver : list) { |
| 4759 | if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) { |
| 4760 | DestroyTransceiverChannel(transceiver); |
| 4761 | } |
| 4762 | } |
| 4763 | for (const auto& transceiver : list) { |
| 4764 | if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) { |
| 4765 | DestroyTransceiverChannel(transceiver); |
| 4766 | } |
| 4767 | } |
| 4768 |
| 4769 | DestroyDataChannelTransport({}); |
| 4770 | } |
| 4771 |
| 4772 | void SdpOfferAnswerHandler::GenerateMediaDescriptionOptions( |
| 4773 | const SessionDescriptionInterface* session_desc, |
| 4774 | RtpTransceiverDirection audio_direction, |
| 4775 | RtpTransceiverDirection video_direction, |
| 4776 | absl::optional<size_t>* audio_index, |
| 4777 | absl::optional<size_t>* video_index, |
| 4778 | absl::optional<size_t>* data_index, |
| 4779 | cricket::MediaSessionOptions* session_options) { |
| 4780 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4781 | for (const cricket::ContentInfo& content : |
| 4782 | session_desc->description()->contents()) { |
| 4783 | if (IsAudioContent(&content)) { |
| 4784 | // If we already have an audio m= section, reject this extra one. |
| 4785 | if (*audio_index) { |
| 4786 | session_options->media_description_options.push_back( |
| 4787 | cricket::MediaDescriptionOptions( |
| 4788 | cricket::MEDIA_TYPE_AUDIO, content.name, |
| 4789 | RtpTransceiverDirection::kInactive, /*stopped=*/true)); |
| 4790 | } else { |
| 4791 | bool stopped = (audio_direction == RtpTransceiverDirection::kInactive); |
| 4792 | session_options->media_description_options.push_back( |
| 4793 | cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO, |
| 4794 | content.name, audio_direction, |
| 4795 | stopped)); |
| 4796 | *audio_index = session_options->media_description_options.size() - 1; |
| 4797 | } |
| 4798 | session_options->media_description_options.back().header_extensions = |
| 4799 | channel_manager()->GetSupportedAudioRtpHeaderExtensions(); |
| 4800 | } else if (IsVideoContent(&content)) { |
| 4801 | // If we already have an video m= section, reject this extra one. |
| 4802 | if (*video_index) { |
| 4803 | session_options->media_description_options.push_back( |
| 4804 | cricket::MediaDescriptionOptions( |
| 4805 | cricket::MEDIA_TYPE_VIDEO, content.name, |
| 4806 | RtpTransceiverDirection::kInactive, /*stopped=*/true)); |
| 4807 | } else { |
| 4808 | bool stopped = (video_direction == RtpTransceiverDirection::kInactive); |
| 4809 | session_options->media_description_options.push_back( |
| 4810 | cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO, |
| 4811 | content.name, video_direction, |
| 4812 | stopped)); |
| 4813 | *video_index = session_options->media_description_options.size() - 1; |
| 4814 | } |
| 4815 | session_options->media_description_options.back().header_extensions = |
| 4816 | channel_manager()->GetSupportedVideoRtpHeaderExtensions(); |
| 4817 | } else if (IsUnsupportedContent(&content)) { |
| 4818 | session_options->media_description_options.push_back( |
| 4819 | cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_UNSUPPORTED, |
| 4820 | content.name, |
| 4821 | RtpTransceiverDirection::kInactive, |
| 4822 | /*stopped=*/true)); |
| 4823 | } else { |
| 4824 | RTC_DCHECK(IsDataContent(&content)); |
| 4825 | // If we already have an data m= section, reject this extra one. |
| 4826 | if (*data_index) { |
| 4827 | session_options->media_description_options.push_back( |
| 4828 | GetMediaDescriptionOptionsForRejectedData(content.name)); |
| 4829 | } else { |
| 4830 | session_options->media_description_options.push_back( |
| 4831 | GetMediaDescriptionOptionsForActiveData(content.name)); |
| 4832 | *data_index = session_options->media_description_options.size() - 1; |
| 4833 | } |
| 4834 | } |
| 4835 | } |
| 4836 | } |
| 4837 |
| 4838 | cricket::MediaDescriptionOptions |
| 4839 | SdpOfferAnswerHandler::GetMediaDescriptionOptionsForActiveData( |
| 4840 | const std::string& mid) const { |
| 4841 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4842 | // Direction for data sections is meaningless, but legacy endpoints might |
| 4843 | // expect sendrecv. |
| 4844 | cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid, |
| 4845 | RtpTransceiverDirection::kSendRecv, |
| 4846 | /*stopped=*/false); |
| 4847 | return options; |
| 4848 | } |
| 4849 |
| 4850 | cricket::MediaDescriptionOptions |
| 4851 | SdpOfferAnswerHandler::GetMediaDescriptionOptionsForRejectedData( |
| 4852 | const std::string& mid) const { |
| 4853 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4854 | cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid, |
| 4855 | RtpTransceiverDirection::kInactive, |
| 4856 | /*stopped=*/true); |
| 4857 | return options; |
| 4858 | } |
| 4859 |
| 4860 | bool SdpOfferAnswerHandler::UpdatePayloadTypeDemuxingState( |
| 4861 | cricket::ContentSource source, |
| 4862 | const std::map<std::string, const cricket::ContentGroup*>& |
| 4863 | bundle_groups_by_mid) { |
| 4864 | TRACE_EVENT0("webrtc", |
| 4865 | "SdpOfferAnswerHandler::UpdatePayloadTypeDemuxingState"); |
| 4866 | RTC_DCHECK_RUN_ON(signaling_thread()); |
| 4867 | // We may need to delete any created default streams and disable creation of |
| 4868 | // new ones on the basis of payload type. This is needed to avoid SSRC |
| 4869 | // collisions in Call's RtpDemuxer, in the case that a transceiver has |
| 4870 | // created a default stream, and then some other channel gets the SSRC |
| 4871 | // signaled in the corresponding Unified Plan "m=" section. Specifically, we |
| 4872 | // need to disable payload type based demuxing when two bundled "m=" sections |
| 4873 | // are using the same payload type(s). For more context |
| 4874 | // see https://bugs.chromium.org/p/webrtc/issues/detail?id=11477 |
| 4875 | const SessionDescriptionInterface* sdesc = |
| 4876 | (source == cricket::CS_LOCAL ? local_description() |
| 4877 | : remote_description()); |
| 4878 | struct PayloadTypes { |
| 4879 | std::set<int> audio_payload_types; |
| 4880 | std::set<int> video_payload_types; |
| 4881 | bool pt_demuxing_possible_audio = true; |
| 4882 | bool pt_demuxing_possible_video = true; |
| 4883 | }; |
| 4884 | std::map<const cricket::ContentGroup*, PayloadTypes> payload_types_by_bundle; |
| 4885 | // If the MID is missing from *any* receiving m= section, this is set to true. |
| 4886 | bool mid_header_extension_missing_audio = false; |
| 4887 | bool mid_header_extension_missing_video = false; |
| 4888 | for (auto& content_info : sdesc->description()->contents()) { |
| 4889 | auto it = bundle_groups_by_mid.find(content_info.name); |
| 4890 | const cricket::ContentGroup* bundle_group = |
| 4891 | it != bundle_groups_by_mid.end() ? it->second : nullptr; |
| 4892 | // If this m= section isn't bundled, it's safe to demux by payload type |
| 4893 | // since other m= sections using the same payload type will also be using |
| 4894 | // different transports. |
| 4895 | if (!bundle_group) { |
| 4896 | continue; |
| 4897 | } |
| 4898 | PayloadTypes* payload_types = &payload_types_by_bundle[bundle_group]; |
| 4899 | if (content_info.rejected || |
| 4900 | (source == cricket::ContentSource::CS_LOCAL && |
| 4901 | !RtpTransceiverDirectionHasRecv( |
| 4902 | content_info.media_description()->direction())) || |
| 4903 | (source == cricket::ContentSource::CS_REMOTE && |
| 4904 | !RtpTransceiverDirectionHasSend( |
| 4905 | content_info.media_description()->direction()))) { |
| 4906 | // Ignore transceivers that are not receiving. |
| 4907 | continue; |
| 4908 | } |
| 4909 | switch (content_info.media_description()->type()) { |
| 4910 | case cricket::MediaType::MEDIA_TYPE_AUDIO: { |
| 4911 | if (!mid_header_extension_missing_audio) { |
| 4912 | mid_header_extension_missing_audio = |
| 4913 | !ContentHasHeaderExtension(content_info, RtpExtension::kMidUri); |
| 4914 | } |
| 4915 | const cricket::AudioContentDescription* audio_desc = |
| 4916 | content_info.media_description()->as_audio(); |
| 4917 | for (const cricket::AudioCodec& audio : audio_desc->codecs()) { |
| 4918 | if (payload_types->audio_payload_types.count(audio.id)) { |
| 4919 | // Two m= sections are using the same payload type, thus demuxing |
| 4920 | // by payload type is not possible. |
| 4921 | payload_types->pt_demuxing_possible_audio = false; |
| 4922 | } |
| 4923 | payload_types->audio_payload_types.insert(audio.id); |
| 4924 | } |
| 4925 | break; |
| 4926 | } |
| 4927 | case cricket::MediaType::MEDIA_TYPE_VIDEO: { |
| 4928 | if (!mid_header_extension_missing_video) { |
| 4929 | mid_header_extension_missing_video = |
| 4930 | !ContentHasHeaderExtension(content_info, RtpExtension::kMidUri); |
| 4931 | } |
| 4932 | const cricket::VideoContentDescription* video_desc = |
| 4933 | content_info.media_description()->as_video(); |
| 4934 | for (const cricket::VideoCodec& video : video_desc->codecs()) { |
| 4935 | if (payload_types->video_payload_types.count(video.id)) { |
| 4936 | // Two m= sections are using the same payload type, thus demuxing |
| 4937 | // by payload type is not possible. |
| 4938 | payload_types->pt_demuxing_possible_video = false; |
| 4939 | } |
| 4940 | payload_types->video_payload_types.insert(video.id); |
| 4941 | } |
| 4942 | break; |
| 4943 | } |
| 4944 | default: |
| 4945 | // Ignore data channels. |
| 4946 | continue; |
| 4947 | } |
| 4948 | } |
| 4949 |
| 4950 | // Gather all updates ahead of time so that all channels can be updated in a |
| 4951 | // single Invoke; necessary due to thread guards. |
| 4952 | std::vector<std::pair<RtpTransceiverDirection, cricket::ChannelInterface*>> |
| 4953 | channels_to_update; |
| 4954 | for (const auto& transceiver : transceivers()->ListInternal()) { |
| 4955 | cricket::ChannelInterface* channel = transceiver->channel(); |
| 4956 | const ContentInfo* content = |
| 4957 | FindMediaSectionForTransceiver(transceiver, sdesc); |
| 4958 | if (!channel || !content) { |
| 4959 | continue; |
| 4960 | } |
| 4961 | RtpTransceiverDirection local_direction = |
| 4962 | content->media_description()->direction(); |
| 4963 | if (source == cricket::CS_REMOTE) { |
| 4964 | local_direction = RtpTransceiverDirectionReversed(local_direction); |
| 4965 | } |
| 4966 | channels_to_update.emplace_back(local_direction, transceiver->channel()); |
| 4967 | } |
| 4968 |
| 4969 | if (channels_to_update.empty()) { |
| 4970 | return true; |
| 4971 | } |
| 4972 |
| 4973 | // In Unified Plan, payload type demuxing is useful for legacy endpoints that |
| 4974 | // don't support the MID header extension, but it can also cause incorrrect |
| 4975 | // forwarding of packets when going from one m= section to multiple m= |
| 4976 | // sections in the same BUNDLE. This only happens if media arrives prior to |
| 4977 | // negotiation, but this can cause missing video and unsignalled ssrc bugs |
| 4978 | // severe enough to warrant disabling PT demuxing in such cases. Therefore, if |
| 4979 | // a MID header extension is present on all m= sections for a given kind |
| 4980 | // (audio/video) then we use that as an OK to disable payload type demuxing in |
| 4981 | // BUNDLEs of that kind. However if PT demuxing was ever turned on (e.g. MID |
| 4982 | // was ever removed on ANY m= section of that kind) then we continue to allow |
| 4983 | // PT demuxing in order to prevent disabling it in follow-up O/A exchanges and |
| 4984 | // allowing early media by PT. |
| 4985 | bool bundled_pt_demux_allowed_audio = !IsUnifiedPlan() || |
| 4986 | mid_header_extension_missing_audio || |
| 4987 | pt_demuxing_has_been_used_audio_; |
| 4988 | bool bundled_pt_demux_allowed_video = !IsUnifiedPlan() || |
| 4989 | mid_header_extension_missing_video || |
| 4990 | pt_demuxing_has_been_used_video_; |
| 4991 | // Kill switch for the above change. |
| 4992 | if (field_trial::IsEnabled(kAlwaysAllowPayloadTypeDemuxingFieldTrialName)) { |
| 4993 | // TODO(https://crbug.com/webrtc/12814): If disabling PT-based demux does |
| 4994 | // not trigger regressions, remove this kill switch. |
| 4995 | bundled_pt_demux_allowed_audio = true; |
| 4996 | bundled_pt_demux_allowed_video = true; |
| 4997 | } |
| 4998 |
| 4999 | return pc_->worker_thread()->Invoke<bool>( |
| 5000 | RTC_FROM_HERE, |
| 5001 | [&channels_to_update, &bundle_groups_by_mid, &payload_types_by_bundle, |
| 5002 | bundled_pt_demux_allowed_audio, bundled_pt_demux_allowed_video, |
| 5003 | pt_demuxing_has_been_used_audio = &pt_demuxing_has_been_used_audio_, |
| 5004 | pt_demuxing_has_been_used_video = &pt_demuxing_has_been_used_video_]() { |
| 5005 | for (const auto& it : channels_to_update) { |
| 5006 | RtpTransceiverDirection local_direction = it.first; |
| 5007 | cricket::ChannelInterface* channel = it.second; |
| 5008 | cricket::MediaType media_type = channel->media_type(); |
| 5009 | auto bundle_it = bundle_groups_by_mid.find(channel->content_name()); |
| 5010 | const cricket::ContentGroup* bundle_group = |
| 5011 | bundle_it != bundle_groups_by_mid.end() ? bundle_it->second |
| 5012 | : nullptr; |
| 5013 | if (media_type == cricket::MediaType::MEDIA_TYPE_AUDIO) { |
| 5014 | bool pt_demux_enabled = |
| 5015 | RtpTransceiverDirectionHasRecv(local_direction) && |
| 5016 | (!bundle_group || (bundled_pt_demux_allowed_audio && |
| 5017 | payload_types_by_bundle[bundle_group] |
| 5018 | .pt_demuxing_possible_audio)); |
| 5019 | if (pt_demux_enabled) { |
| 5020 | *pt_demuxing_has_been_used_audio = true; |
| 5021 | } |
| 5022 | if (!channel->SetPayloadTypeDemuxingEnabled(pt_demux_enabled)) { |
| 5023 | return false; |
| 5024 | } |
| 5025 | } else if (media_type == cricket::MediaType::MEDIA_TYPE_VIDEO) { |
| 5026 | bool pt_demux_enabled = |
| 5027 | RtpTransceiverDirectionHasRecv(local_direction) && |
| 5028 | (!bundle_group || (bundled_pt_demux_allowed_video && |
| 5029 | payload_types_by_bundle[bundle_group] |
| 5030 | .pt_demuxing_possible_video)); |
| 5031 | if (pt_demux_enabled) { |
| 5032 | *pt_demuxing_has_been_used_video = true; |
| 5033 | } |
| 5034 | if (!channel->SetPayloadTypeDemuxingEnabled(pt_demux_enabled)) { |
| 5035 | return false; |
| 5036 | } |
| 5037 | } |
| 5038 | } |
| 5039 | return true; |
| 5040 | }); |
| 5041 | } |
| 5042 |
| 5043 | } // namespace webrtc |
| 5044 |