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