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#include <map>
34#include <set>
35#include <utility>
36
37#include "talk/media/base/mediachannel.h"
38#include "talk/media/base/mediaengine.h"
39#include "talk/media/base/streamparams.h"
40#include "talk/media/base/videocapturer.h"
41#include "talk/session/media/audiomonitor.h"
42#include "talk/session/media/bundlefilter.h"
43#include "talk/session/media/mediamonitor.h"
44#include "talk/session/media/mediasession.h"
45#include "talk/session/media/rtcpmuxfilter.h"
46#include "talk/session/media/srtpfilter.h"
47#include "webrtc/audio/audio_sink.h"
48#include "webrtc/base/asyncudpsocket.h"
49#include "webrtc/base/criticalsection.h"
50#include "webrtc/base/network.h"
51#include "webrtc/base/sigslot.h"
52#include "webrtc/base/window.h"
53#include "webrtc/p2p/base/transportcontroller.h"
54#include "webrtc/p2p/client/socketmonitor.h"
55
56namespace webrtc {
57class AudioSinkInterface;
58}  // namespace webrtc
59
60namespace cricket {
61
62struct CryptoParams;
63class MediaContentDescription;
64struct ViewRequest;
65
66enum SinkType {
67  SINK_PRE_CRYPTO,  // Sink packets before encryption or after decryption.
68  SINK_POST_CRYPTO  // Sink packets after encryption or before decryption.
69};
70
71// BaseChannel contains logic common to voice and video, including
72// enable, marshaling calls to a worker thread, and
73// connection and media monitors.
74//
75// WARNING! SUBCLASSES MUST CALL Deinit() IN THEIR DESTRUCTORS!
76// This is required to avoid a data race between the destructor modifying the
77// vtable, and the media channel's thread using BaseChannel as the
78// NetworkInterface.
79
80class BaseChannel
81    : public rtc::MessageHandler, public sigslot::has_slots<>,
82      public MediaChannel::NetworkInterface,
83      public ConnectionStatsGetter {
84 public:
85  BaseChannel(rtc::Thread* thread,
86              MediaChannel* channel,
87              TransportController* transport_controller,
88              const std::string& content_name,
89              bool rtcp);
90  virtual ~BaseChannel();
91  bool Init();
92  // Deinit may be called multiple times and is simply ignored if it's alreay
93  // done.
94  void Deinit();
95
96  rtc::Thread* worker_thread() const { return worker_thread_; }
97  const std::string& content_name() const { return content_name_; }
98  const std::string& transport_name() const { return transport_name_; }
99  TransportChannel* transport_channel() const {
100    return transport_channel_;
101  }
102  TransportChannel* rtcp_transport_channel() const {
103    return rtcp_transport_channel_;
104  }
105  bool enabled() const { return enabled_; }
106
107  // This function returns true if we are using SRTP.
108  bool secure() const { return srtp_filter_.IsActive(); }
109  // The following function returns true if we are using
110  // DTLS-based keying. If you turned off SRTP later, however
111  // you could have secure() == false and dtls_secure() == true.
112  bool secure_dtls() const { return dtls_keyed_; }
113  // This function returns true if we require secure channel for call setup.
114  bool secure_required() const { return secure_required_; }
115
116  bool writable() const { return writable_; }
117
118  // Activate RTCP mux, regardless of the state so far.  Once
119  // activated, it can not be deactivated, and if the remote
120  // description doesn't support RTCP mux, setting the remote
121  // description will fail.
122  void ActivateRtcpMux();
123  bool SetTransport(const std::string& transport_name);
124  bool PushdownLocalDescription(const SessionDescription* local_desc,
125                                ContentAction action,
126                                std::string* error_desc);
127  bool PushdownRemoteDescription(const SessionDescription* remote_desc,
128                                ContentAction action,
129                                std::string* error_desc);
130  // Channel control
131  bool SetLocalContent(const MediaContentDescription* content,
132                       ContentAction action,
133                       std::string* error_desc);
134  bool SetRemoteContent(const MediaContentDescription* content,
135                        ContentAction action,
136                        std::string* error_desc);
137
138  bool Enable(bool enable);
139
140  // Multiplexing
141  bool AddRecvStream(const StreamParams& sp);
142  bool RemoveRecvStream(uint32_t ssrc);
143  bool AddSendStream(const StreamParams& sp);
144  bool RemoveSendStream(uint32_t ssrc);
145
146  // Monitoring
147  void StartConnectionMonitor(int cms);
148  void StopConnectionMonitor();
149  // For ConnectionStatsGetter, used by ConnectionMonitor
150  bool GetConnectionStats(ConnectionInfos* infos) override;
151
152  BundleFilter* bundle_filter() { return &bundle_filter_; }
153
154  const std::vector<StreamParams>& local_streams() const {
155    return local_streams_;
156  }
157  const std::vector<StreamParams>& remote_streams() const {
158    return remote_streams_;
159  }
160
161  sigslot::signal2<BaseChannel*, bool> SignalDtlsSetupFailure;
162  void SignalDtlsSetupFailure_w(bool rtcp);
163  void SignalDtlsSetupFailure_s(bool rtcp);
164
165  // Used for latency measurements.
166  sigslot::signal1<BaseChannel*> SignalFirstPacketReceived;
167
168  // Made public for easier testing.
169  void SetReadyToSend(bool rtcp, bool ready);
170
171  // Only public for unit tests.  Otherwise, consider protected.
172  int SetOption(SocketType type, rtc::Socket::Option o, int val)
173      override;
174
175  SrtpFilter* srtp_filter() { return &srtp_filter_; }
176
177 protected:
178  virtual MediaChannel* media_channel() const { return media_channel_; }
179  // Sets the |transport_channel_| (and |rtcp_transport_channel_|, if |rtcp_| is
180  // true). Gets the transport channels from |transport_controller_|.
181  bool SetTransport_w(const std::string& transport_name);
182
183  void set_transport_channel(TransportChannel* transport);
184  void set_rtcp_transport_channel(TransportChannel* transport,
185                                  bool update_writablity);
186
187  bool was_ever_writable() const { return was_ever_writable_; }
188  void set_local_content_direction(MediaContentDirection direction) {
189    local_content_direction_ = direction;
190  }
191  void set_remote_content_direction(MediaContentDirection direction) {
192    remote_content_direction_ = direction;
193  }
194  void set_secure_required(bool secure_required) {
195    secure_required_ = secure_required;
196  }
197  bool IsReadyToReceive() const;
198  bool IsReadyToSend() const;
199  rtc::Thread* signaling_thread() {
200    return transport_controller_->signaling_thread();
201  }
202  bool rtcp_transport_enabled() const { return rtcp_transport_enabled_; }
203
204  void ConnectToTransportChannel(TransportChannel* tc);
205  void DisconnectFromTransportChannel(TransportChannel* tc);
206
207  void FlushRtcpMessages();
208
209  // NetworkInterface implementation, called by MediaEngine
210  bool SendPacket(rtc::Buffer* packet,
211                          const rtc::PacketOptions& options) override;
212  bool SendRtcp(rtc::Buffer* packet, const rtc::PacketOptions& options)
213      override;
214
215  // From TransportChannel
216  void OnWritableState(TransportChannel* channel);
217  virtual void OnChannelRead(TransportChannel* channel,
218                             const char* data,
219                             size_t len,
220                             const rtc::PacketTime& packet_time,
221                             int flags);
222  void OnReadyToSend(TransportChannel* channel);
223
224  void OnDtlsState(TransportChannel* channel, DtlsTransportState state);
225
226  bool PacketIsRtcp(const TransportChannel* channel, const char* data,
227                    size_t len);
228  bool SendPacket(bool rtcp,
229                  rtc::Buffer* packet,
230                  const rtc::PacketOptions& options);
231  virtual bool WantsPacket(bool rtcp, rtc::Buffer* packet);
232  void HandlePacket(bool rtcp, rtc::Buffer* packet,
233                    const rtc::PacketTime& packet_time);
234
235  void EnableMedia_w();
236  void DisableMedia_w();
237  void UpdateWritableState_w();
238  void ChannelWritable_w();
239  void ChannelNotWritable_w();
240  bool AddRecvStream_w(const StreamParams& sp);
241  bool RemoveRecvStream_w(uint32_t ssrc);
242  bool AddSendStream_w(const StreamParams& sp);
243  bool RemoveSendStream_w(uint32_t ssrc);
244  virtual bool ShouldSetupDtlsSrtp() const;
245  // Do the DTLS key expansion and impose it on the SRTP/SRTCP filters.
246  // |rtcp_channel| indicates whether to set up the RTP or RTCP filter.
247  bool SetupDtlsSrtp(bool rtcp_channel);
248  void MaybeSetupDtlsSrtp_w();
249  // Set the DTLS-SRTP cipher policy on this channel as appropriate.
250  bool SetDtlsSrtpCryptoSuites(TransportChannel* tc, bool rtcp);
251
252  virtual void ChangeState() = 0;
253
254  // Gets the content info appropriate to the channel (audio or video).
255  virtual const ContentInfo* GetFirstContent(
256      const SessionDescription* sdesc) = 0;
257  bool UpdateLocalStreams_w(const std::vector<StreamParams>& streams,
258                            ContentAction action,
259                            std::string* error_desc);
260  bool UpdateRemoteStreams_w(const std::vector<StreamParams>& streams,
261                             ContentAction action,
262                             std::string* error_desc);
263  virtual bool SetLocalContent_w(const MediaContentDescription* content,
264                                 ContentAction action,
265                                 std::string* error_desc) = 0;
266  virtual bool SetRemoteContent_w(const MediaContentDescription* content,
267                                  ContentAction action,
268                                  std::string* error_desc) = 0;
269  bool SetRtpTransportParameters_w(const MediaContentDescription* content,
270                                   ContentAction action,
271                                   ContentSource src,
272                                   std::string* error_desc);
273
274  // Helper method to get RTP Absoulute SendTime extension header id if
275  // present in remote supported extensions list.
276  void MaybeCacheRtpAbsSendTimeHeaderExtension(
277      const std::vector<RtpHeaderExtension>& extensions);
278
279  bool CheckSrtpConfig(const std::vector<CryptoParams>& cryptos,
280                       bool* dtls,
281                       std::string* error_desc);
282  bool SetSrtp_w(const std::vector<CryptoParams>& params,
283                 ContentAction action,
284                 ContentSource src,
285                 std::string* error_desc);
286  void ActivateRtcpMux_w();
287  bool SetRtcpMux_w(bool enable,
288                    ContentAction action,
289                    ContentSource src,
290                    std::string* error_desc);
291
292  // From MessageHandler
293  void OnMessage(rtc::Message* pmsg) override;
294
295  // Handled in derived classes
296  // Get the SRTP crypto suites to use for RTP media
297  virtual void GetSrtpCryptoSuites(std::vector<int>* crypto_suites) const = 0;
298  virtual void OnConnectionMonitorUpdate(ConnectionMonitor* monitor,
299      const std::vector<ConnectionInfo>& infos) = 0;
300
301  // Helper function for invoking bool-returning methods on the worker thread.
302  template <class FunctorT>
303  bool InvokeOnWorker(const FunctorT& functor) {
304    return worker_thread_->Invoke<bool>(functor);
305  }
306
307 private:
308  rtc::Thread* worker_thread_;
309  TransportController* transport_controller_;
310  MediaChannel* media_channel_;
311  std::vector<StreamParams> local_streams_;
312  std::vector<StreamParams> remote_streams_;
313
314  const std::string content_name_;
315  std::string transport_name_;
316  bool rtcp_transport_enabled_;
317  TransportChannel* transport_channel_;
318  std::vector<std::pair<rtc::Socket::Option, int> > socket_options_;
319  TransportChannel* rtcp_transport_channel_;
320  std::vector<std::pair<rtc::Socket::Option, int> > rtcp_socket_options_;
321  SrtpFilter srtp_filter_;
322  RtcpMuxFilter rtcp_mux_filter_;
323  BundleFilter bundle_filter_;
324  rtc::scoped_ptr<ConnectionMonitor> connection_monitor_;
325  bool enabled_;
326  bool writable_;
327  bool rtp_ready_to_send_;
328  bool rtcp_ready_to_send_;
329  bool was_ever_writable_;
330  MediaContentDirection local_content_direction_;
331  MediaContentDirection remote_content_direction_;
332  bool has_received_packet_;
333  bool dtls_keyed_;
334  bool secure_required_;
335  int rtp_abs_sendtime_extn_id_;
336};
337
338// VoiceChannel is a specialization that adds support for early media, DTMF,
339// and input/output level monitoring.
340class VoiceChannel : public BaseChannel {
341 public:
342  VoiceChannel(rtc::Thread* thread,
343               MediaEngineInterface* media_engine,
344               VoiceMediaChannel* channel,
345               TransportController* transport_controller,
346               const std::string& content_name,
347               bool rtcp);
348  ~VoiceChannel();
349  bool Init();
350
351  // Configure sending media on the stream with SSRC |ssrc|
352  // If there is only one sending stream SSRC 0 can be used.
353  bool SetAudioSend(uint32_t ssrc,
354                    bool enable,
355                    const AudioOptions* options,
356                    AudioRenderer* renderer);
357
358  // downcasts a MediaChannel
359  virtual VoiceMediaChannel* media_channel() const {
360    return static_cast<VoiceMediaChannel*>(BaseChannel::media_channel());
361  }
362
363  void SetEarlyMedia(bool enable);
364  // This signal is emitted when we have gone a period of time without
365  // receiving early media. When received, a UI should start playing its
366  // own ringing sound
367  sigslot::signal1<VoiceChannel*> SignalEarlyMediaTimeout;
368
369  // Returns if the telephone-event has been negotiated.
370  bool CanInsertDtmf();
371  // Send and/or play a DTMF |event| according to the |flags|.
372  // The DTMF out-of-band signal will be used on sending.
373  // The |ssrc| should be either 0 or a valid send stream ssrc.
374  // The valid value for the |event| are 0 which corresponding to DTMF
375  // event 0-9, *, #, A-D.
376  bool InsertDtmf(uint32_t ssrc, int event_code, int duration);
377  bool SetOutputVolume(uint32_t ssrc, double volume);
378  void SetRawAudioSink(uint32_t ssrc,
379                       rtc::scoped_ptr<webrtc::AudioSinkInterface> sink);
380
381  // Get statistics about the current media session.
382  bool GetStats(VoiceMediaInfo* stats);
383
384  // Monitoring functions
385  sigslot::signal2<VoiceChannel*, const std::vector<ConnectionInfo>&>
386      SignalConnectionMonitor;
387
388  void StartMediaMonitor(int cms);
389  void StopMediaMonitor();
390  sigslot::signal2<VoiceChannel*, const VoiceMediaInfo&> SignalMediaMonitor;
391
392  void StartAudioMonitor(int cms);
393  void StopAudioMonitor();
394  bool IsAudioMonitorRunning() const;
395  sigslot::signal2<VoiceChannel*, const AudioInfo&> SignalAudioMonitor;
396
397  int GetInputLevel_w();
398  int GetOutputLevel_w();
399  void GetActiveStreams_w(AudioInfo::StreamList* actives);
400
401 private:
402  // overrides from BaseChannel
403  virtual void OnChannelRead(TransportChannel* channel,
404                             const char* data, size_t len,
405                             const rtc::PacketTime& packet_time,
406                             int flags);
407  virtual void ChangeState();
408  virtual const ContentInfo* GetFirstContent(const SessionDescription* sdesc);
409  virtual bool SetLocalContent_w(const MediaContentDescription* content,
410                                 ContentAction action,
411                                 std::string* error_desc);
412  virtual bool SetRemoteContent_w(const MediaContentDescription* content,
413                                  ContentAction action,
414                                  std::string* error_desc);
415  void HandleEarlyMediaTimeout();
416  bool InsertDtmf_w(uint32_t ssrc, int event, int duration);
417  bool SetOutputVolume_w(uint32_t ssrc, double volume);
418  bool GetStats_w(VoiceMediaInfo* stats);
419
420  virtual void OnMessage(rtc::Message* pmsg);
421  virtual void GetSrtpCryptoSuites(std::vector<int>* crypto_suites) const;
422  virtual void OnConnectionMonitorUpdate(
423      ConnectionMonitor* monitor, const std::vector<ConnectionInfo>& infos);
424  virtual void OnMediaMonitorUpdate(
425      VoiceMediaChannel* media_channel, const VoiceMediaInfo& info);
426  void OnAudioMonitorUpdate(AudioMonitor* monitor, const AudioInfo& info);
427
428  static const int kEarlyMediaTimeout = 1000;
429  MediaEngineInterface* media_engine_;
430  bool received_media_;
431  rtc::scoped_ptr<VoiceMediaMonitor> media_monitor_;
432  rtc::scoped_ptr<AudioMonitor> audio_monitor_;
433
434  // Last AudioSendParameters sent down to the media_channel() via
435  // SetSendParameters.
436  AudioSendParameters last_send_params_;
437  // Last AudioRecvParameters sent down to the media_channel() via
438  // SetRecvParameters.
439  AudioRecvParameters last_recv_params_;
440};
441
442// VideoChannel is a specialization for video.
443class VideoChannel : public BaseChannel {
444 public:
445  VideoChannel(rtc::Thread* thread,
446               VideoMediaChannel* channel,
447               TransportController* transport_controller,
448               const std::string& content_name,
449               bool rtcp);
450  ~VideoChannel();
451  bool Init();
452
453  // downcasts a MediaChannel
454  virtual VideoMediaChannel* media_channel() const {
455    return static_cast<VideoMediaChannel*>(BaseChannel::media_channel());
456  }
457
458  bool SetRenderer(uint32_t ssrc, VideoRenderer* renderer);
459  bool ApplyViewRequest(const ViewRequest& request);
460
461  // TODO(pthatcher): Refactor to use a "capture id" instead of an
462  // ssrc here as the "key".
463  // Passes ownership of the capturer to the channel.
464  bool AddScreencast(uint32_t ssrc, VideoCapturer* capturer);
465  bool SetCapturer(uint32_t ssrc, VideoCapturer* capturer);
466  bool RemoveScreencast(uint32_t ssrc);
467  // True if we've added a screencast.  Doesn't matter if the capturer
468  // has been started or not.
469  bool IsScreencasting();
470  // Get statistics about the current media session.
471  bool GetStats(VideoMediaInfo* stats);
472
473  sigslot::signal2<VideoChannel*, const std::vector<ConnectionInfo>&>
474      SignalConnectionMonitor;
475
476  void StartMediaMonitor(int cms);
477  void StopMediaMonitor();
478  sigslot::signal2<VideoChannel*, const VideoMediaInfo&> SignalMediaMonitor;
479  sigslot::signal2<uint32_t, rtc::WindowEvent> SignalScreencastWindowEvent;
480
481  bool SendIntraFrame();
482  bool RequestIntraFrame();
483
484  bool SetVideoSend(uint32_t ssrc, bool enable, const VideoOptions* options);
485
486 private:
487  typedef std::map<uint32_t, VideoCapturer*> ScreencastMap;
488
489  // overrides from BaseChannel
490  virtual void ChangeState();
491  virtual const ContentInfo* GetFirstContent(const SessionDescription* sdesc);
492  virtual bool SetLocalContent_w(const MediaContentDescription* content,
493                                 ContentAction action,
494                                 std::string* error_desc);
495  virtual bool SetRemoteContent_w(const MediaContentDescription* content,
496                                  ContentAction action,
497                                  std::string* error_desc);
498  bool ApplyViewRequest_w(const ViewRequest& request);
499
500  bool AddScreencast_w(uint32_t ssrc, VideoCapturer* capturer);
501  bool RemoveScreencast_w(uint32_t ssrc);
502  void OnScreencastWindowEvent_s(uint32_t ssrc, rtc::WindowEvent we);
503  bool IsScreencasting_w() const;
504  bool GetStats_w(VideoMediaInfo* stats);
505
506  virtual void OnMessage(rtc::Message* pmsg);
507  virtual void GetSrtpCryptoSuites(std::vector<int>* crypto_suites) const;
508  virtual void OnConnectionMonitorUpdate(
509      ConnectionMonitor* monitor, const std::vector<ConnectionInfo>& infos);
510  virtual void OnMediaMonitorUpdate(
511      VideoMediaChannel* media_channel, const VideoMediaInfo& info);
512  virtual void OnScreencastWindowEvent(uint32_t ssrc, rtc::WindowEvent event);
513  virtual void OnStateChange(VideoCapturer* capturer, CaptureState ev);
514  bool GetLocalSsrc(const VideoCapturer* capturer, uint32_t* ssrc);
515
516  VideoRenderer* renderer_;
517  ScreencastMap screencast_capturers_;
518  rtc::scoped_ptr<VideoMediaMonitor> media_monitor_;
519
520  rtc::WindowEvent previous_we_;
521
522  // Last VideoSendParameters sent down to the media_channel() via
523  // SetSendParameters.
524  VideoSendParameters last_send_params_;
525  // Last VideoRecvParameters sent down to the media_channel() via
526  // SetRecvParameters.
527  VideoRecvParameters last_recv_params_;
528};
529
530// DataChannel is a specialization for data.
531class DataChannel : public BaseChannel {
532 public:
533  DataChannel(rtc::Thread* thread,
534              DataMediaChannel* media_channel,
535              TransportController* transport_controller,
536              const std::string& content_name,
537              bool rtcp);
538  ~DataChannel();
539  bool Init();
540
541  virtual bool SendData(const SendDataParams& params,
542                        const rtc::Buffer& payload,
543                        SendDataResult* result);
544
545  void StartMediaMonitor(int cms);
546  void StopMediaMonitor();
547
548  // Should be called on the signaling thread only.
549  bool ready_to_send_data() const {
550    return ready_to_send_data_;
551  }
552
553  sigslot::signal2<DataChannel*, const DataMediaInfo&> SignalMediaMonitor;
554  sigslot::signal2<DataChannel*, const std::vector<ConnectionInfo>&>
555      SignalConnectionMonitor;
556  sigslot::signal3<DataChannel*, const ReceiveDataParams&, const rtc::Buffer&>
557      SignalDataReceived;
558  // Signal for notifying when the channel becomes ready to send data.
559  // That occurs when the channel is enabled, the transport is writable,
560  // both local and remote descriptions are set, and the channel is unblocked.
561  sigslot::signal1<bool> SignalReadyToSendData;
562  // Signal for notifying that the remote side has closed the DataChannel.
563  sigslot::signal1<uint32_t> SignalStreamClosedRemotely;
564
565 protected:
566  // downcasts a MediaChannel.
567  virtual DataMediaChannel* media_channel() const {
568    return static_cast<DataMediaChannel*>(BaseChannel::media_channel());
569  }
570
571 private:
572  struct SendDataMessageData : public rtc::MessageData {
573    SendDataMessageData(const SendDataParams& params,
574                        const rtc::Buffer* payload,
575                        SendDataResult* result)
576        : params(params),
577          payload(payload),
578          result(result),
579          succeeded(false) {
580    }
581
582    const SendDataParams& params;
583    const rtc::Buffer* payload;
584    SendDataResult* result;
585    bool succeeded;
586  };
587
588  struct DataReceivedMessageData : public rtc::MessageData {
589    // We copy the data because the data will become invalid after we
590    // handle DataMediaChannel::SignalDataReceived but before we fire
591    // SignalDataReceived.
592    DataReceivedMessageData(
593        const ReceiveDataParams& params, const char* data, size_t len)
594        : params(params),
595          payload(data, len) {
596    }
597    const ReceiveDataParams params;
598    const rtc::Buffer payload;
599  };
600
601  typedef rtc::TypedMessageData<bool> DataChannelReadyToSendMessageData;
602
603  // overrides from BaseChannel
604  virtual const ContentInfo* GetFirstContent(const SessionDescription* sdesc);
605  // If data_channel_type_ is DCT_NONE, set it.  Otherwise, check that
606  // it's the same as what was set previously.  Returns false if it's
607  // set to one type one type and changed to another type later.
608  bool SetDataChannelType(DataChannelType new_data_channel_type,
609                          std::string* error_desc);
610  // Same as SetDataChannelType, but extracts the type from the
611  // DataContentDescription.
612  bool SetDataChannelTypeFromContent(const DataContentDescription* content,
613                                     std::string* error_desc);
614  virtual bool SetLocalContent_w(const MediaContentDescription* content,
615                                 ContentAction action,
616                                 std::string* error_desc);
617  virtual bool SetRemoteContent_w(const MediaContentDescription* content,
618                                  ContentAction action,
619                                  std::string* error_desc);
620  virtual void ChangeState();
621  virtual bool WantsPacket(bool rtcp, rtc::Buffer* packet);
622
623  virtual void OnMessage(rtc::Message* pmsg);
624  virtual void GetSrtpCryptoSuites(std::vector<int>* crypto_suites) const;
625  virtual void OnConnectionMonitorUpdate(
626      ConnectionMonitor* monitor, const std::vector<ConnectionInfo>& infos);
627  virtual void OnMediaMonitorUpdate(
628      DataMediaChannel* media_channel, const DataMediaInfo& info);
629  virtual bool ShouldSetupDtlsSrtp() const;
630  void OnDataReceived(
631      const ReceiveDataParams& params, const char* data, size_t len);
632  void OnDataChannelError(uint32_t ssrc, DataMediaChannel::Error error);
633  void OnDataChannelReadyToSend(bool writable);
634  void OnStreamClosedRemotely(uint32_t sid);
635
636  rtc::scoped_ptr<DataMediaMonitor> media_monitor_;
637  // TODO(pthatcher): Make a separate SctpDataChannel and
638  // RtpDataChannel instead of using this.
639  DataChannelType data_channel_type_;
640  bool ready_to_send_data_;
641
642  // Last DataSendParameters sent down to the media_channel() via
643  // SetSendParameters.
644  DataSendParameters last_send_params_;
645  // Last DataRecvParameters sent down to the media_channel() via
646  // SetRecvParameters.
647  DataRecvParameters last_recv_params_;
648};
649
650}  // namespace cricket
651
652#endif  // TALK_SESSION_MEDIA_CHANNEL_H_
653