Upstream version 6.35.121.0
[platform/framework/web/crosswalk.git] / src / third_party / libjingle / source / talk / app / webrtc / webrtcsession.h
1 /*
2  * libjingle
3  * Copyright 2012, Google Inc.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  *  1. Redistributions of source code must retain the above copyright notice,
9  *     this list of conditions and the following disclaimer.
10  *  2. Redistributions in binary form must reproduce the above copyright notice,
11  *     this list of conditions and the following disclaimer in the documentation
12  *     and/or other materials provided with the distribution.
13  *  3. The name of the author may not be used to endorse or promote products
14  *     derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19  * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #ifndef TALK_APP_WEBRTC_WEBRTCSESSION_H_
29 #define TALK_APP_WEBRTC_WEBRTCSESSION_H_
30
31 #include <string>
32
33 #include "talk/app/webrtc/peerconnectioninterface.h"
34 #include "talk/app/webrtc/dtmfsender.h"
35 #include "talk/app/webrtc/mediastreamprovider.h"
36 #include "talk/app/webrtc/datachannel.h"
37 #include "talk/app/webrtc/statstypes.h"
38 #include "talk/base/sigslot.h"
39 #include "talk/base/thread.h"
40 #include "talk/media/base/mediachannel.h"
41 #include "talk/p2p/base/session.h"
42 #include "talk/session/media/mediasession.h"
43
44 namespace cricket {
45
46 class BaseChannel;
47 class ChannelManager;
48 class DataChannel;
49 class StatsReport;
50 class Transport;
51 class VideoCapturer;
52 class VideoChannel;
53 class VoiceChannel;
54
55 }  // namespace cricket
56
57 namespace webrtc {
58 class IceRestartAnswerLatch;
59 class MediaStreamSignaling;
60 class WebRtcSessionDescriptionFactory;
61
62 extern const char kBundleWithoutRtcpMux[];
63 extern const char kCreateChannelFailed[];
64 extern const char kInvalidCandidates[];
65 extern const char kInvalidSdp[];
66 extern const char kMlineMismatch[];
67 extern const char kPushDownTDFailed[];
68 extern const char kSdpWithoutDtlsFingerprint[];
69 extern const char kSdpWithoutSdesCrypto[];
70 extern const char kSdpWithoutIceUfragPwd[];
71 extern const char kSdpWithoutSdesAndDtlsDisabled[];
72 extern const char kSessionError[];
73 extern const char kSessionErrorDesc[];
74
75 // ICE state callback interface.
76 class IceObserver {
77  public:
78   IceObserver() {}
79   // Called any time the IceConnectionState changes
80   virtual void OnIceConnectionChange(
81       PeerConnectionInterface::IceConnectionState new_state) {}
82   // Called any time the IceGatheringState changes
83   virtual void OnIceGatheringChange(
84       PeerConnectionInterface::IceGatheringState new_state) {}
85   // New Ice candidate have been found.
86   virtual void OnIceCandidate(const IceCandidateInterface* candidate) = 0;
87   // All Ice candidates have been found.
88   // TODO(bemasc): Remove this once callers transition to OnIceGatheringChange.
89   // (via PeerConnectionObserver)
90   virtual void OnIceComplete() {}
91
92  protected:
93   ~IceObserver() {}
94
95  private:
96   DISALLOW_COPY_AND_ASSIGN(IceObserver);
97 };
98
99 class WebRtcSession : public cricket::BaseSession,
100                       public AudioProviderInterface,
101                       public DataChannelFactory,
102                       public VideoProviderInterface,
103                       public DtmfProviderInterface,
104                       public DataChannelProviderInterface {
105  public:
106   WebRtcSession(cricket::ChannelManager* channel_manager,
107                 talk_base::Thread* signaling_thread,
108                 talk_base::Thread* worker_thread,
109                 cricket::PortAllocator* port_allocator,
110                 MediaStreamSignaling* mediastream_signaling);
111   virtual ~WebRtcSession();
112
113   bool Initialize(const PeerConnectionFactoryInterface::Options& options,
114                   const MediaConstraintsInterface* constraints,
115                   DTLSIdentityServiceInterface* dtls_identity_service);
116   // Deletes the voice, video and data channel and changes the session state
117   // to STATE_RECEIVEDTERMINATE.
118   void Terminate();
119
120   void RegisterIceObserver(IceObserver* observer) {
121     ice_observer_ = observer;
122   }
123
124   virtual cricket::VoiceChannel* voice_channel() {
125     return voice_channel_.get();
126   }
127   virtual cricket::VideoChannel* video_channel() {
128     return video_channel_.get();
129   }
130   virtual cricket::DataChannel* data_channel() {
131     return data_channel_.get();
132   }
133
134   void SetSdesPolicy(cricket::SecurePolicy secure_policy);
135   cricket::SecurePolicy SdesPolicy() const;
136
137   // Get current ssl role from transport.
138   bool GetSslRole(talk_base::SSLRole* role);
139
140   // Generic error message callback from WebRtcSession.
141   // TODO - It may be necessary to supply error code as well.
142   sigslot::signal0<> SignalError;
143
144   void CreateOffer(CreateSessionDescriptionObserver* observer,
145                    const MediaConstraintsInterface* constraints);
146   void CreateAnswer(CreateSessionDescriptionObserver* observer,
147                     const MediaConstraintsInterface* constraints);
148   // The ownership of |desc| will be transferred after this call.
149   bool SetLocalDescription(SessionDescriptionInterface* desc,
150                            std::string* err_desc);
151   // The ownership of |desc| will be transferred after this call.
152   bool SetRemoteDescription(SessionDescriptionInterface* desc,
153                             std::string* err_desc);
154   bool ProcessIceMessage(const IceCandidateInterface* ice_candidate);
155   const SessionDescriptionInterface* local_description() const {
156     return local_desc_.get();
157   }
158   const SessionDescriptionInterface* remote_description() const {
159     return remote_desc_.get();
160   }
161
162   // Get the id used as a media stream track's "id" field from ssrc.
163   virtual bool GetTrackIdBySsrc(uint32 ssrc, std::string* id);
164
165   // AudioMediaProviderInterface implementation.
166   virtual void SetAudioPlayout(uint32 ssrc, bool enable,
167                                cricket::AudioRenderer* renderer) OVERRIDE;
168   virtual void SetAudioSend(uint32 ssrc, bool enable,
169                             const cricket::AudioOptions& options,
170                             cricket::AudioRenderer* renderer) OVERRIDE;
171   virtual void SetAudioPlayoutVolume(uint32 ssrc, double volume) OVERRIDE;
172
173   // Implements VideoMediaProviderInterface.
174   virtual bool SetCaptureDevice(uint32 ssrc,
175                                 cricket::VideoCapturer* camera) OVERRIDE;
176   virtual void SetVideoPlayout(uint32 ssrc,
177                                bool enable,
178                                cricket::VideoRenderer* renderer) OVERRIDE;
179   virtual void SetVideoSend(uint32 ssrc, bool enable,
180                             const cricket::VideoOptions* options) OVERRIDE;
181
182   // Implements DtmfProviderInterface.
183   virtual bool CanInsertDtmf(const std::string& track_id);
184   virtual bool InsertDtmf(const std::string& track_id,
185                           int code, int duration);
186   virtual sigslot::signal0<>* GetOnDestroyedSignal();
187
188   // Implements DataChannelProviderInterface.
189   virtual bool SendData(const cricket::SendDataParams& params,
190                         const talk_base::Buffer& payload,
191                         cricket::SendDataResult* result) OVERRIDE;
192   virtual bool ConnectDataChannel(DataChannel* webrtc_data_channel) OVERRIDE;
193   virtual void DisconnectDataChannel(DataChannel* webrtc_data_channel) OVERRIDE;
194   virtual void AddSctpDataStream(uint32 sid) OVERRIDE;
195   virtual void RemoveSctpDataStream(uint32 sid) OVERRIDE;
196   virtual bool ReadyToSendData() const OVERRIDE;
197
198   // Implements DataChannelFactory.
199   talk_base::scoped_refptr<DataChannel> CreateDataChannel(
200       const std::string& label,
201       const InternalDataChannelInit* config) OVERRIDE;
202
203   cricket::DataChannelType data_channel_type() const;
204
205   bool IceRestartPending() const;
206
207   void ResetIceRestartLatch();
208
209   // Called when an SSLIdentity is generated or retrieved by
210   // WebRTCSessionDescriptionFactory. Should happen before setLocalDescription.
211   void OnIdentityReady(talk_base::SSLIdentity* identity);
212
213   // For unit test.
214   bool waiting_for_identity() const;
215
216  private:
217   // Indicates the type of SessionDescription in a call to SetLocalDescription
218   // and SetRemoteDescription.
219   enum Action {
220     kOffer,
221     kPrAnswer,
222     kAnswer,
223   };
224
225   // Invokes ConnectChannels() on transport proxies, which initiates ice
226   // candidates allocation.
227   bool StartCandidatesAllocation();
228   bool UpdateSessionState(Action action, cricket::ContentSource source,
229                           std::string* err_desc);
230   static Action GetAction(const std::string& type);
231
232   // Transport related callbacks, override from cricket::BaseSession.
233   virtual void OnTransportRequestSignaling(cricket::Transport* transport);
234   virtual void OnTransportConnecting(cricket::Transport* transport);
235   virtual void OnTransportWritable(cricket::Transport* transport);
236   virtual void OnTransportCompleted(cricket::Transport* transport);
237   virtual void OnTransportFailed(cricket::Transport* transport);
238   virtual void OnTransportProxyCandidatesReady(
239       cricket::TransportProxy* proxy,
240       const cricket::Candidates& candidates);
241   virtual void OnCandidatesAllocationDone();
242
243   // Creates local session description with audio and video contents.
244   bool CreateDefaultLocalDescription();
245   // Enables media channels to allow sending of media.
246   void EnableChannels();
247   // Creates a JsepIceCandidate and adds it to the local session description
248   // and notify observers. Called when a new local candidate have been found.
249   void ProcessNewLocalCandidate(const std::string& content_name,
250                                 const cricket::Candidates& candidates);
251   // Returns the media index for a local ice candidate given the content name.
252   // Returns false if the local session description does not have a media
253   // content called  |content_name|.
254   bool GetLocalCandidateMediaIndex(const std::string& content_name,
255                                    int* sdp_mline_index);
256   // Uses all remote candidates in |remote_desc| in this session.
257   bool UseCandidatesInSessionDescription(
258       const SessionDescriptionInterface* remote_desc);
259   // Uses |candidate| in this session.
260   bool UseCandidate(const IceCandidateInterface* candidate);
261   // Deletes the corresponding channel of contents that don't exist in |desc|.
262   // |desc| can be null. This means that all channels are deleted.
263   void RemoveUnusedChannelsAndTransports(
264       const cricket::SessionDescription* desc);
265
266   // Allocates media channels based on the |desc|. If |desc| doesn't have
267   // the BUNDLE option, this method will disable BUNDLE in PortAllocator.
268   // This method will also delete any existing media channels before creating.
269   bool CreateChannels(const cricket::SessionDescription* desc);
270
271   // Helper methods to create media channels.
272   bool CreateVoiceChannel(const cricket::ContentInfo* content);
273   bool CreateVideoChannel(const cricket::ContentInfo* content);
274   bool CreateDataChannel(const cricket::ContentInfo* content);
275
276   // Copy the candidates from |saved_candidates_| to |dest_desc|.
277   // The |saved_candidates_| will be cleared after this function call.
278   void CopySavedCandidates(SessionDescriptionInterface* dest_desc);
279
280   // Listens to SCTP CONTROL messages on unused SIDs and process them as OPEN
281   // messages.
282   void OnDataChannelMessageReceived(cricket::DataChannel* channel,
283                                     const cricket::ReceiveDataParams& params,
284                                     const talk_base::Buffer& payload);
285
286   bool GetLocalTrackId(uint32 ssrc, std::string* track_id);
287   bool GetRemoteTrackId(uint32 ssrc, std::string* track_id);
288
289   std::string BadStateErrMsg(State state);
290   void SetIceConnectionState(PeerConnectionInterface::IceConnectionState state);
291
292   bool ValidateBundleSettings(const cricket::SessionDescription* desc);
293   bool HasRtcpMuxEnabled(const cricket::ContentInfo* content);
294   // Below methods are helper methods which verifies SDP.
295   bool ValidateSessionDescription(const SessionDescriptionInterface* sdesc,
296                                   cricket::ContentSource source,
297                                   std::string* err_desc);
298
299   // Check if a call to SetLocalDescription is acceptable with |action|.
300   bool ExpectSetLocalDescription(Action action);
301   // Check if a call to SetRemoteDescription is acceptable with |action|.
302   bool ExpectSetRemoteDescription(Action action);
303   // Verifies a=setup attribute as per RFC 5763.
304   bool ValidateDtlsSetupAttribute(const cricket::SessionDescription* desc,
305                                   Action action);
306
307   std::string GetSessionErrorMsg();
308
309   talk_base::scoped_ptr<cricket::VoiceChannel> voice_channel_;
310   talk_base::scoped_ptr<cricket::VideoChannel> video_channel_;
311   talk_base::scoped_ptr<cricket::DataChannel> data_channel_;
312   cricket::ChannelManager* channel_manager_;
313   MediaStreamSignaling* mediastream_signaling_;
314   IceObserver* ice_observer_;
315   PeerConnectionInterface::IceConnectionState ice_connection_state_;
316   talk_base::scoped_ptr<SessionDescriptionInterface> local_desc_;
317   talk_base::scoped_ptr<SessionDescriptionInterface> remote_desc_;
318   // Candidates that arrived before the remote description was set.
319   std::vector<IceCandidateInterface*> saved_candidates_;
320   // If the remote peer is using a older version of implementation.
321   bool older_version_remote_peer_;
322   bool dtls_enabled_;
323   // Specifies which kind of data channel is allowed. This is controlled
324   // by the chrome command-line flag and constraints:
325   // 1. If chrome command-line switch 'enable-sctp-data-channels' is enabled,
326   // constraint kEnableDtlsSrtp is true, and constaint kEnableRtpDataChannels is
327   // not set or false, SCTP is allowed (DCT_SCTP);
328   // 2. If constraint kEnableRtpDataChannels is true, RTP is allowed (DCT_RTP);
329   // 3. If both 1&2 are false, data channel is not allowed (DCT_NONE).
330   cricket::DataChannelType data_channel_type_;
331   talk_base::scoped_ptr<IceRestartAnswerLatch> ice_restart_latch_;
332
333   talk_base::scoped_ptr<WebRtcSessionDescriptionFactory>
334       webrtc_session_desc_factory_;
335
336   sigslot::signal0<> SignalVoiceChannelDestroyed;
337   sigslot::signal0<> SignalVideoChannelDestroyed;
338   sigslot::signal0<> SignalDataChannelDestroyed;
339
340   // Member variables for caching global options.
341   cricket::AudioOptions audio_options_;
342   cricket::VideoOptions video_options_;
343
344   DISALLOW_COPY_AND_ASSIGN(WebRtcSession);
345 };
346 }  // namespace webrtc
347
348 #endif  // TALK_APP_WEBRTC_WEBRTCSESSION_H_