Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / libjingle / source / talk / media / base / mediachannel.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_MEDIA_BASE_MEDIACHANNEL_H_
29 #define TALK_MEDIA_BASE_MEDIACHANNEL_H_
30
31 #include <string>
32 #include <vector>
33
34 #include "talk/base/basictypes.h"
35 #include "talk/base/buffer.h"
36 #include "talk/base/dscp.h"
37 #include "talk/base/logging.h"
38 #include "talk/base/sigslot.h"
39 #include "talk/base/socket.h"
40 #include "talk/base/window.h"
41 #include "talk/media/base/codec.h"
42 #include "talk/media/base/constants.h"
43 #include "talk/media/base/streamparams.h"
44 // TODO(juberti): re-evaluate this include
45 #include "talk/session/media/audiomonitor.h"
46
47 namespace talk_base {
48 class Buffer;
49 class RateLimiter;
50 class Timing;
51 }
52
53 namespace cricket {
54
55 class AudioRenderer;
56 struct RtpHeader;
57 class ScreencastId;
58 struct VideoFormat;
59 class VideoCapturer;
60 class VideoRenderer;
61
62 const int kMinRtpHeaderExtensionId = 1;
63 const int kMaxRtpHeaderExtensionId = 255;
64 const int kScreencastDefaultFps = 5;
65 const int kHighStartBitrate = 1500;
66
67 // Used in AudioOptions and VideoOptions to signify "unset" values.
68 template <class T>
69 class Settable {
70  public:
71   Settable() : set_(false), val_() {}
72   explicit Settable(T val) : set_(true), val_(val) {}
73
74   bool IsSet() const {
75     return set_;
76   }
77
78   bool Get(T* out) const {
79     *out = val_;
80     return set_;
81   }
82
83   T GetWithDefaultIfUnset(const T& default_value) const {
84     return set_ ? val_ : default_value;
85   }
86
87   virtual void Set(T val) {
88     set_ = true;
89     val_ = val;
90   }
91
92   void Clear() {
93     Set(T());
94     set_ = false;
95   }
96
97   void SetFrom(const Settable<T>& o) {
98     // Set this value based on the value of o, iff o is set.  If this value is
99     // set and o is unset, the current value will be unchanged.
100     T val;
101     if (o.Get(&val)) {
102       Set(val);
103     }
104   }
105
106   std::string ToString() const {
107     return set_ ? talk_base::ToString(val_) : "";
108   }
109
110   bool operator==(const Settable<T>& o) const {
111     // Equal if both are unset with any value or both set with the same value.
112     return (set_ == o.set_) && (!set_ || (val_ == o.val_));
113   }
114
115   bool operator!=(const Settable<T>& o) const {
116     return !operator==(o);
117   }
118
119  protected:
120   void InitializeValue(const T &val) {
121     val_ = val;
122   }
123
124  private:
125   bool set_;
126   T val_;
127 };
128
129 class SettablePercent : public Settable<float> {
130  public:
131   virtual void Set(float val) {
132     if (val < 0) {
133       val = 0;
134     }
135     if (val >  1.0) {
136       val = 1.0;
137     }
138     Settable<float>::Set(val);
139   }
140 };
141
142 template <class T>
143 static std::string ToStringIfSet(const char* key, const Settable<T>& val) {
144   std::string str;
145   if (val.IsSet()) {
146     str = key;
147     str += ": ";
148     str += val.ToString();
149     str += ", ";
150   }
151   return str;
152 }
153
154 // Options that can be applied to a VoiceMediaChannel or a VoiceMediaEngine.
155 // Used to be flags, but that makes it hard to selectively apply options.
156 // We are moving all of the setting of options to structs like this,
157 // but some things currently still use flags.
158 struct AudioOptions {
159   void SetAll(const AudioOptions& change) {
160     echo_cancellation.SetFrom(change.echo_cancellation);
161     auto_gain_control.SetFrom(change.auto_gain_control);
162     rx_auto_gain_control.SetFrom(change.rx_auto_gain_control);
163     noise_suppression.SetFrom(change.noise_suppression);
164     highpass_filter.SetFrom(change.highpass_filter);
165     stereo_swapping.SetFrom(change.stereo_swapping);
166     typing_detection.SetFrom(change.typing_detection);
167     aecm_generate_comfort_noise.SetFrom(change.aecm_generate_comfort_noise);
168     conference_mode.SetFrom(change.conference_mode);
169     adjust_agc_delta.SetFrom(change.adjust_agc_delta);
170     experimental_agc.SetFrom(change.experimental_agc);
171     experimental_aec.SetFrom(change.experimental_aec);
172     experimental_ns.SetFrom(change.experimental_ns);
173     aec_dump.SetFrom(change.aec_dump);
174     tx_agc_target_dbov.SetFrom(change.tx_agc_target_dbov);
175     tx_agc_digital_compression_gain.SetFrom(
176         change.tx_agc_digital_compression_gain);
177     tx_agc_limiter.SetFrom(change.tx_agc_limiter);
178     rx_agc_target_dbov.SetFrom(change.rx_agc_target_dbov);
179     rx_agc_digital_compression_gain.SetFrom(
180         change.rx_agc_digital_compression_gain);
181     rx_agc_limiter.SetFrom(change.rx_agc_limiter);
182     recording_sample_rate.SetFrom(change.recording_sample_rate);
183     playout_sample_rate.SetFrom(change.playout_sample_rate);
184     dscp.SetFrom(change.dscp);
185   }
186
187   bool operator==(const AudioOptions& o) const {
188     return echo_cancellation == o.echo_cancellation &&
189         auto_gain_control == o.auto_gain_control &&
190         rx_auto_gain_control == o.rx_auto_gain_control &&
191         noise_suppression == o.noise_suppression &&
192         highpass_filter == o.highpass_filter &&
193         stereo_swapping == o.stereo_swapping &&
194         typing_detection == o.typing_detection &&
195         aecm_generate_comfort_noise == o.aecm_generate_comfort_noise &&
196         conference_mode == o.conference_mode &&
197         experimental_agc == o.experimental_agc &&
198         experimental_aec == o.experimental_aec &&
199         experimental_ns == o.experimental_ns &&
200         adjust_agc_delta == o.adjust_agc_delta &&
201         aec_dump == o.aec_dump &&
202         tx_agc_target_dbov == o.tx_agc_target_dbov &&
203         tx_agc_digital_compression_gain == o.tx_agc_digital_compression_gain &&
204         tx_agc_limiter == o.tx_agc_limiter &&
205         rx_agc_target_dbov == o.rx_agc_target_dbov &&
206         rx_agc_digital_compression_gain == o.rx_agc_digital_compression_gain &&
207         rx_agc_limiter == o.rx_agc_limiter &&
208         recording_sample_rate == o.recording_sample_rate &&
209         playout_sample_rate == o.playout_sample_rate &&
210         dscp == o.dscp;
211   }
212
213   std::string ToString() const {
214     std::ostringstream ost;
215     ost << "AudioOptions {";
216     ost << ToStringIfSet("aec", echo_cancellation);
217     ost << ToStringIfSet("agc", auto_gain_control);
218     ost << ToStringIfSet("rx_agc", rx_auto_gain_control);
219     ost << ToStringIfSet("ns", noise_suppression);
220     ost << ToStringIfSet("hf", highpass_filter);
221     ost << ToStringIfSet("swap", stereo_swapping);
222     ost << ToStringIfSet("typing", typing_detection);
223     ost << ToStringIfSet("comfort_noise", aecm_generate_comfort_noise);
224     ost << ToStringIfSet("conference", conference_mode);
225     ost << ToStringIfSet("agc_delta", adjust_agc_delta);
226     ost << ToStringIfSet("experimental_agc", experimental_agc);
227     ost << ToStringIfSet("experimental_aec", experimental_aec);
228     ost << ToStringIfSet("experimental_ns", experimental_ns);
229     ost << ToStringIfSet("aec_dump", aec_dump);
230     ost << ToStringIfSet("tx_agc_target_dbov", tx_agc_target_dbov);
231     ost << ToStringIfSet("tx_agc_digital_compression_gain",
232         tx_agc_digital_compression_gain);
233     ost << ToStringIfSet("tx_agc_limiter", tx_agc_limiter);
234     ost << ToStringIfSet("rx_agc_target_dbov", rx_agc_target_dbov);
235     ost << ToStringIfSet("rx_agc_digital_compression_gain",
236         rx_agc_digital_compression_gain);
237     ost << ToStringIfSet("rx_agc_limiter", rx_agc_limiter);
238     ost << ToStringIfSet("recording_sample_rate", recording_sample_rate);
239     ost << ToStringIfSet("playout_sample_rate", playout_sample_rate);
240     ost << ToStringIfSet("dscp", dscp);
241     ost << "}";
242     return ost.str();
243   }
244
245   // Audio processing that attempts to filter away the output signal from
246   // later inbound pickup.
247   Settable<bool> echo_cancellation;
248   // Audio processing to adjust the sensitivity of the local mic dynamically.
249   Settable<bool> auto_gain_control;
250   // Audio processing to apply gain to the remote audio.
251   Settable<bool> rx_auto_gain_control;
252   // Audio processing to filter out background noise.
253   Settable<bool> noise_suppression;
254   // Audio processing to remove background noise of lower frequencies.
255   Settable<bool> highpass_filter;
256   // Audio processing to swap the left and right channels.
257   Settable<bool> stereo_swapping;
258   // Audio processing to detect typing.
259   Settable<bool> typing_detection;
260   Settable<bool> aecm_generate_comfort_noise;
261   Settable<bool> conference_mode;
262   Settable<int> adjust_agc_delta;
263   Settable<bool> experimental_agc;
264   Settable<bool> experimental_aec;
265   Settable<bool> experimental_ns;
266   Settable<bool> aec_dump;
267   // Note that tx_agc_* only applies to non-experimental AGC.
268   Settable<uint16> tx_agc_target_dbov;
269   Settable<uint16> tx_agc_digital_compression_gain;
270   Settable<bool> tx_agc_limiter;
271   Settable<uint16> rx_agc_target_dbov;
272   Settable<uint16> rx_agc_digital_compression_gain;
273   Settable<bool> rx_agc_limiter;
274   Settable<uint32> recording_sample_rate;
275   Settable<uint32> playout_sample_rate;
276   // Set DSCP value for packet sent from audio channel.
277   Settable<bool> dscp;
278 };
279
280 // Options that can be applied to a VideoMediaChannel or a VideoMediaEngine.
281 // Used to be flags, but that makes it hard to selectively apply options.
282 // We are moving all of the setting of options to structs like this,
283 // but some things currently still use flags.
284 struct VideoOptions {
285   enum HighestBitrate {
286     NORMAL,
287     HIGH,
288     VERY_HIGH
289   };
290
291   VideoOptions() {
292     process_adaptation_threshhold.Set(kProcessCpuThreshold);
293     system_low_adaptation_threshhold.Set(kLowSystemCpuThreshold);
294     system_high_adaptation_threshhold.Set(kHighSystemCpuThreshold);
295     unsignalled_recv_stream_limit.Set(kNumDefaultUnsignalledVideoRecvStreams);
296   }
297
298   void SetAll(const VideoOptions& change) {
299     adapt_input_to_encoder.SetFrom(change.adapt_input_to_encoder);
300     adapt_input_to_cpu_usage.SetFrom(change.adapt_input_to_cpu_usage);
301     adapt_cpu_with_smoothing.SetFrom(change.adapt_cpu_with_smoothing);
302     adapt_view_switch.SetFrom(change.adapt_view_switch);
303     video_adapt_third.SetFrom(change.video_adapt_third);
304     video_noise_reduction.SetFrom(change.video_noise_reduction);
305     video_one_layer_screencast.SetFrom(change.video_one_layer_screencast);
306     video_high_bitrate.SetFrom(change.video_high_bitrate);
307     video_start_bitrate.SetFrom(change.video_start_bitrate);
308     video_temporal_layer_screencast.SetFrom(
309         change.video_temporal_layer_screencast);
310     video_temporal_layer_realtime.SetFrom(
311         change.video_temporal_layer_realtime);
312     video_leaky_bucket.SetFrom(change.video_leaky_bucket);
313     video_highest_bitrate.SetFrom(change.video_highest_bitrate);
314     cpu_overuse_detection.SetFrom(change.cpu_overuse_detection);
315     cpu_underuse_threshold.SetFrom(change.cpu_underuse_threshold);
316     cpu_overuse_threshold.SetFrom(change.cpu_overuse_threshold);
317     cpu_overuse_encode_usage.SetFrom(change.cpu_overuse_encode_usage);
318     conference_mode.SetFrom(change.conference_mode);
319     process_adaptation_threshhold.SetFrom(change.process_adaptation_threshhold);
320     system_low_adaptation_threshhold.SetFrom(
321         change.system_low_adaptation_threshhold);
322     system_high_adaptation_threshhold.SetFrom(
323         change.system_high_adaptation_threshhold);
324     buffered_mode_latency.SetFrom(change.buffered_mode_latency);
325     lower_min_bitrate.SetFrom(change.lower_min_bitrate);
326     dscp.SetFrom(change.dscp);
327     suspend_below_min_bitrate.SetFrom(change.suspend_below_min_bitrate);
328     unsignalled_recv_stream_limit.SetFrom(change.unsignalled_recv_stream_limit);
329     use_simulcast_adapter.SetFrom(change.use_simulcast_adapter);
330     skip_encoding_unused_streams.SetFrom(change.skip_encoding_unused_streams);
331     screencast_min_bitrate.SetFrom(change.screencast_min_bitrate);
332     use_improved_wifi_bandwidth_estimator.SetFrom(
333         change.use_improved_wifi_bandwidth_estimator);
334   }
335
336   bool operator==(const VideoOptions& o) const {
337     return adapt_input_to_encoder == o.adapt_input_to_encoder &&
338         adapt_input_to_cpu_usage == o.adapt_input_to_cpu_usage &&
339         adapt_cpu_with_smoothing == o.adapt_cpu_with_smoothing &&
340         adapt_view_switch == o.adapt_view_switch &&
341         video_adapt_third == o.video_adapt_third &&
342         video_noise_reduction == o.video_noise_reduction &&
343         video_one_layer_screencast == o.video_one_layer_screencast &&
344         video_high_bitrate == o.video_high_bitrate &&
345         video_start_bitrate == o.video_start_bitrate &&
346         video_temporal_layer_screencast == o.video_temporal_layer_screencast &&
347         video_temporal_layer_realtime == o.video_temporal_layer_realtime &&
348         video_leaky_bucket == o.video_leaky_bucket &&
349         video_highest_bitrate == o.video_highest_bitrate &&
350         cpu_overuse_detection == o.cpu_overuse_detection &&
351         cpu_underuse_threshold == o.cpu_underuse_threshold &&
352         cpu_overuse_threshold == o.cpu_overuse_threshold &&
353         cpu_overuse_encode_usage == o.cpu_overuse_encode_usage &&
354         conference_mode == o.conference_mode &&
355         process_adaptation_threshhold == o.process_adaptation_threshhold &&
356         system_low_adaptation_threshhold ==
357             o.system_low_adaptation_threshhold &&
358         system_high_adaptation_threshhold ==
359             o.system_high_adaptation_threshhold &&
360         buffered_mode_latency == o.buffered_mode_latency &&
361         lower_min_bitrate == o.lower_min_bitrate &&
362         dscp == o.dscp &&
363         suspend_below_min_bitrate == o.suspend_below_min_bitrate &&
364         unsignalled_recv_stream_limit == o.unsignalled_recv_stream_limit &&
365         use_simulcast_adapter == o.use_simulcast_adapter &&
366         skip_encoding_unused_streams == o.skip_encoding_unused_streams &&
367         screencast_min_bitrate == o.screencast_min_bitrate &&
368         use_improved_wifi_bandwidth_estimator ==
369             o.use_improved_wifi_bandwidth_estimator;
370   }
371
372   std::string ToString() const {
373     std::ostringstream ost;
374     ost << "VideoOptions {";
375     ost << ToStringIfSet("encoder adaption", adapt_input_to_encoder);
376     ost << ToStringIfSet("cpu adaption", adapt_input_to_cpu_usage);
377     ost << ToStringIfSet("cpu adaptation smoothing", adapt_cpu_with_smoothing);
378     ost << ToStringIfSet("adapt view switch", adapt_view_switch);
379     ost << ToStringIfSet("video adapt third", video_adapt_third);
380     ost << ToStringIfSet("noise reduction", video_noise_reduction);
381     ost << ToStringIfSet("1 layer screencast", video_one_layer_screencast);
382     ost << ToStringIfSet("high bitrate", video_high_bitrate);
383     ost << ToStringIfSet("start bitrate", video_start_bitrate);
384     ost << ToStringIfSet("video temporal layer screencast",
385                          video_temporal_layer_screencast);
386     ost << ToStringIfSet("video temporal layer realtime",
387                          video_temporal_layer_realtime);
388     ost << ToStringIfSet("leaky bucket", video_leaky_bucket);
389     ost << ToStringIfSet("highest video bitrate", video_highest_bitrate);
390     ost << ToStringIfSet("cpu overuse detection", cpu_overuse_detection);
391     ost << ToStringIfSet("cpu underuse threshold", cpu_underuse_threshold);
392     ost << ToStringIfSet("cpu overuse threshold", cpu_overuse_threshold);
393     ost << ToStringIfSet("cpu overuse encode usage",
394                          cpu_overuse_encode_usage);
395     ost << ToStringIfSet("conference mode", conference_mode);
396     ost << ToStringIfSet("process", process_adaptation_threshhold);
397     ost << ToStringIfSet("low", system_low_adaptation_threshhold);
398     ost << ToStringIfSet("high", system_high_adaptation_threshhold);
399     ost << ToStringIfSet("buffered mode latency", buffered_mode_latency);
400     ost << ToStringIfSet("lower min bitrate", lower_min_bitrate);
401     ost << ToStringIfSet("dscp", dscp);
402     ost << ToStringIfSet("suspend below min bitrate",
403                          suspend_below_min_bitrate);
404     ost << ToStringIfSet("num channels for early receive",
405                          unsignalled_recv_stream_limit);
406     ost << ToStringIfSet("use simulcast adapter", use_simulcast_adapter);
407     ost << ToStringIfSet("skip encoding unused streams",
408                          skip_encoding_unused_streams);
409     ost << ToStringIfSet("screencast min bitrate", screencast_min_bitrate);
410     ost << ToStringIfSet("improved wifi bwe",
411                          use_improved_wifi_bandwidth_estimator);
412     ost << "}";
413     return ost.str();
414   }
415
416   // Encoder adaption, which is the gd callback in LMI, and TBA in WebRTC.
417   Settable<bool> adapt_input_to_encoder;
418   // Enable CPU adaptation?
419   Settable<bool> adapt_input_to_cpu_usage;
420   // Enable CPU adaptation smoothing?
421   Settable<bool> adapt_cpu_with_smoothing;
422   // Enable Adapt View Switch?
423   Settable<bool> adapt_view_switch;
424   // Enable video adapt third?
425   Settable<bool> video_adapt_third;
426   // Enable denoising?
427   Settable<bool> video_noise_reduction;
428   // Experimental: Enable one layer screencast?
429   Settable<bool> video_one_layer_screencast;
430   // Experimental: Enable WebRtc higher bitrate?
431   Settable<bool> video_high_bitrate;
432   // Experimental: Enable WebRtc higher start bitrate?
433   Settable<int> video_start_bitrate;
434   // Experimental: Enable WebRTC layered screencast.
435   Settable<bool> video_temporal_layer_screencast;
436   // Experimental: Enable WebRTC temporal layer strategy for realtime video.
437   Settable<bool> video_temporal_layer_realtime;
438   // Enable WebRTC leaky bucket when sending media packets.
439   Settable<bool> video_leaky_bucket;
440   // Set highest bitrate mode for video.
441   Settable<HighestBitrate> video_highest_bitrate;
442   // Enable WebRTC Cpu Overuse Detection, which is a new version of the CPU
443   // adaptation algorithm. So this option will override the
444   // |adapt_input_to_cpu_usage|.
445   Settable<bool> cpu_overuse_detection;
446   // Low threshold for cpu overuse adaptation in ms.  (Adapt up)
447   Settable<int> cpu_underuse_threshold;
448   // High threshold for cpu overuse adaptation in ms.  (Adapt down)
449   Settable<int> cpu_overuse_threshold;
450   // Use encode usage for cpu detection.
451   Settable<bool> cpu_overuse_encode_usage;
452   // Use conference mode?
453   Settable<bool> conference_mode;
454   // Threshhold for process cpu adaptation.  (Process limit)
455   SettablePercent process_adaptation_threshhold;
456   // Low threshhold for cpu adaptation.  (Adapt up)
457   SettablePercent system_low_adaptation_threshhold;
458   // High threshhold for cpu adaptation.  (Adapt down)
459   SettablePercent system_high_adaptation_threshhold;
460   // Specify buffered mode latency in milliseconds.
461   Settable<int> buffered_mode_latency;
462   // Make minimum configured send bitrate even lower than usual, at 30kbit.
463   Settable<bool> lower_min_bitrate;
464   // Set DSCP value for packet sent from video channel.
465   Settable<bool> dscp;
466   // Enable WebRTC suspension of video. No video frames will be sent when the
467   // bitrate is below the configured minimum bitrate.
468   Settable<bool> suspend_below_min_bitrate;
469   // Limit on the number of early receive channels that can be created.
470   Settable<int> unsignalled_recv_stream_limit;
471   // Enable use of simulcast adapter.
472   Settable<bool> use_simulcast_adapter;
473   // Enables the encoder to skip encoding stream not actually sent due to too
474   // low available bit rate.
475   Settable<bool> skip_encoding_unused_streams;
476   // Force screencast to use a minimum bitrate
477   Settable<int> screencast_min_bitrate;
478   // Enable improved bandwidth estiamtor on wifi.
479   Settable<bool> use_improved_wifi_bandwidth_estimator;
480 };
481
482 // A class for playing out soundclips.
483 class SoundclipMedia {
484  public:
485   enum SoundclipFlags {
486     SF_LOOP = 1,
487   };
488
489   virtual ~SoundclipMedia() {}
490
491   // Plays a sound out to the speakers with the given audio stream. The stream
492   // must be 16-bit little-endian 16 kHz PCM. If a stream is already playing
493   // on this SoundclipMedia, it is stopped. If clip is NULL, nothing is played.
494   // Returns whether it was successful.
495   virtual bool PlaySound(const char *clip, int len, int flags) = 0;
496 };
497
498 struct RtpHeaderExtension {
499   RtpHeaderExtension() : id(0) {}
500   RtpHeaderExtension(const std::string& u, int i) : uri(u), id(i) {}
501   std::string uri;
502   int id;
503   // TODO(juberti): SendRecv direction;
504
505   bool operator==(const RtpHeaderExtension& ext) const {
506     // id is a reserved word in objective-c. Therefore the id attribute has to
507     // be a fully qualified name in order to compile on IOS.
508     return this->id == ext.id &&
509         uri == ext.uri;
510   }
511 };
512
513 // Returns the named header extension if found among all extensions, NULL
514 // otherwise.
515 inline const RtpHeaderExtension* FindHeaderExtension(
516     const std::vector<RtpHeaderExtension>& extensions,
517     const std::string& name) {
518   for (std::vector<RtpHeaderExtension>::const_iterator it = extensions.begin();
519        it != extensions.end(); ++it) {
520     if (it->uri == name)
521       return &(*it);
522   }
523   return NULL;
524 }
525
526 enum MediaChannelOptions {
527   // Tune the stream for conference mode.
528   OPT_CONFERENCE = 0x0001
529 };
530
531 enum VoiceMediaChannelOptions {
532   // Tune the audio stream for vcs with different target levels.
533   OPT_AGC_MINUS_10DB = 0x80000000
534 };
535
536 // DTMF flags to control if a DTMF tone should be played and/or sent.
537 enum DtmfFlags {
538   DF_PLAY = 0x01,
539   DF_SEND = 0x02,
540 };
541
542 class MediaChannel : public sigslot::has_slots<> {
543  public:
544   class NetworkInterface {
545    public:
546     enum SocketType { ST_RTP, ST_RTCP };
547     virtual bool SendPacket(
548         talk_base::Buffer* packet,
549         talk_base::DiffServCodePoint dscp = talk_base::DSCP_NO_CHANGE) = 0;
550     virtual bool SendRtcp(
551         talk_base::Buffer* packet,
552         talk_base::DiffServCodePoint dscp = talk_base::DSCP_NO_CHANGE) = 0;
553     virtual int SetOption(SocketType type, talk_base::Socket::Option opt,
554                           int option) = 0;
555     virtual ~NetworkInterface() {}
556   };
557
558   MediaChannel() : network_interface_(NULL) {}
559   virtual ~MediaChannel() {}
560
561   // Sets the abstract interface class for sending RTP/RTCP data.
562   virtual void SetInterface(NetworkInterface *iface) {
563     talk_base::CritScope cs(&network_interface_crit_);
564     network_interface_ = iface;
565   }
566
567   // Called when a RTP packet is received.
568   virtual void OnPacketReceived(talk_base::Buffer* packet,
569                                 const talk_base::PacketTime& packet_time) = 0;
570   // Called when a RTCP packet is received.
571   virtual void OnRtcpReceived(talk_base::Buffer* packet,
572                               const talk_base::PacketTime& packet_time) = 0;
573   // Called when the socket's ability to send has changed.
574   virtual void OnReadyToSend(bool ready) = 0;
575   // Creates a new outgoing media stream with SSRCs and CNAME as described
576   // by sp.
577   virtual bool AddSendStream(const StreamParams& sp) = 0;
578   // Removes an outgoing media stream.
579   // ssrc must be the first SSRC of the media stream if the stream uses
580   // multiple SSRCs.
581   virtual bool RemoveSendStream(uint32 ssrc) = 0;
582   // Creates a new incoming media stream with SSRCs and CNAME as described
583   // by sp.
584   virtual bool AddRecvStream(const StreamParams& sp) = 0;
585   // Removes an incoming media stream.
586   // ssrc must be the first SSRC of the media stream if the stream uses
587   // multiple SSRCs.
588   virtual bool RemoveRecvStream(uint32 ssrc) = 0;
589
590   // Mutes the channel.
591   virtual bool MuteStream(uint32 ssrc, bool on) = 0;
592
593   // Sets the RTP extension headers and IDs to use when sending RTP.
594   virtual bool SetRecvRtpHeaderExtensions(
595       const std::vector<RtpHeaderExtension>& extensions) = 0;
596   virtual bool SetSendRtpHeaderExtensions(
597       const std::vector<RtpHeaderExtension>& extensions) = 0;
598   // Returns the absoulte sendtime extension id value from media channel.
599   virtual int GetRtpSendTimeExtnId() const {
600     return -1;
601   }
602   // Sets the initial bandwidth to use when sending starts.
603   virtual bool SetStartSendBandwidth(int bps) = 0;
604   // Sets the maximum allowed bandwidth to use when sending data.
605   virtual bool SetMaxSendBandwidth(int bps) = 0;
606
607   // Base method to send packet using NetworkInterface.
608   bool SendPacket(talk_base::Buffer* packet) {
609     return DoSendPacket(packet, false);
610   }
611
612   bool SendRtcp(talk_base::Buffer* packet) {
613     return DoSendPacket(packet, true);
614   }
615
616   int SetOption(NetworkInterface::SocketType type,
617                 talk_base::Socket::Option opt,
618                 int option) {
619     talk_base::CritScope cs(&network_interface_crit_);
620     if (!network_interface_)
621       return -1;
622
623     return network_interface_->SetOption(type, opt, option);
624   }
625
626  protected:
627   // This method sets DSCP |value| on both RTP and RTCP channels.
628   int SetDscp(talk_base::DiffServCodePoint value) {
629     int ret;
630     ret = SetOption(NetworkInterface::ST_RTP,
631                     talk_base::Socket::OPT_DSCP,
632                     value);
633     if (ret == 0) {
634       ret = SetOption(NetworkInterface::ST_RTCP,
635                       talk_base::Socket::OPT_DSCP,
636                       value);
637     }
638     return ret;
639   }
640
641  private:
642   bool DoSendPacket(talk_base::Buffer* packet, bool rtcp) {
643     talk_base::CritScope cs(&network_interface_crit_);
644     if (!network_interface_)
645       return false;
646
647     return (!rtcp) ? network_interface_->SendPacket(packet) :
648                      network_interface_->SendRtcp(packet);
649   }
650
651   // |network_interface_| can be accessed from the worker_thread and
652   // from any MediaEngine threads. This critical section is to protect accessing
653   // of network_interface_ object.
654   talk_base::CriticalSection network_interface_crit_;
655   NetworkInterface* network_interface_;
656 };
657
658 enum SendFlags {
659   SEND_NOTHING,
660   SEND_RINGBACKTONE,
661   SEND_MICROPHONE
662 };
663
664 // The stats information is structured as follows:
665 // Media are represented by either MediaSenderInfo or MediaReceiverInfo.
666 // Media contains a vector of SSRC infos that are exclusively used by this
667 // media. (SSRCs shared between media streams can't be represented.)
668
669 // Information about an SSRC.
670 // This data may be locally recorded, or received in an RTCP SR or RR.
671 struct SsrcSenderInfo {
672   SsrcSenderInfo()
673       : ssrc(0),
674     timestamp(0) {
675   }
676   uint32 ssrc;
677   double timestamp;  // NTP timestamp, represented as seconds since epoch.
678 };
679
680 struct SsrcReceiverInfo {
681   SsrcReceiverInfo()
682       : ssrc(0),
683         timestamp(0) {
684   }
685   uint32 ssrc;
686   double timestamp;
687 };
688
689 struct MediaSenderInfo {
690   MediaSenderInfo()
691       : bytes_sent(0),
692         packets_sent(0),
693         packets_lost(0),
694         fraction_lost(0.0),
695         rtt_ms(0) {
696   }
697   void add_ssrc(const SsrcSenderInfo& stat) {
698     local_stats.push_back(stat);
699   }
700   // Temporary utility function for call sites that only provide SSRC.
701   // As more info is added into SsrcSenderInfo, this function should go away.
702   void add_ssrc(uint32 ssrc) {
703     SsrcSenderInfo stat;
704     stat.ssrc = ssrc;
705     add_ssrc(stat);
706   }
707   // Utility accessor for clients that are only interested in ssrc numbers.
708   std::vector<uint32> ssrcs() const {
709     std::vector<uint32> retval;
710     for (std::vector<SsrcSenderInfo>::const_iterator it = local_stats.begin();
711          it != local_stats.end(); ++it) {
712       retval.push_back(it->ssrc);
713     }
714     return retval;
715   }
716   // Utility accessor for clients that make the assumption only one ssrc
717   // exists per media.
718   // This will eventually go away.
719   uint32 ssrc() const {
720     if (local_stats.size() > 0) {
721       return local_stats[0].ssrc;
722     } else {
723       return 0;
724     }
725   }
726   int64 bytes_sent;
727   int packets_sent;
728   int packets_lost;
729   float fraction_lost;
730   int rtt_ms;
731   std::string codec_name;
732   std::vector<SsrcSenderInfo> local_stats;
733   std::vector<SsrcReceiverInfo> remote_stats;
734 };
735
736 template<class T>
737 struct VariableInfo {
738   VariableInfo()
739       : min_val(),
740         mean(0.0),
741         max_val(),
742         variance(0.0) {
743   }
744   T min_val;
745   double mean;
746   T max_val;
747   double variance;
748 };
749
750 struct MediaReceiverInfo {
751   MediaReceiverInfo()
752       : bytes_rcvd(0),
753         packets_rcvd(0),
754         packets_lost(0),
755         fraction_lost(0.0) {
756   }
757   void add_ssrc(const SsrcReceiverInfo& stat) {
758     local_stats.push_back(stat);
759   }
760   // Temporary utility function for call sites that only provide SSRC.
761   // As more info is added into SsrcSenderInfo, this function should go away.
762   void add_ssrc(uint32 ssrc) {
763     SsrcReceiverInfo stat;
764     stat.ssrc = ssrc;
765     add_ssrc(stat);
766   }
767   std::vector<uint32> ssrcs() const {
768     std::vector<uint32> retval;
769     for (std::vector<SsrcReceiverInfo>::const_iterator it = local_stats.begin();
770          it != local_stats.end(); ++it) {
771       retval.push_back(it->ssrc);
772     }
773     return retval;
774   }
775   // Utility accessor for clients that make the assumption only one ssrc
776   // exists per media.
777   // This will eventually go away.
778   uint32 ssrc() const {
779     if (local_stats.size() > 0) {
780       return local_stats[0].ssrc;
781     } else {
782       return 0;
783     }
784   }
785
786   int64 bytes_rcvd;
787   int packets_rcvd;
788   int packets_lost;
789   float fraction_lost;
790   std::vector<SsrcReceiverInfo> local_stats;
791   std::vector<SsrcSenderInfo> remote_stats;
792 };
793
794 struct VoiceSenderInfo : public MediaSenderInfo {
795   VoiceSenderInfo()
796       : ext_seqnum(0),
797         jitter_ms(0),
798         audio_level(0),
799         aec_quality_min(0.0),
800         echo_delay_median_ms(0),
801         echo_delay_std_ms(0),
802         echo_return_loss(0),
803         echo_return_loss_enhancement(0),
804         typing_noise_detected(false) {
805   }
806
807   int ext_seqnum;
808   int jitter_ms;
809   int audio_level;
810   float aec_quality_min;
811   int echo_delay_median_ms;
812   int echo_delay_std_ms;
813   int echo_return_loss;
814   int echo_return_loss_enhancement;
815   bool typing_noise_detected;
816 };
817
818 struct VoiceReceiverInfo : public MediaReceiverInfo {
819   VoiceReceiverInfo()
820       : ext_seqnum(0),
821         jitter_ms(0),
822         jitter_buffer_ms(0),
823         jitter_buffer_preferred_ms(0),
824         delay_estimate_ms(0),
825         audio_level(0),
826         expand_rate(0),
827         decoding_calls_to_silence_generator(0),
828         decoding_calls_to_neteq(0),
829         decoding_normal(0),
830         decoding_plc(0),
831         decoding_cng(0),
832         decoding_plc_cng(0) {
833   }
834
835   int ext_seqnum;
836   int jitter_ms;
837   int jitter_buffer_ms;
838   int jitter_buffer_preferred_ms;
839   int delay_estimate_ms;
840   int audio_level;
841   // fraction of synthesized speech inserted through pre-emptive expansion
842   float expand_rate;
843   int decoding_calls_to_silence_generator;
844   int decoding_calls_to_neteq;
845   int decoding_normal;
846   int decoding_plc;
847   int decoding_cng;
848   int decoding_plc_cng;
849 };
850
851 struct VideoSenderInfo : public MediaSenderInfo {
852   VideoSenderInfo()
853       : packets_cached(0),
854         firs_rcvd(0),
855         plis_rcvd(0),
856         nacks_rcvd(0),
857         input_frame_width(0),
858         input_frame_height(0),
859         send_frame_width(0),
860         send_frame_height(0),
861         framerate_input(0),
862         framerate_sent(0),
863         nominal_bitrate(0),
864         preferred_bitrate(0),
865         adapt_reason(0),
866         capture_jitter_ms(0),
867         avg_encode_ms(0),
868         encode_usage_percent(0),
869         capture_queue_delay_ms_per_s(0) {
870   }
871
872   std::vector<SsrcGroup> ssrc_groups;
873   int packets_cached;
874   int firs_rcvd;
875   int plis_rcvd;
876   int nacks_rcvd;
877   int input_frame_width;
878   int input_frame_height;
879   int send_frame_width;
880   int send_frame_height;
881   int framerate_input;
882   int framerate_sent;
883   int nominal_bitrate;
884   int preferred_bitrate;
885   int adapt_reason;
886   int capture_jitter_ms;
887   int avg_encode_ms;
888   int encode_usage_percent;
889   int capture_queue_delay_ms_per_s;
890   VariableInfo<int> adapt_frame_drops;
891   VariableInfo<int> effects_frame_drops;
892   VariableInfo<double> capturer_frame_time;
893 };
894
895 struct VideoReceiverInfo : public MediaReceiverInfo {
896   VideoReceiverInfo()
897       : packets_concealed(0),
898         firs_sent(0),
899         plis_sent(0),
900         nacks_sent(0),
901         frame_width(0),
902         frame_height(0),
903         framerate_rcvd(0),
904         framerate_decoded(0),
905         framerate_output(0),
906         framerate_render_input(0),
907         framerate_render_output(0),
908         decode_ms(0),
909         max_decode_ms(0),
910         jitter_buffer_ms(0),
911         min_playout_delay_ms(0),
912         render_delay_ms(0),
913         target_delay_ms(0),
914         current_delay_ms(0),
915         capture_start_ntp_time_ms(0) {
916   }
917
918   std::vector<SsrcGroup> ssrc_groups;
919   int packets_concealed;
920   int firs_sent;
921   int plis_sent;
922   int nacks_sent;
923   int frame_width;
924   int frame_height;
925   int framerate_rcvd;
926   int framerate_decoded;
927   int framerate_output;
928   // Framerate as sent to the renderer.
929   int framerate_render_input;
930   // Framerate that the renderer reports.
931   int framerate_render_output;
932
933   // All stats below are gathered per-VideoReceiver, but some will be correlated
934   // across MediaStreamTracks.  NOTE(hta): when sinking stats into per-SSRC
935   // structures, reflect this in the new layout.
936
937   // Current frame decode latency.
938   int decode_ms;
939   // Maximum observed frame decode latency.
940   int max_decode_ms;
941   // Jitter (network-related) latency.
942   int jitter_buffer_ms;
943   // Requested minimum playout latency.
944   int min_playout_delay_ms;
945   // Requested latency to account for rendering delay.
946   int render_delay_ms;
947   // Target overall delay: network+decode+render, accounting for
948   // min_playout_delay_ms.
949   int target_delay_ms;
950   // Current overall delay, possibly ramping towards target_delay_ms.
951   int current_delay_ms;
952
953   // Estimated capture start time in NTP time in ms.
954   int64 capture_start_ntp_time_ms;
955 };
956
957 struct DataSenderInfo : public MediaSenderInfo {
958   DataSenderInfo()
959       : ssrc(0) {
960   }
961
962   uint32 ssrc;
963 };
964
965 struct DataReceiverInfo : public MediaReceiverInfo {
966   DataReceiverInfo()
967       : ssrc(0) {
968   }
969
970   uint32 ssrc;
971 };
972
973 struct BandwidthEstimationInfo {
974   BandwidthEstimationInfo()
975       : available_send_bandwidth(0),
976         available_recv_bandwidth(0),
977         target_enc_bitrate(0),
978         actual_enc_bitrate(0),
979         retransmit_bitrate(0),
980         transmit_bitrate(0),
981         bucket_delay(0),
982         total_received_propagation_delta_ms(0) {
983   }
984
985   int available_send_bandwidth;
986   int available_recv_bandwidth;
987   int target_enc_bitrate;
988   int actual_enc_bitrate;
989   int retransmit_bitrate;
990   int transmit_bitrate;
991   int bucket_delay;
992   // The following stats are only valid when
993   // StatsOptions::include_received_propagation_stats is true.
994   int total_received_propagation_delta_ms;
995   std::vector<int> recent_received_propagation_delta_ms;
996   std::vector<int64> recent_received_packet_group_arrival_time_ms;
997 };
998
999 struct VoiceMediaInfo {
1000   void Clear() {
1001     senders.clear();
1002     receivers.clear();
1003   }
1004   std::vector<VoiceSenderInfo> senders;
1005   std::vector<VoiceReceiverInfo> receivers;
1006 };
1007
1008 struct VideoMediaInfo {
1009   void Clear() {
1010     senders.clear();
1011     receivers.clear();
1012     bw_estimations.clear();
1013   }
1014   std::vector<VideoSenderInfo> senders;
1015   std::vector<VideoReceiverInfo> receivers;
1016   std::vector<BandwidthEstimationInfo> bw_estimations;
1017 };
1018
1019 struct DataMediaInfo {
1020   void Clear() {
1021     senders.clear();
1022     receivers.clear();
1023   }
1024   std::vector<DataSenderInfo> senders;
1025   std::vector<DataReceiverInfo> receivers;
1026 };
1027
1028 struct StatsOptions {
1029   StatsOptions() : include_received_propagation_stats(false) {}
1030
1031   bool include_received_propagation_stats;
1032 };
1033
1034 class VoiceMediaChannel : public MediaChannel {
1035  public:
1036   enum Error {
1037     ERROR_NONE = 0,                       // No error.
1038     ERROR_OTHER,                          // Other errors.
1039     ERROR_REC_DEVICE_OPEN_FAILED = 100,   // Could not open mic.
1040     ERROR_REC_DEVICE_MUTED,               // Mic was muted by OS.
1041     ERROR_REC_DEVICE_SILENT,              // No background noise picked up.
1042     ERROR_REC_DEVICE_SATURATION,          // Mic input is clipping.
1043     ERROR_REC_DEVICE_REMOVED,             // Mic was removed while active.
1044     ERROR_REC_RUNTIME_ERROR,              // Processing is encountering errors.
1045     ERROR_REC_SRTP_ERROR,                 // Generic SRTP failure.
1046     ERROR_REC_SRTP_AUTH_FAILED,           // Failed to authenticate packets.
1047     ERROR_REC_TYPING_NOISE_DETECTED,      // Typing noise is detected.
1048     ERROR_PLAY_DEVICE_OPEN_FAILED = 200,  // Could not open playout.
1049     ERROR_PLAY_DEVICE_MUTED,              // Playout muted by OS.
1050     ERROR_PLAY_DEVICE_REMOVED,            // Playout removed while active.
1051     ERROR_PLAY_RUNTIME_ERROR,             // Errors in voice processing.
1052     ERROR_PLAY_SRTP_ERROR,                // Generic SRTP failure.
1053     ERROR_PLAY_SRTP_AUTH_FAILED,          // Failed to authenticate packets.
1054     ERROR_PLAY_SRTP_REPLAY,               // Packet replay detected.
1055   };
1056
1057   VoiceMediaChannel() {}
1058   virtual ~VoiceMediaChannel() {}
1059   // Sets the codecs/payload types to be used for incoming media.
1060   virtual bool SetRecvCodecs(const std::vector<AudioCodec>& codecs) = 0;
1061   // Sets the codecs/payload types to be used for outgoing media.
1062   virtual bool SetSendCodecs(const std::vector<AudioCodec>& codecs) = 0;
1063   // Starts or stops playout of received audio.
1064   virtual bool SetPlayout(bool playout) = 0;
1065   // Starts or stops sending (and potentially capture) of local audio.
1066   virtual bool SetSend(SendFlags flag) = 0;
1067   // Sets the renderer object to be used for the specified remote audio stream.
1068   virtual bool SetRemoteRenderer(uint32 ssrc, AudioRenderer* renderer) = 0;
1069   // Sets the renderer object to be used for the specified local audio stream.
1070   virtual bool SetLocalRenderer(uint32 ssrc, AudioRenderer* renderer) = 0;
1071   // Gets current energy levels for all incoming streams.
1072   virtual bool GetActiveStreams(AudioInfo::StreamList* actives) = 0;
1073   // Get the current energy level of the stream sent to the speaker.
1074   virtual int GetOutputLevel() = 0;
1075   // Get the time in milliseconds since last recorded keystroke, or negative.
1076   virtual int GetTimeSinceLastTyping() = 0;
1077   // Temporarily exposed field for tuning typing detect options.
1078   virtual void SetTypingDetectionParameters(int time_window,
1079     int cost_per_typing, int reporting_threshold, int penalty_decay,
1080     int type_event_delay) = 0;
1081   // Set left and right scale for speaker output volume of the specified ssrc.
1082   virtual bool SetOutputScaling(uint32 ssrc, double left, double right) = 0;
1083   // Get left and right scale for speaker output volume of the specified ssrc.
1084   virtual bool GetOutputScaling(uint32 ssrc, double* left, double* right) = 0;
1085   // Specifies a ringback tone to be played during call setup.
1086   virtual bool SetRingbackTone(const char *buf, int len) = 0;
1087   // Plays or stops the aforementioned ringback tone
1088   virtual bool PlayRingbackTone(uint32 ssrc, bool play, bool loop) = 0;
1089   // Returns if the telephone-event has been negotiated.
1090   virtual bool CanInsertDtmf() { return false; }
1091   // Send and/or play a DTMF |event| according to the |flags|.
1092   // The DTMF out-of-band signal will be used on sending.
1093   // The |ssrc| should be either 0 or a valid send stream ssrc.
1094   // The valid value for the |event| are 0 to 15 which corresponding to
1095   // DTMF event 0-9, *, #, A-D.
1096   virtual bool InsertDtmf(uint32 ssrc, int event, int duration, int flags) = 0;
1097   // Gets quality stats for the channel.
1098   virtual bool GetStats(VoiceMediaInfo* info) = 0;
1099   // Gets last reported error for this media channel.
1100   virtual void GetLastMediaError(uint32* ssrc,
1101                                  VoiceMediaChannel::Error* error) {
1102     ASSERT(error != NULL);
1103     *error = ERROR_NONE;
1104   }
1105   // Sets the media options to use.
1106   virtual bool SetOptions(const AudioOptions& options) = 0;
1107   virtual bool GetOptions(AudioOptions* options) const = 0;
1108
1109   // Signal errors from MediaChannel.  Arguments are:
1110   //     ssrc(uint32), and error(VoiceMediaChannel::Error).
1111   sigslot::signal2<uint32, VoiceMediaChannel::Error> SignalMediaError;
1112 };
1113
1114 class VideoMediaChannel : public MediaChannel {
1115  public:
1116   enum Error {
1117     ERROR_NONE = 0,                       // No error.
1118     ERROR_OTHER,                          // Other errors.
1119     ERROR_REC_DEVICE_OPEN_FAILED = 100,   // Could not open camera.
1120     ERROR_REC_DEVICE_NO_DEVICE,           // No camera.
1121     ERROR_REC_DEVICE_IN_USE,              // Device is in already use.
1122     ERROR_REC_DEVICE_REMOVED,             // Device is removed.
1123     ERROR_REC_SRTP_ERROR,                 // Generic sender SRTP failure.
1124     ERROR_REC_SRTP_AUTH_FAILED,           // Failed to authenticate packets.
1125     ERROR_REC_CPU_MAX_CANT_DOWNGRADE,     // Can't downgrade capture anymore.
1126     ERROR_PLAY_SRTP_ERROR = 200,          // Generic receiver SRTP failure.
1127     ERROR_PLAY_SRTP_AUTH_FAILED,          // Failed to authenticate packets.
1128     ERROR_PLAY_SRTP_REPLAY,               // Packet replay detected.
1129   };
1130
1131   VideoMediaChannel() : renderer_(NULL) {}
1132   virtual ~VideoMediaChannel() {}
1133   // Sets the codecs/payload types to be used for incoming media.
1134   virtual bool SetRecvCodecs(const std::vector<VideoCodec>& codecs) = 0;
1135   // Sets the codecs/payload types to be used for outgoing media.
1136   virtual bool SetSendCodecs(const std::vector<VideoCodec>& codecs) = 0;
1137   // Gets the currently set codecs/payload types to be used for outgoing media.
1138   virtual bool GetSendCodec(VideoCodec* send_codec) = 0;
1139   // Sets the format of a specified outgoing stream.
1140   virtual bool SetSendStreamFormat(uint32 ssrc, const VideoFormat& format) = 0;
1141   // Starts or stops playout of received video.
1142   virtual bool SetRender(bool render) = 0;
1143   // Starts or stops transmission (and potentially capture) of local video.
1144   virtual bool SetSend(bool send) = 0;
1145   // Sets the renderer object to be used for the specified stream.
1146   // If SSRC is 0, the renderer is used for the 'default' stream.
1147   virtual bool SetRenderer(uint32 ssrc, VideoRenderer* renderer) = 0;
1148   // If |ssrc| is 0, replace the default capturer (engine capturer) with
1149   // |capturer|. If |ssrc| is non zero create a new stream with |ssrc| as SSRC.
1150   virtual bool SetCapturer(uint32 ssrc, VideoCapturer* capturer) = 0;
1151   // Gets quality stats for the channel.
1152   virtual bool GetStats(const StatsOptions& options, VideoMediaInfo* info) = 0;
1153   // This is needed for MediaMonitor to use the same template for voice, video
1154   // and data MediaChannels.
1155   bool GetStats(VideoMediaInfo* info) {
1156     return GetStats(StatsOptions(), info);
1157   }
1158
1159   // Send an intra frame to the receivers.
1160   virtual bool SendIntraFrame() = 0;
1161   // Reuqest each of the remote senders to send an intra frame.
1162   virtual bool RequestIntraFrame() = 0;
1163   // Sets the media options to use.
1164   virtual bool SetOptions(const VideoOptions& options) = 0;
1165   virtual bool GetOptions(VideoOptions* options) const = 0;
1166   virtual void UpdateAspectRatio(int ratio_w, int ratio_h) = 0;
1167
1168   // Signal errors from MediaChannel.  Arguments are:
1169   //     ssrc(uint32), and error(VideoMediaChannel::Error).
1170   sigslot::signal2<uint32, Error> SignalMediaError;
1171
1172  protected:
1173   VideoRenderer *renderer_;
1174 };
1175
1176 enum DataMessageType {
1177   // Chrome-Internal use only.  See SctpDataMediaChannel for the actual PPID
1178   // values.
1179   DMT_NONE = 0,
1180   DMT_CONTROL = 1,
1181   DMT_BINARY = 2,
1182   DMT_TEXT = 3,
1183 };
1184
1185 // Info about data received in DataMediaChannel.  For use in
1186 // DataMediaChannel::SignalDataReceived and in all of the signals that
1187 // signal fires, on up the chain.
1188 struct ReceiveDataParams {
1189   // The in-packet stream indentifier.
1190   // For SCTP, this is really SID, not SSRC.
1191   uint32 ssrc;
1192   // The type of message (binary, text, or control).
1193   DataMessageType type;
1194   // A per-stream value incremented per packet in the stream.
1195   int seq_num;
1196   // A per-stream value monotonically increasing with time.
1197   int timestamp;
1198
1199   ReceiveDataParams() :
1200       ssrc(0),
1201       type(DMT_TEXT),
1202       seq_num(0),
1203       timestamp(0) {
1204   }
1205 };
1206
1207 struct SendDataParams {
1208   // The in-packet stream indentifier.
1209   // For SCTP, this is really SID, not SSRC.
1210   uint32 ssrc;
1211   // The type of message (binary, text, or control).
1212   DataMessageType type;
1213
1214   // For SCTP, whether to send messages flagged as ordered or not.
1215   // If false, messages can be received out of order.
1216   bool ordered;
1217   // For SCTP, whether the messages are sent reliably or not.
1218   // If false, messages may be lost.
1219   bool reliable;
1220   // For SCTP, if reliable == false, provide partial reliability by
1221   // resending up to this many times.  Either count or millis
1222   // is supported, not both at the same time.
1223   int max_rtx_count;
1224   // For SCTP, if reliable == false, provide partial reliability by
1225   // resending for up to this many milliseconds.  Either count or millis
1226   // is supported, not both at the same time.
1227   int max_rtx_ms;
1228
1229   SendDataParams() :
1230       ssrc(0),
1231       type(DMT_TEXT),
1232       // TODO(pthatcher): Make these true by default?
1233       ordered(false),
1234       reliable(false),
1235       max_rtx_count(0),
1236       max_rtx_ms(0) {
1237   }
1238 };
1239
1240 enum SendDataResult { SDR_SUCCESS, SDR_ERROR, SDR_BLOCK };
1241
1242 class DataMediaChannel : public MediaChannel {
1243  public:
1244   enum Error {
1245     ERROR_NONE = 0,                       // No error.
1246     ERROR_OTHER,                          // Other errors.
1247     ERROR_SEND_SRTP_ERROR = 200,          // Generic SRTP failure.
1248     ERROR_SEND_SRTP_AUTH_FAILED,          // Failed to authenticate packets.
1249     ERROR_RECV_SRTP_ERROR,                // Generic SRTP failure.
1250     ERROR_RECV_SRTP_AUTH_FAILED,          // Failed to authenticate packets.
1251     ERROR_RECV_SRTP_REPLAY,               // Packet replay detected.
1252   };
1253
1254   virtual ~DataMediaChannel() {}
1255
1256   virtual bool SetSendCodecs(const std::vector<DataCodec>& codecs) = 0;
1257   virtual bool SetRecvCodecs(const std::vector<DataCodec>& codecs) = 0;
1258
1259   virtual bool MuteStream(uint32 ssrc, bool on) { return false; }
1260   // TODO(pthatcher): Implement this.
1261   virtual bool GetStats(DataMediaInfo* info) { return true; }
1262
1263   virtual bool SetSend(bool send) = 0;
1264   virtual bool SetReceive(bool receive) = 0;
1265
1266   virtual bool SendData(
1267       const SendDataParams& params,
1268       const talk_base::Buffer& payload,
1269       SendDataResult* result = NULL) = 0;
1270   // Signals when data is received (params, data, len)
1271   sigslot::signal3<const ReceiveDataParams&,
1272                    const char*,
1273                    size_t> SignalDataReceived;
1274   // Signal errors from MediaChannel.  Arguments are:
1275   //     ssrc(uint32), and error(DataMediaChannel::Error).
1276   sigslot::signal2<uint32, DataMediaChannel::Error> SignalMediaError;
1277   // Signal when the media channel is ready to send the stream. Arguments are:
1278   //     writable(bool)
1279   sigslot::signal1<bool> SignalReadyToSend;
1280 };
1281
1282 }  // namespace cricket
1283
1284 #endif  // TALK_MEDIA_BASE_MEDIACHANNEL_H_