1 /* 2 * Copyright (C) 2012 Google Inc. All rights reserved. 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that the following conditions 6 * are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer 12 * in the documentation and/or other materials provided with the 13 * distribution. 14 * 3. Neither the name of Google Inc. nor the names of its contributors 15 * may be used to endorse or promote products derived from this 16 * software without specific prior written permission. 17 * 18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 */ 30 31 #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_PEER_CONNECTION_H_ 32 #define THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_PEER_CONNECTION_H_ 33 34 #include <memory> 35 #include <utility> 36 37 #include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h" 38 #include "third_party/blink/renderer/bindings/core/v8/script_promise.h" 39 #include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h" 40 #include "third_party/blink/renderer/core/execution_context/execution_context_lifecycle_observer.h" 41 #include "third_party/blink/renderer/modules/crypto/normalize_algorithm.h" 42 #include "third_party/blink/renderer/modules/event_target_modules.h" 43 #include "third_party/blink/renderer/modules/mediastream/media_stream.h" 44 #include "third_party/blink/renderer/modules/peerconnection/call_setup_state_tracker.h" 45 #include "third_party/blink/renderer/modules/peerconnection/rtc_ice_candidate.h" 46 #include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_controller.h" 47 #include "third_party/blink/renderer/modules/peerconnection/rtc_peer_connection_handler.h" 48 #include "third_party/blink/renderer/modules/peerconnection/rtc_rtp_transceiver.h" 49 #include "third_party/blink/renderer/modules/peerconnection/rtc_session_description_enums.h" 50 #include "third_party/blink/renderer/platform/heap/heap_allocator.h" 51 #include "third_party/blink/renderer/platform/mediastream/media_constraints.h" 52 #include "third_party/blink/renderer/platform/peerconnection/rtc_peer_connection_handler_client.h" 53 #include "third_party/blink/renderer/platform/peerconnection/rtc_session_description_request.h" 54 #include "third_party/blink/renderer/platform/peerconnection/rtc_void_request.h" 55 #include "third_party/blink/renderer/platform/scheduler/public/frame_scheduler.h" 56 #include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h" 57 #include "third_party/blink/renderer/platform/wtf/hash_set.h" 58 #include "third_party/blink/renderer/platform/wtf/vector.h" 59 60 namespace blink { 61 62 class ExceptionState; 63 class MediaStreamTrack; 64 class MediaStreamTrackOrString; 65 class RTCAnswerOptions; 66 class RTCConfiguration; 67 class RTCDtlsTransport; 68 class RTCDTMFSender; 69 class RTCDataChannel; 70 class RTCDataChannelInit; 71 class RTCIceCandidateInitOrRTCIceCandidate; 72 class RTCIceTransport; 73 class RTCOfferOptions; 74 class RTCPeerConnectionTest; 75 class RTCRtpReceiver; 76 class RTCRtpSender; 77 class RTCRtpTransceiverInit; 78 class RTCSctpTransport; 79 class RTCSessionDescription; 80 class RTCSessionDescriptionInit; 81 class ScriptState; 82 class V8RTCPeerConnectionErrorCallback; 83 class V8RTCSessionDescriptionCallback; 84 class V8RTCStatsCallback; 85 class V8VoidFunction; 86 87 extern const char kOnlySupportedInUnifiedPlanMessage[]; 88 89 // This enum is used to track usage of SDP during the transition of the default 90 // "sdpSemantics" value from "Plan B" to "Unified Plan". Usage refers to 91 // operations such as createOffer(), createAnswer(), setLocalDescription() and 92 // setRemoteDescription(). "Complex" SDP refers to SDP that is not compatible 93 // between SDP formats. Usage of SDP falls into two categories: "safe" and 94 // "unsafe". Applications with unsafe usage are predicted to break when the 95 // default changes. This includes complex SDP usage and relying on the default 96 // sdpSemantics. kUnknown is used if the SDP format could not be deduced, such 97 // as if SDP could not be parsed. 98 enum class SdpUsageCategory { 99 kSafe = 0, 100 kUnsafe = 1, 101 kUnknown = 2, 102 kMaxValue = kUnknown, 103 }; 104 105 MODULES_EXPORT SdpUsageCategory 106 DeduceSdpUsageCategory(const String& sdp_type, 107 const String& sdp, 108 bool sdp_semantics_specified, 109 webrtc::SdpSemantics sdp_semantics); 110 111 class MODULES_EXPORT RTCPeerConnection final 112 : public EventTargetWithInlineData, 113 public RTCPeerConnectionHandlerClient, 114 public ActiveScriptWrappable<RTCPeerConnection>, 115 public ExecutionContextLifecycleObserver, 116 public MediaStreamObserver { 117 DEFINE_WRAPPERTYPEINFO(); 118 USING_PRE_FINALIZER(RTCPeerConnection, Dispose); 119 120 public: 121 static RTCPeerConnection* Create(ExecutionContext*, 122 const RTCConfiguration*, 123 const Dictionary&, 124 ExceptionState&); 125 static RTCPeerConnection* Create(ExecutionContext*, 126 const RTCConfiguration*, 127 const ScriptValue&, 128 ExceptionState&); 129 static RTCPeerConnection* Create(ExecutionContext*, 130 const RTCConfiguration*, 131 ExceptionState&); 132 133 RTCPeerConnection(ExecutionContext*, 134 webrtc::PeerConnectionInterface::RTCConfiguration, 135 bool sdp_semantics_specified, 136 bool force_encoded_audio_insertable_streams, 137 bool force_encoded_video_insertable_streams, 138 MediaConstraints, 139 ExceptionState&); 140 ~RTCPeerConnection() override; 141 142 ScriptPromise createOffer(ScriptState*, 143 const RTCOfferOptions*, 144 ExceptionState&); 145 ScriptPromise createOffer(ScriptState*, 146 V8RTCSessionDescriptionCallback*, 147 V8RTCPeerConnectionErrorCallback*, 148 const ScriptValue&, 149 ExceptionState&); 150 ScriptPromise createOffer(ScriptState*, 151 V8RTCSessionDescriptionCallback*, 152 V8RTCPeerConnectionErrorCallback*, 153 ExceptionState&); 154 ScriptPromise CreateOffer(ScriptState*, 155 V8RTCSessionDescriptionCallback*, 156 V8RTCPeerConnectionErrorCallback*, 157 const Dictionary&, 158 ExceptionState&); 159 160 ScriptPromise createAnswer(ScriptState*, 161 const RTCAnswerOptions*, 162 ExceptionState&); 163 ScriptPromise createAnswer(ScriptState*, 164 V8RTCSessionDescriptionCallback*, 165 V8RTCPeerConnectionErrorCallback*, 166 const ScriptValue&, 167 ExceptionState&); 168 ScriptPromise createAnswer(ScriptState*, 169 V8RTCSessionDescriptionCallback*, 170 V8RTCPeerConnectionErrorCallback*, 171 ExceptionState&); 172 ScriptPromise CreateAnswer(ScriptState*, 173 V8RTCSessionDescriptionCallback*, 174 V8RTCPeerConnectionErrorCallback*, 175 const Dictionary&); 176 177 ScriptPromise setLocalDescription(ScriptState*); 178 ScriptPromise setLocalDescription(ScriptState*, 179 const RTCSessionDescriptionInit*, 180 ExceptionState&); 181 ScriptPromise setLocalDescription( 182 ScriptState*, 183 const RTCSessionDescriptionInit*, 184 V8VoidFunction*, 185 V8RTCPeerConnectionErrorCallback* = nullptr); 186 RTCSessionDescription* localDescription() const; 187 RTCSessionDescription* currentLocalDescription() const; 188 RTCSessionDescription* pendingLocalDescription() const; 189 190 ScriptPromise setRemoteDescription(ScriptState*, 191 const RTCSessionDescriptionInit*, 192 ExceptionState&); 193 ScriptPromise setRemoteDescription( 194 ScriptState*, 195 const RTCSessionDescriptionInit*, 196 V8VoidFunction*, 197 V8RTCPeerConnectionErrorCallback* = nullptr); 198 RTCSessionDescription* remoteDescription() const; 199 RTCSessionDescription* currentRemoteDescription() const; 200 RTCSessionDescription* pendingRemoteDescription() const; 201 202 String signalingState() const; 203 204 RTCConfiguration* getConfiguration(ScriptState*) const; 205 void setConfiguration(ScriptState*, const RTCConfiguration*, ExceptionState&); 206 207 // Certificate management 208 // http://w3c.github.io/webrtc-pc/#sec.cert-mgmt 209 static ScriptPromise generateCertificate( 210 ScriptState*, 211 const AlgorithmIdentifier& keygen_algorithm, 212 ExceptionState&); 213 214 ScriptPromise addIceCandidate(ScriptState*, 215 const RTCIceCandidateInitOrRTCIceCandidate&, 216 ExceptionState&); 217 ScriptPromise addIceCandidate(ScriptState*, 218 const RTCIceCandidateInitOrRTCIceCandidate&, 219 V8VoidFunction*, 220 V8RTCPeerConnectionErrorCallback*, 221 ExceptionState&); 222 223 String iceGatheringState() const; 224 225 String iceConnectionState() const; 226 227 String connectionState() const; 228 229 base::Optional<bool> canTrickleIceCandidates() const; 230 231 void restartIce(); 232 233 // A local stream is any stream associated with a sender. 234 MediaStreamVector getLocalStreams() const; 235 // A remote stream is any stream associated with a receiver. 236 MediaStreamVector getRemoteStreams() const; 237 MediaStream* getRemoteStreamById(const String&) const; 238 bool IsRemoteStream(MediaStream* stream) const; 239 240 void addStream(ScriptState*, 241 MediaStream*, 242 const ScriptValue& media_constraints, 243 ExceptionState&); 244 void addStream(ScriptState*, MediaStream*, ExceptionState&); 245 void AddStream(ScriptState*, 246 MediaStream*, 247 const Dictionary& media_constraints, 248 ExceptionState&); 249 250 void removeStream(MediaStream*, ExceptionState&); 251 252 // Calls LegacyCallbackBasedGetStats() or PromiseBasedGetStats() (or rejects 253 // with an exception) depending on type, see rtc_peer_connection.idl. 254 ScriptPromise getStats(ScriptState* script_state, ExceptionState&); 255 ScriptPromise getStats(ScriptState* script_state, 256 ScriptValue callback_or_selector, 257 ExceptionState&); 258 ScriptPromise getStats(ScriptState* script_state, 259 ScriptValue callback_or_selector, 260 ScriptValue legacy_selector, 261 ExceptionState&); 262 ScriptPromise LegacyCallbackBasedGetStats( 263 ScriptState*, 264 V8RTCStatsCallback* success_callback, 265 MediaStreamTrack* selector); 266 ScriptPromise PromiseBasedGetStats(ScriptState*, 267 MediaStreamTrack* selector, 268 ExceptionState&); 269 270 const HeapVector<Member<RTCRtpTransceiver>>& getTransceivers() const; 271 const HeapVector<Member<RTCRtpSender>>& getSenders() const; 272 const HeapVector<Member<RTCRtpReceiver>>& getReceivers() const; 273 RTCRtpTransceiver* addTransceiver(const MediaStreamTrackOrString&, 274 const RTCRtpTransceiverInit*, 275 ExceptionState&); 276 RTCRtpSender* addTrack(MediaStreamTrack*, MediaStreamVector, ExceptionState&); 277 void removeTrack(RTCRtpSender*, ExceptionState&); 278 DEFINE_ATTRIBUTE_EVENT_LISTENER(track, kTrack) 279 280 RTCSctpTransport* sctp() const; 281 RTCDataChannel* createDataChannel(ScriptState*, 282 String label, 283 const RTCDataChannelInit*, 284 ExceptionState&); 285 286 RTCDTMFSender* createDTMFSender(MediaStreamTrack*, ExceptionState&); 287 IsClosed()288 bool IsClosed() { return closed_; } 289 void close(); 290 291 // Makes the peer connection aware of the track. This is used to map web 292 // tracks to blink tracks, as is necessary for plumbing. There is no need to 293 // unregister the track because Weak references are used. 294 void RegisterTrack(MediaStreamTrack*); 295 296 // We allow getStats after close, but not other calls or callbacks. ShouldFireDefaultCallbacks()297 bool ShouldFireDefaultCallbacks() { 298 return !closed_ && !peer_handler_unregistered_; 299 } ShouldFireGetStatsCallback()300 bool ShouldFireGetStatsCallback() { return !peer_handler_unregistered_; } 301 302 DEFINE_ATTRIBUTE_EVENT_LISTENER(negotiationneeded, kNegotiationneeded) 303 DEFINE_ATTRIBUTE_EVENT_LISTENER(icecandidate, kIcecandidate) 304 DEFINE_ATTRIBUTE_EVENT_LISTENER(signalingstatechange, kSignalingstatechange) 305 DEFINE_ATTRIBUTE_EVENT_LISTENER(addstream, kAddstream) 306 DEFINE_ATTRIBUTE_EVENT_LISTENER(removestream, kRemovestream) 307 DEFINE_ATTRIBUTE_EVENT_LISTENER(iceconnectionstatechange, 308 kIceconnectionstatechange) 309 DEFINE_ATTRIBUTE_EVENT_LISTENER(connectionstatechange, kConnectionstatechange) 310 DEFINE_ATTRIBUTE_EVENT_LISTENER(icegatheringstatechange, 311 kIcegatheringstatechange) 312 DEFINE_ATTRIBUTE_EVENT_LISTENER(datachannel, kDatachannel) 313 DEFINE_ATTRIBUTE_EVENT_LISTENER(icecandidateerror, kIcecandidateerror) 314 315 // Utility to note result of CreateOffer / CreateAnswer 316 void NoteSdpCreated(const RTCSessionDescription&); 317 // Utility to report SDP usage of setLocalDescription / setRemoteDescription. 318 enum class SetSdpOperationType { 319 kSetLocalDescription, 320 kSetRemoteDescription, 321 }; 322 void ReportSetSdpUsage( 323 SetSdpOperationType operation_type, 324 const RTCSessionDescriptionInit* session_description_init) const; 325 326 // MediaStreamObserver 327 void OnStreamAddTrack(MediaStream*, MediaStreamTrack*) override; 328 void OnStreamRemoveTrack(MediaStream*, MediaStreamTrack*) override; 329 330 // RTCPeerConnectionHandlerClient 331 void NegotiationNeeded() override; 332 333 void DidGenerateICECandidate(RTCIceCandidatePlatform*) override; 334 void DidFailICECandidate(const String& address, 335 base::Optional<uint16_t> port, 336 const String& host_candidate, 337 const String& url, 338 int error_code, 339 const String& error_text) override; 340 void DidChangeSessionDescriptions( 341 RTCSessionDescriptionPlatform* pending_local_description, 342 RTCSessionDescriptionPlatform* current_local_description, 343 RTCSessionDescriptionPlatform* pending_remote_description, 344 RTCSessionDescriptionPlatform* current_remote_description) override; 345 void DidChangeIceGatheringState( 346 webrtc::PeerConnectionInterface::IceGatheringState) override; 347 void DidChangeIceConnectionState( 348 webrtc::PeerConnectionInterface::IceConnectionState) override; 349 void DidChangePeerConnectionState( 350 webrtc::PeerConnectionInterface::PeerConnectionState) override; 351 void DidModifyReceiversPlanB( 352 webrtc::PeerConnectionInterface::SignalingState, 353 Vector<std::unique_ptr<RTCRtpReceiverPlatform>> platform_receivers_added, 354 Vector<std::unique_ptr<RTCRtpReceiverPlatform>> 355 platform_receivers_removed) override; 356 void DidModifySctpTransport(WebRTCSctpTransportSnapshot) override; 357 void DidModifyTransceivers(webrtc::PeerConnectionInterface::SignalingState, 358 Vector<std::unique_ptr<RTCRtpTransceiverPlatform>>, 359 Vector<uintptr_t>, 360 bool is_remote_description) override; 361 void DidAddRemoteDataChannel( 362 scoped_refptr<webrtc::DataChannelInterface> channel) override; 363 void DidNoteInterestingUsage(int usage_pattern) override; 364 void UnregisterPeerConnectionHandler() override; 365 void ClosePeerConnection() override; 366 367 // EventTarget 368 const AtomicString& InterfaceName() const override; 369 ExecutionContext* GetExecutionContext() const override; 370 371 // ExecutionContextLifecycleObserver 372 void ContextDestroyed() override; 373 374 // ScriptWrappable 375 // We keep the this object alive until either stopped or closed. HasPendingActivity()376 bool HasPendingActivity() const final { 377 return !closed_ && !peer_handler_unregistered_; 378 } 379 380 // For testing; exported to testing/InternalWebRTCPeerConnection 381 static int PeerConnectionCount(); 382 static int PeerConnectionCountLimit(); 383 384 // SLD/SRD Helper method, public for testing. 385 // This function returns a value that indicates if complex SDP is being used 386 // and whether a format is explicitly specified. If the SDP is not complex or 387 // it could not be parsed, base::nullopt is returned. 388 // When "Complex" SDP (i.e., SDP that has multiple tracks) is used without 389 // explicitly specifying the SDP format, there may be errors if the 390 // application assumes a format that differs from the actual default format. 391 base::Optional<ComplexSdpCategory> CheckForComplexSdp( 392 const RTCSessionDescriptionInit* session_description_init) const; 393 394 const CallSetupStateTracker& call_setup_state_tracker() const; 395 void NoteCallSetupStateEventPending( 396 RTCPeerConnection::SetSdpOperationType operation, 397 const RTCSessionDescriptionInit& description); 398 void NoteSessionDescriptionRequestCompleted( 399 RTCCreateSessionDescriptionOperation operation, 400 bool success); 401 void NoteVoidRequestCompleted(RTCSetSessionDescriptionOperation operation, 402 bool success); 403 static void GenerateCertificateCompleted( 404 ScriptPromiseResolver* resolver, 405 rtc::scoped_refptr<rtc::RTCCertificate> certificate); 406 // Checks if the document that the peer connection lives in has ever executed 407 // getUserMedia(). 408 bool HasDocumentMedia() const; 409 410 // Called by RTCIceTransport::OnStateChange to update the ice connection 411 // state. 412 void UpdateIceConnectionState(); 413 sdp_semantics()414 webrtc::SdpSemantics sdp_semantics() { return sdp_semantics_; } 415 force_encoded_audio_insertable_streams()416 bool force_encoded_audio_insertable_streams() { 417 return force_encoded_audio_insertable_streams_; 418 } 419 force_encoded_video_insertable_streams()420 bool force_encoded_video_insertable_streams() { 421 return force_encoded_video_insertable_streams_; 422 } 423 424 void Trace(Visitor*) const override; 425 426 base::TimeTicks WebRtcTimestampToBlinkTimestamp( 427 base::TimeTicks webrtc_monotonic_time) const; 428 429 using RtcPeerConnectionHandlerFactoryCallback = 430 base::RepeatingCallback<std::unique_ptr<RTCPeerConnectionHandler>()>; 431 static void SetRtcPeerConnectionHandlerFactoryForTesting( 432 RtcPeerConnectionHandlerFactoryCallback); 433 434 private: 435 friend class InternalsRTCPeerConnection; 436 FRIEND_TEST_ALL_PREFIXES(RTCPeerConnectionTest, GetAudioTrack); 437 FRIEND_TEST_ALL_PREFIXES(RTCPeerConnectionTest, GetVideoTrack); 438 FRIEND_TEST_ALL_PREFIXES(RTCPeerConnectionTest, GetAudioAndVideoTrack); 439 FRIEND_TEST_ALL_PREFIXES(RTCPeerConnectionTest, GetTrackRemoveStreamAndGCAll); 440 FRIEND_TEST_ALL_PREFIXES(RTCPeerConnectionTest, 441 GetTrackRemoveStreamAndGCWithPersistentComponent); 442 FRIEND_TEST_ALL_PREFIXES(RTCPeerConnectionTest, 443 GetTrackRemoveStreamAndGCWithPersistentStream); 444 445 typedef base::OnceCallback<bool()> BoolFunction; 446 class EventWrapper final : public GarbageCollected<EventWrapper> { 447 public: 448 EventWrapper(Event*, BoolFunction); 449 // Returns true if |m_setupFunction| returns true or it is null. 450 // |m_event| will only be fired if setup() returns true; 451 bool Setup(); 452 453 void Trace(Visitor*) const; 454 455 Member<Event> event_; 456 457 private: 458 BoolFunction setup_function_; 459 }; 460 void Dispose(); 461 462 void MaybeDispatchEvent(Event*); 463 // TODO(hbos): Remove any remaining uses of ScheduleDispatchEvent. 464 void ScheduleDispatchEvent(Event*); 465 void ScheduleDispatchEvent(Event*, BoolFunction); 466 void DispatchScheduledEvents(); 467 MediaStreamTrack* GetTrack(MediaStreamComponent*) const; 468 RTCRtpSender* FindSenderForTrackAndStream(MediaStreamTrack*, MediaStream*); 469 HeapVector<Member<RTCRtpSender>>::iterator FindSender( 470 const RTCRtpSenderPlatform& web_sender); 471 HeapVector<Member<RTCRtpReceiver>>::iterator FindReceiver( 472 const RTCRtpReceiverPlatform& platform_receiver); 473 HeapVector<Member<RTCRtpTransceiver>>::iterator FindTransceiver( 474 const RTCRtpTransceiverPlatform& platform_transceiver); 475 476 // Creates or updates the sender such that it is up-to-date with the 477 // RTCRtpSenderPlatform in all regards *except for streams*. The web sender 478 // only knows of stream IDs; updating the stream objects requires additional 479 // logic which is different depending on context, e.g: 480 // - If created/updated with addTrack(), the streams were supplied as 481 // arguments. 482 // The web sender's web track must already have a correspondent blink track in 483 // |tracks_|. The caller is responsible for ensuring this with 484 // RegisterTrack(), e.g: 485 // - On addTrack(), the track is supplied as an argument. 486 RTCRtpSender* CreateOrUpdateSender(std::unique_ptr<RTCRtpSenderPlatform>, 487 String kind); 488 // Creates or updates the receiver such that it is up-to-date with the 489 // RTCRtpReceiverPlatform in all regards *except for streams*. The web 490 // receiver only knows of stream IDs; updating the stream objects requires 491 // additional logic which is different depending on context, e.g: 492 // - If created/updated with setRemoteDescription(), there is an algorithm for 493 // processing the addition/removal of remote tracks which includes how to 494 // create and update the associated streams set. 495 RTCRtpReceiver* CreateOrUpdateReceiver( 496 std::unique_ptr<RTCRtpReceiverPlatform>); 497 // Creates or updates the transceiver such that it, including its sender and 498 // receiver, are up-to-date with the RTCRtpTransceiverPlatform in all regerds 499 // *except for sender and receiver streams*. The web sender and web receiver 500 // only knows of stream IDs; updating the stream objects require additional 501 // logic which is different depending on context. See above. 502 RTCRtpTransceiver* CreateOrUpdateTransceiver( 503 std::unique_ptr<RTCRtpTransceiverPlatform>); 504 505 // Creates or updates the RTCDtlsTransport object corresponding to the 506 // given webrtc::DtlsTransportInterface object. 507 RTCDtlsTransport* CreateOrUpdateDtlsTransport( 508 rtc::scoped_refptr<webrtc::DtlsTransportInterface>, 509 const webrtc::DtlsTransportInformation& info); 510 511 // Creates or updates the RTCIceTransport object corresponding to the given 512 // webrtc::IceTransportInterface object. 513 RTCIceTransport* CreateOrUpdateIceTransport( 514 rtc::scoped_refptr<webrtc::IceTransportInterface>); 515 516 // Update the |receiver->streams()| to the streams indicated by |stream_ids|, 517 // adding to |remove_list| and |add_list| accordingly. 518 // https://w3c.github.io/webrtc-pc/#set-associated-remote-streams 519 void SetAssociatedMediaStreams( 520 RTCRtpReceiver* receiver, 521 const Vector<String>& stream_ids, 522 HeapVector<std::pair<Member<MediaStream>, Member<MediaStreamTrack>>>* 523 remove_list, 524 HeapVector<std::pair<Member<MediaStream>, Member<MediaStreamTrack>>>* 525 add_list); 526 527 // Sets the signaling state synchronously, and dispatches a 528 // signalingstatechange event synchronously or asynchronously depending on 529 // |dispatch_event_immediately|. 530 // TODO(hbos): The ability to not fire the event asynchronously is there 531 // because CloseInternal() has historically fired asynchronously along with 532 // other asynchronously fired events. If close() does not fire any events, 533 // |dispatch_event_immediately| can be removed. https://crbug.com/849247 534 void ChangeSignalingState(webrtc::PeerConnectionInterface::SignalingState, 535 bool dispatch_event_immediately); 536 // The remaining "Change" methods set the state asynchronously and fire the 537 // corresponding event immediately after changing the state (if it was really 538 // changed). 539 // 540 // The "Set" methods are called asynchronously by the "Change" methods, and 541 // set the corresponding state without firing an event, returning true if the 542 // state was really changed. 543 // 544 // This is done because the standard guarantees that state changes and the 545 // corresponding events will happen in the same task; it shouldn't be 546 // possible to, for example, end up with two "icegatheringstatechange" events 547 // that are delayed somehow and cause the application to read a "complete" 548 // gathering state twice, missing the "gathering" state in the middle. 549 void ChangeIceGatheringState( 550 webrtc::PeerConnectionInterface::IceGatheringState); 551 bool SetIceGatheringState(webrtc::PeerConnectionInterface::IceGatheringState); 552 553 void ChangeIceConnectionState( 554 webrtc::PeerConnectionInterface::IceConnectionState); 555 webrtc::PeerConnectionInterface::IceConnectionState 556 ComputeIceConnectionState(); 557 bool HasAnyFailedIceTransport() const; 558 bool HasAnyDisconnectedIceTransport() const; 559 bool HasAllNewOrClosedIceTransports() const; 560 bool HasAnyNewOrCheckingIceTransport() const; 561 bool HasAllCompletedOrClosedIceTransports() const; 562 bool HasAllConnectedCompletedOrClosedIceTransports() const; 563 564 void ChangePeerConnectionState( 565 webrtc::PeerConnectionInterface::PeerConnectionState); 566 bool SetPeerConnectionState( 567 webrtc::PeerConnectionInterface::PeerConnectionState); 568 569 void CloseInternal(); 570 571 void RecordRapporMetrics(); 572 573 DOMException* checkSdpForStateErrors(ExecutionContext*, 574 const RTCSessionDescriptionInit*, 575 String* sdp); 576 void MaybeWarnAboutUnsafeSdp( 577 const RTCSessionDescriptionInit* session_description_init) const; 578 579 HeapHashSet<Member<RTCIceTransport>> ActiveIceTransports() const; 580 581 Member<RTCSessionDescription> pending_local_description_; 582 Member<RTCSessionDescription> current_local_description_; 583 Member<RTCSessionDescription> pending_remote_description_; 584 Member<RTCSessionDescription> current_remote_description_; 585 webrtc::PeerConnectionInterface::SignalingState signaling_state_; 586 webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state_; 587 webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state_; 588 webrtc::PeerConnectionInterface::PeerConnectionState peer_connection_state_; 589 // TODO(https://crbug.com/857004): The trackers' metrics are currently not 590 // uploaded; either use the metrics it produces (i.e. revert 591 // https://chromium-review.googlesource.com/c/chromium/src/+/1991421) or 592 // delete all CallSetupStateTracker code for good. 593 CallSetupStateTracker call_setup_state_tracker_; 594 595 // A map containing any track that is in use by the peer connection. This 596 // includes tracks of |rtp_senders_| and |rtp_receivers_|. 597 HeapHashMap<WeakMember<MediaStreamComponent>, WeakMember<MediaStreamTrack>> 598 tracks_; 599 // In Plan B, senders and receivers exist independently of one another. 600 // In Unified Plan, all senders and receivers are the sender-receiver pairs of 601 // transceivers. 602 // TODO(hbos): When Plan B is removed, remove |rtp_senders_| and 603 // |rtp_receivers_| since these are part of |transceivers_|. 604 // https://crbug.com/857004 605 HeapVector<Member<RTCRtpSender>> rtp_senders_; 606 HeapVector<Member<RTCRtpReceiver>> rtp_receivers_; 607 HeapVector<Member<RTCRtpTransceiver>> transceivers_; 608 609 // A map of all webrtc::DtlsTransports that have a corresponding 610 // RTCDtlsTransport object. Garbage collection will remove map entries 611 // when they are no longer in use. 612 // Note: Transports may exist in the map even if they are not currently 613 // in use, since garbage collection only happens when needed. 614 HeapHashMap<webrtc::DtlsTransportInterface*, WeakMember<RTCDtlsTransport>> 615 dtls_transports_by_native_transport_; 616 // The same kind of map for webrtc::IceTransports. 617 HeapHashMap<webrtc::IceTransportInterface*, WeakMember<RTCIceTransport>> 618 ice_transports_by_native_transport_; 619 620 // TODO(crbug.com/787254): Use RTCPeerConnectionHandler. 621 std::unique_ptr<RTCPeerConnectionHandler> peer_handler_; 622 623 base::OnceClosure dispatch_events_task_created_callback_for_testing_; 624 TaskHandle dispatch_scheduled_events_task_handle_; 625 HeapVector<Member<EventWrapper>> scheduled_events_; 626 627 // This handle notifies scheduler about an active connection associated 628 // with a frame. Handle should be destroyed when connection is closed. 629 FrameScheduler::SchedulingAffectingFeatureHandle 630 feature_handle_for_scheduler_; 631 632 // When the |peer_handler_| is unregistered, the native peer connection is 633 // closed and disappears from the chrome://webrtc-internals page. This happens 634 // when page context is destroyed. 635 // 636 // Note that the peer connection can be |closed_| without being unregistered 637 // (in which case it is still visible in chrome://webrtc-internals). If 638 // context is destroyed before the peer connection is closed, the native peer 639 // connection will be closed and stop surfacing states to blink but the blink 640 // peer connection will be unaware of the native layer being closed. 641 bool peer_handler_unregistered_; 642 // Reflects the RTCPeerConnection's [[IsClosed]] internal slot. 643 // https://w3c.github.io/webrtc-pc/#dfn-isclosed 644 // TODO(https://crbug.com/1083204): According to spec, the peer connection can 645 // only be closed through the close() API. However, our implementation can 646 // also be closed asynchronously by the |peer_handler_|, such as in response 647 // to laptop lid close on some system (depending on OS and settings). 648 bool closed_; 649 // When true, events on the RTCPeerConnection will not be dispatched to 650 // JavaScript. This happens when close() is called but not if the peer 651 // connection was closed asynchronously. This also happens if the context is 652 // destroyed. 653 // TODO(https://crbug.com/1083204): When we are spec compliant and don't close 654 // the peer connection asynchronously, this can be removed in favor of 655 // |closed_|. 656 bool suppress_events_; 657 658 // Internal state [[LastOffer]] and [[LastAnswer]] 659 String last_offer_; 660 String last_answer_; 661 662 Member<RTCSctpTransport> sctp_transport_; 663 bool has_data_channels_; // For RAPPOR metrics 664 // In Plan B, senders and receivers are added or removed independently of one 665 // another. In Unified Plan, senders and receivers are created in pairs as 666 // transceivers. Transceivers may become inactive, but are never removed. 667 // The value of this member affects the behavior of some methods and what 668 // information is surfaced from webrtc. This has the value "kPlanB" or 669 // "kUnifiedPlan", if constructed with "kDefault" it is translated to one or 670 // the other. 671 webrtc::SdpSemantics sdp_semantics_; 672 // Whether sdpSemantics was specified at construction. 673 bool sdp_semantics_specified_; 674 675 // Blink and WebRTC timestamp diff. 676 const base::TimeDelta blink_webrtc_time_diff_; 677 678 // Insertable streams. 679 bool force_encoded_audio_insertable_streams_; 680 bool force_encoded_video_insertable_streams_; 681 }; 682 683 } // namespace blink 684 685 #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_PEERCONNECTION_RTC_PEER_CONNECTION_H_ 686