Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / libjingle / source / talk / media / webrtc / webrtcvoiceengine.cc
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 #ifdef HAVE_CONFIG_H
29 #include <config.h>
30 #endif
31
32 #ifdef HAVE_WEBRTC_VOICE
33
34 #include "talk/media/webrtc/webrtcvoiceengine.h"
35
36 #include <algorithm>
37 #include <cstdio>
38 #include <string>
39 #include <vector>
40
41 #include "talk/base/base64.h"
42 #include "talk/base/byteorder.h"
43 #include "talk/base/common.h"
44 #include "talk/base/helpers.h"
45 #include "talk/base/logging.h"
46 #include "talk/base/stringencode.h"
47 #include "talk/base/stringutils.h"
48 #include "talk/media/base/audiorenderer.h"
49 #include "talk/media/base/constants.h"
50 #include "talk/media/base/streamparams.h"
51 #include "talk/media/base/voiceprocessor.h"
52 #include "talk/media/webrtc/webrtcvoe.h"
53 #include "webrtc/common.h"
54 #include "webrtc/modules/audio_processing/include/audio_processing.h"
55
56 #ifdef WIN32
57 #include <objbase.h>  // NOLINT
58 #endif
59
60 namespace cricket {
61
62 struct CodecPref {
63   const char* name;
64   int clockrate;
65   int channels;
66   int payload_type;
67   bool is_multi_rate;
68 };
69
70 static const CodecPref kCodecPrefs[] = {
71   { "OPUS",   48000,  2, 111, true },
72   { "ISAC",   16000,  1, 103, true },
73   { "ISAC",   32000,  1, 104, true },
74   { "CELT",   32000,  1, 109, true },
75   { "CELT",   32000,  2, 110, true },
76   { "G722",   16000,  1, 9,   false },
77   { "ILBC",   8000,   1, 102, false },
78   { "PCMU",   8000,   1, 0,   false },
79   { "PCMA",   8000,   1, 8,   false },
80   { "CN",     48000,  1, 107, false },
81   { "CN",     32000,  1, 106, false },
82   { "CN",     16000,  1, 105, false },
83   { "CN",     8000,   1, 13,  false },
84   { "red",    8000,   1, 127, false },
85   { "telephone-event", 8000, 1, 126, false },
86 };
87
88 // For Linux/Mac, using the default device is done by specifying index 0 for
89 // VoE 4.0 and not -1 (which was the case for VoE 3.5).
90 //
91 // On Windows Vista and newer, Microsoft introduced the concept of "Default
92 // Communications Device". This means that there are two types of default
93 // devices (old Wave Audio style default and Default Communications Device).
94 //
95 // On Windows systems which only support Wave Audio style default, uses either
96 // -1 or 0 to select the default device.
97 //
98 // On Windows systems which support both "Default Communication Device" and
99 // old Wave Audio style default, use -1 for Default Communications Device and
100 // -2 for Wave Audio style default, which is what we want to use for clips.
101 // It's not clear yet whether the -2 index is handled properly on other OSes.
102
103 #ifdef WIN32
104 static const int kDefaultAudioDeviceId = -1;
105 static const int kDefaultSoundclipDeviceId = -2;
106 #else
107 static const int kDefaultAudioDeviceId = 0;
108 #endif
109
110 // extension header for audio levels, as defined in
111 // http://tools.ietf.org/html/draft-ietf-avtext-client-to-mixer-audio-level-03
112 static const char kRtpAudioLevelHeaderExtension[] =
113     "urn:ietf:params:rtp-hdrext:ssrc-audio-level";
114 static const int kRtpAudioLevelHeaderExtensionId = 1;
115
116 static const char kIsacCodecName[] = "ISAC";
117 static const char kL16CodecName[] = "L16";
118 // Codec parameters for Opus.
119 static const int kOpusMonoBitrate = 32000;
120 // Parameter used for NACK.
121 // This value is equivalent to 5 seconds of audio data at 20 ms per packet.
122 static const int kNackMaxPackets = 250;
123 static const int kOpusStereoBitrate = 64000;
124 // draft-spittka-payload-rtp-opus-03
125 // Opus bitrate should be in the range between 6000 and 510000.
126 static const int kOpusMinBitrate = 6000;
127 static const int kOpusMaxBitrate = 510000;
128 // Default audio dscp value.
129 // See http://tools.ietf.org/html/rfc2474 for details.
130 // See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
131 static const talk_base::DiffServCodePoint kAudioDscpValue = talk_base::DSCP_EF;
132
133 // Ensure we open the file in a writeable path on ChromeOS and Android. This
134 // workaround can be removed when it's possible to specify a filename for audio
135 // option based AEC dumps.
136 //
137 // TODO(grunell): Use a string in the options instead of hardcoding it here
138 // and let the embedder choose the filename (crbug.com/264223).
139 //
140 // NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
141 // below.
142 #if defined(CHROMEOS)
143 static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
144 #elif defined(ANDROID)
145 static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
146 #else
147 static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
148 #endif
149
150 // Dumps an AudioCodec in RFC 2327-ish format.
151 static std::string ToString(const AudioCodec& codec) {
152   std::stringstream ss;
153   ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
154      << " (" << codec.id << ")";
155   return ss.str();
156 }
157 static std::string ToString(const webrtc::CodecInst& codec) {
158   std::stringstream ss;
159   ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
160      << " (" << codec.pltype << ")";
161   return ss.str();
162 }
163
164 static void LogMultiline(talk_base::LoggingSeverity sev, char* text) {
165   const char* delim = "\r\n";
166   for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
167     LOG_V(sev) << tok;
168   }
169 }
170
171 // Severity is an integer because it comes is assumed to be from command line.
172 static int SeverityToFilter(int severity) {
173   int filter = webrtc::kTraceNone;
174   switch (severity) {
175     case talk_base::LS_VERBOSE:
176       filter |= webrtc::kTraceAll;
177     case talk_base::LS_INFO:
178       filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
179     case talk_base::LS_WARNING:
180       filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
181     case talk_base::LS_ERROR:
182       filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
183   }
184   return filter;
185 }
186
187 static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
188   for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
189     if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
190         kCodecPrefs[i].clockrate == codec.plfreq) {
191       return kCodecPrefs[i].is_multi_rate;
192     }
193   }
194   return false;
195 }
196
197 static bool FindCodec(const std::vector<AudioCodec>& codecs,
198                       const AudioCodec& codec,
199                       AudioCodec* found_codec) {
200   for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
201        it != codecs.end(); ++it) {
202     if (it->Matches(codec)) {
203       if (found_codec != NULL) {
204         *found_codec = *it;
205       }
206       return true;
207     }
208   }
209   return false;
210 }
211
212 static bool IsNackEnabled(const AudioCodec& codec) {
213   return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
214                                               kParamValueEmpty));
215 }
216
217 // Gets the default set of options applied to the engine. Historically, these
218 // were supplied as a combination of flags from the channel manager (ec, agc,
219 // ns, and highpass) and the rest hardcoded in InitInternal.
220 static AudioOptions GetDefaultEngineOptions() {
221   AudioOptions options;
222   options.echo_cancellation.Set(true);
223   options.auto_gain_control.Set(true);
224   options.noise_suppression.Set(true);
225   options.highpass_filter.Set(true);
226   options.stereo_swapping.Set(false);
227   options.typing_detection.Set(true);
228   options.conference_mode.Set(false);
229   options.adjust_agc_delta.Set(0);
230   options.experimental_agc.Set(false);
231   options.experimental_aec.Set(false);
232   options.experimental_ns.Set(false);
233   options.aec_dump.Set(false);
234   options.experimental_acm.Set(false);
235   return options;
236 }
237
238 class WebRtcSoundclipMedia : public SoundclipMedia {
239  public:
240   explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
241       : engine_(engine), webrtc_channel_(-1) {
242     engine_->RegisterSoundclip(this);
243   }
244
245   virtual ~WebRtcSoundclipMedia() {
246     engine_->UnregisterSoundclip(this);
247     if (webrtc_channel_ != -1) {
248       // We shouldn't have to call Disable() here. DeleteChannel() should call
249       // StopPlayout() while deleting the channel.  We should fix the bug
250       // inside WebRTC and remove the Disable() call bellow.  This work is
251       // tracked by bug http://b/issue?id=5382855.
252       PlaySound(NULL, 0, 0);
253       Disable();
254       if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
255           == -1) {
256         LOG_RTCERR1(DeleteChannel, webrtc_channel_);
257       }
258     }
259   }
260
261   bool Init() {
262     if (!engine_->voe_sc()) {
263       return false;
264     }
265     webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
266     if (webrtc_channel_ == -1) {
267       LOG_RTCERR0(CreateChannel);
268       return false;
269     }
270     return true;
271   }
272
273   bool Enable() {
274     if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
275       LOG_RTCERR1(StartPlayout, webrtc_channel_);
276       return false;
277     }
278     return true;
279   }
280
281   bool Disable() {
282     if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
283       LOG_RTCERR1(StopPlayout, webrtc_channel_);
284       return false;
285     }
286     return true;
287   }
288
289   virtual bool PlaySound(const char *buf, int len, int flags) {
290     // The voe file api is not available in chrome.
291     if (!engine_->voe_sc()->file()) {
292       return false;
293     }
294     // Must stop playing the current sound (if any), because we are about to
295     // modify the stream.
296     if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
297         == -1) {
298       LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
299       return false;
300     }
301
302     if (buf) {
303       stream_.reset(new WebRtcSoundclipStream(buf, len));
304       stream_->set_loop((flags & SF_LOOP) != 0);
305       stream_->Rewind();
306
307       // Play it.
308       if (engine_->voe_sc()->file()->StartPlayingFileLocally(
309           webrtc_channel_, stream_.get()) == -1) {
310         LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
311         LOG(LS_ERROR) << "Unable to start soundclip";
312         return false;
313       }
314     } else {
315       stream_.reset();
316     }
317     return true;
318   }
319
320   int GetLastEngineError() const { return engine_->voe_sc()->error(); }
321
322  private:
323   WebRtcVoiceEngine *engine_;
324   int webrtc_channel_;
325   talk_base::scoped_ptr<WebRtcSoundclipStream> stream_;
326 };
327
328 WebRtcVoiceEngine::WebRtcVoiceEngine()
329     : voe_wrapper_(new VoEWrapper()),
330       voe_wrapper_sc_(new VoEWrapper()),
331       voe_wrapper_sc_initialized_(false),
332       tracing_(new VoETraceWrapper()),
333       adm_(NULL),
334       adm_sc_(NULL),
335       log_filter_(SeverityToFilter(kDefaultLogSeverity)),
336       is_dumping_aec_(false),
337       desired_local_monitor_enable_(false),
338       use_experimental_acm_(false),
339       tx_processor_ssrc_(0),
340       rx_processor_ssrc_(0) {
341   Construct();
342 }
343
344 WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
345                                      VoEWrapper* voe_wrapper_sc,
346                                      VoETraceWrapper* tracing)
347     : voe_wrapper_(voe_wrapper),
348       voe_wrapper_sc_(voe_wrapper_sc),
349       voe_wrapper_sc_initialized_(false),
350       tracing_(tracing),
351       adm_(NULL),
352       adm_sc_(NULL),
353       log_filter_(SeverityToFilter(kDefaultLogSeverity)),
354       is_dumping_aec_(false),
355       desired_local_monitor_enable_(false),
356       use_experimental_acm_(false),
357       tx_processor_ssrc_(0),
358       rx_processor_ssrc_(0) {
359   Construct();
360 }
361
362 void WebRtcVoiceEngine::Construct() {
363   SetTraceFilter(log_filter_);
364   initialized_ = false;
365   LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
366   SetTraceOptions("");
367   if (tracing_->SetTraceCallback(this) == -1) {
368     LOG_RTCERR0(SetTraceCallback);
369   }
370   if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
371     LOG_RTCERR0(RegisterVoiceEngineObserver);
372   }
373   // Clear the default agc state.
374   memset(&default_agc_config_, 0, sizeof(default_agc_config_));
375
376   // Load our audio codec list.
377   ConstructCodecs();
378
379   // Load our RTP Header extensions.
380   rtp_header_extensions_.push_back(
381       RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
382                          kRtpAudioLevelHeaderExtensionId));
383   options_ = GetDefaultEngineOptions();
384
385   // Initialize the VoE Configuration to the default ACM.
386   voe_config_.Set<webrtc::AudioCodingModuleFactory>(
387       new webrtc::AudioCodingModuleFactory);
388 }
389
390 static bool IsOpus(const AudioCodec& codec) {
391   return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
392 }
393
394 static bool IsIsac(const AudioCodec& codec) {
395   return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
396 }
397
398 // True if params["stereo"] == "1"
399 static bool IsOpusStereoEnabled(const AudioCodec& codec) {
400   CodecParameterMap::const_iterator param =
401       codec.params.find(kCodecParamStereo);
402   if (param == codec.params.end()) {
403     return false;
404   }
405   return param->second == kParamValueTrue;
406 }
407
408 static bool IsValidOpusBitrate(int bitrate) {
409   return (bitrate >= kOpusMinBitrate && bitrate <= kOpusMaxBitrate);
410 }
411
412 // Returns 0 if params[kCodecParamMaxAverageBitrate] is not defined or invalid.
413 // Returns the value of params[kCodecParamMaxAverageBitrate] otherwise.
414 static int GetOpusBitrateFromParams(const AudioCodec& codec) {
415   int bitrate = 0;
416   if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
417     return 0;
418   }
419   if (!IsValidOpusBitrate(bitrate)) {
420     LOG(LS_WARNING) << "Codec parameter \"maxaveragebitrate\" has an "
421                     << "invalid value: " << bitrate;
422     return 0;
423   }
424   return bitrate;
425 }
426
427 void WebRtcVoiceEngine::ConstructCodecs() {
428   LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
429   int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
430   for (int i = 0; i < ncodecs; ++i) {
431     webrtc::CodecInst voe_codec;
432     if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
433       // Skip uncompressed formats.
434       if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
435         continue;
436       }
437
438       const CodecPref* pref = NULL;
439       for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
440         if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
441             kCodecPrefs[j].clockrate == voe_codec.plfreq &&
442             kCodecPrefs[j].channels == voe_codec.channels) {
443           pref = &kCodecPrefs[j];
444           break;
445         }
446       }
447
448       if (pref) {
449         // Use the payload type that we've configured in our pref table;
450         // use the offset in our pref table to determine the sort order.
451         AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
452                          voe_codec.rate, voe_codec.channels,
453                          ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
454         LOG(LS_INFO) << ToString(codec);
455         if (IsIsac(codec)) {
456           // Indicate auto-bandwidth in signaling.
457           codec.bitrate = 0;
458         }
459         if (IsOpus(codec)) {
460           // Only add fmtp parameters that differ from the spec.
461           if (kPreferredMinPTime != kOpusDefaultMinPTime) {
462             codec.params[kCodecParamMinPTime] =
463                 talk_base::ToString(kPreferredMinPTime);
464           }
465           if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
466             codec.params[kCodecParamMaxPTime] =
467                 talk_base::ToString(kPreferredMaxPTime);
468           }
469           // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
470           // when they can be set to values other than the default.
471         }
472         codecs_.push_back(codec);
473       } else {
474         LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
475       }
476     }
477   }
478   // Make sure they are in local preference order.
479   std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
480 }
481
482 WebRtcVoiceEngine::~WebRtcVoiceEngine() {
483   LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
484   if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
485     LOG_RTCERR0(DeRegisterVoiceEngineObserver);
486   }
487   if (adm_) {
488     voe_wrapper_.reset();
489     adm_->Release();
490     adm_ = NULL;
491   }
492   if (adm_sc_) {
493     voe_wrapper_sc_.reset();
494     adm_sc_->Release();
495     adm_sc_ = NULL;
496   }
497
498   // Test to see if the media processor was deregistered properly
499   ASSERT(SignalRxMediaFrame.is_empty());
500   ASSERT(SignalTxMediaFrame.is_empty());
501
502   tracing_->SetTraceCallback(NULL);
503 }
504
505 bool WebRtcVoiceEngine::Init(talk_base::Thread* worker_thread) {
506   LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
507   bool res = InitInternal();
508   if (res) {
509     LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
510   } else {
511     LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
512     Terminate();
513   }
514   return res;
515 }
516
517 bool WebRtcVoiceEngine::InitInternal() {
518   // Temporarily turn logging level up for the Init call
519   int old_filter = log_filter_;
520   int extended_filter = log_filter_ | SeverityToFilter(talk_base::LS_INFO);
521   SetTraceFilter(extended_filter);
522   SetTraceOptions("");
523
524   // Init WebRtc VoiceEngine.
525   if (voe_wrapper_->base()->Init(adm_) == -1) {
526     LOG_RTCERR0_EX(Init, voe_wrapper_->error());
527     SetTraceFilter(old_filter);
528     return false;
529   }
530
531   SetTraceFilter(old_filter);
532   SetTraceOptions(log_options_);
533
534   // Log the VoiceEngine version info
535   char buffer[1024] = "";
536   voe_wrapper_->base()->GetVersion(buffer);
537   LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
538   LogMultiline(talk_base::LS_INFO, buffer);
539
540   // Save the default AGC configuration settings. This must happen before
541   // calling SetOptions or the default will be overwritten.
542   if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
543     LOG_RTCERR0(GetAgcConfig);
544     return false;
545   }
546
547   // Set defaults for options, so that ApplyOptions applies them explicitly
548   // when we clear option (channel) overrides. External clients can still
549   // modify the defaults via SetOptions (on the media engine).
550   if (!SetOptions(GetDefaultEngineOptions())) {
551     return false;
552   }
553
554   // Print our codec list again for the call diagnostic log
555   LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
556   for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
557       it != codecs_.end(); ++it) {
558     LOG(LS_INFO) << ToString(*it);
559   }
560
561   // Disable the DTMF playout when a tone is sent.
562   // PlayDtmfTone will be used if local playout is needed.
563   if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
564     LOG_RTCERR1(SetDtmfFeedbackStatus, false);
565   }
566
567   initialized_ = true;
568   return true;
569 }
570
571 bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
572   if (voe_wrapper_sc_initialized_) {
573     return true;
574   }
575   // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
576   // be false, so subsequent calls to EnsureSoundclipEngineInit will
577   // probably just fail again. That's acceptable behavior.
578 #if defined(LINUX) && !defined(HAVE_LIBPULSE)
579   voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
580 #endif
581
582   // Initialize the VoiceEngine instance that we'll use to play out sound clips.
583   if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
584     LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
585     return false;
586   }
587
588   // On Windows, tell it to use the default sound (not communication) devices.
589   // First check whether there is a valid sound device for playback.
590   // TODO(juberti): Clean this up when we support setting the soundclip device.
591 #ifdef WIN32
592   // The SetPlayoutDevice may not be implemented in the case of external ADM.
593   // TODO(ronghuawu): We should only check the adm_sc_ here, but current
594   // PeerConnection interface never set the adm_sc_, so need to check both
595   // in order to determine if the external adm is used.
596   if (!adm_ && !adm_sc_) {
597     int num_of_devices = 0;
598     if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
599         num_of_devices > 0) {
600       if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
601           == -1) {
602         LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
603                        voe_wrapper_sc_->error());
604         return false;
605       }
606     } else {
607       LOG(LS_WARNING) << "No valid sound playout device found.";
608     }
609   }
610 #endif
611   voe_wrapper_sc_initialized_ = true;
612   LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
613   return true;
614 }
615
616 void WebRtcVoiceEngine::Terminate() {
617   LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
618   initialized_ = false;
619
620   StopAecDump();
621
622   if (voe_wrapper_sc_) {
623     voe_wrapper_sc_initialized_ = false;
624     voe_wrapper_sc_->base()->Terminate();
625   }
626   voe_wrapper_->base()->Terminate();
627   desired_local_monitor_enable_ = false;
628 }
629
630 int WebRtcVoiceEngine::GetCapabilities() {
631   return AUDIO_SEND | AUDIO_RECV;
632 }
633
634 VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
635   WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
636   if (!ch->valid()) {
637     delete ch;
638     ch = NULL;
639   }
640   return ch;
641 }
642
643 SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
644   if (!EnsureSoundclipEngineInit()) {
645     LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
646                   << "initialize.";
647     return NULL;
648   }
649   WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
650   if (!soundclip->Init() || !soundclip->Enable()) {
651     delete soundclip;
652     return NULL;
653   }
654   return soundclip;
655 }
656
657 bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
658   if (!ApplyOptions(options)) {
659     return false;
660   }
661   options_ = options;
662   return true;
663 }
664
665 bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
666   LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
667   if (!ApplyOptions(overrides)) {
668     return false;
669   }
670   option_overrides_ = overrides;
671   return true;
672 }
673
674 bool WebRtcVoiceEngine::ClearOptionOverrides() {
675   LOG(LS_INFO) << "Clearing option overrides.";
676   AudioOptions options = options_;
677   // Only call ApplyOptions if |options_overrides_| contains overrided options.
678   // ApplyOptions affects NS, AGC other options that is shared between
679   // all WebRtcVoiceEngineChannels.
680   if (option_overrides_ == AudioOptions()) {
681     return true;
682   }
683
684   if (!ApplyOptions(options)) {
685     return false;
686   }
687   option_overrides_ = AudioOptions();
688   return true;
689 }
690
691 // AudioOptions defaults are set in InitInternal (for options with corresponding
692 // MediaEngineInterface flags) and in SetOptions(int) for flagless options.
693 bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
694   AudioOptions options = options_in;  // The options are modified below.
695   // kEcConference is AEC with high suppression.
696   webrtc::EcModes ec_mode = webrtc::kEcConference;
697   webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
698   webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
699   webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
700   bool aecm_comfort_noise = false;
701   if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
702     LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
703                     << aecm_comfort_noise << " (default is false).";
704   }
705
706 #if defined(IOS)
707   // On iOS, VPIO provides built-in EC and AGC.
708   options.echo_cancellation.Set(false);
709   options.auto_gain_control.Set(false);
710 #elif defined(ANDROID)
711   ec_mode = webrtc::kEcAecm;
712 #endif
713
714 #if defined(IOS) || defined(ANDROID)
715   // Set the AGC mode for iOS as well despite disabling it above, to avoid
716   // unsupported configuration errors from webrtc.
717   agc_mode = webrtc::kAgcFixedDigital;
718   options.typing_detection.Set(false);
719   options.experimental_agc.Set(false);
720   options.experimental_aec.Set(false);
721   options.experimental_ns.Set(false);
722 #endif
723
724   LOG(LS_INFO) << "Applying audio options: " << options.ToString();
725
726   // Configure whether ACM1 or ACM2 is used.
727   bool enable_acm2 = false;
728   if (options.experimental_acm.Get(&enable_acm2)) {
729     EnableExperimentalAcm(enable_acm2);
730   }
731
732   webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
733
734   bool echo_cancellation;
735   if (options.echo_cancellation.Get(&echo_cancellation)) {
736     if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
737       LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
738       return false;
739     } else {
740       LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
741                       << " with mode " << ec_mode;
742     }
743 #if !defined(ANDROID)
744     // TODO(ajm): Remove the error return on Android from webrtc.
745     if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
746       LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
747       return false;
748     }
749 #endif
750     if (ec_mode == webrtc::kEcAecm) {
751       if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
752         LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
753         return false;
754       }
755     }
756   }
757
758   bool auto_gain_control;
759   if (options.auto_gain_control.Get(&auto_gain_control)) {
760     if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
761       LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
762       return false;
763     } else {
764       LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
765                       << " with mode " << agc_mode;
766     }
767   }
768
769   if (options.tx_agc_target_dbov.IsSet() ||
770       options.tx_agc_digital_compression_gain.IsSet() ||
771       options.tx_agc_limiter.IsSet()) {
772     // Override default_agc_config_. Generally, an unset option means "leave
773     // the VoE bits alone" in this function, so we want whatever is set to be
774     // stored as the new "default". If we didn't, then setting e.g.
775     // tx_agc_target_dbov would reset digital compression gain and limiter
776     // settings.
777     // Also, if we don't update default_agc_config_, then adjust_agc_delta
778     // would be an offset from the original values, and not whatever was set
779     // explicitly.
780     default_agc_config_.targetLeveldBOv =
781         options.tx_agc_target_dbov.GetWithDefaultIfUnset(
782             default_agc_config_.targetLeveldBOv);
783     default_agc_config_.digitalCompressionGaindB =
784         options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
785             default_agc_config_.digitalCompressionGaindB);
786     default_agc_config_.limiterEnable =
787         options.tx_agc_limiter.GetWithDefaultIfUnset(
788             default_agc_config_.limiterEnable);
789     if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
790       LOG_RTCERR3(SetAgcConfig,
791                   default_agc_config_.targetLeveldBOv,
792                   default_agc_config_.digitalCompressionGaindB,
793                   default_agc_config_.limiterEnable);
794       return false;
795     }
796   }
797
798   bool noise_suppression;
799   if (options.noise_suppression.Get(&noise_suppression)) {
800     if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
801       LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
802       return false;
803     } else {
804       LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
805                       << " with mode " << ns_mode;
806     }
807   }
808
809 #ifdef USE_WEBRTC_DEV_BRANCH
810   bool experimental_ns;
811   if (options.experimental_ns.Get(&experimental_ns)) {
812     webrtc::AudioProcessing* audioproc =
813         voe_wrapper_->base()->audio_processing();
814     // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
815     // returns NULL on audio_processing().
816     if (audioproc) {
817       if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
818         LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
819         return false;
820       }
821     } else {
822       LOG(LS_VERBOSE) << "Experimental noise suppression set to "
823                       << experimental_ns;
824     }
825   }
826 #endif  // USE_WEBRTC_DEV_BRANCH
827
828   bool highpass_filter;
829   if (options.highpass_filter.Get(&highpass_filter)) {
830     if (voep->EnableHighPassFilter(highpass_filter) == -1) {
831       LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
832       return false;
833     }
834   }
835
836   bool stereo_swapping;
837   if (options.stereo_swapping.Get(&stereo_swapping)) {
838     voep->EnableStereoChannelSwapping(stereo_swapping);
839     if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
840       LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
841       return false;
842     }
843   }
844
845   bool typing_detection;
846   if (options.typing_detection.Get(&typing_detection)) {
847     if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
848       // In case of error, log the info and continue
849       LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
850     }
851   }
852
853   int adjust_agc_delta;
854   if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
855     if (!AdjustAgcLevel(adjust_agc_delta)) {
856       return false;
857     }
858   }
859
860   bool aec_dump;
861   if (options.aec_dump.Get(&aec_dump)) {
862     if (aec_dump)
863       StartAecDump(kAecDumpByAudioOptionFilename);
864     else
865       StopAecDump();
866   }
867
868   bool experimental_aec;
869   if (options.experimental_aec.Get(&experimental_aec)) {
870     webrtc::AudioProcessing* audioproc =
871         voe_wrapper_->base()->audio_processing();
872     // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
873     // returns NULL on audio_processing().
874     if (audioproc) {
875       webrtc::Config config;
876       config.Set<webrtc::DelayCorrection>(
877           new webrtc::DelayCorrection(experimental_aec));
878       audioproc->SetExtraOptions(config);
879     }
880   }
881
882   uint32 recording_sample_rate;
883   if (options.recording_sample_rate.Get(&recording_sample_rate)) {
884     if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
885       LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
886     }
887   }
888
889   uint32 playout_sample_rate;
890   if (options.playout_sample_rate.Get(&playout_sample_rate)) {
891     if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
892       LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
893     }
894   }
895
896
897   return true;
898 }
899
900 bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
901   voe_wrapper_->processing()->SetDelayOffsetMs(offset);
902   if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
903     LOG_RTCERR1(SetDelayOffsetMs, offset);
904     return false;
905   }
906
907   return true;
908 }
909
910 struct ResumeEntry {
911   ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
912       : channel(c),
913         playout(p),
914         send(s) {
915   }
916
917   WebRtcVoiceMediaChannel *channel;
918   bool playout;
919   SendFlags send;
920 };
921
922 // TODO(juberti): Refactor this so that the core logic can be used to set the
923 // soundclip device. At that time, reinstate the soundclip pause/resume code.
924 bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
925                                    const Device* out_device) {
926 #if !defined(IOS)
927   int in_id = in_device ? talk_base::FromString<int>(in_device->id) :
928       kDefaultAudioDeviceId;
929   int out_id = out_device ? talk_base::FromString<int>(out_device->id) :
930       kDefaultAudioDeviceId;
931   // The device manager uses -1 as the default device, which was the case for
932   // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
933 #ifndef WIN32
934   if (-1 == in_id) {
935     in_id = kDefaultAudioDeviceId;
936   }
937   if (-1 == out_id) {
938     out_id = kDefaultAudioDeviceId;
939   }
940 #endif
941
942   std::string in_name = (in_id != kDefaultAudioDeviceId) ?
943       in_device->name : "Default device";
944   std::string out_name = (out_id != kDefaultAudioDeviceId) ?
945       out_device->name : "Default device";
946   LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
947             << ") and speaker to (id=" << out_id << ", name=" << out_name
948             << ")";
949
950   // If we're running the local monitor, we need to stop it first.
951   bool ret = true;
952   if (!PauseLocalMonitor()) {
953     LOG(LS_WARNING) << "Failed to pause local monitor";
954     ret = false;
955   }
956
957   // Must also pause all audio playback and capture.
958   for (ChannelList::const_iterator i = channels_.begin();
959        i != channels_.end(); ++i) {
960     WebRtcVoiceMediaChannel *channel = *i;
961     if (!channel->PausePlayout()) {
962       LOG(LS_WARNING) << "Failed to pause playout";
963       ret = false;
964     }
965     if (!channel->PauseSend()) {
966       LOG(LS_WARNING) << "Failed to pause send";
967       ret = false;
968     }
969   }
970
971   // Find the recording device id in VoiceEngine and set recording device.
972   if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
973     ret = false;
974   }
975   if (ret) {
976     if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
977       LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
978       ret = false;
979     }
980   }
981
982   // Find the playout device id in VoiceEngine and set playout device.
983   if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
984     LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
985     ret = false;
986   }
987   if (ret) {
988     if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
989       LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
990       ret = false;
991     }
992   }
993
994   // Resume all audio playback and capture.
995   for (ChannelList::const_iterator i = channels_.begin();
996        i != channels_.end(); ++i) {
997     WebRtcVoiceMediaChannel *channel = *i;
998     if (!channel->ResumePlayout()) {
999       LOG(LS_WARNING) << "Failed to resume playout";
1000       ret = false;
1001     }
1002     if (!channel->ResumeSend()) {
1003       LOG(LS_WARNING) << "Failed to resume send";
1004       ret = false;
1005     }
1006   }
1007
1008   // Resume local monitor.
1009   if (!ResumeLocalMonitor()) {
1010     LOG(LS_WARNING) << "Failed to resume local monitor";
1011     ret = false;
1012   }
1013
1014   if (ret) {
1015     LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1016                  << ") and speaker to (id="<< out_id << " name=" << out_name
1017                  << ")";
1018   }
1019
1020   return ret;
1021 #else
1022   return true;
1023 #endif  // !IOS
1024 }
1025
1026 bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1027   bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1028   // In Linux, VoiceEngine uses the same device dev_id as the device manager.
1029 #if defined(LINUX) || defined(ANDROID)
1030   *rtc_id = dev_id;
1031   return true;
1032 #else
1033   // In Windows and Mac, we need to find the VoiceEngine device id by name
1034   // unless the input dev_id is the default device id.
1035   if (kDefaultAudioDeviceId == dev_id) {
1036     *rtc_id = dev_id;
1037     return true;
1038   }
1039
1040   // Get the number of VoiceEngine audio devices.
1041   int count = 0;
1042   if (is_input) {
1043     if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1044       LOG_RTCERR0(GetNumOfRecordingDevices);
1045       return false;
1046     }
1047   } else {
1048     if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1049       LOG_RTCERR0(GetNumOfPlayoutDevices);
1050       return false;
1051     }
1052   }
1053
1054   for (int i = 0; i < count; ++i) {
1055     char name[128];
1056     char guid[128];
1057     if (is_input) {
1058       voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1059       LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1060     } else {
1061       voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1062       LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1063     }
1064
1065     std::string webrtc_name(name);
1066     if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1067       *rtc_id = i;
1068       return true;
1069     }
1070   }
1071   LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1072   return false;
1073 #endif
1074 }
1075
1076 bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1077   unsigned int ulevel;
1078   if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1079     LOG_RTCERR1(GetSpeakerVolume, level);
1080     return false;
1081   }
1082   *level = ulevel;
1083   return true;
1084 }
1085
1086 bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1087   ASSERT(level >= 0 && level <= 255);
1088   if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1089     LOG_RTCERR1(SetSpeakerVolume, level);
1090     return false;
1091   }
1092   return true;
1093 }
1094
1095 int WebRtcVoiceEngine::GetInputLevel() {
1096   unsigned int ulevel;
1097   return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1098       static_cast<int>(ulevel) : -1;
1099 }
1100
1101 bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1102   desired_local_monitor_enable_ = enable;
1103   return ChangeLocalMonitor(desired_local_monitor_enable_);
1104 }
1105
1106 bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1107   // The voe file api is not available in chrome.
1108   if (!voe_wrapper_->file()) {
1109     return false;
1110   }
1111   if (enable && !monitor_) {
1112     monitor_.reset(new WebRtcMonitorStream);
1113     if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1114       LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1115       // Must call Stop() because there are some cases where Start will report
1116       // failure but still change the state, and if we leave VE in the on state
1117       // then it could crash later when trying to invoke methods on our monitor.
1118       voe_wrapper_->file()->StopRecordingMicrophone();
1119       monitor_.reset();
1120       return false;
1121     }
1122   } else if (!enable && monitor_) {
1123     voe_wrapper_->file()->StopRecordingMicrophone();
1124     monitor_.reset();
1125   }
1126   return true;
1127 }
1128
1129 bool WebRtcVoiceEngine::PauseLocalMonitor() {
1130   return ChangeLocalMonitor(false);
1131 }
1132
1133 bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1134   return ChangeLocalMonitor(desired_local_monitor_enable_);
1135 }
1136
1137 const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1138   return codecs_;
1139 }
1140
1141 bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1142   return FindWebRtcCodec(in, NULL);
1143 }
1144
1145 // Get the VoiceEngine codec that matches |in|, with the supplied settings.
1146 bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1147                                         webrtc::CodecInst* out) {
1148   int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1149   for (int i = 0; i < ncodecs; ++i) {
1150     webrtc::CodecInst voe_codec;
1151     if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1152       AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1153                        voe_codec.rate, voe_codec.channels, 0);
1154       bool multi_rate = IsCodecMultiRate(voe_codec);
1155       // Allow arbitrary rates for ISAC to be specified.
1156       if (multi_rate) {
1157         // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1158         codec.bitrate = 0;
1159       }
1160       if (codec.Matches(in)) {
1161         if (out) {
1162           // Fixup the payload type.
1163           voe_codec.pltype = in.id;
1164
1165           // Set bitrate if specified.
1166           if (multi_rate && in.bitrate != 0) {
1167             voe_codec.rate = in.bitrate;
1168           }
1169
1170           // Apply codec-specific settings.
1171           if (IsIsac(codec)) {
1172             // If ISAC and an explicit bitrate is not specified,
1173             // enable auto bandwidth adjustment.
1174             voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1175           }
1176           *out = voe_codec;
1177         }
1178         return true;
1179       }
1180     }
1181   }
1182   return false;
1183 }
1184 const std::vector<RtpHeaderExtension>&
1185 WebRtcVoiceEngine::rtp_header_extensions() const {
1186   return rtp_header_extensions_;
1187 }
1188
1189 void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1190   // if min_sev == -1, we keep the current log level.
1191   if (min_sev >= 0) {
1192     SetTraceFilter(SeverityToFilter(min_sev));
1193   }
1194   log_options_ = filter;
1195   SetTraceOptions(initialized_ ? log_options_ : "");
1196 }
1197
1198 int WebRtcVoiceEngine::GetLastEngineError() {
1199   return voe_wrapper_->error();
1200 }
1201
1202 void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1203   log_filter_ = filter;
1204   tracing_->SetTraceFilter(filter);
1205 }
1206
1207 // We suppport three different logging settings for VoiceEngine:
1208 // 1. Observer callback that goes into talk diagnostic logfile.
1209 //    Use --logfile and --loglevel
1210 //
1211 // 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1212 //    Use --voice_loglevel --voice_logfilter "tracefile file_name"
1213 //
1214 // 3. EC log and dump for debugging QualityEngine.
1215 //    Use --voice_loglevel --voice_logfilter "recordEC file_name"
1216 //
1217 // For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1218 //    Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1219 void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1220   // Set encrypted trace file.
1221   std::vector<std::string> opts;
1222   talk_base::tokenize(options, ' ', '"', '"', &opts);
1223   std::vector<std::string>::iterator tracefile =
1224       std::find(opts.begin(), opts.end(), "tracefile");
1225   if (tracefile != opts.end() && ++tracefile != opts.end()) {
1226     // Write encrypted debug output (at same loglevel) to file
1227     // EncryptedTraceFile no longer supported.
1228     if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1229       LOG_RTCERR1(SetTraceFile, *tracefile);
1230     }
1231   }
1232
1233   // Allow trace options to override the trace filter. We default
1234   // it to log_filter_ (as a translation of libjingle log levels)
1235   // elsewhere, but this allows clients to explicitly set webrtc
1236   // log levels.
1237   std::vector<std::string>::iterator tracefilter =
1238       std::find(opts.begin(), opts.end(), "tracefilter");
1239   if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
1240     if (!tracing_->SetTraceFilter(talk_base::FromString<int>(*tracefilter))) {
1241       LOG_RTCERR1(SetTraceFilter, *tracefilter);
1242     }
1243   }
1244
1245   // Set AEC dump file
1246   std::vector<std::string>::iterator recordEC =
1247       std::find(opts.begin(), opts.end(), "recordEC");
1248   if (recordEC != opts.end()) {
1249     ++recordEC;
1250     if (recordEC != opts.end())
1251       StartAecDump(recordEC->c_str());
1252     else
1253       StopAecDump();
1254   }
1255 }
1256
1257 // Ignore spammy trace messages, mostly from the stats API when we haven't
1258 // gotten RTCP info yet from the remote side.
1259 bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1260   static const char* kTracesToIgnore[] = {
1261     "\tfailed to GetReportBlockInformation",
1262     "GetRecCodec() failed to get received codec",
1263     "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1264     "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets",  // NOLINT
1265     "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1266     "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet",  // NOLINT
1267     "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1268     "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1269     "SenderInfoReceived No received SR",
1270     "StatisticsRTP() no statistics available",
1271     "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted",  // NOLINT
1272     "TransmitMixer::TypingDetection() pending noise-saturation warning exists",  // NOLINT
1273     "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1274     "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1275     NULL
1276   };
1277   for (const char* const* p = kTracesToIgnore; *p; ++p) {
1278     if (trace.find(*p) != std::string::npos) {
1279       return true;
1280     }
1281   }
1282   return false;
1283 }
1284
1285 void WebRtcVoiceEngine::EnableExperimentalAcm(bool enable) {
1286   if (enable == use_experimental_acm_)
1287     return;
1288   if (enable) {
1289     LOG(LS_INFO) << "VoiceEngine is set to use new ACM (ACM2 + NetEq4).";
1290     voe_config_.Set<webrtc::AudioCodingModuleFactory>(
1291         new webrtc::NewAudioCodingModuleFactory());
1292   } else {
1293     LOG(LS_INFO) << "VoiceEngine is set to use legacy ACM (ACM1 + Neteq3).";
1294     voe_config_.Set<webrtc::AudioCodingModuleFactory>(
1295         new webrtc::AudioCodingModuleFactory());
1296   }
1297   use_experimental_acm_ = enable;
1298 }
1299
1300 void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1301                               int length) {
1302   talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
1303   if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
1304     sev = talk_base::LS_ERROR;
1305   else if (level == webrtc::kTraceWarning)
1306     sev = talk_base::LS_WARNING;
1307   else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
1308     sev = talk_base::LS_INFO;
1309   else if (level == webrtc::kTraceTerseInfo)
1310     sev = talk_base::LS_INFO;
1311
1312   // Skip past boilerplate prefix text
1313   if (length < 72) {
1314     std::string msg(trace, length);
1315     LOG(LS_ERROR) << "Malformed webrtc log message: ";
1316     LOG_V(sev) << msg;
1317   } else {
1318     std::string msg(trace + 71, length - 72);
1319     if (!ShouldIgnoreTrace(msg)) {
1320       LOG_V(sev) << "webrtc: " << msg;
1321     }
1322   }
1323 }
1324
1325 void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
1326   talk_base::CritScope lock(&channels_cs_);
1327   WebRtcVoiceMediaChannel* channel = NULL;
1328   uint32 ssrc = 0;
1329   LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1330                   << channel_num << ".";
1331   if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1332     ASSERT(channel != NULL);
1333     channel->OnError(ssrc, err_code);
1334   } else {
1335     LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1336                   << " could not be found in channel list when error reported.";
1337   }
1338 }
1339
1340 bool WebRtcVoiceEngine::FindChannelAndSsrc(
1341     int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1342   ASSERT(channel != NULL && ssrc != NULL);
1343
1344   *channel = NULL;
1345   *ssrc = 0;
1346   // Find corresponding channel and ssrc
1347   for (ChannelList::const_iterator it = channels_.begin();
1348       it != channels_.end(); ++it) {
1349     ASSERT(*it != NULL);
1350     if ((*it)->FindSsrc(channel_num, ssrc)) {
1351       *channel = *it;
1352       return true;
1353     }
1354   }
1355
1356   return false;
1357 }
1358
1359 // This method will search through the WebRtcVoiceMediaChannels and
1360 // obtain the voice engine's channel number.
1361 bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1362     uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1363   ASSERT(channel_num != NULL);
1364   ASSERT(direction == MPD_RX || direction == MPD_TX);
1365
1366   *channel_num = -1;
1367   // Find corresponding channel for ssrc.
1368   for (ChannelList::const_iterator it = channels_.begin();
1369       it != channels_.end(); ++it) {
1370     ASSERT(*it != NULL);
1371     if (direction & MPD_RX) {
1372       *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1373     }
1374     if (*channel_num == -1 && (direction & MPD_TX)) {
1375       *channel_num = (*it)->GetSendChannelNum(ssrc);
1376     }
1377     if (*channel_num != -1) {
1378       return true;
1379     }
1380   }
1381   LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1382   return false;
1383 }
1384
1385 void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
1386   talk_base::CritScope lock(&channels_cs_);
1387   channels_.push_back(channel);
1388 }
1389
1390 void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
1391   talk_base::CritScope lock(&channels_cs_);
1392   ChannelList::iterator i = std::find(channels_.begin(),
1393                                       channels_.end(),
1394                                       channel);
1395   if (i != channels_.end()) {
1396     channels_.erase(i);
1397   }
1398 }
1399
1400 void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1401   soundclips_.push_back(soundclip);
1402 }
1403
1404 void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1405   SoundclipList::iterator i = std::find(soundclips_.begin(),
1406                                         soundclips_.end(),
1407                                         soundclip);
1408   if (i != soundclips_.end()) {
1409     soundclips_.erase(i);
1410   }
1411 }
1412
1413 // Adjusts the default AGC target level by the specified delta.
1414 // NB: If we start messing with other config fields, we'll want
1415 // to save the current webrtc::AgcConfig as well.
1416 bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1417   webrtc::AgcConfig config = default_agc_config_;
1418   config.targetLeveldBOv -= delta;
1419
1420   LOG(LS_INFO) << "Adjusting AGC level from default -"
1421                << default_agc_config_.targetLeveldBOv << "dB to -"
1422                << config.targetLeveldBOv << "dB";
1423
1424   if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1425     LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1426     return false;
1427   }
1428   return true;
1429 }
1430
1431 bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1432     webrtc::AudioDeviceModule* adm_sc) {
1433   if (initialized_) {
1434     LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1435     return false;
1436   }
1437   if (adm_) {
1438     adm_->Release();
1439     adm_ = NULL;
1440   }
1441   if (adm) {
1442     adm_ = adm;
1443     adm_->AddRef();
1444   }
1445
1446   if (adm_sc_) {
1447     adm_sc_->Release();
1448     adm_sc_ = NULL;
1449   }
1450   if (adm_sc) {
1451     adm_sc_ = adm_sc;
1452     adm_sc_->AddRef();
1453   }
1454   return true;
1455 }
1456
1457 bool WebRtcVoiceEngine::StartAecDump(talk_base::PlatformFile file) {
1458   FILE* aec_dump_file_stream = talk_base::FdopenPlatformFileForWriting(file);
1459   if (!aec_dump_file_stream) {
1460     LOG(LS_ERROR) << "Could not open AEC dump file stream.";
1461     if (!talk_base::ClosePlatformFile(file))
1462       LOG(LS_WARNING) << "Could not close file.";
1463     return false;
1464   }
1465   StopAecDump();
1466   if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
1467       webrtc::AudioProcessing::kNoError) {
1468     LOG_RTCERR0(StartDebugRecording);
1469     fclose(aec_dump_file_stream);
1470     return false;
1471   }
1472   is_dumping_aec_ = true;
1473   return true;
1474 }
1475
1476 bool WebRtcVoiceEngine::RegisterProcessor(
1477     uint32 ssrc,
1478     VoiceProcessor* voice_processor,
1479     MediaProcessorDirection direction) {
1480   bool register_with_webrtc = false;
1481   int channel_id = -1;
1482   bool success = false;
1483   uint32* processor_ssrc = NULL;
1484   bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1485   if (voice_processor == NULL || !found_channel) {
1486     LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1487         << " foundChannel: " << found_channel;
1488     return false;
1489   }
1490
1491   webrtc::ProcessingTypes processing_type;
1492   {
1493     talk_base::CritScope cs(&signal_media_critical_);
1494     if (direction == MPD_RX) {
1495       processing_type = webrtc::kPlaybackAllChannelsMixed;
1496       if (SignalRxMediaFrame.is_empty()) {
1497         register_with_webrtc = true;
1498         processor_ssrc = &rx_processor_ssrc_;
1499       }
1500       SignalRxMediaFrame.connect(voice_processor,
1501                                  &VoiceProcessor::OnFrame);
1502     } else {
1503       processing_type = webrtc::kRecordingPerChannel;
1504       if (SignalTxMediaFrame.is_empty()) {
1505         register_with_webrtc = true;
1506         processor_ssrc = &tx_processor_ssrc_;
1507       }
1508       SignalTxMediaFrame.connect(voice_processor,
1509                                  &VoiceProcessor::OnFrame);
1510     }
1511   }
1512   if (register_with_webrtc) {
1513     // TODO(janahan): when registering consider instantiating a
1514     // a VoeMediaProcess object and not make the engine extend the interface.
1515     if (voe()->media() && voe()->media()->
1516         RegisterExternalMediaProcessing(channel_id,
1517                                         processing_type,
1518                                         *this) != -1) {
1519       LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1520                    << channel_id;
1521       *processor_ssrc = ssrc;
1522       success = true;
1523     } else {
1524       LOG_RTCERR2(RegisterExternalMediaProcessing,
1525                   channel_id,
1526                   processing_type);
1527       success = false;
1528     }
1529   } else {
1530     // If we don't have to register with the engine, we just needed to
1531     // connect a new processor, set success to true;
1532     success = true;
1533   }
1534   return success;
1535 }
1536
1537 bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1538     MediaProcessorDirection channel_direction,
1539     uint32 ssrc,
1540     VoiceProcessor* voice_processor,
1541     MediaProcessorDirection processor_direction) {
1542   bool success = true;
1543   FrameSignal* signal;
1544   webrtc::ProcessingTypes processing_type;
1545   uint32* processor_ssrc = NULL;
1546   if (channel_direction == MPD_RX) {
1547     signal = &SignalRxMediaFrame;
1548     processing_type = webrtc::kPlaybackAllChannelsMixed;
1549     processor_ssrc = &rx_processor_ssrc_;
1550   } else {
1551     signal = &SignalTxMediaFrame;
1552     processing_type = webrtc::kRecordingPerChannel;
1553     processor_ssrc = &tx_processor_ssrc_;
1554   }
1555
1556   int deregister_id = -1;
1557   {
1558     talk_base::CritScope cs(&signal_media_critical_);
1559     if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1560       signal->disconnect(voice_processor);
1561       int channel_id = -1;
1562       bool found_channel = FindChannelNumFromSsrc(ssrc,
1563                                                   channel_direction,
1564                                                   &channel_id);
1565       if (signal->is_empty() && found_channel) {
1566         deregister_id = channel_id;
1567       }
1568     }
1569   }
1570   if (deregister_id != -1) {
1571     if (voe()->media() &&
1572         voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1573         processing_type) != -1) {
1574       *processor_ssrc = 0;
1575       LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1576                    << deregister_id;
1577     } else {
1578       LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1579                   deregister_id,
1580                   processing_type);
1581       success = false;
1582     }
1583   }
1584   return success;
1585 }
1586
1587 bool WebRtcVoiceEngine::UnregisterProcessor(
1588     uint32 ssrc,
1589     VoiceProcessor* voice_processor,
1590     MediaProcessorDirection direction) {
1591   bool success = true;
1592   if (voice_processor == NULL) {
1593     LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1594                     << ssrc;
1595     return false;
1596   }
1597   if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1598     success = false;
1599   }
1600   if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1601     success = false;
1602   }
1603   return success;
1604 }
1605
1606 // Implementing method from WebRtc VoEMediaProcess interface
1607 // Do not lock mux_channel_cs_ in this callback.
1608 void WebRtcVoiceEngine::Process(int channel,
1609                                 webrtc::ProcessingTypes type,
1610                                 int16_t audio10ms[],
1611                                 int length,
1612                                 int sampling_freq,
1613                                 bool is_stereo) {
1614     talk_base::CritScope cs(&signal_media_critical_);
1615     AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1616     if (type == webrtc::kPlaybackAllChannelsMixed) {
1617       SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1618     } else if (type == webrtc::kRecordingPerChannel) {
1619       SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1620     } else {
1621       LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1622                       << " channel: " << channel << " type: " << type
1623                       << " tx_ssrc: " << tx_processor_ssrc_
1624                       << " rx_ssrc: " << rx_processor_ssrc_;
1625     }
1626 }
1627
1628 void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1629   if (!is_dumping_aec_) {
1630     // Start dumping AEC when we are not dumping.
1631     if (voe_wrapper_->processing()->StartDebugRecording(
1632         filename.c_str()) != webrtc::AudioProcessing::kNoError) {
1633       LOG_RTCERR1(StartDebugRecording, filename.c_str());
1634     } else {
1635       is_dumping_aec_ = true;
1636     }
1637   }
1638 }
1639
1640 void WebRtcVoiceEngine::StopAecDump() {
1641   if (is_dumping_aec_) {
1642     // Stop dumping AEC when we are dumping.
1643     if (voe_wrapper_->processing()->StopDebugRecording() !=
1644         webrtc::AudioProcessing::kNoError) {
1645       LOG_RTCERR0(StopDebugRecording);
1646     }
1647     is_dumping_aec_ = false;
1648   }
1649 }
1650
1651 int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
1652   return voice_engine_wrapper->base()->CreateChannel(voe_config_);
1653 }
1654
1655 int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1656   return CreateVoiceChannel(voe_wrapper_.get());
1657 }
1658
1659 int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1660   return CreateVoiceChannel(voe_wrapper_sc_.get());
1661 }
1662
1663 class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1664     : public AudioRenderer::Sink {
1665  public:
1666   WebRtcVoiceChannelRenderer(int ch,
1667                              webrtc::AudioTransport* voe_audio_transport)
1668       : channel_(ch),
1669         voe_audio_transport_(voe_audio_transport),
1670         renderer_(NULL) {
1671   }
1672   virtual ~WebRtcVoiceChannelRenderer() {
1673     Stop();
1674   }
1675
1676   // Starts the rendering by setting a sink to the renderer to get data
1677   // callback.
1678   // TODO(xians): Make sure Start() is called only once.
1679   void Start(AudioRenderer* renderer) {
1680     ASSERT(renderer != NULL);
1681     if (renderer_) {
1682       ASSERT(renderer_ == renderer);
1683       return;
1684     }
1685
1686     // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1687     // in getUserMedia by default.
1688     renderer->AddChannel(channel_);
1689     renderer->SetSink(this);
1690     renderer_ = renderer;
1691   }
1692
1693   // Stops rendering by setting the sink of the renderer to NULL. No data
1694   // callback will be received after this method.
1695   void Stop() {
1696     if (!renderer_)
1697       return;
1698
1699     renderer_->RemoveChannel(channel_);
1700     renderer_->SetSink(NULL);
1701     renderer_ = NULL;
1702   }
1703
1704   // AudioRenderer::Sink implementation.
1705   virtual void OnData(const void* audio_data,
1706                       int bits_per_sample,
1707                       int sample_rate,
1708                       int number_of_channels,
1709                       int number_of_frames) OVERRIDE {
1710     // TODO(xians): Make new interface in AudioTransport to pass the data to
1711     // WebRtc VoE channel.
1712   }
1713
1714   // Accessor to the VoE channel ID.
1715   int channel() const { return channel_; }
1716
1717  private:
1718   const int channel_;
1719   webrtc::AudioTransport* const voe_audio_transport_;
1720
1721   // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1722   // PeerConnection will make sure invalidating the pointer before the object
1723   // goes away.
1724   AudioRenderer* renderer_;
1725 };
1726
1727 // WebRtcVoiceMediaChannel
1728 WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1729     : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1730           engine,
1731           engine->CreateMediaVoiceChannel()),
1732       send_bw_setting_(false),
1733       send_bw_bps_(0),
1734       options_(),
1735       dtmf_allowed_(false),
1736       desired_playout_(false),
1737       nack_enabled_(false),
1738       playout_(false),
1739       typing_noise_detected_(false),
1740       desired_send_(SEND_NOTHING),
1741       send_(SEND_NOTHING),
1742       default_receive_ssrc_(0) {
1743   engine->RegisterChannel(this);
1744   LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1745                   << voe_channel();
1746
1747   ConfigureSendChannel(voe_channel());
1748 }
1749
1750 WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1751   LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1752                   << voe_channel();
1753
1754   // Remove any remaining send streams, the default channel will be deleted
1755   // later.
1756   while (!send_channels_.empty())
1757     RemoveSendStream(send_channels_.begin()->first);
1758
1759   // Unregister ourselves from the engine.
1760   engine()->UnregisterChannel(this);
1761   // Remove any remaining streams.
1762   while (!receive_channels_.empty()) {
1763     RemoveRecvStream(receive_channels_.begin()->first);
1764   }
1765
1766   // Delete the default channel.
1767   DeleteChannel(voe_channel());
1768 }
1769
1770 bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1771   LOG(LS_INFO) << "Setting voice channel options: "
1772                << options.ToString();
1773
1774   // Check if DSCP value is changed from previous.
1775   bool dscp_option_changed = (options_.dscp != options.dscp);
1776
1777   // TODO(xians): Add support to set different options for different send
1778   // streams after we support multiple APMs.
1779
1780   // We retain all of the existing options, and apply the given ones
1781   // on top.  This means there is no way to "clear" options such that
1782   // they go back to the engine default.
1783   options_.SetAll(options);
1784
1785   if (send_ != SEND_NOTHING) {
1786     if (!engine()->SetOptionOverrides(options_)) {
1787       LOG(LS_WARNING) <<
1788           "Failed to engine SetOptionOverrides during channel SetOptions.";
1789       return false;
1790     }
1791   } else {
1792     // Will be interpreted when appropriate.
1793   }
1794
1795   // Receiver-side auto gain control happens per channel, so set it here from
1796   // options. Note that, like conference mode, setting it on the engine won't
1797   // have the desired effect, since voice channels don't inherit options from
1798   // the media engine when those options are applied per-channel.
1799   bool rx_auto_gain_control;
1800   if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1801     if (engine()->voe()->processing()->SetRxAgcStatus(
1802             voe_channel(), rx_auto_gain_control,
1803             webrtc::kAgcFixedDigital) == -1) {
1804       LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1805       return false;
1806     } else {
1807       LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1808                       << " with mode " << webrtc::kAgcFixedDigital;
1809     }
1810   }
1811   if (options.rx_agc_target_dbov.IsSet() ||
1812       options.rx_agc_digital_compression_gain.IsSet() ||
1813       options.rx_agc_limiter.IsSet()) {
1814     webrtc::AgcConfig config;
1815     // If only some of the options are being overridden, get the current
1816     // settings for the channel and bail if they aren't available.
1817     if (!options.rx_agc_target_dbov.IsSet() ||
1818         !options.rx_agc_digital_compression_gain.IsSet() ||
1819         !options.rx_agc_limiter.IsSet()) {
1820       if (engine()->voe()->processing()->GetRxAgcConfig(
1821               voe_channel(), config) != 0) {
1822         LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1823                       << "channel " << voe_channel() << ". Since not all rx "
1824                       << "agc options are specified, unable to safely set rx "
1825                       << "agc options.";
1826         return false;
1827       }
1828     }
1829     config.targetLeveldBOv =
1830         options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1831             config.targetLeveldBOv);
1832     config.digitalCompressionGaindB =
1833         options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1834             config.digitalCompressionGaindB);
1835     config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1836         config.limiterEnable);
1837     if (engine()->voe()->processing()->SetRxAgcConfig(
1838             voe_channel(), config) == -1) {
1839       LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1840                   config.digitalCompressionGaindB, config.limiterEnable);
1841       return false;
1842     }
1843   }
1844   if (dscp_option_changed) {
1845     talk_base::DiffServCodePoint dscp = talk_base::DSCP_DEFAULT;
1846     if (options_.dscp.GetWithDefaultIfUnset(false))
1847       dscp = kAudioDscpValue;
1848     if (MediaChannel::SetDscp(dscp) != 0) {
1849       LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1850     }
1851   }
1852
1853   LOG(LS_INFO) << "Set voice channel options.  Current options: "
1854                << options_.ToString();
1855   return true;
1856 }
1857
1858 bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1859     const std::vector<AudioCodec>& codecs) {
1860   // Set the payload types to be used for incoming media.
1861   LOG(LS_INFO) << "Setting receive voice codecs:";
1862
1863   std::vector<AudioCodec> new_codecs;
1864   // Find all new codecs. We allow adding new codecs but don't allow changing
1865   // the payload type of codecs that is already configured since we might
1866   // already be receiving packets with that payload type.
1867   for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1868        it != codecs.end(); ++it) {
1869     AudioCodec old_codec;
1870     if (FindCodec(recv_codecs_, *it, &old_codec)) {
1871       if (old_codec.id != it->id) {
1872         LOG(LS_ERROR) << it->name << " payload type changed.";
1873         return false;
1874       }
1875     } else {
1876       new_codecs.push_back(*it);
1877     }
1878   }
1879   if (new_codecs.empty()) {
1880     // There are no new codecs to configure. Already configured codecs are
1881     // never removed.
1882     return true;
1883   }
1884
1885   if (playout_) {
1886     // Receive codecs can not be changed while playing. So we temporarily
1887     // pause playout.
1888     PausePlayout();
1889   }
1890
1891   bool ret = true;
1892   for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1893        it != new_codecs.end() && ret; ++it) {
1894     webrtc::CodecInst voe_codec;
1895     if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1896       LOG(LS_INFO) << ToString(*it);
1897       voe_codec.pltype = it->id;
1898       if (default_receive_ssrc_ == 0) {
1899         // Set the receive codecs on the default channel explicitly if the
1900         // default channel is not used by |receive_channels_|, this happens in
1901         // conference mode or in non-conference mode when there is no playout
1902         // channel.
1903         // TODO(xians): Figure out how we use the default channel in conference
1904         // mode.
1905         if (engine()->voe()->codec()->SetRecPayloadType(
1906             voe_channel(), voe_codec) == -1) {
1907           LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1908           ret = false;
1909         }
1910       }
1911
1912       // Set the receive codecs on all receiving channels.
1913       for (ChannelMap::iterator it = receive_channels_.begin();
1914            it != receive_channels_.end() && ret; ++it) {
1915         if (engine()->voe()->codec()->SetRecPayloadType(
1916                 it->second->channel(), voe_codec) == -1) {
1917           LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
1918                       ToString(voe_codec));
1919           ret = false;
1920         }
1921       }
1922     } else {
1923       LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1924       ret = false;
1925     }
1926   }
1927   if (ret) {
1928     recv_codecs_ = codecs;
1929   }
1930
1931   if (desired_playout_ && !playout_) {
1932     ResumePlayout();
1933   }
1934   return ret;
1935 }
1936
1937 bool WebRtcVoiceMediaChannel::SetSendCodecs(
1938     int channel, const std::vector<AudioCodec>& codecs) {
1939   // Disable VAD, and FEC unless we know the other side wants them.
1940   engine()->voe()->codec()->SetVADStatus(channel, false);
1941   engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1942   engine()->voe()->rtp()->SetFECStatus(channel, false);
1943
1944   // Scan through the list to figure out the codec to use for sending, along
1945   // with the proper configuration for VAD and DTMF.
1946   bool first = true;
1947   webrtc::CodecInst send_codec;
1948   memset(&send_codec, 0, sizeof(send_codec));
1949
1950   for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1951        it != codecs.end(); ++it) {
1952     // Ignore codecs we don't know about. The negotiation step should prevent
1953     // this, but double-check to be sure.
1954     webrtc::CodecInst voe_codec;
1955     if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
1956       LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1957       continue;
1958     }
1959
1960     // If OPUS, change what we send according to the "stereo" codec
1961     // parameter, and not the "channels" parameter.  We set
1962     // voe_codec.channels to 2 if "stereo=1" and 1 otherwise.  If
1963     // the bitrate is not specified, i.e. is zero, we set it to the
1964     // appropriate default value for mono or stereo Opus.
1965     if (IsOpus(*it)) {
1966       if (IsOpusStereoEnabled(*it)) {
1967         voe_codec.channels = 2;
1968         if (!IsValidOpusBitrate(it->bitrate)) {
1969           if (it->bitrate != 0) {
1970             LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
1971                             << it->bitrate
1972                             << ") with default opus stereo bitrate: "
1973                             << kOpusStereoBitrate;
1974           }
1975           voe_codec.rate = kOpusStereoBitrate;
1976         }
1977       } else {
1978         voe_codec.channels = 1;
1979         if (!IsValidOpusBitrate(it->bitrate)) {
1980           if (it->bitrate != 0) {
1981             LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
1982                             << it->bitrate
1983                             << ") with default opus mono bitrate: "
1984                             << kOpusMonoBitrate;
1985           }
1986           voe_codec.rate = kOpusMonoBitrate;
1987         }
1988       }
1989       int bitrate_from_params = GetOpusBitrateFromParams(*it);
1990       if (bitrate_from_params != 0) {
1991         voe_codec.rate = bitrate_from_params;
1992       }
1993     }
1994
1995     // Find the DTMF telephone event "codec" and tell VoiceEngine channels
1996     // about it.
1997     if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
1998         _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
1999       if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2000               channel, it->id) == -1) {
2001         LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2002         return false;
2003       }
2004     }
2005
2006     // Turn voice activity detection/comfort noise on if supported.
2007     // Set the wideband CN payload type appropriately.
2008     // (narrowband always uses the static payload type 13).
2009     if (_stricmp(it->name.c_str(), "CN") == 0) {
2010       webrtc::PayloadFrequencies cn_freq;
2011       switch (it->clockrate) {
2012         case 8000:
2013           cn_freq = webrtc::kFreq8000Hz;
2014           break;
2015         case 16000:
2016           cn_freq = webrtc::kFreq16000Hz;
2017           break;
2018         case 32000:
2019           cn_freq = webrtc::kFreq32000Hz;
2020           break;
2021         default:
2022           LOG(LS_WARNING) << "CN frequency " << it->clockrate
2023                           << " not supported.";
2024           continue;
2025       }
2026       // Set the CN payloadtype and the VAD status.
2027       // The CN payload type for 8000 Hz clockrate is fixed at 13.
2028       if (cn_freq != webrtc::kFreq8000Hz) {
2029         if (engine()->voe()->codec()->SetSendCNPayloadType(
2030                 channel, it->id, cn_freq) == -1) {
2031           LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2032           // TODO(ajm): This failure condition will be removed from VoE.
2033           // Restore the return here when we update to a new enough webrtc.
2034           //
2035           // Not returning false because the SetSendCNPayloadType will fail if
2036           // the channel is already sending.
2037           // This can happen if the remote description is applied twice, for
2038           // example in the case of ROAP on top of JSEP, where both side will
2039           // send the offer.
2040         }
2041       }
2042
2043       // Only turn on VAD if we have a CN payload type that matches the
2044       // clockrate for the codec we are going to use.
2045       if (it->clockrate == send_codec.plfreq) {
2046         LOG(LS_INFO) << "Enabling VAD";
2047         if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2048           LOG_RTCERR2(SetVADStatus, channel, true);
2049           return false;
2050         }
2051       }
2052     }
2053
2054     // We'll use the first codec in the list to actually send audio data.
2055     // Be sure to use the payload type requested by the remote side.
2056     // "red", for FEC audio, is a special case where the actual codec to be
2057     // used is specified in params.
2058     if (first) {
2059       if (_stricmp(it->name.c_str(), "red") == 0) {
2060         // Parse out the RED parameters. If we fail, just ignore RED;
2061         // we don't support all possible params/usage scenarios.
2062         if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2063           continue;
2064         }
2065
2066         // Enable redundant encoding of the specified codec. Treat any
2067         // failure as a fatal internal error.
2068         LOG(LS_INFO) << "Enabling FEC";
2069         if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2070           LOG_RTCERR3(SetFECStatus, channel, true, it->id);
2071           return false;
2072         }
2073       } else {
2074         send_codec = voe_codec;
2075         nack_enabled_ = IsNackEnabled(*it);
2076         SetNack(channel, nack_enabled_);
2077       }
2078       first = false;
2079       // Set the codec immediately, since SetVADStatus() depends on whether
2080       // the current codec is mono or stereo.
2081       if (!SetSendCodec(channel, send_codec))
2082         return false;
2083     }
2084   }
2085
2086   // If we're being asked to set an empty list of codecs, due to a buggy client,
2087   // choose the most common format: PCMU
2088   if (first) {
2089     LOG(LS_WARNING) << "Received empty list of codecs; using PCMU/8000";
2090     AudioCodec codec(0, "PCMU", 8000, 0, 1, 0);
2091     engine()->FindWebRtcCodec(codec, &send_codec);
2092     if (!SetSendCodec(channel, send_codec))
2093       return false;
2094   }
2095
2096   // Always update the |send_codec_| to the currently set send codec.
2097   send_codec_.reset(new webrtc::CodecInst(send_codec));
2098
2099   if (send_bw_setting_) {
2100     SetSendBandwidthInternal(send_bw_bps_);
2101   }
2102
2103   return true;
2104 }
2105
2106 bool WebRtcVoiceMediaChannel::SetSendCodecs(
2107     const std::vector<AudioCodec>& codecs) {
2108   dtmf_allowed_ = false;
2109   for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2110        it != codecs.end(); ++it) {
2111     // Find the DTMF telephone event "codec".
2112     if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2113         _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2114       dtmf_allowed_ = true;
2115     }
2116   }
2117
2118   // Cache the codecs in order to configure the channel created later.
2119   send_codecs_ = codecs;
2120   for (ChannelMap::iterator iter = send_channels_.begin();
2121        iter != send_channels_.end(); ++iter) {
2122     if (!SetSendCodecs(iter->second->channel(), codecs)) {
2123       return false;
2124     }
2125   }
2126
2127   SetNack(receive_channels_, nack_enabled_);
2128
2129   return true;
2130 }
2131
2132 void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2133                                       bool nack_enabled) {
2134   for (ChannelMap::const_iterator it = channels.begin();
2135        it != channels.end(); ++it) {
2136     SetNack(it->second->channel(), nack_enabled);
2137   }
2138 }
2139
2140 void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
2141   if (nack_enabled) {
2142     LOG(LS_INFO) << "Enabling NACK for channel " << channel;
2143     engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2144   } else {
2145     LOG(LS_INFO) << "Disabling NACK for channel " << channel;
2146     engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2147   }
2148 }
2149
2150 bool WebRtcVoiceMediaChannel::SetSendCodec(
2151     const webrtc::CodecInst& send_codec) {
2152   LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2153                << ", bitrate=" << send_codec.rate;
2154   for (ChannelMap::iterator iter = send_channels_.begin();
2155        iter != send_channels_.end(); ++iter) {
2156     if (!SetSendCodec(iter->second->channel(), send_codec))
2157       return false;
2158   }
2159
2160   return true;
2161 }
2162
2163 bool WebRtcVoiceMediaChannel::SetSendCodec(
2164     int channel, const webrtc::CodecInst& send_codec) {
2165   LOG(LS_INFO) << "Send channel " << channel <<  " selected voice codec "
2166                << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2167
2168   if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2169     LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
2170     return false;
2171   }
2172   return true;
2173 }
2174
2175 bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2176     const std::vector<RtpHeaderExtension>& extensions) {
2177   // We don't support any incoming extensions headers right now.
2178   return true;
2179 }
2180
2181 bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2182     const std::vector<RtpHeaderExtension>& extensions) {
2183   // Enable the audio level extension header if requested.
2184   std::vector<RtpHeaderExtension>::const_iterator it;
2185   for (it = extensions.begin(); it != extensions.end(); ++it) {
2186     if (it->uri == kRtpAudioLevelHeaderExtension) {
2187       break;
2188     }
2189   }
2190
2191   bool enable = (it != extensions.end());
2192   int id = 0;
2193
2194   if (enable) {
2195     id = it->id;
2196     if (id < kMinRtpHeaderExtensionId ||
2197         id > kMaxRtpHeaderExtensionId) {
2198       LOG(LS_WARNING) << "Invalid RTP header extension id " << id;
2199       return false;
2200     }
2201   }
2202
2203   LOG(LS_INFO) << "Enabling audio level header extension with ID " << id;
2204   for (ChannelMap::const_iterator iter = send_channels_.begin();
2205        iter != send_channels_.end(); ++iter) {
2206     if (engine()->voe()->rtp()->SetRTPAudioLevelIndicationStatus(
2207             iter->second->channel(), enable, id) == -1) {
2208       LOG_RTCERR3(SetRTPAudioLevelIndicationStatus,
2209                   iter->second->channel(), enable, id);
2210       return false;
2211     }
2212   }
2213
2214   return true;
2215 }
2216
2217 bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2218   desired_playout_ = playout;
2219   return ChangePlayout(desired_playout_);
2220 }
2221
2222 bool WebRtcVoiceMediaChannel::PausePlayout() {
2223   return ChangePlayout(false);
2224 }
2225
2226 bool WebRtcVoiceMediaChannel::ResumePlayout() {
2227   return ChangePlayout(desired_playout_);
2228 }
2229
2230 bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2231   if (playout_ == playout) {
2232     return true;
2233   }
2234
2235   // Change the playout of all channels to the new state.
2236   bool result = true;
2237   if (receive_channels_.empty()) {
2238     // Only toggle the default channel if we don't have any other channels.
2239     result = SetPlayout(voe_channel(), playout);
2240   }
2241   for (ChannelMap::iterator it = receive_channels_.begin();
2242        it != receive_channels_.end() && result; ++it) {
2243     if (!SetPlayout(it->second->channel(), playout)) {
2244       LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
2245                     << it->second->channel() << " failed";
2246       result = false;
2247     }
2248   }
2249
2250   if (result) {
2251     playout_ = playout;
2252   }
2253   return result;
2254 }
2255
2256 bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2257   desired_send_ = send;
2258   if (!send_channels_.empty())
2259     return ChangeSend(desired_send_);
2260   return true;
2261 }
2262
2263 bool WebRtcVoiceMediaChannel::PauseSend() {
2264   return ChangeSend(SEND_NOTHING);
2265 }
2266
2267 bool WebRtcVoiceMediaChannel::ResumeSend() {
2268   return ChangeSend(desired_send_);
2269 }
2270
2271 bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2272   if (send_ == send) {
2273     return true;
2274   }
2275
2276   // Change the settings on each send channel.
2277   if (send == SEND_MICROPHONE)
2278     engine()->SetOptionOverrides(options_);
2279
2280   // Change the settings on each send channel.
2281   for (ChannelMap::iterator iter = send_channels_.begin();
2282        iter != send_channels_.end(); ++iter) {
2283     if (!ChangeSend(iter->second->channel(), send))
2284       return false;
2285   }
2286
2287   // Clear up the options after stopping sending.
2288   if (send == SEND_NOTHING)
2289     engine()->ClearOptionOverrides();
2290
2291   send_ = send;
2292   return true;
2293 }
2294
2295 bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2296   if (send == SEND_MICROPHONE) {
2297     if (engine()->voe()->base()->StartSend(channel) == -1) {
2298       LOG_RTCERR1(StartSend, channel);
2299       return false;
2300     }
2301     if (engine()->voe()->file() &&
2302         engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2303       LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2304       return false;
2305     }
2306   } else {  // SEND_NOTHING
2307     ASSERT(send == SEND_NOTHING);
2308     if (engine()->voe()->base()->StopSend(channel) == -1) {
2309       LOG_RTCERR1(StopSend, channel);
2310       return false;
2311     }
2312   }
2313
2314   return true;
2315 }
2316
2317 void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2318   if (engine()->voe()->network()->RegisterExternalTransport(
2319           channel, *this) == -1) {
2320     LOG_RTCERR2(RegisterExternalTransport, channel, this);
2321   }
2322
2323   // Enable RTCP (for quality stats and feedback messages)
2324   EnableRtcp(channel);
2325
2326   // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2327   ResetRecvCodecs(channel);
2328 }
2329
2330 bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2331   if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2332     LOG_RTCERR1(DeRegisterExternalTransport, channel);
2333   }
2334
2335   if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2336     LOG_RTCERR1(DeleteChannel, channel);
2337     return false;
2338   }
2339
2340   return true;
2341 }
2342
2343 bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2344   // If the default channel is already used for sending create a new channel
2345   // otherwise use the default channel for sending.
2346   int channel = GetSendChannelNum(sp.first_ssrc());
2347   if (channel != -1) {
2348     LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2349     return false;
2350   }
2351
2352   bool default_channel_is_available = true;
2353   for (ChannelMap::const_iterator iter = send_channels_.begin();
2354        iter != send_channels_.end(); ++iter) {
2355     if (IsDefaultChannel(iter->second->channel())) {
2356       default_channel_is_available = false;
2357       break;
2358     }
2359   }
2360   if (default_channel_is_available) {
2361     channel = voe_channel();
2362   } else {
2363     // Create a new channel for sending audio data.
2364     channel = engine()->CreateMediaVoiceChannel();
2365     if (channel == -1) {
2366       LOG_RTCERR0(CreateChannel);
2367       return false;
2368     }
2369
2370     ConfigureSendChannel(channel);
2371   }
2372
2373   // Save the channel to send_channels_, so that RemoveSendStream() can still
2374   // delete the channel in case failure happens below.
2375 #ifdef USE_WEBRTC_DEV_BRANCH
2376   webrtc::AudioTransport* audio_transport =
2377       engine()->voe()->base()->audio_transport();
2378 #else
2379   webrtc::AudioTransport* audio_transport = NULL;
2380 #endif
2381   send_channels_.insert(std::make_pair(
2382       sp.first_ssrc(),
2383       new WebRtcVoiceChannelRenderer(channel, audio_transport)));
2384
2385   // Set the send (local) SSRC.
2386   // If there are multiple send SSRCs, we can only set the first one here, and
2387   // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2388   // (with a codec requires multiple SSRC(s)).
2389   if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2390     LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2391     return false;
2392   }
2393
2394   // At this point the channel's local SSRC has been updated. If the channel is
2395   // the default channel make sure that all the receive channels are updated as
2396   // well. Receive channels have to have the same SSRC as the default channel in
2397   // order to send receiver reports with this SSRC.
2398   if (IsDefaultChannel(channel)) {
2399     for (ChannelMap::const_iterator it = receive_channels_.begin();
2400          it != receive_channels_.end(); ++it) {
2401       // Only update the SSRC for non-default channels.
2402       if (!IsDefaultChannel(it->second->channel())) {
2403         if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
2404                                                  sp.first_ssrc()) != 0) {
2405           LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
2406           return false;
2407         }
2408       }
2409     }
2410   }
2411
2412   if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
2413      LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2414      return false;
2415   }
2416
2417   // Set the current codecs to be used for the new channel.
2418   if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
2419     return false;
2420
2421   return ChangeSend(channel, desired_send_);
2422 }
2423
2424 bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2425   ChannelMap::iterator it = send_channels_.find(ssrc);
2426   if (it == send_channels_.end()) {
2427     LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2428                     << " which doesn't exist.";
2429     return false;
2430   }
2431
2432   int channel = it->second->channel();
2433   ChangeSend(channel, SEND_NOTHING);
2434
2435   // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2436   // this will disconnect the audio renderer with the send channel.
2437   delete it->second;
2438   send_channels_.erase(it);
2439
2440   if (IsDefaultChannel(channel)) {
2441     // Do not delete the default channel since the receive channels depend on
2442     // the default channel, recycle it instead.
2443     ChangeSend(channel, SEND_NOTHING);
2444   } else {
2445     // Clean up and delete the send channel.
2446     LOG(LS_INFO) << "Removing audio send stream " << ssrc
2447                  << " with VoiceEngine channel #" << channel << ".";
2448     if (!DeleteChannel(channel))
2449       return false;
2450   }
2451
2452   if (send_channels_.empty())
2453     ChangeSend(SEND_NOTHING);
2454
2455   return true;
2456 }
2457
2458 bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
2459   talk_base::CritScope lock(&receive_channels_cs_);
2460
2461   if (!VERIFY(sp.ssrcs.size() == 1))
2462     return false;
2463   uint32 ssrc = sp.first_ssrc();
2464
2465   if (ssrc == 0) {
2466     LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2467     return false;
2468   }
2469
2470   if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2471     LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
2472     return false;
2473   }
2474
2475   // Reuse default channel for recv stream in non-conference mode call
2476   // when the default channel is not being used.
2477 #ifdef USE_WEBRTC_DEV_BRANCH
2478   webrtc::AudioTransport* audio_transport =
2479       engine()->voe()->base()->audio_transport();
2480 #else
2481   webrtc::AudioTransport* audio_transport = NULL;
2482 #endif
2483   if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2484     LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2485                  << " reuse default channel";
2486     default_receive_ssrc_ = sp.first_ssrc();
2487     receive_channels_.insert(std::make_pair(
2488         default_receive_ssrc_,
2489         new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
2490     return SetPlayout(voe_channel(), playout_);
2491   }
2492
2493   // Create a new channel for receiving audio data.
2494   int channel = engine()->CreateMediaVoiceChannel();
2495   if (channel == -1) {
2496     LOG_RTCERR0(CreateChannel);
2497     return false;
2498   }
2499
2500   if (!ConfigureRecvChannel(channel)) {
2501     DeleteChannel(channel);
2502     return false;
2503   }
2504
2505   receive_channels_.insert(
2506       std::make_pair(
2507           ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
2508
2509   LOG(LS_INFO) << "New audio stream " << ssrc
2510                << " registered to VoiceEngine channel #"
2511                << channel << ".";
2512   return true;
2513 }
2514
2515 bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
2516   // Configure to use external transport, like our default channel.
2517   if (engine()->voe()->network()->RegisterExternalTransport(
2518           channel, *this) == -1) {
2519     LOG_RTCERR2(SetExternalTransport, channel, this);
2520     return false;
2521   }
2522
2523   // Use the same SSRC as our default channel (so the RTCP reports are correct).
2524   unsigned int send_ssrc = 0;
2525   webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2526   if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
2527     LOG_RTCERR1(GetSendSSRC, channel);
2528     return false;
2529   }
2530   if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
2531     LOG_RTCERR1(SetSendSSRC, channel);
2532     return false;
2533   }
2534
2535   // Use the same recv payload types as our default channel.
2536   ResetRecvCodecs(channel);
2537   if (!recv_codecs_.empty()) {
2538     for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2539         it != recv_codecs_.end(); ++it) {
2540       webrtc::CodecInst voe_codec;
2541       if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2542         voe_codec.pltype = it->id;
2543         voe_codec.rate = 0;  // Needed to make GetRecPayloadType work for ISAC
2544         if (engine()->voe()->codec()->GetRecPayloadType(
2545             voe_channel(), voe_codec) != -1) {
2546           if (engine()->voe()->codec()->SetRecPayloadType(
2547               channel, voe_codec) == -1) {
2548             LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2549             return false;
2550           }
2551         }
2552       }
2553     }
2554   }
2555
2556   if (InConferenceMode()) {
2557     // To be in par with the video, voe_channel() is not used for receiving in
2558     // a conference call.
2559     if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2560       // This is the first stream in a multi user meeting. We can now
2561       // disable playback of the default stream. This since the default
2562       // stream will probably have received some initial packets before
2563       // the new stream was added. This will mean that the CN state from
2564       // the default channel will be mixed in with the other streams
2565       // throughout the whole meeting, which might be disturbing.
2566       LOG(LS_INFO) << "Disabling playback on the default voice channel";
2567       SetPlayout(voe_channel(), false);
2568     }
2569   }
2570   SetNack(channel, nack_enabled_);
2571
2572   return SetPlayout(channel, playout_);
2573 }
2574
2575 bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
2576   talk_base::CritScope lock(&receive_channels_cs_);
2577   ChannelMap::iterator it = receive_channels_.find(ssrc);
2578   if (it == receive_channels_.end()) {
2579     LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2580                     << " which doesn't exist.";
2581     return false;
2582   }
2583
2584   // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2585   // will disconnect the audio renderer with the receive channel.
2586   // Cache the channel before the deletion.
2587   const int channel = it->second->channel();
2588   delete it->second;
2589   receive_channels_.erase(it);
2590
2591   if (ssrc == default_receive_ssrc_) {
2592     ASSERT(IsDefaultChannel(channel));
2593     // Recycle the default channel is for recv stream.
2594     if (playout_)
2595       SetPlayout(voe_channel(), false);
2596
2597     default_receive_ssrc_ = 0;
2598     return true;
2599   }
2600
2601   LOG(LS_INFO) << "Removing audio stream " << ssrc
2602                << " with VoiceEngine channel #" << channel << ".";
2603   if (!DeleteChannel(channel))
2604     return false;
2605
2606   bool enable_default_channel_playout = false;
2607   if (receive_channels_.empty()) {
2608     // The last stream was removed. We can now enable the default
2609     // channel for new channels to be played out immediately without
2610     // waiting for AddStream messages.
2611     // We do this for both conference mode and non-conference mode.
2612     // TODO(oja): Does the default channel still have it's CN state?
2613     enable_default_channel_playout = true;
2614   }
2615   if (!InConferenceMode() && receive_channels_.size() == 1 &&
2616       default_receive_ssrc_ != 0) {
2617     // Only the default channel is active, enable the playout on default
2618     // channel.
2619     enable_default_channel_playout = true;
2620   }
2621   if (enable_default_channel_playout && playout_) {
2622     LOG(LS_INFO) << "Enabling playback on the default voice channel";
2623     SetPlayout(voe_channel(), true);
2624   }
2625
2626   return true;
2627 }
2628
2629 bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2630                                                 AudioRenderer* renderer) {
2631   ChannelMap::iterator it = receive_channels_.find(ssrc);
2632   if (it == receive_channels_.end()) {
2633     if (renderer) {
2634       // Return an error if trying to set a valid renderer with an invalid ssrc.
2635       LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
2636       return false;
2637     }
2638
2639     // The channel likely has gone away, do nothing.
2640     return true;
2641   }
2642
2643   if (renderer)
2644     it->second->Start(renderer);
2645   else
2646     it->second->Stop();
2647
2648   return true;
2649 }
2650
2651 bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2652                                                AudioRenderer* renderer) {
2653   ChannelMap::iterator it = send_channels_.find(ssrc);
2654   if (it == send_channels_.end()) {
2655     if (renderer) {
2656       // Return an error if trying to set a valid renderer with an invalid ssrc.
2657       LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2658       return false;
2659     }
2660
2661     // The channel likely has gone away, do nothing.
2662     return true;
2663   }
2664
2665   if (renderer)
2666     it->second->Start(renderer);
2667   else
2668     it->second->Stop();
2669
2670   return true;
2671 }
2672
2673 bool WebRtcVoiceMediaChannel::GetActiveStreams(
2674     AudioInfo::StreamList* actives) {
2675   // In conference mode, the default channel should not be in
2676   // |receive_channels_|.
2677   actives->clear();
2678   for (ChannelMap::iterator it = receive_channels_.begin();
2679        it != receive_channels_.end(); ++it) {
2680     int level = GetOutputLevel(it->second->channel());
2681     if (level > 0) {
2682       actives->push_back(std::make_pair(it->first, level));
2683     }
2684   }
2685   return true;
2686 }
2687
2688 int WebRtcVoiceMediaChannel::GetOutputLevel() {
2689   // return the highest output level of all streams
2690   int highest = GetOutputLevel(voe_channel());
2691   for (ChannelMap::iterator it = receive_channels_.begin();
2692        it != receive_channels_.end(); ++it) {
2693     int level = GetOutputLevel(it->second->channel());
2694     highest = talk_base::_max(level, highest);
2695   }
2696   return highest;
2697 }
2698
2699 int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2700   int ret;
2701   if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2702     // In case of error, log the info and continue
2703     LOG_RTCERR0(TimeSinceLastTyping);
2704     ret = -1;
2705   } else {
2706     ret *= 1000;  // We return ms, webrtc returns seconds.
2707   }
2708   return ret;
2709 }
2710
2711 void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2712     int cost_per_typing, int reporting_threshold, int penalty_decay,
2713     int type_event_delay) {
2714   if (engine()->voe()->processing()->SetTypingDetectionParameters(
2715           time_window, cost_per_typing,
2716           reporting_threshold, penalty_decay, type_event_delay) == -1) {
2717     // In case of error, log the info and continue
2718     LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2719                 cost_per_typing, reporting_threshold, penalty_decay,
2720                 type_event_delay);
2721   }
2722 }
2723
2724 bool WebRtcVoiceMediaChannel::SetOutputScaling(
2725     uint32 ssrc, double left, double right) {
2726   talk_base::CritScope lock(&receive_channels_cs_);
2727   // Collect the channels to scale the output volume.
2728   std::vector<int> channels;
2729   if (0 == ssrc) {  // Collect all channels, including the default one.
2730     // Default channel is not in receive_channels_ if it is not being used for
2731     // playout.
2732     if (default_receive_ssrc_ == 0)
2733       channels.push_back(voe_channel());
2734     for (ChannelMap::const_iterator it = receive_channels_.begin();
2735          it != receive_channels_.end(); ++it) {
2736       channels.push_back(it->second->channel());
2737     }
2738   } else {  // Collect only the channel of the specified ssrc.
2739     int channel = GetReceiveChannelNum(ssrc);
2740     if (-1 == channel) {
2741       LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2742       return false;
2743     }
2744     channels.push_back(channel);
2745   }
2746
2747   // Scale the output volume for the collected channels. We first normalize to
2748   // scale the volume and then set the left and right pan.
2749   float scale = static_cast<float>(talk_base::_max(left, right));
2750   if (scale > 0.0001f) {
2751     left /= scale;
2752     right /= scale;
2753   }
2754   for (std::vector<int>::const_iterator it = channels.begin();
2755       it != channels.end(); ++it) {
2756     if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2757         *it, scale)) {
2758       LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2759       return false;
2760     }
2761     if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2762         *it, static_cast<float>(left), static_cast<float>(right))) {
2763       LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2764       // Do not return if fails. SetOutputVolumePan is not available for all
2765       // pltforms.
2766     }
2767     LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2768                  << " right=" << right * scale
2769                  << " for channel " << *it << " and ssrc " << ssrc;
2770   }
2771   return true;
2772 }
2773
2774 bool WebRtcVoiceMediaChannel::GetOutputScaling(
2775     uint32 ssrc, double* left, double* right) {
2776   if (!left || !right) return false;
2777
2778   talk_base::CritScope lock(&receive_channels_cs_);
2779   // Determine which channel based on ssrc.
2780   int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2781   if (channel == -1) {
2782     LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2783     return false;
2784   }
2785
2786   float scaling;
2787   if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2788       channel, scaling)) {
2789     LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2790     return false;
2791   }
2792
2793   float left_pan;
2794   float right_pan;
2795   if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2796       channel, left_pan, right_pan)) {
2797     LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2798     // If GetOutputVolumePan fails, we use the default left and right pan.
2799     left_pan = 1.0f;
2800     right_pan = 1.0f;
2801   }
2802
2803   *left = scaling * left_pan;
2804   *right = scaling * right_pan;
2805   return true;
2806 }
2807
2808 bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2809   ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2810   return true;
2811 }
2812
2813 bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2814                                              bool play, bool loop) {
2815   if (!ringback_tone_) {
2816     return false;
2817   }
2818
2819   // The voe file api is not available in chrome.
2820   if (!engine()->voe()->file()) {
2821     return false;
2822   }
2823
2824   // Determine which VoiceEngine channel to play on.
2825   int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2826   if (channel == -1) {
2827     return false;
2828   }
2829
2830   // Make sure the ringtone is cued properly, and play it out.
2831   if (play) {
2832     ringback_tone_->set_loop(loop);
2833     ringback_tone_->Rewind();
2834     if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2835         ringback_tone_.get()) == -1) {
2836       LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2837       LOG(LS_ERROR) << "Unable to start ringback tone";
2838       return false;
2839     }
2840     ringback_channels_.insert(channel);
2841     LOG(LS_INFO) << "Started ringback on channel " << channel;
2842   } else {
2843     if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2844         engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2845       LOG_RTCERR1(StopPlayingFileLocally, channel);
2846       return false;
2847     }
2848     LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2849     ringback_channels_.erase(channel);
2850   }
2851
2852   return true;
2853 }
2854
2855 bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2856   return dtmf_allowed_;
2857 }
2858
2859 bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2860                                          int duration, int flags) {
2861   if (!dtmf_allowed_) {
2862     return false;
2863   }
2864
2865   // Send the event.
2866   if (flags & cricket::DF_SEND) {
2867     int channel = -1;
2868     if (ssrc == 0) {
2869       bool default_channel_is_inuse = false;
2870       for (ChannelMap::const_iterator iter = send_channels_.begin();
2871            iter != send_channels_.end(); ++iter) {
2872         if (IsDefaultChannel(iter->second->channel())) {
2873           default_channel_is_inuse = true;
2874           break;
2875         }
2876       }
2877       if (default_channel_is_inuse) {
2878         channel = voe_channel();
2879       } else if (!send_channels_.empty()) {
2880         channel = send_channels_.begin()->second->channel();
2881       }
2882     } else {
2883       channel = GetSendChannelNum(ssrc);
2884     }
2885     if (channel == -1) {
2886       LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2887                       << ssrc << " is not in use.";
2888       return false;
2889     }
2890     // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
2891     if (engine()->voe()->dtmf()->SendTelephoneEvent(
2892             channel, event, true, duration) == -1) {
2893       LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
2894       return false;
2895     }
2896   }
2897
2898   // Play the event.
2899   if (flags & cricket::DF_PLAY) {
2900     // Play DTMF tone locally.
2901     if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
2902       LOG_RTCERR2(PlayDtmfTone, event, duration);
2903       return false;
2904     }
2905   }
2906
2907   return true;
2908 }
2909
2910 void WebRtcVoiceMediaChannel::OnPacketReceived(
2911     talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
2912   // Pick which channel to send this packet to. If this packet doesn't match
2913   // any multiplexed streams, just send it to the default channel. Otherwise,
2914   // send it to the specific decoder instance for that stream.
2915   int which_channel = GetReceiveChannelNum(
2916       ParseSsrc(packet->data(), packet->length(), false));
2917   if (which_channel == -1) {
2918     which_channel = voe_channel();
2919   }
2920
2921   // Stop any ringback that might be playing on the channel.
2922   // It's possible the ringback has already stopped, ih which case we'll just
2923   // use the opportunity to remove the channel from ringback_channels_.
2924   if (engine()->voe()->file()) {
2925     const std::set<int>::iterator it = ringback_channels_.find(which_channel);
2926     if (it != ringback_channels_.end()) {
2927       if (engine()->voe()->file()->IsPlayingFileLocally(
2928           which_channel) == 1) {
2929         engine()->voe()->file()->StopPlayingFileLocally(which_channel);
2930         LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
2931                      << " due to incoming media";
2932       }
2933       ringback_channels_.erase(which_channel);
2934     }
2935   }
2936
2937   // Pass it off to the decoder.
2938   engine()->voe()->network()->ReceivedRTPPacket(
2939       which_channel,
2940       packet->data(),
2941       static_cast<unsigned int>(packet->length()));
2942 }
2943
2944 void WebRtcVoiceMediaChannel::OnRtcpReceived(
2945     talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
2946   // Sending channels need all RTCP packets with feedback information.
2947   // Even sender reports can contain attached report blocks.
2948   // Receiving channels need sender reports in order to create
2949   // correct receiver reports.
2950   int type = 0;
2951   if (!GetRtcpType(packet->data(), packet->length(), &type)) {
2952     LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2953     return;
2954   }
2955
2956   // If it is a sender report, find the channel that is listening.
2957   bool has_sent_to_default_channel = false;
2958   if (type == kRtcpTypeSR) {
2959     int which_channel = GetReceiveChannelNum(
2960         ParseSsrc(packet->data(), packet->length(), true));
2961     if (which_channel != -1) {
2962       engine()->voe()->network()->ReceivedRTCPPacket(
2963           which_channel,
2964           packet->data(),
2965           static_cast<unsigned int>(packet->length()));
2966
2967       if (IsDefaultChannel(which_channel))
2968         has_sent_to_default_channel = true;
2969     }
2970   }
2971
2972   // SR may continue RR and any RR entry may correspond to any one of the send
2973   // channels. So all RTCP packets must be forwarded all send channels. VoE
2974   // will filter out RR internally.
2975   for (ChannelMap::iterator iter = send_channels_.begin();
2976        iter != send_channels_.end(); ++iter) {
2977     // Make sure not sending the same packet to default channel more than once.
2978     if (IsDefaultChannel(iter->second->channel()) &&
2979         has_sent_to_default_channel)
2980       continue;
2981
2982     engine()->voe()->network()->ReceivedRTCPPacket(
2983         iter->second->channel(),
2984         packet->data(),
2985         static_cast<unsigned int>(packet->length()));
2986   }
2987 }
2988
2989 bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
2990   int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
2991   if (channel == -1) {
2992     LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2993     return false;
2994   }
2995   if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
2996     LOG_RTCERR2(SetInputMute, channel, muted);
2997     return false;
2998   }
2999   return true;
3000 }
3001
3002 bool WebRtcVoiceMediaChannel::SetStartSendBandwidth(int bps) {
3003   // TODO(andresp): Add support for setting an independent start bandwidth when
3004   // bandwidth estimation is enabled for voice engine.
3005   return false;
3006 }
3007
3008 bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
3009   LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
3010
3011   return SetSendBandwidthInternal(bps);
3012 }
3013
3014 bool WebRtcVoiceMediaChannel::SetSendBandwidthInternal(int bps) {
3015   LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBandwidthInternal.";
3016
3017   send_bw_setting_ = true;
3018   send_bw_bps_ = bps;
3019
3020   if (!send_codec_) {
3021     LOG(LS_INFO) << "The send codec has not been set up yet. "
3022                  << "The send bandwidth setting will be applied later.";
3023     return true;
3024   }
3025
3026   // Bandwidth is auto by default.
3027   // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3028   // SetMaxSendBandwith(0), the second call removes the previous limit.
3029   if (bps <= 0)
3030     return true;
3031
3032   webrtc::CodecInst codec = *send_codec_;
3033   bool is_multi_rate = IsCodecMultiRate(codec);
3034
3035   if (is_multi_rate) {
3036     // If codec is multi-rate then just set the bitrate.
3037     codec.rate = bps;
3038     if (!SetSendCodec(codec)) {
3039       LOG(LS_INFO) << "Failed to set codec " << codec.plname
3040                    << " to bitrate " << bps << " bps.";
3041       return false;
3042     }
3043     return true;
3044   } else {
3045     // If codec is not multi-rate and |bps| is less than the fixed bitrate
3046     // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3047     // fixed bitrate then ignore.
3048     if (bps < codec.rate) {
3049       LOG(LS_INFO) << "Failed to set codec " << codec.plname
3050                    << " to bitrate " << bps << " bps"
3051                    << ", requires at least " << codec.rate << " bps.";
3052       return false;
3053     }
3054     return true;
3055   }
3056 }
3057
3058 bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
3059   bool echo_metrics_on = false;
3060   // These can take on valid negative values, so use the lowest possible level
3061   // as default rather than -1.
3062   int echo_return_loss = -100;
3063   int echo_return_loss_enhancement = -100;
3064   // These can also be negative, but in practice -1 is only used to signal
3065   // insufficient data, since the resolution is limited to multiples of 4 ms.
3066   int echo_delay_median_ms = -1;
3067   int echo_delay_std_ms = -1;
3068   if (engine()->voe()->processing()->GetEcMetricsStatus(
3069           echo_metrics_on) != -1 && echo_metrics_on) {
3070     // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3071     // here, but it appears to be unsuitable currently. Revisit after this is
3072     // investigated: http://b/issue?id=5666755
3073     int erl, erle, rerl, anlp;
3074     if (engine()->voe()->processing()->GetEchoMetrics(
3075             erl, erle, rerl, anlp) != -1) {
3076       echo_return_loss = erl;
3077       echo_return_loss_enhancement = erle;
3078     }
3079
3080     int median, std;
3081     if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3082       echo_delay_median_ms = median;
3083       echo_delay_std_ms = std;
3084     }
3085   }
3086
3087   webrtc::CallStatistics cs;
3088   unsigned int ssrc;
3089   webrtc::CodecInst codec;
3090   unsigned int level;
3091
3092   for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3093        channel_iter != send_channels_.end(); ++channel_iter) {
3094     const int channel = channel_iter->second->channel();
3095
3096     // Fill in the sender info, based on what we know, and what the
3097     // remote side told us it got from its RTCP report.
3098     VoiceSenderInfo sinfo;
3099
3100     if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3101         engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3102       continue;
3103     }
3104
3105     sinfo.add_ssrc(ssrc);
3106     sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3107     sinfo.bytes_sent = cs.bytesSent;
3108     sinfo.packets_sent = cs.packetsSent;
3109     // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3110     // returns 0 to indicate an error value.
3111     sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3112
3113     // Get data from the last remote RTCP report. Use default values if no data
3114     // available.
3115     sinfo.fraction_lost = -1.0;
3116     sinfo.jitter_ms = -1;
3117     sinfo.packets_lost = -1;
3118     sinfo.ext_seqnum = -1;
3119     std::vector<webrtc::ReportBlock> receive_blocks;
3120     if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3121             channel, &receive_blocks) != -1 &&
3122         engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3123       std::vector<webrtc::ReportBlock>::iterator iter;
3124       for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3125            ++iter) {
3126         // Lookup report for send ssrc only.
3127         if (iter->source_SSRC == sinfo.ssrc()) {
3128           // Convert Q8 to floating point.
3129           sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3130           // Convert samples to milliseconds.
3131           if (codec.plfreq / 1000 > 0) {
3132             sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3133           }
3134           sinfo.packets_lost = iter->cumulative_num_packets_lost;
3135           sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3136           break;
3137         }
3138       }
3139     }
3140
3141     // Local speech level.
3142     sinfo.audio_level = (engine()->voe()->volume()->
3143         GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3144
3145     // TODO(xians): We are injecting the same APM logging to all the send
3146     // channels here because there is no good way to know which send channel
3147     // is using the APM. The correct fix is to allow the send channels to have
3148     // their own APM so that we can feed the correct APM logging to different
3149     // send channels. See issue crbug/264611 .
3150     sinfo.echo_return_loss = echo_return_loss;
3151     sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3152     sinfo.echo_delay_median_ms = echo_delay_median_ms;
3153     sinfo.echo_delay_std_ms = echo_delay_std_ms;
3154     // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3155     sinfo.aec_quality_min = -1;
3156     sinfo.typing_noise_detected = typing_noise_detected_;
3157
3158     info->senders.push_back(sinfo);
3159   }
3160
3161   // Build the list of receivers, one for each receiving channel, or 1 in
3162   // a 1:1 call.
3163   std::vector<int> channels;
3164   for (ChannelMap::const_iterator it = receive_channels_.begin();
3165        it != receive_channels_.end(); ++it) {
3166     channels.push_back(it->second->channel());
3167   }
3168   if (channels.empty()) {
3169     channels.push_back(voe_channel());
3170   }
3171
3172   // Get the SSRC and stats for each receiver, based on our own calculations.
3173   for (std::vector<int>::const_iterator it = channels.begin();
3174        it != channels.end(); ++it) {
3175     memset(&cs, 0, sizeof(cs));
3176     if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3177         engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3178         engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3179       VoiceReceiverInfo rinfo;
3180       rinfo.add_ssrc(ssrc);
3181       rinfo.bytes_rcvd = cs.bytesReceived;
3182       rinfo.packets_rcvd = cs.packetsReceived;
3183       // The next four fields are from the most recently sent RTCP report.
3184       // Convert Q8 to floating point.
3185       rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3186       rinfo.packets_lost = cs.cumulativeLost;
3187       rinfo.ext_seqnum = cs.extendedMax;
3188       // Convert samples to milliseconds.
3189       if (codec.plfreq / 1000 > 0) {
3190         rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3191       }
3192
3193       // Get jitter buffer and total delay (alg + jitter + playout) stats.
3194       webrtc::NetworkStatistics ns;
3195       if (engine()->voe()->neteq() &&
3196           engine()->voe()->neteq()->GetNetworkStatistics(
3197               *it, ns) != -1) {
3198         rinfo.jitter_buffer_ms = ns.currentBufferSize;
3199         rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3200         rinfo.expand_rate =
3201             static_cast<float>(ns.currentExpandRate) / (1 << 14);
3202       }
3203
3204       webrtc::AudioDecodingCallStats ds;
3205       if (engine()->voe()->neteq() &&
3206           engine()->voe()->neteq()->GetDecodingCallStatistics(
3207               *it, &ds) != -1) {
3208         rinfo.decoding_calls_to_silence_generator =
3209             ds.calls_to_silence_generator;
3210         rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3211         rinfo.decoding_normal = ds.decoded_normal;
3212         rinfo.decoding_plc = ds.decoded_plc;
3213         rinfo.decoding_cng = ds.decoded_cng;
3214         rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3215       }
3216
3217       if (engine()->voe()->sync()) {
3218         int jitter_buffer_delay_ms = 0;
3219         int playout_buffer_delay_ms = 0;
3220         engine()->voe()->sync()->GetDelayEstimate(
3221             *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3222         rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3223             playout_buffer_delay_ms;
3224       }
3225
3226       // Get speech level.
3227       rinfo.audio_level = (engine()->voe()->volume()->
3228           GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3229       info->receivers.push_back(rinfo);
3230     }
3231   }
3232
3233   return true;
3234 }
3235
3236 void WebRtcVoiceMediaChannel::GetLastMediaError(
3237     uint32* ssrc, VoiceMediaChannel::Error* error) {
3238   ASSERT(ssrc != NULL);
3239   ASSERT(error != NULL);
3240   FindSsrc(voe_channel(), ssrc);
3241   *error = WebRtcErrorToChannelError(GetLastEngineError());
3242 }
3243
3244 bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
3245   talk_base::CritScope lock(&receive_channels_cs_);
3246   ASSERT(ssrc != NULL);
3247   if (channel_num == -1 && send_ != SEND_NOTHING) {
3248     // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3249     // This means the error is not limited to a specific channel.  Signal the
3250     // message using ssrc=0.  If the current channel is sending, use this
3251     // channel for sending the message.
3252     *ssrc = 0;
3253     return true;
3254   } else {
3255     // Check whether this is a sending channel.
3256     for (ChannelMap::const_iterator it = send_channels_.begin();
3257          it != send_channels_.end(); ++it) {
3258       if (it->second->channel() == channel_num) {
3259         // This is a sending channel.
3260         uint32 local_ssrc = 0;
3261         if (engine()->voe()->rtp()->GetLocalSSRC(
3262                 channel_num, local_ssrc) != -1) {
3263           *ssrc = local_ssrc;
3264         }
3265         return true;
3266       }
3267     }
3268
3269     // Check whether this is a receiving channel.
3270     for (ChannelMap::const_iterator it = receive_channels_.begin();
3271         it != receive_channels_.end(); ++it) {
3272       if (it->second->channel() == channel_num) {
3273         *ssrc = it->first;
3274         return true;
3275       }
3276     }
3277   }
3278   return false;
3279 }
3280
3281 void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
3282   if (error == VE_TYPING_NOISE_WARNING) {
3283     typing_noise_detected_ = true;
3284   } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3285     typing_noise_detected_ = false;
3286   }
3287   SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3288 }
3289
3290 int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3291   unsigned int ulevel;
3292   int ret =
3293       engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3294   return (ret == 0) ? static_cast<int>(ulevel) : -1;
3295 }
3296
3297 int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
3298   ChannelMap::iterator it = receive_channels_.find(ssrc);
3299   if (it != receive_channels_.end())
3300     return it->second->channel();
3301   return (ssrc == default_receive_ssrc_) ?  voe_channel() : -1;
3302 }
3303
3304 int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
3305   ChannelMap::iterator it = send_channels_.find(ssrc);
3306   if (it != send_channels_.end())
3307     return it->second->channel();
3308
3309   return -1;
3310 }
3311
3312 bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3313     const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3314   // Get the RED encodings from the parameter with no name. This may
3315   // change based on what is discussed on the Jingle list.
3316   // The encoding parameter is of the form "a/b"; we only support where
3317   // a == b. Verify this and parse out the value into red_pt.
3318   // If the parameter value is absent (as it will be until we wire up the
3319   // signaling of this message), use the second codec specified (i.e. the
3320   // one after "red") as the encoding parameter.
3321   int red_pt = -1;
3322   std::string red_params;
3323   CodecParameterMap::const_iterator it = red_codec.params.find("");
3324   if (it != red_codec.params.end()) {
3325     red_params = it->second;
3326     std::vector<std::string> red_pts;
3327     if (talk_base::split(red_params, '/', &red_pts) != 2 ||
3328         red_pts[0] != red_pts[1] ||
3329         !talk_base::FromString(red_pts[0], &red_pt)) {
3330       LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3331       return false;
3332     }
3333   } else if (red_codec.params.empty()) {
3334     LOG(LS_WARNING) << "RED params not present, using defaults";
3335     if (all_codecs.size() > 1) {
3336       red_pt = all_codecs[1].id;
3337     }
3338   }
3339
3340   // Try to find red_pt in |codecs|.
3341   std::vector<AudioCodec>::const_iterator codec;
3342   for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3343     if (codec->id == red_pt)
3344       break;
3345   }
3346
3347   // If we find the right codec, that will be the codec we pass to
3348   // SetSendCodec, with the desired payload type.
3349   if (codec != all_codecs.end() &&
3350     engine()->FindWebRtcCodec(*codec, send_codec)) {
3351   } else {
3352     LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3353     return false;
3354   }
3355
3356   return true;
3357 }
3358
3359 bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3360   if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
3361     LOG_RTCERR2(SetRTCPStatus, channel, 1);
3362     return false;
3363   }
3364   // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3365   // what we want to do with them.
3366   // engine()->voe().EnableVQMon(voe_channel(), true);
3367   // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3368   return true;
3369 }
3370
3371 bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3372   int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3373   for (int i = 0; i < ncodecs; ++i) {
3374     webrtc::CodecInst voe_codec;
3375     if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3376       voe_codec.pltype = -1;
3377       if (engine()->voe()->codec()->SetRecPayloadType(
3378           channel, voe_codec) == -1) {
3379         LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3380         return false;
3381       }
3382     }
3383   }
3384   return true;
3385 }
3386
3387 bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3388   if (playout) {
3389     LOG(LS_INFO) << "Starting playout for channel #" << channel;
3390     if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3391       LOG_RTCERR1(StartPlayout, channel);
3392       return false;
3393     }
3394   } else {
3395     LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3396     engine()->voe()->base()->StopPlayout(channel);
3397   }
3398   return true;
3399 }
3400
3401 uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3402                                         bool rtcp) {
3403   size_t ssrc_pos = (!rtcp) ? 8 : 4;
3404   uint32 ssrc = 0;
3405   if (len >= (ssrc_pos + sizeof(ssrc))) {
3406     ssrc = talk_base::GetBE32(static_cast<const char*>(data) + ssrc_pos);
3407   }
3408   return ssrc;
3409 }
3410
3411 // Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3412 VoiceMediaChannel::Error
3413     WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3414   switch (err_code) {
3415     case 0:
3416       return ERROR_NONE;
3417     case VE_CANNOT_START_RECORDING:
3418     case VE_MIC_VOL_ERROR:
3419     case VE_GET_MIC_VOL_ERROR:
3420     case VE_CANNOT_ACCESS_MIC_VOL:
3421       return ERROR_REC_DEVICE_OPEN_FAILED;
3422     case VE_SATURATION_WARNING:
3423       return ERROR_REC_DEVICE_SATURATION;
3424     case VE_REC_DEVICE_REMOVED:
3425       return ERROR_REC_DEVICE_REMOVED;
3426     case VE_RUNTIME_REC_WARNING:
3427     case VE_RUNTIME_REC_ERROR:
3428       return ERROR_REC_RUNTIME_ERROR;
3429     case VE_CANNOT_START_PLAYOUT:
3430     case VE_SPEAKER_VOL_ERROR:
3431     case VE_GET_SPEAKER_VOL_ERROR:
3432     case VE_CANNOT_ACCESS_SPEAKER_VOL:
3433       return ERROR_PLAY_DEVICE_OPEN_FAILED;
3434     case VE_RUNTIME_PLAY_WARNING:
3435     case VE_RUNTIME_PLAY_ERROR:
3436       return ERROR_PLAY_RUNTIME_ERROR;
3437     case VE_TYPING_NOISE_WARNING:
3438       return ERROR_REC_TYPING_NOISE_DETECTED;
3439     default:
3440       return VoiceMediaChannel::ERROR_OTHER;
3441   }
3442 }
3443
3444 int WebRtcSoundclipStream::Read(void *buf, int len) {
3445   size_t res = 0;
3446   mem_.Read(buf, len, &res, NULL);
3447   return static_cast<int>(res);
3448 }
3449
3450 int WebRtcSoundclipStream::Rewind() {
3451   mem_.Rewind();
3452   // Return -1 to keep VoiceEngine from looping.
3453   return (loop_) ? 0 : -1;
3454 }
3455
3456 }  // namespace cricket
3457
3458 #endif  // HAVE_WEBRTC_VOICE