Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / libjingle / source / talk / session / media / channel.h
1 /*
2  * libjingle
3  * Copyright 2004 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_SESSION_MEDIA_CHANNEL_H_
29 #define TALK_SESSION_MEDIA_CHANNEL_H_
30
31 #include <string>
32 #include <vector>
33
34 #include "talk/base/asyncudpsocket.h"
35 #include "talk/base/criticalsection.h"
36 #include "talk/base/network.h"
37 #include "talk/base/sigslot.h"
38 #include "talk/base/window.h"
39 #include "talk/media/base/mediachannel.h"
40 #include "talk/media/base/mediaengine.h"
41 #include "talk/media/base/screencastid.h"
42 #include "talk/media/base/streamparams.h"
43 #include "talk/media/base/videocapturer.h"
44 #include "talk/p2p/base/session.h"
45 #include "talk/p2p/client/socketmonitor.h"
46 #include "talk/session/media/audiomonitor.h"
47 #include "talk/session/media/mediamonitor.h"
48 #include "talk/session/media/mediasession.h"
49 #include "talk/session/media/rtcpmuxfilter.h"
50 #include "talk/session/media/srtpfilter.h"
51 #include "talk/session/media/ssrcmuxfilter.h"
52
53 namespace cricket {
54
55 struct CryptoParams;
56 class MediaContentDescription;
57 struct TypingMonitorOptions;
58 class TypingMonitor;
59 struct ViewRequest;
60
61 enum SinkType {
62   SINK_PRE_CRYPTO,  // Sink packets before encryption or after decryption.
63   SINK_POST_CRYPTO  // Sink packets after encryption or before decryption.
64 };
65
66 // BaseChannel contains logic common to voice and video, including
67 // enable/mute, marshaling calls to a worker thread, and
68 // connection and media monitors.
69 //
70 // WARNING! SUBCLASSES MUST CALL Deinit() IN THEIR DESTRUCTORS!
71 // This is required to avoid a data race between the destructor modifying the
72 // vtable, and the media channel's thread using BaseChannel as the
73 // NetworkInterface.
74
75 class BaseChannel
76     : public talk_base::MessageHandler, public sigslot::has_slots<>,
77       public MediaChannel::NetworkInterface {
78  public:
79   BaseChannel(talk_base::Thread* thread, MediaEngineInterface* media_engine,
80               MediaChannel* channel, BaseSession* session,
81               const std::string& content_name, bool rtcp);
82   virtual ~BaseChannel();
83   bool Init(TransportChannel* transport_channel,
84             TransportChannel* rtcp_transport_channel);
85   // Deinit may be called multiple times and is simply ignored if it's alreay
86   // done.
87   void Deinit();
88
89   talk_base::Thread* worker_thread() const { return worker_thread_; }
90   BaseSession* session() const { return session_; }
91   const std::string& content_name() { return content_name_; }
92   TransportChannel* transport_channel() const {
93     return transport_channel_;
94   }
95   TransportChannel* rtcp_transport_channel() const {
96     return rtcp_transport_channel_;
97   }
98   bool enabled() const { return enabled_; }
99
100   // This function returns true if we are using SRTP.
101   bool secure() const { return srtp_filter_.IsActive(); }
102   // The following function returns true if we are using
103   // DTLS-based keying. If you turned off SRTP later, however
104   // you could have secure() == false and dtls_secure() == true.
105   bool secure_dtls() const { return dtls_keyed_; }
106   // This function returns true if we require secure channel for call setup.
107   bool secure_required() const { return secure_required_; }
108
109   bool writable() const { return writable_; }
110   bool IsStreamMuted(uint32 ssrc);
111
112   // Channel control
113   bool SetLocalContent(const MediaContentDescription* content,
114                        ContentAction action,
115                        std::string* error_desc);
116   bool SetRemoteContent(const MediaContentDescription* content,
117                         ContentAction action,
118                         std::string* error_desc);
119
120   bool Enable(bool enable);
121   // Mute sending media on the stream with SSRC |ssrc|
122   // If there is only one sending stream SSRC 0 can be used.
123   bool MuteStream(uint32 ssrc, bool mute);
124
125   // Multiplexing
126   bool AddRecvStream(const StreamParams& sp);
127   bool RemoveRecvStream(uint32 ssrc);
128   bool AddSendStream(const StreamParams& sp);
129   bool RemoveSendStream(uint32 ssrc);
130
131   // Monitoring
132   void StartConnectionMonitor(int cms);
133   void StopConnectionMonitor();
134
135   void set_srtp_signal_silent_time(uint32 silent_time) {
136     srtp_filter_.set_signal_silent_time(silent_time);
137   }
138
139   void set_content_name(const std::string& content_name) {
140     ASSERT(signaling_thread()->IsCurrent());
141     ASSERT(!writable_);
142     if (session_->state() != BaseSession::STATE_INIT) {
143       LOG(LS_ERROR) << "Content name for a channel can be changed only "
144                     << "when BaseSession is in STATE_INIT state.";
145       return;
146     }
147     content_name_ = content_name;
148   }
149
150   template <class T>
151   void RegisterSendSink(T* sink,
152                         void (T::*OnPacket)(const void*, size_t, bool),
153                         SinkType type) {
154     talk_base::CritScope cs(&signal_send_packet_cs_);
155     if (SINK_POST_CRYPTO == type) {
156       SignalSendPacketPostCrypto.disconnect(sink);
157       SignalSendPacketPostCrypto.connect(sink, OnPacket);
158     } else {
159       SignalSendPacketPreCrypto.disconnect(sink);
160       SignalSendPacketPreCrypto.connect(sink, OnPacket);
161     }
162   }
163
164   void UnregisterSendSink(sigslot::has_slots<>* sink,
165                           SinkType type) {
166     talk_base::CritScope cs(&signal_send_packet_cs_);
167     if (SINK_POST_CRYPTO == type) {
168       SignalSendPacketPostCrypto.disconnect(sink);
169     } else {
170       SignalSendPacketPreCrypto.disconnect(sink);
171     }
172   }
173
174   bool HasSendSinks(SinkType type) {
175     talk_base::CritScope cs(&signal_send_packet_cs_);
176     if (SINK_POST_CRYPTO == type) {
177       return !SignalSendPacketPostCrypto.is_empty();
178     } else {
179       return !SignalSendPacketPreCrypto.is_empty();
180     }
181   }
182
183   template <class T>
184   void RegisterRecvSink(T* sink,
185                         void (T::*OnPacket)(const void*, size_t, bool),
186                         SinkType type) {
187     talk_base::CritScope cs(&signal_recv_packet_cs_);
188     if (SINK_POST_CRYPTO == type) {
189       SignalRecvPacketPostCrypto.disconnect(sink);
190       SignalRecvPacketPostCrypto.connect(sink, OnPacket);
191     } else {
192       SignalRecvPacketPreCrypto.disconnect(sink);
193       SignalRecvPacketPreCrypto.connect(sink, OnPacket);
194     }
195   }
196
197   void UnregisterRecvSink(sigslot::has_slots<>* sink,
198                           SinkType type) {
199     talk_base::CritScope cs(&signal_recv_packet_cs_);
200     if (SINK_POST_CRYPTO == type) {
201       SignalRecvPacketPostCrypto.disconnect(sink);
202     } else {
203       SignalRecvPacketPreCrypto.disconnect(sink);
204     }
205   }
206
207   bool HasRecvSinks(SinkType type) {
208     talk_base::CritScope cs(&signal_recv_packet_cs_);
209     if (SINK_POST_CRYPTO == type) {
210       return !SignalRecvPacketPostCrypto.is_empty();
211     } else {
212       return !SignalRecvPacketPreCrypto.is_empty();
213     }
214   }
215
216   SsrcMuxFilter* ssrc_filter() { return &ssrc_filter_; }
217
218   const std::vector<StreamParams>& local_streams() const {
219     return local_streams_;
220   }
221   const std::vector<StreamParams>& remote_streams() const {
222     return remote_streams_;
223   }
224
225   // Used for latency measurements.
226   sigslot::signal1<BaseChannel*> SignalFirstPacketReceived;
227
228   // Used to alert UI when the muted status changes, perhaps autonomously.
229   sigslot::repeater2<BaseChannel*, bool> SignalAutoMuted;
230
231   // Made public for easier testing.
232   void SetReadyToSend(TransportChannel* channel, bool ready);
233
234  protected:
235   MediaEngineInterface* media_engine() const { return media_engine_; }
236   virtual MediaChannel* media_channel() const { return media_channel_; }
237   void set_rtcp_transport_channel(TransportChannel* transport);
238   bool was_ever_writable() const { return was_ever_writable_; }
239   void set_local_content_direction(MediaContentDirection direction) {
240     local_content_direction_ = direction;
241   }
242   void set_remote_content_direction(MediaContentDirection direction) {
243     remote_content_direction_ = direction;
244   }
245   bool IsReadyToReceive() const;
246   bool IsReadyToSend() const;
247   talk_base::Thread* signaling_thread() { return session_->signaling_thread(); }
248   SrtpFilter* srtp_filter() { return &srtp_filter_; }
249   bool rtcp() const { return rtcp_; }
250
251   void FlushRtcpMessages();
252
253   // NetworkInterface implementation, called by MediaEngine
254   virtual bool SendPacket(talk_base::Buffer* packet,
255                           talk_base::DiffServCodePoint dscp);
256   virtual bool SendRtcp(talk_base::Buffer* packet,
257                         talk_base::DiffServCodePoint dscp);
258   virtual int SetOption(SocketType type, talk_base::Socket::Option o, int val);
259
260   // From TransportChannel
261   void OnWritableState(TransportChannel* channel);
262   virtual void OnChannelRead(TransportChannel* channel,
263                              const char* data,
264                              size_t len,
265                              const talk_base::PacketTime& packet_time,
266                              int flags);
267   void OnReadyToSend(TransportChannel* channel);
268
269   bool PacketIsRtcp(const TransportChannel* channel, const char* data,
270                     size_t len);
271   bool SendPacket(bool rtcp, talk_base::Buffer* packet,
272                   talk_base::DiffServCodePoint dscp);
273   virtual bool WantsPacket(bool rtcp, talk_base::Buffer* packet);
274   void HandlePacket(bool rtcp, talk_base::Buffer* packet,
275                     const talk_base::PacketTime& packet_time);
276
277   // Apply the new local/remote session description.
278   void OnNewLocalDescription(BaseSession* session, ContentAction action);
279   void OnNewRemoteDescription(BaseSession* session, ContentAction action);
280
281   void EnableMedia_w();
282   void DisableMedia_w();
283   virtual bool MuteStream_w(uint32 ssrc, bool mute);
284   bool IsStreamMuted_w(uint32 ssrc);
285   void ChannelWritable_w();
286   void ChannelNotWritable_w();
287   bool AddRecvStream_w(const StreamParams& sp);
288   bool RemoveRecvStream_w(uint32 ssrc);
289   bool AddSendStream_w(const StreamParams& sp);
290   bool RemoveSendStream_w(uint32 ssrc);
291   virtual bool ShouldSetupDtlsSrtp() const;
292   // Do the DTLS key expansion and impose it on the SRTP/SRTCP filters.
293   // |rtcp_channel| indicates whether to set up the RTP or RTCP filter.
294   bool SetupDtlsSrtp(bool rtcp_channel);
295   // Set the DTLS-SRTP cipher policy on this channel as appropriate.
296   bool SetDtlsSrtpCiphers(TransportChannel *tc, bool rtcp);
297
298   virtual void ChangeState() = 0;
299
300   // Gets the content info appropriate to the channel (audio or video).
301   virtual const ContentInfo* GetFirstContent(
302       const SessionDescription* sdesc) = 0;
303   bool UpdateLocalStreams_w(const std::vector<StreamParams>& streams,
304                             ContentAction action,
305                             std::string* error_desc);
306   bool UpdateRemoteStreams_w(const std::vector<StreamParams>& streams,
307                              ContentAction action,
308                              std::string* error_desc);
309   bool SetBaseLocalContent_w(const MediaContentDescription* content,
310                              ContentAction action,
311                              std::string* error_desc);
312   virtual bool SetLocalContent_w(const MediaContentDescription* content,
313                                  ContentAction action,
314                                  std::string* error_desc) = 0;
315   bool SetBaseRemoteContent_w(const MediaContentDescription* content,
316                               ContentAction action,
317                               std::string* error_desc);
318   virtual bool SetRemoteContent_w(const MediaContentDescription* content,
319                                   ContentAction action,
320                                   std::string* error_desc) = 0;
321
322   bool CheckSrtpConfig(const std::vector<CryptoParams>& cryptos,
323                        bool* dtls,
324                        std::string* error_desc);
325   bool SetSrtp_w(const std::vector<CryptoParams>& params,
326                  ContentAction action,
327                  ContentSource src,
328                  std::string* error_desc);
329   bool SetRtcpMux_w(bool enable,
330                     ContentAction action,
331                     ContentSource src,
332                     std::string* error_desc);
333
334   // From MessageHandler
335   virtual void OnMessage(talk_base::Message* pmsg);
336
337   // Handled in derived classes
338   // Get the SRTP ciphers to use for RTP media
339   virtual void GetSrtpCiphers(std::vector<std::string>* ciphers) const = 0;
340   virtual void OnConnectionMonitorUpdate(SocketMonitor* monitor,
341       const std::vector<ConnectionInfo>& infos) = 0;
342
343   // Helper function for invoking bool-returning methods on the worker thread.
344   template <class FunctorT>
345   bool InvokeOnWorker(const FunctorT& functor) {
346     return worker_thread_->Invoke<bool>(functor);
347   }
348
349  private:
350   sigslot::signal3<const void*, size_t, bool> SignalSendPacketPreCrypto;
351   sigslot::signal3<const void*, size_t, bool> SignalSendPacketPostCrypto;
352   sigslot::signal3<const void*, size_t, bool> SignalRecvPacketPreCrypto;
353   sigslot::signal3<const void*, size_t, bool> SignalRecvPacketPostCrypto;
354   talk_base::CriticalSection signal_send_packet_cs_;
355   talk_base::CriticalSection signal_recv_packet_cs_;
356
357   talk_base::Thread* worker_thread_;
358   MediaEngineInterface* media_engine_;
359   BaseSession* session_;
360   MediaChannel* media_channel_;
361   std::vector<StreamParams> local_streams_;
362   std::vector<StreamParams> remote_streams_;
363
364   std::string content_name_;
365   bool rtcp_;
366   TransportChannel* transport_channel_;
367   TransportChannel* rtcp_transport_channel_;
368   SrtpFilter srtp_filter_;
369   RtcpMuxFilter rtcp_mux_filter_;
370   SsrcMuxFilter ssrc_filter_;
371   talk_base::scoped_ptr<SocketMonitor> socket_monitor_;
372   bool enabled_;
373   bool writable_;
374   bool rtp_ready_to_send_;
375   bool rtcp_ready_to_send_;
376   bool was_ever_writable_;
377   MediaContentDirection local_content_direction_;
378   MediaContentDirection remote_content_direction_;
379   std::set<uint32> muted_streams_;
380   bool has_received_packet_;
381   bool dtls_keyed_;
382   bool secure_required_;
383 };
384
385 // VoiceChannel is a specialization that adds support for early media, DTMF,
386 // and input/output level monitoring.
387 class VoiceChannel : public BaseChannel {
388  public:
389   VoiceChannel(talk_base::Thread* thread, MediaEngineInterface* media_engine,
390                VoiceMediaChannel* channel, BaseSession* session,
391                const std::string& content_name, bool rtcp);
392   ~VoiceChannel();
393   bool Init();
394   bool SetRemoteRenderer(uint32 ssrc, AudioRenderer* renderer);
395   bool SetLocalRenderer(uint32 ssrc, AudioRenderer* renderer);
396
397   // downcasts a MediaChannel
398   virtual VoiceMediaChannel* media_channel() const {
399     return static_cast<VoiceMediaChannel*>(BaseChannel::media_channel());
400   }
401
402   bool SetRingbackTone(const void* buf, int len);
403   void SetEarlyMedia(bool enable);
404   // This signal is emitted when we have gone a period of time without
405   // receiving early media. When received, a UI should start playing its
406   // own ringing sound
407   sigslot::signal1<VoiceChannel*> SignalEarlyMediaTimeout;
408
409   bool PlayRingbackTone(uint32 ssrc, bool play, bool loop);
410   // TODO(ronghuawu): Replace PressDTMF with InsertDtmf.
411   bool PressDTMF(int digit, bool playout);
412   // Returns if the telephone-event has been negotiated.
413   bool CanInsertDtmf();
414   // Send and/or play a DTMF |event| according to the |flags|.
415   // The DTMF out-of-band signal will be used on sending.
416   // The |ssrc| should be either 0 or a valid send stream ssrc.
417   // The valid value for the |event| are 0 which corresponding to DTMF
418   // event 0-9, *, #, A-D.
419   bool InsertDtmf(uint32 ssrc, int event_code, int duration, int flags);
420   bool SetOutputScaling(uint32 ssrc, double left, double right);
421   // Get statistics about the current media session.
422   bool GetStats(VoiceMediaInfo* stats);
423
424   // Monitoring functions
425   sigslot::signal2<VoiceChannel*, const std::vector<ConnectionInfo>&>
426       SignalConnectionMonitor;
427
428   void StartMediaMonitor(int cms);
429   void StopMediaMonitor();
430   sigslot::signal2<VoiceChannel*, const VoiceMediaInfo&> SignalMediaMonitor;
431
432   void StartAudioMonitor(int cms);
433   void StopAudioMonitor();
434   bool IsAudioMonitorRunning() const;
435   sigslot::signal2<VoiceChannel*, const AudioInfo&> SignalAudioMonitor;
436
437   void StartTypingMonitor(const TypingMonitorOptions& settings);
438   void StopTypingMonitor();
439   bool IsTypingMonitorRunning() const;
440
441   // Overrides BaseChannel::MuteStream_w.
442   virtual bool MuteStream_w(uint32 ssrc, bool mute);
443
444   int GetInputLevel_w();
445   int GetOutputLevel_w();
446   void GetActiveStreams_w(AudioInfo::StreamList* actives);
447
448   // Signal errors from VoiceMediaChannel.  Arguments are:
449   //     ssrc(uint32), and error(VoiceMediaChannel::Error).
450   sigslot::signal3<VoiceChannel*, uint32, VoiceMediaChannel::Error>
451       SignalMediaError;
452
453   // Configuration and setting.
454   bool SetChannelOptions(const AudioOptions& options);
455
456  private:
457   // overrides from BaseChannel
458   virtual void OnChannelRead(TransportChannel* channel,
459                              const char* data, size_t len,
460                              const talk_base::PacketTime& packet_time,
461                              int flags);
462   virtual void ChangeState();
463   virtual const ContentInfo* GetFirstContent(const SessionDescription* sdesc);
464   virtual bool SetLocalContent_w(const MediaContentDescription* content,
465                                  ContentAction action,
466                                  std::string* error_desc);
467   virtual bool SetRemoteContent_w(const MediaContentDescription* content,
468                                   ContentAction action,
469                                   std::string* error_desc);
470   bool SetRingbackTone_w(const void* buf, int len);
471   bool PlayRingbackTone_w(uint32 ssrc, bool play, bool loop);
472   void HandleEarlyMediaTimeout();
473   bool InsertDtmf_w(uint32 ssrc, int event, int duration, int flags);
474   bool SetOutputScaling_w(uint32 ssrc, double left, double right);
475   bool GetStats_w(VoiceMediaInfo* stats);
476
477   virtual void OnMessage(talk_base::Message* pmsg);
478   virtual void GetSrtpCiphers(std::vector<std::string>* ciphers) const;
479   virtual void OnConnectionMonitorUpdate(
480       SocketMonitor* monitor, const std::vector<ConnectionInfo>& infos);
481   virtual void OnMediaMonitorUpdate(
482       VoiceMediaChannel* media_channel, const VoiceMediaInfo& info);
483   void OnAudioMonitorUpdate(AudioMonitor* monitor, const AudioInfo& info);
484   void OnVoiceChannelError(uint32 ssrc, VoiceMediaChannel::Error error);
485   void SendLastMediaError();
486   void OnSrtpError(uint32 ssrc, SrtpFilter::Mode mode, SrtpFilter::Error error);
487
488   static const int kEarlyMediaTimeout = 1000;
489   bool received_media_;
490   talk_base::scoped_ptr<VoiceMediaMonitor> media_monitor_;
491   talk_base::scoped_ptr<AudioMonitor> audio_monitor_;
492   talk_base::scoped_ptr<TypingMonitor> typing_monitor_;
493 };
494
495 // VideoChannel is a specialization for video.
496 class VideoChannel : public BaseChannel {
497  public:
498   // Make screen capturer virtual so that it can be overriden in testing.
499   // E.g. used to test that window events are triggered correctly.
500   class ScreenCapturerFactory {
501    public:
502     virtual VideoCapturer* CreateScreenCapturer(const ScreencastId& window) = 0;
503     virtual ~ScreenCapturerFactory() {}
504   };
505
506   VideoChannel(talk_base::Thread* thread, MediaEngineInterface* media_engine,
507                VideoMediaChannel* channel, BaseSession* session,
508                const std::string& content_name, bool rtcp,
509                VoiceChannel* voice_channel);
510   ~VideoChannel();
511   bool Init();
512
513   bool SetRenderer(uint32 ssrc, VideoRenderer* renderer);
514   bool ApplyViewRequest(const ViewRequest& request);
515
516   // TODO(pthatcher): Refactor to use a "capture id" instead of an
517   // ssrc here as the "key".
518   VideoCapturer* AddScreencast(uint32 ssrc, const ScreencastId& id);
519   bool SetCapturer(uint32 ssrc, VideoCapturer* capturer);
520   bool RemoveScreencast(uint32 ssrc);
521   // True if we've added a screencast.  Doesn't matter if the capturer
522   // has been started or not.
523   bool IsScreencasting();
524   int GetScreencastFps(uint32 ssrc);
525   int GetScreencastMaxPixels(uint32 ssrc);
526   // Get statistics about the current media session.
527   bool GetStats(const StatsOptions& options, VideoMediaInfo* stats);
528
529   sigslot::signal2<VideoChannel*, const std::vector<ConnectionInfo>&>
530       SignalConnectionMonitor;
531
532   void StartMediaMonitor(int cms);
533   void StopMediaMonitor();
534   sigslot::signal2<VideoChannel*, const VideoMediaInfo&> SignalMediaMonitor;
535   sigslot::signal2<uint32, talk_base::WindowEvent> SignalScreencastWindowEvent;
536
537   bool SendIntraFrame();
538   bool RequestIntraFrame();
539   sigslot::signal3<VideoChannel*, uint32, VideoMediaChannel::Error>
540       SignalMediaError;
541
542   void SetScreenCaptureFactory(
543       ScreenCapturerFactory* screencapture_factory);
544
545   // Configuration and setting.
546   bool SetChannelOptions(const VideoOptions& options);
547
548  protected:
549   // downcasts a MediaChannel
550   virtual VideoMediaChannel* media_channel() const {
551     return static_cast<VideoMediaChannel*>(BaseChannel::media_channel());
552   }
553
554  private:
555   typedef std::map<uint32, VideoCapturer*> ScreencastMap;
556   struct ScreencastDetailsData;
557
558   // overrides from BaseChannel
559   virtual void ChangeState();
560   virtual const ContentInfo* GetFirstContent(const SessionDescription* sdesc);
561   virtual bool SetLocalContent_w(const MediaContentDescription* content,
562                                  ContentAction action,
563                                  std::string* error_desc);
564   virtual bool SetRemoteContent_w(const MediaContentDescription* content,
565                                   ContentAction action,
566                                   std::string* error_desc);
567   bool ApplyViewRequest_w(const ViewRequest& request);
568
569   VideoCapturer* AddScreencast_w(uint32 ssrc, const ScreencastId& id);
570   bool RemoveScreencast_w(uint32 ssrc);
571   void OnScreencastWindowEvent_s(uint32 ssrc, talk_base::WindowEvent we);
572   bool IsScreencasting_w() const;
573   void GetScreencastDetails_w(ScreencastDetailsData* d) const;
574   void SetScreenCaptureFactory_w(
575       ScreenCapturerFactory* screencapture_factory);
576   bool GetStats_w(VideoMediaInfo* stats);
577
578   virtual void OnMessage(talk_base::Message* pmsg);
579   virtual void GetSrtpCiphers(std::vector<std::string>* ciphers) const;
580   virtual void OnConnectionMonitorUpdate(
581       SocketMonitor* monitor, const std::vector<ConnectionInfo>& infos);
582   virtual void OnMediaMonitorUpdate(
583       VideoMediaChannel* media_channel, const VideoMediaInfo& info);
584   virtual void OnScreencastWindowEvent(uint32 ssrc,
585                                        talk_base::WindowEvent event);
586   virtual void OnStateChange(VideoCapturer* capturer, CaptureState ev);
587   bool GetLocalSsrc(const VideoCapturer* capturer, uint32* ssrc);
588
589   void OnVideoChannelError(uint32 ssrc, VideoMediaChannel::Error error);
590   void OnSrtpError(uint32 ssrc, SrtpFilter::Mode mode, SrtpFilter::Error error);
591
592   VoiceChannel* voice_channel_;
593   VideoRenderer* renderer_;
594   talk_base::scoped_ptr<ScreenCapturerFactory> screencapture_factory_;
595   ScreencastMap screencast_capturers_;
596   talk_base::scoped_ptr<VideoMediaMonitor> media_monitor_;
597
598   talk_base::WindowEvent previous_we_;
599 };
600
601 // DataChannel is a specialization for data.
602 class DataChannel : public BaseChannel {
603  public:
604   DataChannel(talk_base::Thread* thread,
605               DataMediaChannel* media_channel,
606               BaseSession* session,
607               const std::string& content_name,
608               bool rtcp);
609   ~DataChannel();
610   bool Init();
611
612   virtual bool SendData(const SendDataParams& params,
613                         const talk_base::Buffer& payload,
614                         SendDataResult* result);
615
616   void StartMediaMonitor(int cms);
617   void StopMediaMonitor();
618
619   // Should be called on the signaling thread only.
620   bool ready_to_send_data() const {
621     return ready_to_send_data_;
622   }
623
624   sigslot::signal2<DataChannel*, const DataMediaInfo&> SignalMediaMonitor;
625   sigslot::signal2<DataChannel*, const std::vector<ConnectionInfo>&>
626       SignalConnectionMonitor;
627   sigslot::signal3<DataChannel*, uint32, DataMediaChannel::Error>
628       SignalMediaError;
629   sigslot::signal3<DataChannel*,
630                    const ReceiveDataParams&,
631                    const talk_base::Buffer&>
632       SignalDataReceived;
633   // Signal for notifying when the channel becomes ready to send data.
634   // That occurs when the channel is enabled, the transport is writable,
635   // both local and remote descriptions are set, and the channel is unblocked.
636   sigslot::signal1<bool> SignalReadyToSendData;
637
638  protected:
639   // downcasts a MediaChannel.
640   virtual DataMediaChannel* media_channel() const {
641     return static_cast<DataMediaChannel*>(BaseChannel::media_channel());
642   }
643
644  private:
645   struct SendDataMessageData : public talk_base::MessageData {
646     SendDataMessageData(const SendDataParams& params,
647                         const talk_base::Buffer* payload,
648                         SendDataResult* result)
649         : params(params),
650           payload(payload),
651           result(result),
652           succeeded(false) {
653     }
654
655     const SendDataParams& params;
656     const talk_base::Buffer* payload;
657     SendDataResult* result;
658     bool succeeded;
659   };
660
661   struct DataReceivedMessageData : public talk_base::MessageData {
662     // We copy the data because the data will become invalid after we
663     // handle DataMediaChannel::SignalDataReceived but before we fire
664     // SignalDataReceived.
665     DataReceivedMessageData(
666         const ReceiveDataParams& params, const char* data, size_t len)
667         : params(params),
668           payload(data, len) {
669     }
670     const ReceiveDataParams params;
671     const talk_base::Buffer payload;
672   };
673
674   typedef talk_base::TypedMessageData<bool> DataChannelReadyToSendMessageData;
675
676   // overrides from BaseChannel
677   virtual const ContentInfo* GetFirstContent(const SessionDescription* sdesc);
678   // If data_channel_type_ is DCT_NONE, set it.  Otherwise, check that
679   // it's the same as what was set previously.  Returns false if it's
680   // set to one type one type and changed to another type later.
681   bool SetDataChannelType(DataChannelType new_data_channel_type,
682                           std::string* error_desc);
683   // Same as SetDataChannelType, but extracts the type from the
684   // DataContentDescription.
685   bool SetDataChannelTypeFromContent(const DataContentDescription* content,
686                                      std::string* error_desc);
687   virtual bool SetLocalContent_w(const MediaContentDescription* content,
688                                  ContentAction action,
689                                  std::string* error_desc);
690   virtual bool SetRemoteContent_w(const MediaContentDescription* content,
691                                   ContentAction action,
692                                   std::string* error_desc);
693   virtual void ChangeState();
694   virtual bool WantsPacket(bool rtcp, talk_base::Buffer* packet);
695
696   virtual void OnMessage(talk_base::Message* pmsg);
697   virtual void GetSrtpCiphers(std::vector<std::string>* ciphers) const;
698   virtual void OnConnectionMonitorUpdate(
699       SocketMonitor* monitor, const std::vector<ConnectionInfo>& infos);
700   virtual void OnMediaMonitorUpdate(
701       DataMediaChannel* media_channel, const DataMediaInfo& info);
702   virtual bool ShouldSetupDtlsSrtp() const;
703   void OnDataReceived(
704       const ReceiveDataParams& params, const char* data, size_t len);
705   void OnDataChannelError(uint32 ssrc, DataMediaChannel::Error error);
706   void OnDataChannelReadyToSend(bool writable);
707   void OnSrtpError(uint32 ssrc, SrtpFilter::Mode mode, SrtpFilter::Error error);
708
709   talk_base::scoped_ptr<DataMediaMonitor> media_monitor_;
710   // TODO(pthatcher): Make a separate SctpDataChannel and
711   // RtpDataChannel instead of using this.
712   DataChannelType data_channel_type_;
713   bool ready_to_send_data_;
714 };
715
716 }  // namespace cricket
717
718 #endif  // TALK_SESSION_MEDIA_CHANNEL_H_