Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(50)

Side by Side Diff: webrtc/api/webrtcsession.h

Issue 2514883002: Create //webrtc/api:libjingle_peerconnection_api + refactorings. (Closed)
Patch Set: Rebase Created 4 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 /*
2 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #ifndef WEBRTC_API_WEBRTCSESSION_H_
12 #define WEBRTC_API_WEBRTCSESSION_H_
13
14 #include <memory>
15 #include <set>
16 #include <string>
17 #include <vector>
18
19 #include "webrtc/api/datachannel.h"
20 #include "webrtc/api/dtmfsender.h"
21 #include "webrtc/api/mediacontroller.h"
22 #include "webrtc/api/peerconnectioninterface.h"
23 #include "webrtc/api/statstypes.h"
24 #include "webrtc/base/constructormagic.h"
25 #include "webrtc/base/sigslot.h"
26 #include "webrtc/base/sslidentity.h"
27 #include "webrtc/base/thread.h"
28 #include "webrtc/media/base/mediachannel.h"
29 #include "webrtc/p2p/base/candidate.h"
30 #include "webrtc/p2p/base/transportcontroller.h"
31 #include "webrtc/pc/mediasession.h"
32
33 #ifdef HAVE_QUIC
34 #include "webrtc/api/quicdatatransport.h"
35 #endif // HAVE_QUIC
36
37 namespace cricket {
38
39 class ChannelManager;
40 class DataChannel;
41 class StatsReport;
42 class VideoChannel;
43 class VoiceChannel;
44
45 #ifdef HAVE_QUIC
46 class QuicTransportChannel;
47 #endif // HAVE_QUIC
48
49 } // namespace cricket
50
51 namespace webrtc {
52
53 class IceRestartAnswerLatch;
54 class JsepIceCandidate;
55 class MediaStreamSignaling;
56 class WebRtcSessionDescriptionFactory;
57
58 extern const char kBundleWithoutRtcpMux[];
59 extern const char kCreateChannelFailed[];
60 extern const char kInvalidCandidates[];
61 extern const char kInvalidSdp[];
62 extern const char kMlineMismatch[];
63 extern const char kPushDownTDFailed[];
64 extern const char kSdpWithoutDtlsFingerprint[];
65 extern const char kSdpWithoutSdesCrypto[];
66 extern const char kSdpWithoutIceUfragPwd[];
67 extern const char kSdpWithoutSdesAndDtlsDisabled[];
68 extern const char kSessionError[];
69 extern const char kSessionErrorDesc[];
70 extern const char kDtlsSetupFailureRtp[];
71 extern const char kDtlsSetupFailureRtcp[];
72 extern const char kEnableBundleFailed[];
73
74 // Maximum number of received video streams that will be processed by webrtc
75 // even if they are not signalled beforehand.
76 extern const int kMaxUnsignalledRecvStreams;
77
78 // ICE state callback interface.
79 class IceObserver {
80 public:
81 IceObserver() {}
82 // Called any time the IceConnectionState changes
83 // TODO(honghaiz): Change the name to OnIceConnectionStateChange so as to
84 // conform to the w3c standard.
85 virtual void OnIceConnectionChange(
86 PeerConnectionInterface::IceConnectionState new_state) {}
87 // Called any time the IceGatheringState changes
88 virtual void OnIceGatheringChange(
89 PeerConnectionInterface::IceGatheringState new_state) {}
90 // New Ice candidate have been found.
91 virtual void OnIceCandidate(const IceCandidateInterface* candidate) = 0;
92
93 // Some local ICE candidates have been removed.
94 virtual void OnIceCandidatesRemoved(
95 const std::vector<cricket::Candidate>& candidates) = 0;
96
97 // Called whenever the state changes between receiving and not receiving.
98 virtual void OnIceConnectionReceivingChange(bool receiving) {}
99
100 protected:
101 ~IceObserver() {}
102
103 private:
104 RTC_DISALLOW_COPY_AND_ASSIGN(IceObserver);
105 };
106
107 // Statistics for all the transports of the session.
108 typedef std::map<std::string, cricket::TransportStats> TransportStatsMap;
109 typedef std::map<std::string, std::string> ProxyTransportMap;
110
111 // TODO(pthatcher): Think of a better name for this. We already have
112 // a TransportStats in transport.h. Perhaps TransportsStats?
113 struct SessionStats {
114 ProxyTransportMap proxy_to_transport;
115 TransportStatsMap transport_stats;
116 };
117
118 // A WebRtcSession manages general session state. This includes negotiation
119 // of both the application-level and network-level protocols: the former
120 // defines what will be sent and the latter defines how it will be sent. Each
121 // network-level protocol is represented by a Transport object. Each Transport
122 // participates in the network-level negotiation. The individual streams of
123 // packets are represented by TransportChannels. The application-level protocol
124 // is represented by SessionDecription objects.
125 class WebRtcSession :
126
127 public DtmfProviderInterface,
128 public DataChannelProviderInterface,
129 public sigslot::has_slots<> {
130 public:
131 enum State {
132 STATE_INIT = 0,
133 STATE_SENTOFFER, // Sent offer, waiting for answer.
134 STATE_RECEIVEDOFFER, // Received an offer. Need to send answer.
135 STATE_SENTPRANSWER, // Sent provisional answer. Need to send answer.
136 STATE_RECEIVEDPRANSWER, // Received provisional answer, waiting for answer.
137 STATE_INPROGRESS, // Offer/answer exchange completed.
138 STATE_CLOSED, // Close() was called.
139 };
140
141 enum Error {
142 ERROR_NONE = 0, // no error
143 ERROR_CONTENT = 1, // channel errors in SetLocalContent/SetRemoteContent
144 ERROR_TRANSPORT = 2, // transport error of some kind
145 };
146
147 WebRtcSession(
148 webrtc::MediaControllerInterface* media_controller,
149 rtc::Thread* network_thread,
150 rtc::Thread* worker_thread,
151 rtc::Thread* signaling_thread,
152 cricket::PortAllocator* port_allocator,
153 std::unique_ptr<cricket::TransportController> transport_controller);
154 virtual ~WebRtcSession();
155
156 // These are const to allow them to be called from const methods.
157 rtc::Thread* network_thread() const { return network_thread_; }
158 rtc::Thread* worker_thread() const { return worker_thread_; }
159 rtc::Thread* signaling_thread() const { return signaling_thread_; }
160
161 // The ID of this session.
162 const std::string& id() const { return sid_; }
163
164 bool Initialize(
165 const PeerConnectionFactoryInterface::Options& options,
166 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
167 const PeerConnectionInterface::RTCConfiguration& rtc_configuration);
168 // Deletes the voice, video and data channel and changes the session state
169 // to STATE_CLOSED.
170 void Close();
171
172 // Returns true if we were the initial offerer.
173 bool initial_offerer() const { return initial_offerer_; }
174
175 // Returns the current state of the session. See the enum above for details.
176 // Each time the state changes, we will fire this signal.
177 State state() const { return state_; }
178 sigslot::signal2<WebRtcSession*, State> SignalState;
179
180 // Returns the last error in the session. See the enum above for details.
181 Error error() const { return error_; }
182 const std::string& error_desc() const { return error_desc_; }
183
184 void RegisterIceObserver(IceObserver* observer) {
185 ice_observer_ = observer;
186 }
187
188 virtual cricket::VoiceChannel* voice_channel() {
189 return voice_channel_.get();
190 }
191 virtual cricket::VideoChannel* video_channel() {
192 return video_channel_.get();
193 }
194 virtual cricket::DataChannel* data_channel() {
195 return data_channel_.get();
196 }
197
198 cricket::BaseChannel* GetChannel(const std::string& content_name);
199
200 cricket::SecurePolicy SdesPolicy() const;
201
202 // Get current ssl role from transport.
203 bool GetSslRole(const std::string& transport_name, rtc::SSLRole* role);
204
205 // Get current SSL role for this channel's transport.
206 // If |transport| is null, returns false.
207 bool GetSslRole(const cricket::BaseChannel* channel, rtc::SSLRole* role);
208
209 void CreateOffer(
210 CreateSessionDescriptionObserver* observer,
211 const PeerConnectionInterface::RTCOfferAnswerOptions& options,
212 const cricket::MediaSessionOptions& session_options);
213 void CreateAnswer(CreateSessionDescriptionObserver* observer,
214 const cricket::MediaSessionOptions& session_options);
215 // The ownership of |desc| will be transferred after this call.
216 bool SetLocalDescription(SessionDescriptionInterface* desc,
217 std::string* err_desc);
218 // The ownership of |desc| will be transferred after this call.
219 bool SetRemoteDescription(SessionDescriptionInterface* desc,
220 std::string* err_desc);
221 bool ProcessIceMessage(const IceCandidateInterface* ice_candidate);
222
223 bool RemoveRemoteIceCandidates(
224 const std::vector<cricket::Candidate>& candidates);
225
226 cricket::IceConfig ParseIceConfig(
227 const PeerConnectionInterface::RTCConfiguration& config) const;
228
229 void SetIceConfig(const cricket::IceConfig& ice_config);
230
231 // Start gathering candidates for any new transports, or transports doing an
232 // ICE restart.
233 void MaybeStartGathering();
234
235 const SessionDescriptionInterface* local_description() const {
236 return local_desc_.get();
237 }
238 const SessionDescriptionInterface* remote_description() const {
239 return remote_desc_.get();
240 }
241
242 // Get the id used as a media stream track's "id" field from ssrc.
243 virtual bool GetLocalTrackIdBySsrc(uint32_t ssrc, std::string* track_id);
244 virtual bool GetRemoteTrackIdBySsrc(uint32_t ssrc, std::string* track_id);
245
246 // Implements DtmfProviderInterface.
247 bool CanInsertDtmf(const std::string& track_id) override;
248 bool InsertDtmf(const std::string& track_id,
249 int code, int duration) override;
250 sigslot::signal0<>* GetOnDestroyedSignal() override;
251
252 // Implements DataChannelProviderInterface.
253 bool SendData(const cricket::SendDataParams& params,
254 const rtc::CopyOnWriteBuffer& payload,
255 cricket::SendDataResult* result) override;
256 bool ConnectDataChannel(DataChannel* webrtc_data_channel) override;
257 void DisconnectDataChannel(DataChannel* webrtc_data_channel) override;
258 void AddSctpDataStream(int sid) override;
259 void RemoveSctpDataStream(int sid) override;
260 bool ReadyToSendData() const override;
261
262 // Returns stats for all channels of all transports.
263 // This avoids exposing the internal structures used to track them.
264 virtual bool GetTransportStats(SessionStats* stats);
265
266 // Get stats for a specific channel
267 bool GetChannelTransportStats(cricket::BaseChannel* ch, SessionStats* stats);
268
269 // virtual so it can be mocked in unit tests
270 virtual bool GetLocalCertificate(
271 const std::string& transport_name,
272 rtc::scoped_refptr<rtc::RTCCertificate>* certificate);
273
274 // Caller owns returned certificate
275 virtual std::unique_ptr<rtc::SSLCertificate> GetRemoteSSLCertificate(
276 const std::string& transport_name);
277
278 cricket::DataChannelType data_channel_type() const;
279
280 // Returns true if there was an ICE restart initiated by the remote offer.
281 bool IceRestartPending(const std::string& content_name) const;
282
283 // Set the "needs-ice-restart" flag as described in JSEP. After the flag is
284 // set, offers should generate new ufrags/passwords until an ICE restart
285 // occurs.
286 void SetNeedsIceRestartFlag();
287 // Returns true if the ICE restart flag above was set, and no ICE restart has
288 // occurred yet for this transport (by applying a local description with
289 // changed ufrag/password). If the transport has been deleted as a result of
290 // bundling, returns false.
291 bool NeedsIceRestart(const std::string& content_name) const;
292
293 // Called when an RTCCertificate is generated or retrieved by
294 // WebRTCSessionDescriptionFactory. Should happen before setLocalDescription.
295 void OnCertificateReady(
296 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate);
297 void OnDtlsSetupFailure(cricket::BaseChannel*, bool rtcp);
298
299 // For unit test.
300 bool waiting_for_certificate_for_testing() const;
301 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate_for_testing();
302
303 void set_metrics_observer(
304 webrtc::MetricsObserverInterface* metrics_observer) {
305 metrics_observer_ = metrics_observer;
306 transport_controller_->SetMetricsObserver(metrics_observer);
307 }
308
309 // Called when voice_channel_, video_channel_ and data_channel_ are created
310 // and destroyed. As a result of, for example, setting a new description.
311 sigslot::signal0<> SignalVoiceChannelCreated;
312 sigslot::signal0<> SignalVoiceChannelDestroyed;
313 sigslot::signal0<> SignalVideoChannelCreated;
314 sigslot::signal0<> SignalVideoChannelDestroyed;
315 sigslot::signal0<> SignalDataChannelCreated;
316 sigslot::signal0<> SignalDataChannelDestroyed;
317 // Called when the whole session is destroyed.
318 sigslot::signal0<> SignalDestroyed;
319
320 // Called when a valid data channel OPEN message is received.
321 // std::string represents the data channel label.
322 sigslot::signal2<const std::string&, const InternalDataChannelInit&>
323 SignalDataChannelOpenMessage;
324 #ifdef HAVE_QUIC
325 QuicDataTransport* quic_data_transport() {
326 return quic_data_transport_.get();
327 }
328 #endif // HAVE_QUIC
329
330 private:
331 // Indicates the type of SessionDescription in a call to SetLocalDescription
332 // and SetRemoteDescription.
333 enum Action {
334 kOffer,
335 kPrAnswer,
336 kAnswer,
337 };
338
339 // Log session state.
340 void LogState(State old_state, State new_state);
341
342 // Updates the state, signaling if necessary.
343 virtual void SetState(State state);
344
345 // Updates the error state, signaling if necessary.
346 // TODO(ronghuawu): remove the SetError method that doesn't take |error_desc|.
347 virtual void SetError(Error error, const std::string& error_desc);
348
349 bool UpdateSessionState(Action action, cricket::ContentSource source,
350 std::string* err_desc);
351 static Action GetAction(const std::string& type);
352 // Push the media parts of the local or remote session description
353 // down to all of the channels.
354 bool PushdownMediaDescription(cricket::ContentAction action,
355 cricket::ContentSource source,
356 std::string* error_desc);
357
358 bool PushdownTransportDescription(cricket::ContentSource source,
359 cricket::ContentAction action,
360 std::string* error_desc);
361
362 // Helper methods to push local and remote transport descriptions.
363 bool PushdownLocalTransportDescription(
364 const cricket::SessionDescription* sdesc,
365 cricket::ContentAction action,
366 std::string* error_desc);
367 bool PushdownRemoteTransportDescription(
368 const cricket::SessionDescription* sdesc,
369 cricket::ContentAction action,
370 std::string* error_desc);
371
372 // Returns true and the TransportInfo of the given |content_name|
373 // from |description|. Returns false if it's not available.
374 static bool GetTransportDescription(
375 const cricket::SessionDescription* description,
376 const std::string& content_name,
377 cricket::TransportDescription* info);
378
379 // Returns the name of the transport channel when BUNDLE is enabled, or
380 // nullptr if the channel is not part of any bundle.
381 const std::string* GetBundleTransportName(
382 const cricket::ContentInfo* content,
383 const cricket::ContentGroup* bundle);
384
385 // Cause all the BaseChannels in the bundle group to have the same
386 // transport channel.
387 bool EnableBundle(const cricket::ContentGroup& bundle);
388
389 // Enables media channels to allow sending of media.
390 void EnableChannels();
391 // Returns the media index for a local ice candidate given the content name.
392 // Returns false if the local session description does not have a media
393 // content called |content_name|.
394 bool GetLocalCandidateMediaIndex(const std::string& content_name,
395 int* sdp_mline_index);
396 // Uses all remote candidates in |remote_desc| in this session.
397 bool UseCandidatesInSessionDescription(
398 const SessionDescriptionInterface* remote_desc);
399 // Uses |candidate| in this session.
400 bool UseCandidate(const IceCandidateInterface* candidate);
401 // Deletes the corresponding channel of contents that don't exist in |desc|.
402 // |desc| can be null. This means that all channels are deleted.
403 void RemoveUnusedChannels(const cricket::SessionDescription* desc);
404
405 // Allocates media channels based on the |desc|. If |desc| doesn't have
406 // the BUNDLE option, this method will disable BUNDLE in PortAllocator.
407 // This method will also delete any existing media channels before creating.
408 bool CreateChannels(const cricket::SessionDescription* desc);
409
410 // Helper methods to create media channels.
411 bool CreateVoiceChannel(const cricket::ContentInfo* content,
412 const std::string* bundle_transport);
413 bool CreateVideoChannel(const cricket::ContentInfo* content,
414 const std::string* bundle_transport);
415 bool CreateDataChannel(const cricket::ContentInfo* content,
416 const std::string* bundle_transport);
417
418 // Listens to SCTP CONTROL messages on unused SIDs and process them as OPEN
419 // messages.
420 void OnDataChannelMessageReceived(cricket::DataChannel* channel,
421 const cricket::ReceiveDataParams& params,
422 const rtc::CopyOnWriteBuffer& payload);
423
424 std::string BadStateErrMsg(State state);
425 void SetIceConnectionState(PeerConnectionInterface::IceConnectionState state);
426 void SetIceConnectionReceiving(bool receiving);
427
428 bool ValidateBundleSettings(const cricket::SessionDescription* desc);
429 bool HasRtcpMuxEnabled(const cricket::ContentInfo* content);
430 // Below methods are helper methods which verifies SDP.
431 bool ValidateSessionDescription(const SessionDescriptionInterface* sdesc,
432 cricket::ContentSource source,
433 std::string* err_desc);
434
435 // Check if a call to SetLocalDescription is acceptable with |action|.
436 bool ExpectSetLocalDescription(Action action);
437 // Check if a call to SetRemoteDescription is acceptable with |action|.
438 bool ExpectSetRemoteDescription(Action action);
439 // Verifies a=setup attribute as per RFC 5763.
440 bool ValidateDtlsSetupAttribute(const cricket::SessionDescription* desc,
441 Action action);
442
443 // Returns true if we are ready to push down the remote candidate.
444 // |remote_desc| is the new remote description, or NULL if the current remote
445 // description should be used. Output |valid| is true if the candidate media
446 // index is valid.
447 bool ReadyToUseRemoteCandidate(const IceCandidateInterface* candidate,
448 const SessionDescriptionInterface* remote_desc,
449 bool* valid);
450
451 // Returns true if SRTP (either using DTLS-SRTP or SDES) is required by
452 // this session.
453 bool SrtpRequired() const;
454
455 void OnTransportControllerConnectionState(cricket::IceConnectionState state);
456 void OnTransportControllerReceiving(bool receiving);
457 void OnTransportControllerGatheringState(cricket::IceGatheringState state);
458 void OnTransportControllerCandidatesGathered(
459 const std::string& transport_name,
460 const std::vector<cricket::Candidate>& candidates);
461 void OnTransportControllerCandidatesRemoved(
462 const std::vector<cricket::Candidate>& candidates);
463
464 std::string GetSessionErrorMsg();
465
466 // Invoked when TransportController connection completion is signaled.
467 // Reports stats for all transports in use.
468 void ReportTransportStats();
469
470 // Gather the usage of IPv4/IPv6 as best connection.
471 void ReportBestConnectionState(const cricket::TransportStats& stats);
472
473 void ReportNegotiatedCiphers(const cricket::TransportStats& stats);
474
475 void OnSentPacket_w(const rtc::SentPacket& sent_packet);
476
477 const std::string GetTransportName(const std::string& content_name);
478
479 void OnDtlsHandshakeError(rtc::SSLHandshakeError error);
480
481 rtc::Thread* const network_thread_;
482 rtc::Thread* const worker_thread_;
483 rtc::Thread* const signaling_thread_;
484
485 State state_ = STATE_INIT;
486 Error error_ = ERROR_NONE;
487 std::string error_desc_;
488
489 const std::string sid_;
490 bool initial_offerer_ = false;
491
492 std::unique_ptr<cricket::TransportController> transport_controller_;
493 MediaControllerInterface* media_controller_;
494 std::unique_ptr<cricket::VoiceChannel> voice_channel_;
495 std::unique_ptr<cricket::VideoChannel> video_channel_;
496 std::unique_ptr<cricket::DataChannel> data_channel_;
497 cricket::ChannelManager* channel_manager_;
498 IceObserver* ice_observer_;
499 PeerConnectionInterface::IceConnectionState ice_connection_state_;
500 bool ice_connection_receiving_;
501 std::unique_ptr<SessionDescriptionInterface> local_desc_;
502 std::unique_ptr<SessionDescriptionInterface> remote_desc_;
503 // If the remote peer is using a older version of implementation.
504 bool older_version_remote_peer_;
505 bool dtls_enabled_;
506 // Specifies which kind of data channel is allowed. This is controlled
507 // by the chrome command-line flag and constraints:
508 // 1. If chrome command-line switch 'enable-sctp-data-channels' is enabled,
509 // constraint kEnableDtlsSrtp is true, and constaint kEnableRtpDataChannels is
510 // not set or false, SCTP is allowed (DCT_SCTP);
511 // 2. If constraint kEnableRtpDataChannels is true, RTP is allowed (DCT_RTP);
512 // 3. If both 1&2 are false, data channel is not allowed (DCT_NONE).
513 // The data channel type could be DCT_QUIC if the QUIC data channel is
514 // enabled.
515 cricket::DataChannelType data_channel_type_;
516 // List of content names for which the remote side triggered an ICE restart.
517 std::set<std::string> pending_ice_restarts_;
518
519 std::unique_ptr<WebRtcSessionDescriptionFactory> webrtc_session_desc_factory_;
520
521 // Member variables for caching global options.
522 cricket::AudioOptions audio_options_;
523 cricket::VideoOptions video_options_;
524 MetricsObserverInterface* metrics_observer_;
525
526 // Declares the bundle policy for the WebRTCSession.
527 PeerConnectionInterface::BundlePolicy bundle_policy_;
528
529 // Declares the RTCP mux policy for the WebRTCSession.
530 PeerConnectionInterface::RtcpMuxPolicy rtcp_mux_policy_;
531
532 bool received_first_video_packet_ = false;
533 bool received_first_audio_packet_ = false;
534
535 #ifdef HAVE_QUIC
536 std::unique_ptr<QuicDataTransport> quic_data_transport_;
537 #endif // HAVE_QUIC
538
539 RTC_DISALLOW_COPY_AND_ASSIGN(WebRtcSession);
540 };
541 } // namespace webrtc
542
543 #endif // WEBRTC_API_WEBRTCSESSION_H_
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698