blob: 90ca8cbff40b148f86e648df287fdc6dbfbbf654 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
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
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000041#include "talk/media/base/audiorenderer.h"
42#include "talk/media/base/constants.h"
43#include "talk/media/base/streamparams.h"
44#include "talk/media/base/voiceprocessor.h"
45#include "talk/media/webrtc/webrtcvoe.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000046#include "webrtc/base/base64.h"
47#include "webrtc/base/byteorder.h"
48#include "webrtc/base/common.h"
49#include "webrtc/base/helpers.h"
50#include "webrtc/base/logging.h"
51#include "webrtc/base/stringencode.h"
52#include "webrtc/base/stringutils.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000053#include "webrtc/common.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054#include "webrtc/modules/audio_processing/include/audio_processing.h"
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +000055#include "webrtc/video_engine/include/vie_network.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056
57#ifdef WIN32
58#include <objbase.h> // NOLINT
59#endif
60
61namespace cricket {
62
63struct CodecPref {
64 const char* name;
65 int clockrate;
66 int channels;
67 int payload_type;
68 bool is_multi_rate;
69};
70
71static const CodecPref kCodecPrefs[] = {
72 { "OPUS", 48000, 2, 111, true },
73 { "ISAC", 16000, 1, 103, true },
74 { "ISAC", 32000, 1, 104, true },
75 { "CELT", 32000, 1, 109, true },
76 { "CELT", 32000, 2, 110, true },
77 { "G722", 16000, 1, 9, false },
78 { "ILBC", 8000, 1, 102, false },
79 { "PCMU", 8000, 1, 0, false },
80 { "PCMA", 8000, 1, 8, false },
81 { "CN", 48000, 1, 107, false },
82 { "CN", 32000, 1, 106, false },
83 { "CN", 16000, 1, 105, false },
84 { "CN", 8000, 1, 13, false },
85 { "red", 8000, 1, 127, false },
86 { "telephone-event", 8000, 1, 126, false },
87};
88
89// For Linux/Mac, using the default device is done by specifying index 0 for
90// VoE 4.0 and not -1 (which was the case for VoE 3.5).
91//
92// On Windows Vista and newer, Microsoft introduced the concept of "Default
93// Communications Device". This means that there are two types of default
94// devices (old Wave Audio style default and Default Communications Device).
95//
96// On Windows systems which only support Wave Audio style default, uses either
97// -1 or 0 to select the default device.
98//
99// On Windows systems which support both "Default Communication Device" and
100// old Wave Audio style default, use -1 for Default Communications Device and
101// -2 for Wave Audio style default, which is what we want to use for clips.
102// It's not clear yet whether the -2 index is handled properly on other OSes.
103
104#ifdef WIN32
105static const int kDefaultAudioDeviceId = -1;
106static const int kDefaultSoundclipDeviceId = -2;
107#else
108static const int kDefaultAudioDeviceId = 0;
109#endif
110
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111static const char kIsacCodecName[] = "ISAC";
112static const char kL16CodecName[] = "L16";
113// Codec parameters for Opus.
114static const int kOpusMonoBitrate = 32000;
115// Parameter used for NACK.
116// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
117static const int kNackMaxPackets = 250;
118static const int kOpusStereoBitrate = 64000;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000119// draft-spittka-payload-rtp-opus-03
120// Opus bitrate should be in the range between 6000 and 510000.
121static const int kOpusMinBitrate = 6000;
122static const int kOpusMaxBitrate = 510000;
wu@webrtc.orgde305012013-10-31 15:40:38 +0000123// Default audio dscp value.
124// See http://tools.ietf.org/html/rfc2474 for details.
125// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000126static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000127
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000128// Ensure we open the file in a writeable path on ChromeOS and Android. This
129// workaround can be removed when it's possible to specify a filename for audio
130// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000131//
132// TODO(grunell): Use a string in the options instead of hardcoding it here
133// and let the embedder choose the filename (crbug.com/264223).
134//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000135// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
136// below.
137#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000138static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000139#elif defined(ANDROID)
140static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000141#else
142static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
143#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000144
145// Dumps an AudioCodec in RFC 2327-ish format.
146static std::string ToString(const AudioCodec& codec) {
147 std::stringstream ss;
148 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
149 << " (" << codec.id << ")";
150 return ss.str();
151}
152static std::string ToString(const webrtc::CodecInst& codec) {
153 std::stringstream ss;
154 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
155 << " (" << codec.pltype << ")";
156 return ss.str();
157}
158
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000159static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000160 const char* delim = "\r\n";
161 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
162 LOG_V(sev) << tok;
163 }
164}
165
166// Severity is an integer because it comes is assumed to be from command line.
167static int SeverityToFilter(int severity) {
168 int filter = webrtc::kTraceNone;
169 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000170 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000171 filter |= webrtc::kTraceAll;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000172 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000173 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000174 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000175 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000176 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000177 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
178 }
179 return filter;
180}
181
182static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
183 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
184 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
185 kCodecPrefs[i].clockrate == codec.plfreq) {
186 return kCodecPrefs[i].is_multi_rate;
187 }
188 }
189 return false;
190}
191
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000192static bool IsTelephoneEventCodec(const std::string& name) {
193 return _stricmp(name.c_str(), "telephone-event") == 0;
194}
195
196static bool IsCNCodec(const std::string& name) {
197 return _stricmp(name.c_str(), "CN") == 0;
198}
199
200static bool IsRedCodec(const std::string& name) {
201 return _stricmp(name.c_str(), "red") == 0;
202}
203
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000204static bool FindCodec(const std::vector<AudioCodec>& codecs,
205 const AudioCodec& codec,
206 AudioCodec* found_codec) {
207 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
208 it != codecs.end(); ++it) {
209 if (it->Matches(codec)) {
210 if (found_codec != NULL) {
211 *found_codec = *it;
212 }
213 return true;
214 }
215 }
216 return false;
217}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000218
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000219static bool IsNackEnabled(const AudioCodec& codec) {
220 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
221 kParamValueEmpty));
222}
223
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000224// Gets the default set of options applied to the engine. Historically, these
225// were supplied as a combination of flags from the channel manager (ec, agc,
226// ns, and highpass) and the rest hardcoded in InitInternal.
227static AudioOptions GetDefaultEngineOptions() {
228 AudioOptions options;
229 options.echo_cancellation.Set(true);
230 options.auto_gain_control.Set(true);
231 options.noise_suppression.Set(true);
232 options.highpass_filter.Set(true);
233 options.stereo_swapping.Set(false);
234 options.typing_detection.Set(true);
235 options.conference_mode.Set(false);
236 options.adjust_agc_delta.Set(0);
237 options.experimental_agc.Set(false);
238 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000239 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000240 options.aec_dump.Set(false);
241 return options;
242}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000243
244class WebRtcSoundclipMedia : public SoundclipMedia {
245 public:
246 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
247 : engine_(engine), webrtc_channel_(-1) {
248 engine_->RegisterSoundclip(this);
249 }
250
251 virtual ~WebRtcSoundclipMedia() {
252 engine_->UnregisterSoundclip(this);
253 if (webrtc_channel_ != -1) {
254 // We shouldn't have to call Disable() here. DeleteChannel() should call
255 // StopPlayout() while deleting the channel. We should fix the bug
256 // inside WebRTC and remove the Disable() call bellow. This work is
257 // tracked by bug http://b/issue?id=5382855.
258 PlaySound(NULL, 0, 0);
259 Disable();
260 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
261 == -1) {
262 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
263 }
264 }
265 }
266
267 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000268 if (!engine_->voe_sc()) {
269 return false;
270 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000271 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000272 if (webrtc_channel_ == -1) {
273 LOG_RTCERR0(CreateChannel);
274 return false;
275 }
276 return true;
277 }
278
279 bool Enable() {
280 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
281 LOG_RTCERR1(StartPlayout, webrtc_channel_);
282 return false;
283 }
284 return true;
285 }
286
287 bool Disable() {
288 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
289 LOG_RTCERR1(StopPlayout, webrtc_channel_);
290 return false;
291 }
292 return true;
293 }
294
295 virtual bool PlaySound(const char *buf, int len, int flags) {
296 // The voe file api is not available in chrome.
297 if (!engine_->voe_sc()->file()) {
298 return false;
299 }
300 // Must stop playing the current sound (if any), because we are about to
301 // modify the stream.
302 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
303 == -1) {
304 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
305 return false;
306 }
307
308 if (buf) {
309 stream_.reset(new WebRtcSoundclipStream(buf, len));
310 stream_->set_loop((flags & SF_LOOP) != 0);
311 stream_->Rewind();
312
313 // Play it.
314 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
315 webrtc_channel_, stream_.get()) == -1) {
316 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
317 LOG(LS_ERROR) << "Unable to start soundclip";
318 return false;
319 }
320 } else {
321 stream_.reset();
322 }
323 return true;
324 }
325
326 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
327
328 private:
329 WebRtcVoiceEngine *engine_;
330 int webrtc_channel_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000331 rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000332};
333
334WebRtcVoiceEngine::WebRtcVoiceEngine()
335 : voe_wrapper_(new VoEWrapper()),
336 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000337 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000338 tracing_(new VoETraceWrapper()),
339 adm_(NULL),
340 adm_sc_(NULL),
341 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
342 is_dumping_aec_(false),
343 desired_local_monitor_enable_(false),
344 tx_processor_ssrc_(0),
345 rx_processor_ssrc_(0) {
346 Construct();
347}
348
349WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
350 VoEWrapper* voe_wrapper_sc,
351 VoETraceWrapper* tracing)
352 : voe_wrapper_(voe_wrapper),
353 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000354 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000355 tracing_(tracing),
356 adm_(NULL),
357 adm_sc_(NULL),
358 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
359 is_dumping_aec_(false),
360 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000361 tx_processor_ssrc_(0),
362 rx_processor_ssrc_(0) {
363 Construct();
364}
365
366void WebRtcVoiceEngine::Construct() {
367 SetTraceFilter(log_filter_);
368 initialized_ = false;
369 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
370 SetTraceOptions("");
371 if (tracing_->SetTraceCallback(this) == -1) {
372 LOG_RTCERR0(SetTraceCallback);
373 }
374 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
375 LOG_RTCERR0(RegisterVoiceEngineObserver);
376 }
377 // Clear the default agc state.
378 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
379
380 // Load our audio codec list.
381 ConstructCodecs();
382
383 // Load our RTP Header extensions.
384 rtp_header_extensions_.push_back(
385 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
386 kRtpAudioLevelHeaderExtensionDefaultId));
387 rtp_header_extensions_.push_back(
388 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
389 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
390 options_ = GetDefaultEngineOptions();
391}
392
393static bool IsOpus(const AudioCodec& codec) {
394 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
395}
396
397static bool IsIsac(const AudioCodec& codec) {
398 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
399}
400
401// True if params["stereo"] == "1"
402static bool IsOpusStereoEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000403 int value;
404 return codec.GetParam(kCodecParamStereo, &value) && value == 1;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000405}
406
407static bool IsValidOpusBitrate(int bitrate) {
408 return (bitrate >= kOpusMinBitrate && bitrate <= kOpusMaxBitrate);
409}
410
411// Returns 0 if params[kCodecParamMaxAverageBitrate] is not defined or invalid.
412// Returns the value of params[kCodecParamMaxAverageBitrate] otherwise.
413static int GetOpusBitrateFromParams(const AudioCodec& codec) {
414 int bitrate = 0;
415 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
416 return 0;
417 }
418 if (!IsValidOpusBitrate(bitrate)) {
419 LOG(LS_WARNING) << "Codec parameter \"maxaveragebitrate\" has an "
420 << "invalid value: " << bitrate;
421 return 0;
422 }
423 return bitrate;
424}
425
buildbot@webrtc.orgfbd13282014-06-19 19:50:55 +0000426// Return true if params[kCodecParamUseInbandFec] == "1", false
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000427// otherwise.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000428static bool IsOpusFecEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000429 int value;
430 return codec.GetParam(kCodecParamUseInbandFec, &value) && value == 1;
431}
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000432
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000433void WebRtcVoiceEngine::ConstructCodecs() {
434 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
435 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
436 for (int i = 0; i < ncodecs; ++i) {
437 webrtc::CodecInst voe_codec;
438 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
439 // Skip uncompressed formats.
440 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
441 continue;
442 }
443
444 const CodecPref* pref = NULL;
445 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
446 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
447 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
448 kCodecPrefs[j].channels == voe_codec.channels) {
449 pref = &kCodecPrefs[j];
450 break;
451 }
452 }
453
454 if (pref) {
455 // Use the payload type that we've configured in our pref table;
456 // use the offset in our pref table to determine the sort order.
457 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
458 voe_codec.rate, voe_codec.channels,
459 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
460 LOG(LS_INFO) << ToString(codec);
461 if (IsIsac(codec)) {
462 // Indicate auto-bandwidth in signaling.
463 codec.bitrate = 0;
464 }
465 if (IsOpus(codec)) {
466 // Only add fmtp parameters that differ from the spec.
467 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
468 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000469 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000470 }
471 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
472 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000473 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000474 }
475 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
476 // when they can be set to values other than the default.
477 }
478 codecs_.push_back(codec);
479 } else {
480 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
481 }
482 }
483 }
484 // Make sure they are in local preference order.
485 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
486}
487
488WebRtcVoiceEngine::~WebRtcVoiceEngine() {
489 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
490 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
491 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
492 }
493 if (adm_) {
494 voe_wrapper_.reset();
495 adm_->Release();
496 adm_ = NULL;
497 }
498 if (adm_sc_) {
499 voe_wrapper_sc_.reset();
500 adm_sc_->Release();
501 adm_sc_ = NULL;
502 }
503
504 // Test to see if the media processor was deregistered properly
505 ASSERT(SignalRxMediaFrame.is_empty());
506 ASSERT(SignalTxMediaFrame.is_empty());
507
508 tracing_->SetTraceCallback(NULL);
509}
510
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000511bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000512 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
513 bool res = InitInternal();
514 if (res) {
515 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
516 } else {
517 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
518 Terminate();
519 }
520 return res;
521}
522
523bool WebRtcVoiceEngine::InitInternal() {
524 // Temporarily turn logging level up for the Init call
525 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000526 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000527 SetTraceFilter(extended_filter);
528 SetTraceOptions("");
529
530 // Init WebRtc VoiceEngine.
531 if (voe_wrapper_->base()->Init(adm_) == -1) {
532 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
533 SetTraceFilter(old_filter);
534 return false;
535 }
536
537 SetTraceFilter(old_filter);
538 SetTraceOptions(log_options_);
539
540 // Log the VoiceEngine version info
541 char buffer[1024] = "";
542 voe_wrapper_->base()->GetVersion(buffer);
543 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000544 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000545
546 // Save the default AGC configuration settings. This must happen before
547 // calling SetOptions or the default will be overwritten.
548 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
549 LOG_RTCERR0(GetAgcConfig);
550 return false;
551 }
552
553 // Set defaults for options, so that ApplyOptions applies them explicitly
554 // when we clear option (channel) overrides. External clients can still
555 // modify the defaults via SetOptions (on the media engine).
556 if (!SetOptions(GetDefaultEngineOptions())) {
557 return false;
558 }
559
560 // Print our codec list again for the call diagnostic log
561 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
562 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
563 it != codecs_.end(); ++it) {
564 LOG(LS_INFO) << ToString(*it);
565 }
566
567 // Disable the DTMF playout when a tone is sent.
568 // PlayDtmfTone will be used if local playout is needed.
569 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
570 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
571 }
572
573 initialized_ = true;
574 return true;
575}
576
577bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
578 if (voe_wrapper_sc_initialized_) {
579 return true;
580 }
581 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
582 // be false, so subsequent calls to EnsureSoundclipEngineInit will
583 // probably just fail again. That's acceptable behavior.
584#if defined(LINUX) && !defined(HAVE_LIBPULSE)
585 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
586#endif
587
588 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
589 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
590 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
591 return false;
592 }
593
594 // On Windows, tell it to use the default sound (not communication) devices.
595 // First check whether there is a valid sound device for playback.
596 // TODO(juberti): Clean this up when we support setting the soundclip device.
597#ifdef WIN32
598 // The SetPlayoutDevice may not be implemented in the case of external ADM.
599 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
600 // PeerConnection interface never set the adm_sc_, so need to check both
601 // in order to determine if the external adm is used.
602 if (!adm_ && !adm_sc_) {
603 int num_of_devices = 0;
604 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
605 num_of_devices > 0) {
606 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
607 == -1) {
608 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
609 voe_wrapper_sc_->error());
610 return false;
611 }
612 } else {
613 LOG(LS_WARNING) << "No valid sound playout device found.";
614 }
615 }
616#endif
617 voe_wrapper_sc_initialized_ = true;
618 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
619 return true;
620}
621
622void WebRtcVoiceEngine::Terminate() {
623 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
624 initialized_ = false;
625
626 StopAecDump();
627
628 if (voe_wrapper_sc_) {
629 voe_wrapper_sc_initialized_ = false;
630 voe_wrapper_sc_->base()->Terminate();
631 }
632 voe_wrapper_->base()->Terminate();
633 desired_local_monitor_enable_ = false;
634}
635
636int WebRtcVoiceEngine::GetCapabilities() {
637 return AUDIO_SEND | AUDIO_RECV;
638}
639
640VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
641 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
642 if (!ch->valid()) {
643 delete ch;
644 ch = NULL;
645 }
646 return ch;
647}
648
649SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
650 if (!EnsureSoundclipEngineInit()) {
651 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
652 << "initialize.";
653 return NULL;
654 }
655 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
656 if (!soundclip->Init() || !soundclip->Enable()) {
657 delete soundclip;
658 return NULL;
659 }
660 return soundclip;
661}
662
663bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
664 if (!ApplyOptions(options)) {
665 return false;
666 }
667 options_ = options;
668 return true;
669}
670
671bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
672 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
673 if (!ApplyOptions(overrides)) {
674 return false;
675 }
676 option_overrides_ = overrides;
677 return true;
678}
679
680bool WebRtcVoiceEngine::ClearOptionOverrides() {
681 LOG(LS_INFO) << "Clearing option overrides.";
682 AudioOptions options = options_;
683 // Only call ApplyOptions if |options_overrides_| contains overrided options.
684 // ApplyOptions affects NS, AGC other options that is shared between
685 // all WebRtcVoiceEngineChannels.
686 if (option_overrides_ == AudioOptions()) {
687 return true;
688 }
689
690 if (!ApplyOptions(options)) {
691 return false;
692 }
693 option_overrides_ = AudioOptions();
694 return true;
695}
696
697// AudioOptions defaults are set in InitInternal (for options with corresponding
698// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
699bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
700 AudioOptions options = options_in; // The options are modified below.
701 // kEcConference is AEC with high suppression.
702 webrtc::EcModes ec_mode = webrtc::kEcConference;
703 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
704 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
705 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
706 bool aecm_comfort_noise = false;
707 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
708 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
709 << aecm_comfort_noise << " (default is false).";
710 }
711
712#if defined(IOS)
713 // On iOS, VPIO provides built-in EC and AGC.
714 options.echo_cancellation.Set(false);
715 options.auto_gain_control.Set(false);
716#elif defined(ANDROID)
717 ec_mode = webrtc::kEcAecm;
718#endif
719
720#if defined(IOS) || defined(ANDROID)
721 // Set the AGC mode for iOS as well despite disabling it above, to avoid
722 // unsupported configuration errors from webrtc.
723 agc_mode = webrtc::kAgcFixedDigital;
724 options.typing_detection.Set(false);
725 options.experimental_agc.Set(false);
726 options.experimental_aec.Set(false);
727 options.experimental_ns.Set(false);
728#endif
729
730 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
731
732 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
733
734 bool echo_cancellation;
735 if (options.echo_cancellation.Get(&echo_cancellation)) {
736 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
737 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
738 return false;
739 } else {
740 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
741 << " with mode " << ec_mode;
742 }
743#if !defined(ANDROID)
744 // TODO(ajm): Remove the error return on Android from webrtc.
745 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
746 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
747 return false;
748 }
749#endif
750 if (ec_mode == webrtc::kEcAecm) {
751 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
752 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
753 return false;
754 }
755 }
756 }
757
758 bool auto_gain_control;
759 if (options.auto_gain_control.Get(&auto_gain_control)) {
760 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
761 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
762 return false;
763 } else {
764 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
765 << " with mode " << agc_mode;
766 }
767 }
768
769 if (options.tx_agc_target_dbov.IsSet() ||
770 options.tx_agc_digital_compression_gain.IsSet() ||
771 options.tx_agc_limiter.IsSet()) {
772 // Override default_agc_config_. Generally, an unset option means "leave
773 // the VoE bits alone" in this function, so we want whatever is set to be
774 // stored as the new "default". If we didn't, then setting e.g.
775 // tx_agc_target_dbov would reset digital compression gain and limiter
776 // settings.
777 // Also, if we don't update default_agc_config_, then adjust_agc_delta
778 // would be an offset from the original values, and not whatever was set
779 // explicitly.
780 default_agc_config_.targetLeveldBOv =
781 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
782 default_agc_config_.targetLeveldBOv);
783 default_agc_config_.digitalCompressionGaindB =
784 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
785 default_agc_config_.digitalCompressionGaindB);
786 default_agc_config_.limiterEnable =
787 options.tx_agc_limiter.GetWithDefaultIfUnset(
788 default_agc_config_.limiterEnable);
789 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
790 LOG_RTCERR3(SetAgcConfig,
791 default_agc_config_.targetLeveldBOv,
792 default_agc_config_.digitalCompressionGaindB,
793 default_agc_config_.limiterEnable);
794 return false;
795 }
796 }
797
798 bool noise_suppression;
799 if (options.noise_suppression.Get(&noise_suppression)) {
800 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
801 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
802 return false;
803 } else {
804 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
805 << " with mode " << ns_mode;
806 }
807 }
808
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000809 bool highpass_filter;
810 if (options.highpass_filter.Get(&highpass_filter)) {
811 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
812 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
813 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
814 return false;
815 }
816 }
817
818 bool stereo_swapping;
819 if (options.stereo_swapping.Get(&stereo_swapping)) {
820 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
821 voep->EnableStereoChannelSwapping(stereo_swapping);
822 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
823 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
824 return false;
825 }
826 }
827
828 bool typing_detection;
829 if (options.typing_detection.Get(&typing_detection)) {
830 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
831 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
832 // In case of error, log the info and continue
833 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
834 }
835 }
836
837 int adjust_agc_delta;
838 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
839 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
840 if (!AdjustAgcLevel(adjust_agc_delta)) {
841 return false;
842 }
843 }
844
845 bool aec_dump;
846 if (options.aec_dump.Get(&aec_dump)) {
847 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
848 if (aec_dump)
849 StartAecDump(kAecDumpByAudioOptionFilename);
850 else
851 StopAecDump();
852 }
853
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000854 webrtc::Config config;
855
856 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000857 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000858 if (experimental_aec_.Get(&experimental_aec)) {
859 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
860 config.Set<webrtc::DelayCorrection>(
861 new webrtc::DelayCorrection(experimental_aec));
862 }
863
864#ifdef USE_WEBRTC_DEV_BRANCH
865 experimental_ns_.SetFrom(options.experimental_ns);
866 bool experimental_ns;
867 if (experimental_ns_.Get(&experimental_ns)) {
868 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
869 config.Set<webrtc::ExperimentalNs>(
870 new webrtc::ExperimentalNs(experimental_ns));
871 }
872#endif
873
874 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
875 // returns NULL on audio_processing().
876 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
877 if (audioproc) {
878 audioproc->SetExtraOptions(config);
879 }
880
881#ifndef USE_WEBRTC_DEV_BRANCH
882 bool experimental_ns;
883 if (options.experimental_ns.Get(&experimental_ns)) {
884 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000885 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
886 // returns NULL on audio_processing().
887 if (audioproc) {
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000888 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
889 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
890 return false;
891 }
892 } else {
893 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
894 << experimental_ns;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000895 }
896 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000897#endif
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000898
899 uint32 recording_sample_rate;
900 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
901 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
902 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
903 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
904 }
905 }
906
907 uint32 playout_sample_rate;
908 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
909 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
910 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
911 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
912 }
913 }
914
915 return true;
916}
917
918bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
919 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
920 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
921 LOG_RTCERR1(SetDelayOffsetMs, offset);
922 return false;
923 }
924
925 return true;
926}
927
928struct ResumeEntry {
929 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
930 : channel(c),
931 playout(p),
932 send(s) {
933 }
934
935 WebRtcVoiceMediaChannel *channel;
936 bool playout;
937 SendFlags send;
938};
939
940// TODO(juberti): Refactor this so that the core logic can be used to set the
941// soundclip device. At that time, reinstate the soundclip pause/resume code.
942bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
943 const Device* out_device) {
944#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000945 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000946 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000947 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000948 kDefaultAudioDeviceId;
949 // The device manager uses -1 as the default device, which was the case for
950 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
951#ifndef WIN32
952 if (-1 == in_id) {
953 in_id = kDefaultAudioDeviceId;
954 }
955 if (-1 == out_id) {
956 out_id = kDefaultAudioDeviceId;
957 }
958#endif
959
960 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
961 in_device->name : "Default device";
962 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
963 out_device->name : "Default device";
964 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
965 << ") and speaker to (id=" << out_id << ", name=" << out_name
966 << ")";
967
968 // If we're running the local monitor, we need to stop it first.
969 bool ret = true;
970 if (!PauseLocalMonitor()) {
971 LOG(LS_WARNING) << "Failed to pause local monitor";
972 ret = false;
973 }
974
975 // Must also pause all audio playback and capture.
976 for (ChannelList::const_iterator i = channels_.begin();
977 i != channels_.end(); ++i) {
978 WebRtcVoiceMediaChannel *channel = *i;
979 if (!channel->PausePlayout()) {
980 LOG(LS_WARNING) << "Failed to pause playout";
981 ret = false;
982 }
983 if (!channel->PauseSend()) {
984 LOG(LS_WARNING) << "Failed to pause send";
985 ret = false;
986 }
987 }
988
989 // Find the recording device id in VoiceEngine and set recording device.
990 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
991 ret = false;
992 }
993 if (ret) {
994 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
995 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
996 ret = false;
997 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +0000998 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
999 if (ap)
1000 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001001 }
1002
1003 // Find the playout device id in VoiceEngine and set playout device.
1004 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1005 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1006 ret = false;
1007 }
1008 if (ret) {
1009 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001010 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011 ret = false;
1012 }
1013 }
1014
1015 // Resume all audio playback and capture.
1016 for (ChannelList::const_iterator i = channels_.begin();
1017 i != channels_.end(); ++i) {
1018 WebRtcVoiceMediaChannel *channel = *i;
1019 if (!channel->ResumePlayout()) {
1020 LOG(LS_WARNING) << "Failed to resume playout";
1021 ret = false;
1022 }
1023 if (!channel->ResumeSend()) {
1024 LOG(LS_WARNING) << "Failed to resume send";
1025 ret = false;
1026 }
1027 }
1028
1029 // Resume local monitor.
1030 if (!ResumeLocalMonitor()) {
1031 LOG(LS_WARNING) << "Failed to resume local monitor";
1032 ret = false;
1033 }
1034
1035 if (ret) {
1036 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1037 << ") and speaker to (id="<< out_id << " name=" << out_name
1038 << ")";
1039 }
1040
1041 return ret;
1042#else
1043 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001044#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001045}
1046
1047bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1048 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1049 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001050#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001051 *rtc_id = dev_id;
1052 return true;
1053#else
1054 // In Windows and Mac, we need to find the VoiceEngine device id by name
1055 // unless the input dev_id is the default device id.
1056 if (kDefaultAudioDeviceId == dev_id) {
1057 *rtc_id = dev_id;
1058 return true;
1059 }
1060
1061 // Get the number of VoiceEngine audio devices.
1062 int count = 0;
1063 if (is_input) {
1064 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1065 LOG_RTCERR0(GetNumOfRecordingDevices);
1066 return false;
1067 }
1068 } else {
1069 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1070 LOG_RTCERR0(GetNumOfPlayoutDevices);
1071 return false;
1072 }
1073 }
1074
1075 for (int i = 0; i < count; ++i) {
1076 char name[128];
1077 char guid[128];
1078 if (is_input) {
1079 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1080 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1081 } else {
1082 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1083 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1084 }
1085
1086 std::string webrtc_name(name);
1087 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1088 *rtc_id = i;
1089 return true;
1090 }
1091 }
1092 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1093 return false;
1094#endif
1095}
1096
1097bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1098 unsigned int ulevel;
1099 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1100 LOG_RTCERR1(GetSpeakerVolume, level);
1101 return false;
1102 }
1103 *level = ulevel;
1104 return true;
1105}
1106
1107bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1108 ASSERT(level >= 0 && level <= 255);
1109 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1110 LOG_RTCERR1(SetSpeakerVolume, level);
1111 return false;
1112 }
1113 return true;
1114}
1115
1116int WebRtcVoiceEngine::GetInputLevel() {
1117 unsigned int ulevel;
1118 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1119 static_cast<int>(ulevel) : -1;
1120}
1121
1122bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1123 desired_local_monitor_enable_ = enable;
1124 return ChangeLocalMonitor(desired_local_monitor_enable_);
1125}
1126
1127bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1128 // The voe file api is not available in chrome.
1129 if (!voe_wrapper_->file()) {
1130 return false;
1131 }
1132 if (enable && !monitor_) {
1133 monitor_.reset(new WebRtcMonitorStream);
1134 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1135 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1136 // Must call Stop() because there are some cases where Start will report
1137 // failure but still change the state, and if we leave VE in the on state
1138 // then it could crash later when trying to invoke methods on our monitor.
1139 voe_wrapper_->file()->StopRecordingMicrophone();
1140 monitor_.reset();
1141 return false;
1142 }
1143 } else if (!enable && monitor_) {
1144 voe_wrapper_->file()->StopRecordingMicrophone();
1145 monitor_.reset();
1146 }
1147 return true;
1148}
1149
1150bool WebRtcVoiceEngine::PauseLocalMonitor() {
1151 return ChangeLocalMonitor(false);
1152}
1153
1154bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1155 return ChangeLocalMonitor(desired_local_monitor_enable_);
1156}
1157
1158const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1159 return codecs_;
1160}
1161
1162bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1163 return FindWebRtcCodec(in, NULL);
1164}
1165
1166// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1167bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1168 webrtc::CodecInst* out) {
1169 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1170 for (int i = 0; i < ncodecs; ++i) {
1171 webrtc::CodecInst voe_codec;
1172 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1173 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1174 voe_codec.rate, voe_codec.channels, 0);
1175 bool multi_rate = IsCodecMultiRate(voe_codec);
1176 // Allow arbitrary rates for ISAC to be specified.
1177 if (multi_rate) {
1178 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1179 codec.bitrate = 0;
1180 }
1181 if (codec.Matches(in)) {
1182 if (out) {
1183 // Fixup the payload type.
1184 voe_codec.pltype = in.id;
1185
1186 // Set bitrate if specified.
1187 if (multi_rate && in.bitrate != 0) {
1188 voe_codec.rate = in.bitrate;
1189 }
1190
1191 // Apply codec-specific settings.
1192 if (IsIsac(codec)) {
1193 // If ISAC and an explicit bitrate is not specified,
1194 // enable auto bandwidth adjustment.
1195 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1196 }
1197 *out = voe_codec;
1198 }
1199 return true;
1200 }
1201 }
1202 }
1203 return false;
1204}
1205const std::vector<RtpHeaderExtension>&
1206WebRtcVoiceEngine::rtp_header_extensions() const {
1207 return rtp_header_extensions_;
1208}
1209
1210void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1211 // if min_sev == -1, we keep the current log level.
1212 if (min_sev >= 0) {
1213 SetTraceFilter(SeverityToFilter(min_sev));
1214 }
1215 log_options_ = filter;
1216 SetTraceOptions(initialized_ ? log_options_ : "");
1217}
1218
1219int WebRtcVoiceEngine::GetLastEngineError() {
1220 return voe_wrapper_->error();
1221}
1222
1223void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1224 log_filter_ = filter;
1225 tracing_->SetTraceFilter(filter);
1226}
1227
1228// We suppport three different logging settings for VoiceEngine:
1229// 1. Observer callback that goes into talk diagnostic logfile.
1230// Use --logfile and --loglevel
1231//
1232// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1233// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1234//
1235// 3. EC log and dump for debugging QualityEngine.
1236// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1237//
1238// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1239// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1240void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1241 // Set encrypted trace file.
1242 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001243 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001244 std::vector<std::string>::iterator tracefile =
1245 std::find(opts.begin(), opts.end(), "tracefile");
1246 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1247 // Write encrypted debug output (at same loglevel) to file
1248 // EncryptedTraceFile no longer supported.
1249 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1250 LOG_RTCERR1(SetTraceFile, *tracefile);
1251 }
1252 }
1253
wu@webrtc.org97077a32013-10-25 21:18:33 +00001254 // Allow trace options to override the trace filter. We default
1255 // it to log_filter_ (as a translation of libjingle log levels)
1256 // elsewhere, but this allows clients to explicitly set webrtc
1257 // log levels.
1258 std::vector<std::string>::iterator tracefilter =
1259 std::find(opts.begin(), opts.end(), "tracefilter");
1260 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001261 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001262 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1263 }
1264 }
1265
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001266 // Set AEC dump file
1267 std::vector<std::string>::iterator recordEC =
1268 std::find(opts.begin(), opts.end(), "recordEC");
1269 if (recordEC != opts.end()) {
1270 ++recordEC;
1271 if (recordEC != opts.end())
1272 StartAecDump(recordEC->c_str());
1273 else
1274 StopAecDump();
1275 }
1276}
1277
1278// Ignore spammy trace messages, mostly from the stats API when we haven't
1279// gotten RTCP info yet from the remote side.
1280bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1281 static const char* kTracesToIgnore[] = {
1282 "\tfailed to GetReportBlockInformation",
1283 "GetRecCodec() failed to get received codec",
1284 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1285 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1286 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1287 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1288 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1289 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1290 "SenderInfoReceived No received SR",
1291 "StatisticsRTP() no statistics available",
1292 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1293 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1294 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1295 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1296 NULL
1297 };
1298 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1299 if (trace.find(*p) != std::string::npos) {
1300 return true;
1301 }
1302 }
1303 return false;
1304}
1305
1306void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1307 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001308 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001309 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001310 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001312 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001313 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001314 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001315 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001316 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001317
1318 // Skip past boilerplate prefix text
1319 if (length < 72) {
1320 std::string msg(trace, length);
1321 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1322 LOG_V(sev) << msg;
1323 } else {
1324 std::string msg(trace + 71, length - 72);
1325 if (!ShouldIgnoreTrace(msg)) {
1326 LOG_V(sev) << "webrtc: " << msg;
1327 }
1328 }
1329}
1330
1331void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001332 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001333 WebRtcVoiceMediaChannel* channel = NULL;
1334 uint32 ssrc = 0;
1335 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1336 << channel_num << ".";
1337 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1338 ASSERT(channel != NULL);
1339 channel->OnError(ssrc, err_code);
1340 } else {
1341 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1342 << " could not be found in channel list when error reported.";
1343 }
1344}
1345
1346bool WebRtcVoiceEngine::FindChannelAndSsrc(
1347 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1348 ASSERT(channel != NULL && ssrc != NULL);
1349
1350 *channel = NULL;
1351 *ssrc = 0;
1352 // Find corresponding channel and ssrc
1353 for (ChannelList::const_iterator it = channels_.begin();
1354 it != channels_.end(); ++it) {
1355 ASSERT(*it != NULL);
1356 if ((*it)->FindSsrc(channel_num, ssrc)) {
1357 *channel = *it;
1358 return true;
1359 }
1360 }
1361
1362 return false;
1363}
1364
1365// This method will search through the WebRtcVoiceMediaChannels and
1366// obtain the voice engine's channel number.
1367bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1368 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1369 ASSERT(channel_num != NULL);
1370 ASSERT(direction == MPD_RX || direction == MPD_TX);
1371
1372 *channel_num = -1;
1373 // Find corresponding channel for ssrc.
1374 for (ChannelList::const_iterator it = channels_.begin();
1375 it != channels_.end(); ++it) {
1376 ASSERT(*it != NULL);
1377 if (direction & MPD_RX) {
1378 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1379 }
1380 if (*channel_num == -1 && (direction & MPD_TX)) {
1381 *channel_num = (*it)->GetSendChannelNum(ssrc);
1382 }
1383 if (*channel_num != -1) {
1384 return true;
1385 }
1386 }
1387 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1388 return false;
1389}
1390
1391void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001392 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001393 channels_.push_back(channel);
1394}
1395
1396void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001397 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001398 ChannelList::iterator i = std::find(channels_.begin(),
1399 channels_.end(),
1400 channel);
1401 if (i != channels_.end()) {
1402 channels_.erase(i);
1403 }
1404}
1405
1406void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1407 soundclips_.push_back(soundclip);
1408}
1409
1410void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1411 SoundclipList::iterator i = std::find(soundclips_.begin(),
1412 soundclips_.end(),
1413 soundclip);
1414 if (i != soundclips_.end()) {
1415 soundclips_.erase(i);
1416 }
1417}
1418
1419// Adjusts the default AGC target level by the specified delta.
1420// NB: If we start messing with other config fields, we'll want
1421// to save the current webrtc::AgcConfig as well.
1422bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1423 webrtc::AgcConfig config = default_agc_config_;
1424 config.targetLeveldBOv -= delta;
1425
1426 LOG(LS_INFO) << "Adjusting AGC level from default -"
1427 << default_agc_config_.targetLeveldBOv << "dB to -"
1428 << config.targetLeveldBOv << "dB";
1429
1430 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1431 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1432 return false;
1433 }
1434 return true;
1435}
1436
1437bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1438 webrtc::AudioDeviceModule* adm_sc) {
1439 if (initialized_) {
1440 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1441 return false;
1442 }
1443 if (adm_) {
1444 adm_->Release();
1445 adm_ = NULL;
1446 }
1447 if (adm) {
1448 adm_ = adm;
1449 adm_->AddRef();
1450 }
1451
1452 if (adm_sc_) {
1453 adm_sc_->Release();
1454 adm_sc_ = NULL;
1455 }
1456 if (adm_sc) {
1457 adm_sc_ = adm_sc;
1458 adm_sc_->AddRef();
1459 }
1460 return true;
1461}
1462
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001463bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1464 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001465 if (!aec_dump_file_stream) {
1466 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001467 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001468 LOG(LS_WARNING) << "Could not close file.";
1469 return false;
1470 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001471 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001472 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001473 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001474 LOG_RTCERR0(StartDebugRecording);
1475 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001476 return false;
1477 }
1478 is_dumping_aec_ = true;
1479 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001480}
1481
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001482bool WebRtcVoiceEngine::RegisterProcessor(
1483 uint32 ssrc,
1484 VoiceProcessor* voice_processor,
1485 MediaProcessorDirection direction) {
1486 bool register_with_webrtc = false;
1487 int channel_id = -1;
1488 bool success = false;
1489 uint32* processor_ssrc = NULL;
1490 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1491 if (voice_processor == NULL || !found_channel) {
1492 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1493 << " foundChannel: " << found_channel;
1494 return false;
1495 }
1496
1497 webrtc::ProcessingTypes processing_type;
1498 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001499 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001500 if (direction == MPD_RX) {
1501 processing_type = webrtc::kPlaybackAllChannelsMixed;
1502 if (SignalRxMediaFrame.is_empty()) {
1503 register_with_webrtc = true;
1504 processor_ssrc = &rx_processor_ssrc_;
1505 }
1506 SignalRxMediaFrame.connect(voice_processor,
1507 &VoiceProcessor::OnFrame);
1508 } else {
1509 processing_type = webrtc::kRecordingPerChannel;
1510 if (SignalTxMediaFrame.is_empty()) {
1511 register_with_webrtc = true;
1512 processor_ssrc = &tx_processor_ssrc_;
1513 }
1514 SignalTxMediaFrame.connect(voice_processor,
1515 &VoiceProcessor::OnFrame);
1516 }
1517 }
1518 if (register_with_webrtc) {
1519 // TODO(janahan): when registering consider instantiating a
1520 // a VoeMediaProcess object and not make the engine extend the interface.
1521 if (voe()->media() && voe()->media()->
1522 RegisterExternalMediaProcessing(channel_id,
1523 processing_type,
1524 *this) != -1) {
1525 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1526 << channel_id;
1527 *processor_ssrc = ssrc;
1528 success = true;
1529 } else {
1530 LOG_RTCERR2(RegisterExternalMediaProcessing,
1531 channel_id,
1532 processing_type);
1533 success = false;
1534 }
1535 } else {
1536 // If we don't have to register with the engine, we just needed to
1537 // connect a new processor, set success to true;
1538 success = true;
1539 }
1540 return success;
1541}
1542
1543bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1544 MediaProcessorDirection channel_direction,
1545 uint32 ssrc,
1546 VoiceProcessor* voice_processor,
1547 MediaProcessorDirection processor_direction) {
1548 bool success = true;
1549 FrameSignal* signal;
1550 webrtc::ProcessingTypes processing_type;
1551 uint32* processor_ssrc = NULL;
1552 if (channel_direction == MPD_RX) {
1553 signal = &SignalRxMediaFrame;
1554 processing_type = webrtc::kPlaybackAllChannelsMixed;
1555 processor_ssrc = &rx_processor_ssrc_;
1556 } else {
1557 signal = &SignalTxMediaFrame;
1558 processing_type = webrtc::kRecordingPerChannel;
1559 processor_ssrc = &tx_processor_ssrc_;
1560 }
1561
1562 int deregister_id = -1;
1563 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001564 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001565 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1566 signal->disconnect(voice_processor);
1567 int channel_id = -1;
1568 bool found_channel = FindChannelNumFromSsrc(ssrc,
1569 channel_direction,
1570 &channel_id);
1571 if (signal->is_empty() && found_channel) {
1572 deregister_id = channel_id;
1573 }
1574 }
1575 }
1576 if (deregister_id != -1) {
1577 if (voe()->media() &&
1578 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1579 processing_type) != -1) {
1580 *processor_ssrc = 0;
1581 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1582 << deregister_id;
1583 } else {
1584 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1585 deregister_id,
1586 processing_type);
1587 success = false;
1588 }
1589 }
1590 return success;
1591}
1592
1593bool WebRtcVoiceEngine::UnregisterProcessor(
1594 uint32 ssrc,
1595 VoiceProcessor* voice_processor,
1596 MediaProcessorDirection direction) {
1597 bool success = true;
1598 if (voice_processor == NULL) {
1599 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1600 << ssrc;
1601 return false;
1602 }
1603 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1604 success = false;
1605 }
1606 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1607 success = false;
1608 }
1609 return success;
1610}
1611
1612// Implementing method from WebRtc VoEMediaProcess interface
1613// Do not lock mux_channel_cs_ in this callback.
1614void WebRtcVoiceEngine::Process(int channel,
1615 webrtc::ProcessingTypes type,
1616 int16_t audio10ms[],
1617 int length,
1618 int sampling_freq,
1619 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001620 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001621 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1622 if (type == webrtc::kPlaybackAllChannelsMixed) {
1623 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1624 } else if (type == webrtc::kRecordingPerChannel) {
1625 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1626 } else {
1627 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1628 << " channel: " << channel << " type: " << type
1629 << " tx_ssrc: " << tx_processor_ssrc_
1630 << " rx_ssrc: " << rx_processor_ssrc_;
1631 }
1632}
1633
1634void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1635 if (!is_dumping_aec_) {
1636 // Start dumping AEC when we are not dumping.
1637 if (voe_wrapper_->processing()->StartDebugRecording(
1638 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001639 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001640 } else {
1641 is_dumping_aec_ = true;
1642 }
1643 }
1644}
1645
1646void WebRtcVoiceEngine::StopAecDump() {
1647 if (is_dumping_aec_) {
1648 // Stop dumping AEC when we are dumping.
1649 if (voe_wrapper_->processing()->StopDebugRecording() !=
1650 webrtc::AudioProcessing::kNoError) {
1651 LOG_RTCERR0(StopDebugRecording);
1652 }
1653 is_dumping_aec_ = false;
1654 }
1655}
1656
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001657int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001658 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001659}
1660
1661int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1662 return CreateVoiceChannel(voe_wrapper_.get());
1663}
1664
1665int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1666 return CreateVoiceChannel(voe_wrapper_sc_.get());
1667}
1668
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001669class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1670 : public AudioRenderer::Sink {
1671 public:
1672 WebRtcVoiceChannelRenderer(int ch,
1673 webrtc::AudioTransport* voe_audio_transport)
1674 : channel_(ch),
1675 voe_audio_transport_(voe_audio_transport),
1676 renderer_(NULL) {
1677 }
1678 virtual ~WebRtcVoiceChannelRenderer() {
1679 Stop();
1680 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001681
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001682 // Starts the rendering by setting a sink to the renderer to get data
1683 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001684 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001685 // TODO(xians): Make sure Start() is called only once.
1686 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001687 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001688 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001689 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001690 ASSERT(renderer_ == renderer);
1691 return;
1692 }
1693
1694 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1695 // in getUserMedia by default.
1696 renderer->AddChannel(channel_);
1697 renderer->SetSink(this);
1698 renderer_ = renderer;
1699 }
1700
1701 // Stops rendering by setting the sink of the renderer to NULL. No data
1702 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001703 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001704 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001705 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001706 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001707 return;
1708
1709 renderer_->RemoveChannel(channel_);
1710 renderer_->SetSink(NULL);
1711 renderer_ = NULL;
1712 }
1713
1714 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001715 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001716 virtual void OnData(const void* audio_data,
1717 int bits_per_sample,
1718 int sample_rate,
1719 int number_of_channels,
1720 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001721 voe_audio_transport_->OnData(channel_,
1722 audio_data,
1723 bits_per_sample,
1724 sample_rate,
1725 number_of_channels,
1726 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001727 }
1728
1729 // Callback from the |renderer_| when it is going away. In case Start() has
1730 // never been called, this callback won't be triggered.
1731 virtual void OnClose() OVERRIDE {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001732 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001733 // Set |renderer_| to NULL to make sure no more callback will get into
1734 // the renderer.
1735 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001736 }
1737
1738 // Accessor to the VoE channel ID.
1739 int channel() const { return channel_; }
1740
1741 private:
1742 const int channel_;
1743 webrtc::AudioTransport* const voe_audio_transport_;
1744
1745 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1746 // PeerConnection will make sure invalidating the pointer before the object
1747 // goes away.
1748 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001749
1750 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001751 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001752};
1753
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001754// WebRtcVoiceMediaChannel
1755WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1756 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1757 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001758 engine->CreateMediaVoiceChannel()),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001759 send_bw_setting_(false),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001760 send_bw_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001761 options_(),
1762 dtmf_allowed_(false),
1763 desired_playout_(false),
1764 nack_enabled_(false),
1765 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001766 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001767 desired_send_(SEND_NOTHING),
1768 send_(SEND_NOTHING),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001769 shared_bwe_vie_(NULL),
1770 shared_bwe_vie_channel_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001771 default_receive_ssrc_(0) {
1772 engine->RegisterChannel(this);
1773 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1774 << voe_channel();
1775
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001776 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001777}
1778
1779WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1780 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1781 << voe_channel();
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001782 ASSERT(shared_bwe_vie_ == NULL);
1783 ASSERT(shared_bwe_vie_channel_ == -1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001784
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001785 // Remove any remaining send streams, the default channel will be deleted
1786 // later.
1787 while (!send_channels_.empty())
1788 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001789
1790 // Unregister ourselves from the engine.
1791 engine()->UnregisterChannel(this);
1792 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001793 while (!receive_channels_.empty()) {
1794 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001795 }
1796
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001797 // Delete the default channel.
1798 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001799}
1800
1801bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1802 LOG(LS_INFO) << "Setting voice channel options: "
1803 << options.ToString();
1804
wu@webrtc.orgde305012013-10-31 15:40:38 +00001805 // Check if DSCP value is changed from previous.
1806 bool dscp_option_changed = (options_.dscp != options.dscp);
1807
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001808 // TODO(xians): Add support to set different options for different send
1809 // streams after we support multiple APMs.
1810
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001811 // We retain all of the existing options, and apply the given ones
1812 // on top. This means there is no way to "clear" options such that
1813 // they go back to the engine default.
1814 options_.SetAll(options);
1815
1816 if (send_ != SEND_NOTHING) {
1817 if (!engine()->SetOptionOverrides(options_)) {
1818 LOG(LS_WARNING) <<
1819 "Failed to engine SetOptionOverrides during channel SetOptions.";
1820 return false;
1821 }
1822 } else {
1823 // Will be interpreted when appropriate.
1824 }
1825
wu@webrtc.org97077a32013-10-25 21:18:33 +00001826 // Receiver-side auto gain control happens per channel, so set it here from
1827 // options. Note that, like conference mode, setting it on the engine won't
1828 // have the desired effect, since voice channels don't inherit options from
1829 // the media engine when those options are applied per-channel.
1830 bool rx_auto_gain_control;
1831 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1832 if (engine()->voe()->processing()->SetRxAgcStatus(
1833 voe_channel(), rx_auto_gain_control,
1834 webrtc::kAgcFixedDigital) == -1) {
1835 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1836 return false;
1837 } else {
1838 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1839 << " with mode " << webrtc::kAgcFixedDigital;
1840 }
1841 }
1842 if (options.rx_agc_target_dbov.IsSet() ||
1843 options.rx_agc_digital_compression_gain.IsSet() ||
1844 options.rx_agc_limiter.IsSet()) {
1845 webrtc::AgcConfig config;
1846 // If only some of the options are being overridden, get the current
1847 // settings for the channel and bail if they aren't available.
1848 if (!options.rx_agc_target_dbov.IsSet() ||
1849 !options.rx_agc_digital_compression_gain.IsSet() ||
1850 !options.rx_agc_limiter.IsSet()) {
1851 if (engine()->voe()->processing()->GetRxAgcConfig(
1852 voe_channel(), config) != 0) {
1853 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1854 << "channel " << voe_channel() << ". Since not all rx "
1855 << "agc options are specified, unable to safely set rx "
1856 << "agc options.";
1857 return false;
1858 }
1859 }
1860 config.targetLeveldBOv =
1861 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1862 config.targetLeveldBOv);
1863 config.digitalCompressionGaindB =
1864 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1865 config.digitalCompressionGaindB);
1866 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1867 config.limiterEnable);
1868 if (engine()->voe()->processing()->SetRxAgcConfig(
1869 voe_channel(), config) == -1) {
1870 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1871 config.digitalCompressionGaindB, config.limiterEnable);
1872 return false;
1873 }
1874 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001875 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001876 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001877 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001878 dscp = kAudioDscpValue;
1879 if (MediaChannel::SetDscp(dscp) != 0) {
1880 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1881 }
1882 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001883
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001884 // Force update of Video Engine BWE forwarding to reflect experiment setting.
1885 if (!SetupSharedBandwidthEstimation(shared_bwe_vie_,
1886 shared_bwe_vie_channel_)) {
1887 return false;
1888 }
1889
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001890 LOG(LS_INFO) << "Set voice channel options. Current options: "
1891 << options_.ToString();
1892 return true;
1893}
1894
1895bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1896 const std::vector<AudioCodec>& codecs) {
1897 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001898 LOG(LS_INFO) << "Setting receive voice codecs:";
1899
1900 std::vector<AudioCodec> new_codecs;
1901 // Find all new codecs. We allow adding new codecs but don't allow changing
1902 // the payload type of codecs that is already configured since we might
1903 // already be receiving packets with that payload type.
1904 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001905 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001906 AudioCodec old_codec;
1907 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1908 if (old_codec.id != it->id) {
1909 LOG(LS_ERROR) << it->name << " payload type changed.";
1910 return false;
1911 }
1912 } else {
1913 new_codecs.push_back(*it);
1914 }
1915 }
1916 if (new_codecs.empty()) {
1917 // There are no new codecs to configure. Already configured codecs are
1918 // never removed.
1919 return true;
1920 }
1921
1922 if (playout_) {
1923 // Receive codecs can not be changed while playing. So we temporarily
1924 // pause playout.
1925 PausePlayout();
1926 }
1927
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001928 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001929 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1930 it != new_codecs.end() && ret; ++it) {
1931 webrtc::CodecInst voe_codec;
1932 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1933 LOG(LS_INFO) << ToString(*it);
1934 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001935 if (default_receive_ssrc_ == 0) {
1936 // Set the receive codecs on the default channel explicitly if the
1937 // default channel is not used by |receive_channels_|, this happens in
1938 // conference mode or in non-conference mode when there is no playout
1939 // channel.
1940 // TODO(xians): Figure out how we use the default channel in conference
1941 // mode.
1942 if (engine()->voe()->codec()->SetRecPayloadType(
1943 voe_channel(), voe_codec) == -1) {
1944 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1945 ret = false;
1946 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001947 }
1948
1949 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001950 for (ChannelMap::iterator it = receive_channels_.begin();
1951 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001952 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001953 it->second->channel(), voe_codec) == -1) {
1954 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001955 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001956 ret = false;
1957 }
1958 }
1959 } else {
1960 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1961 ret = false;
1962 }
1963 }
1964 if (ret) {
1965 recv_codecs_ = codecs;
1966 }
1967
1968 if (desired_playout_ && !playout_) {
1969 ResumePlayout();
1970 }
1971 return ret;
1972}
1973
1974bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001975 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001976 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001977 engine()->voe()->codec()->SetVADStatus(channel, false);
1978 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001979#ifdef USE_WEBRTC_DEV_BRANCH
1980 engine()->voe()->rtp()->SetREDStatus(channel, false);
1981 engine()->voe()->codec()->SetFECStatus(channel, false);
1982#else
1983 // TODO(minyue): Remove code under #else case after new WebRTC roll.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001984 engine()->voe()->rtp()->SetFECStatus(channel, false);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001985#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001986
1987 // Scan through the list to figure out the codec to use for sending, along
1988 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001989 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001990 webrtc::CodecInst send_codec;
1991 memset(&send_codec, 0, sizeof(send_codec));
1992
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001993 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001994 bool enable_codec_fec = false;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001995
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001996 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001997 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1998 it != codecs.end(); ++it) {
1999 // Ignore codecs we don't know about. The negotiation step should prevent
2000 // this, but double-check to be sure.
2001 webrtc::CodecInst voe_codec;
2002 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002003 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002004 continue;
2005 }
2006
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002007 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2008 // Skip telephone-event/CN codec, which will be handled later.
2009 continue;
2010 }
2011
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002012 // If OPUS, change what we send according to the "stereo" codec
2013 // parameter, and not the "channels" parameter. We set
2014 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
2015 // the bitrate is not specified, i.e. is zero, we set it to the
2016 // appropriate default value for mono or stereo Opus.
2017 if (IsOpus(*it)) {
2018 if (IsOpusStereoEnabled(*it)) {
2019 voe_codec.channels = 2;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002020 if (!IsValidOpusBitrate(it->bitrate)) {
2021 if (it->bitrate != 0) {
2022 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2023 << it->bitrate
2024 << ") with default opus stereo bitrate: "
2025 << kOpusStereoBitrate;
2026 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002027 voe_codec.rate = kOpusStereoBitrate;
2028 }
2029 } else {
2030 voe_codec.channels = 1;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002031 if (!IsValidOpusBitrate(it->bitrate)) {
2032 if (it->bitrate != 0) {
2033 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2034 << it->bitrate
2035 << ") with default opus mono bitrate: "
2036 << kOpusMonoBitrate;
2037 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002038 voe_codec.rate = kOpusMonoBitrate;
2039 }
2040 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002041 int bitrate_from_params = GetOpusBitrateFromParams(*it);
2042 if (bitrate_from_params != 0) {
2043 voe_codec.rate = bitrate_from_params;
2044 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002045 }
2046
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002047 // We'll use the first codec in the list to actually send audio data.
2048 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002049 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002050 // used is specified in params.
2051 if (IsRedCodec(it->name)) {
2052 // Parse out the RED parameters. If we fail, just ignore RED;
2053 // we don't support all possible params/usage scenarios.
2054 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2055 continue;
2056 }
2057
2058 // Enable redundant encoding of the specified codec. Treat any
2059 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002060#ifdef USE_WEBRTC_DEV_BRANCH
2061 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2062 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2063 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
2064#else
2065 // TODO(minyue): Remove code under #else case after new WebRTC roll.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002066 LOG(LS_INFO) << "Enabling FEC";
2067 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2068 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002069#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002070 return false;
2071 }
2072 } else {
2073 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002074 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002075 // For Opus as the send codec, we enable inband FEC if requested.
2076 enable_codec_fec = IsOpus(*it) && IsOpusFecEnabled(*it);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002077 }
2078 found_send_codec = true;
2079 break;
2080 }
2081
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002082 if (nack_enabled_ != nack_enabled) {
2083 SetNack(channel, nack_enabled);
2084 nack_enabled_ = nack_enabled;
2085 }
2086
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002087 if (!found_send_codec) {
2088 LOG(LS_WARNING) << "Received empty list of codecs.";
2089 return false;
2090 }
2091
2092 // Set the codec immediately, since SetVADStatus() depends on whether
2093 // the current codec is mono or stereo.
2094 if (!SetSendCodec(channel, send_codec))
2095 return false;
2096
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002097 // FEC should be enabled after SetSendCodec.
2098 if (enable_codec_fec) {
2099 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2100 << channel;
2101#ifdef USE_WEBRTC_DEV_BRANCH
2102 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2103 // Enable codec internal FEC. Treat any failure as fatal internal error.
2104 LOG_RTCERR2(SetFECStatus, channel, true);
2105 return false;
2106 }
2107#endif // USE_WEBRTC_DEV_BRANCH
2108 }
2109
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002110 // Always update the |send_codec_| to the currently set send codec.
2111 send_codec_.reset(new webrtc::CodecInst(send_codec));
2112
2113 if (send_bw_setting_) {
2114 SetSendBandwidthInternal(send_bw_bps_);
2115 }
2116
2117 // Loop through the codecs list again to config the telephone-event/CN codec.
2118 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2119 it != codecs.end(); ++it) {
2120 // Ignore codecs we don't know about. The negotiation step should prevent
2121 // this, but double-check to be sure.
2122 webrtc::CodecInst voe_codec;
2123 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2124 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2125 continue;
2126 }
2127
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002128 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2129 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002130 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002131 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2132 channel, it->id) == -1) {
2133 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2134 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002135 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002136 } else if (IsCNCodec(it->name)) {
2137 // Turn voice activity detection/comfort noise on if supported.
2138 // Set the wideband CN payload type appropriately.
2139 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002140 webrtc::PayloadFrequencies cn_freq;
2141 switch (it->clockrate) {
2142 case 8000:
2143 cn_freq = webrtc::kFreq8000Hz;
2144 break;
2145 case 16000:
2146 cn_freq = webrtc::kFreq16000Hz;
2147 break;
2148 case 32000:
2149 cn_freq = webrtc::kFreq32000Hz;
2150 break;
2151 default:
2152 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2153 << " not supported.";
2154 continue;
2155 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002156 // Set the CN payloadtype and the VAD status.
2157 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2158 if (cn_freq != webrtc::kFreq8000Hz) {
2159 if (engine()->voe()->codec()->SetSendCNPayloadType(
2160 channel, it->id, cn_freq) == -1) {
2161 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2162 // TODO(ajm): This failure condition will be removed from VoE.
2163 // Restore the return here when we update to a new enough webrtc.
2164 //
2165 // Not returning false because the SetSendCNPayloadType will fail if
2166 // the channel is already sending.
2167 // This can happen if the remote description is applied twice, for
2168 // example in the case of ROAP on top of JSEP, where both side will
2169 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002170 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002171 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002172 // Only turn on VAD if we have a CN payload type that matches the
2173 // clockrate for the codec we are going to use.
2174 if (it->clockrate == send_codec.plfreq) {
2175 LOG(LS_INFO) << "Enabling VAD";
2176 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2177 LOG_RTCERR2(SetVADStatus, channel, true);
2178 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002179 }
2180 }
2181 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002182 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002183 return true;
2184}
2185
2186bool WebRtcVoiceMediaChannel::SetSendCodecs(
2187 const std::vector<AudioCodec>& codecs) {
2188 dtmf_allowed_ = false;
2189 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2190 it != codecs.end(); ++it) {
2191 // Find the DTMF telephone event "codec".
2192 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2193 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2194 dtmf_allowed_ = true;
2195 }
2196 }
2197
2198 // Cache the codecs in order to configure the channel created later.
2199 send_codecs_ = codecs;
2200 for (ChannelMap::iterator iter = send_channels_.begin();
2201 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002202 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002203 return false;
2204 }
2205 }
2206
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002207 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002208 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002209 return true;
2210}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002211
2212void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2213 bool nack_enabled) {
2214 for (ChannelMap::const_iterator it = channels.begin();
2215 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002216 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002217 }
2218}
2219
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002220void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002221 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002222 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002223 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2224 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002225 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002226 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2227 }
2228}
2229
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002230bool WebRtcVoiceMediaChannel::SetSendCodec(
2231 const webrtc::CodecInst& send_codec) {
2232 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2233 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002234 for (ChannelMap::iterator iter = send_channels_.begin();
2235 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002236 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002237 return false;
2238 }
2239
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002240 return true;
2241}
2242
2243bool WebRtcVoiceMediaChannel::SetSendCodec(
2244 int channel, const webrtc::CodecInst& send_codec) {
2245 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2246 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2247
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002248 webrtc::CodecInst current_codec;
2249 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2250 (send_codec == current_codec)) {
2251 // Codec is already configured, we can return without setting it again.
2252 return true;
2253 }
2254
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002255 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2256 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002257 return false;
2258 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002259 return true;
2260}
2261
2262bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2263 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002264 if (receive_extensions_ == extensions) {
2265 return true;
2266 }
2267
2268 // The default channel may or may not be in |receive_channels_|. Set the rtp
2269 // header extensions for default channel regardless.
2270 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2271 return false;
2272 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002273
2274 // Loop through all receive channels and enable/disable the extensions.
2275 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2276 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002277 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2278 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002279 return false;
2280 }
2281 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002282
2283 receive_extensions_ = extensions;
2284 return true;
2285}
2286
2287bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2288 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002289 const RtpHeaderExtension* audio_level_extension =
2290 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2291 if (!SetHeaderExtension(
2292 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2293 audio_level_extension)) {
2294 return false;
2295 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002296
2297 const RtpHeaderExtension* send_time_extension =
2298 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2299 if (!SetHeaderExtension(
2300 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2301 send_time_extension)) {
2302 return false;
2303 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002304 return true;
2305}
2306
2307bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2308 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002309 if (send_extensions_ == extensions) {
2310 return true;
2311 }
2312
2313 // The default channel may or may not be in |send_channels_|. Set the rtp
2314 // header extensions for default channel regardless.
2315
2316 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2317 return false;
2318 }
2319
2320 // Loop through all send channels and enable/disable the extensions.
2321 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2322 channel_it != send_channels_.end(); ++channel_it) {
2323 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2324 extensions)) {
2325 return false;
2326 }
2327 }
2328
2329 send_extensions_ = extensions;
2330 return true;
2331}
2332
2333bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2334 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002335 const RtpHeaderExtension* audio_level_extension =
2336 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002337
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002338 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002339 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002340 audio_level_extension)) {
2341 return false;
2342 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002343
2344 const RtpHeaderExtension* send_time_extension =
2345 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002346 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002347 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002348 send_time_extension)) {
2349 return false;
2350 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002351
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002352 return true;
2353}
2354
2355bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2356 desired_playout_ = playout;
2357 return ChangePlayout(desired_playout_);
2358}
2359
2360bool WebRtcVoiceMediaChannel::PausePlayout() {
2361 return ChangePlayout(false);
2362}
2363
2364bool WebRtcVoiceMediaChannel::ResumePlayout() {
2365 return ChangePlayout(desired_playout_);
2366}
2367
2368bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2369 if (playout_ == playout) {
2370 return true;
2371 }
2372
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002373 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002374 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002375 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002376 // Only toggle the default channel if we don't have any other channels.
2377 result = SetPlayout(voe_channel(), playout);
2378 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002379 for (ChannelMap::iterator it = receive_channels_.begin();
2380 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002381 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002382 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002383 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002384 result = false;
2385 }
2386 }
2387
2388 if (result) {
2389 playout_ = playout;
2390 }
2391 return result;
2392}
2393
2394bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2395 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002396 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002397 return ChangeSend(desired_send_);
2398 return true;
2399}
2400
2401bool WebRtcVoiceMediaChannel::PauseSend() {
2402 return ChangeSend(SEND_NOTHING);
2403}
2404
2405bool WebRtcVoiceMediaChannel::ResumeSend() {
2406 return ChangeSend(desired_send_);
2407}
2408
2409bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2410 if (send_ == send) {
2411 return true;
2412 }
2413
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002414 // Change the settings on each send channel.
2415 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002416 engine()->SetOptionOverrides(options_);
2417
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002418 // Change the settings on each send channel.
2419 for (ChannelMap::iterator iter = send_channels_.begin();
2420 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002421 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002422 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002423 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002424
2425 // Clear up the options after stopping sending.
2426 if (send == SEND_NOTHING)
2427 engine()->ClearOptionOverrides();
2428
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002429 send_ = send;
2430 return true;
2431}
2432
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002433bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2434 if (send == SEND_MICROPHONE) {
2435 if (engine()->voe()->base()->StartSend(channel) == -1) {
2436 LOG_RTCERR1(StartSend, channel);
2437 return false;
2438 }
2439 if (engine()->voe()->file() &&
2440 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2441 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2442 return false;
2443 }
2444 } else { // SEND_NOTHING
2445 ASSERT(send == SEND_NOTHING);
2446 if (engine()->voe()->base()->StopSend(channel) == -1) {
2447 LOG_RTCERR1(StopSend, channel);
2448 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002449 }
2450 }
2451
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002452 return true;
2453}
2454
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002455// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002456void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2457 if (engine()->voe()->network()->RegisterExternalTransport(
2458 channel, *this) == -1) {
2459 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2460 }
2461
2462 // Enable RTCP (for quality stats and feedback messages)
2463 EnableRtcp(channel);
2464
2465 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2466 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002467
2468 // Set RTP header extension for the new channel.
2469 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002470}
2471
2472bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2473 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2474 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2475 }
2476
2477 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2478 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002479 return false;
2480 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002481
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002482 return true;
2483}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002484
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002485bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2486 // If the default channel is already used for sending create a new channel
2487 // otherwise use the default channel for sending.
2488 int channel = GetSendChannelNum(sp.first_ssrc());
2489 if (channel != -1) {
2490 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2491 return false;
2492 }
2493
2494 bool default_channel_is_available = true;
2495 for (ChannelMap::const_iterator iter = send_channels_.begin();
2496 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002497 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002498 default_channel_is_available = false;
2499 break;
2500 }
2501 }
2502 if (default_channel_is_available) {
2503 channel = voe_channel();
2504 } else {
2505 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002506 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002507 if (channel == -1) {
2508 LOG_RTCERR0(CreateChannel);
2509 return false;
2510 }
2511
2512 ConfigureSendChannel(channel);
2513 }
2514
2515 // Save the channel to send_channels_, so that RemoveSendStream() can still
2516 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002517 webrtc::AudioTransport* audio_transport =
2518 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002519 send_channels_.insert(std::make_pair(
2520 sp.first_ssrc(),
2521 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002522
2523 // Set the send (local) SSRC.
2524 // If there are multiple send SSRCs, we can only set the first one here, and
2525 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2526 // (with a codec requires multiple SSRC(s)).
2527 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2528 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2529 return false;
2530 }
2531
2532 // At this point the channel's local SSRC has been updated. If the channel is
2533 // the default channel make sure that all the receive channels are updated as
2534 // well. Receive channels have to have the same SSRC as the default channel in
2535 // order to send receiver reports with this SSRC.
2536 if (IsDefaultChannel(channel)) {
2537 for (ChannelMap::const_iterator it = receive_channels_.begin();
2538 it != receive_channels_.end(); ++it) {
2539 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002540 if (!IsDefaultChannel(it->second->channel())) {
2541 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002542 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002543 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002544 return false;
2545 }
2546 }
2547 }
2548 }
2549
2550 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002551 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2552 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002553 }
2554
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002555 // Set the current codecs to be used for the new channel.
2556 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002557 return false;
2558
2559 return ChangeSend(channel, desired_send_);
2560}
2561
2562bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2563 ChannelMap::iterator it = send_channels_.find(ssrc);
2564 if (it == send_channels_.end()) {
2565 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2566 << " which doesn't exist.";
2567 return false;
2568 }
2569
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002570 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002571 ChangeSend(channel, SEND_NOTHING);
2572
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002573 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2574 // this will disconnect the audio renderer with the send channel.
2575 delete it->second;
2576 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002577
2578 if (IsDefaultChannel(channel)) {
2579 // Do not delete the default channel since the receive channels depend on
2580 // the default channel, recycle it instead.
2581 ChangeSend(channel, SEND_NOTHING);
2582 } else {
2583 // Clean up and delete the send channel.
2584 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2585 << " with VoiceEngine channel #" << channel << ".";
2586 if (!DeleteChannel(channel))
2587 return false;
2588 }
2589
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002590 if (send_channels_.empty())
2591 ChangeSend(SEND_NOTHING);
2592
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002593 return true;
2594}
2595
2596bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002597 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002598
2599 if (!VERIFY(sp.ssrcs.size() == 1))
2600 return false;
2601 uint32 ssrc = sp.first_ssrc();
2602
wu@webrtc.org78187522013-10-07 23:32:02 +00002603 if (ssrc == 0) {
2604 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2605 return false;
2606 }
2607
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002608 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2609 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002610 return false;
2611 }
2612
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002613 // Reuse default channel for recv stream in non-conference mode call
2614 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002615 webrtc::AudioTransport* audio_transport =
2616 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002617 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2618 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2619 << " reuse default channel";
2620 default_receive_ssrc_ = sp.first_ssrc();
2621 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002622 default_receive_ssrc_,
2623 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002624 if (!SetupSharedBweOnChannel(voe_channel())) {
2625 return false;
2626 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002627 return SetPlayout(voe_channel(), playout_);
2628 }
2629
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002630 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002631 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002632 if (channel == -1) {
2633 LOG_RTCERR0(CreateChannel);
2634 return false;
2635 }
2636
wu@webrtc.org78187522013-10-07 23:32:02 +00002637 if (!ConfigureRecvChannel(channel)) {
2638 DeleteChannel(channel);
2639 return false;
2640 }
2641
2642 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002643 std::make_pair(
2644 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002645
2646 LOG(LS_INFO) << "New audio stream " << ssrc
2647 << " registered to VoiceEngine channel #"
2648 << channel << ".";
2649 return true;
2650}
2651
2652bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002653 // Configure to use external transport, like our default channel.
2654 if (engine()->voe()->network()->RegisterExternalTransport(
2655 channel, *this) == -1) {
2656 LOG_RTCERR2(SetExternalTransport, channel, this);
2657 return false;
2658 }
2659
2660 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002661 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002662 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2663 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002664 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002665 return false;
2666 }
2667 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002668 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002669 return false;
2670 }
2671
2672 // Use the same recv payload types as our default channel.
2673 ResetRecvCodecs(channel);
2674 if (!recv_codecs_.empty()) {
2675 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2676 it != recv_codecs_.end(); ++it) {
2677 webrtc::CodecInst voe_codec;
2678 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2679 voe_codec.pltype = it->id;
2680 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2681 if (engine()->voe()->codec()->GetRecPayloadType(
2682 voe_channel(), voe_codec) != -1) {
2683 if (engine()->voe()->codec()->SetRecPayloadType(
2684 channel, voe_codec) == -1) {
2685 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2686 return false;
2687 }
2688 }
2689 }
2690 }
2691 }
2692
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002693 if (InConferenceMode()) {
2694 // To be in par with the video, voe_channel() is not used for receiving in
2695 // a conference call.
2696 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2697 // This is the first stream in a multi user meeting. We can now
2698 // disable playback of the default stream. This since the default
2699 // stream will probably have received some initial packets before
2700 // the new stream was added. This will mean that the CN state from
2701 // the default channel will be mixed in with the other streams
2702 // throughout the whole meeting, which might be disturbing.
2703 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2704 SetPlayout(voe_channel(), false);
2705 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002706 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002707 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002708
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002709 // Set RTP header extension for the new channel.
2710 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2711 return false;
2712 }
2713
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002714 // Set up channel to be able to forward incoming packets to video engine BWE.
2715 if (!SetupSharedBweOnChannel(channel)) {
2716 return false;
2717 }
2718
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002719 return SetPlayout(channel, playout_);
2720}
2721
2722bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002723 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002724 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002725 if (it == receive_channels_.end()) {
2726 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2727 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002728 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002729 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002730
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002731 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2732 // will disconnect the audio renderer with the receive channel.
2733 // Cache the channel before the deletion.
2734 const int channel = it->second->channel();
2735 delete it->second;
2736 receive_channels_.erase(it);
2737
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002738 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002739 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002740 // Recycle the default channel is for recv stream.
2741 if (playout_)
2742 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002743
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002744 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002745 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002746 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002747
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002748 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002749 << " with VoiceEngine channel #" << channel << ".";
2750 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002751 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002752
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002753 bool enable_default_channel_playout = false;
2754 if (receive_channels_.empty()) {
2755 // The last stream was removed. We can now enable the default
2756 // channel for new channels to be played out immediately without
2757 // waiting for AddStream messages.
2758 // We do this for both conference mode and non-conference mode.
2759 // TODO(oja): Does the default channel still have it's CN state?
2760 enable_default_channel_playout = true;
2761 }
2762 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2763 default_receive_ssrc_ != 0) {
2764 // Only the default channel is active, enable the playout on default
2765 // channel.
2766 enable_default_channel_playout = true;
2767 }
2768 if (enable_default_channel_playout && playout_) {
2769 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2770 SetPlayout(voe_channel(), true);
2771 }
2772
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002773 return true;
2774}
2775
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002776bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2777 AudioRenderer* renderer) {
2778 ChannelMap::iterator it = receive_channels_.find(ssrc);
2779 if (it == receive_channels_.end()) {
2780 if (renderer) {
2781 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002782 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002783 return false;
2784 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002785
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002786 // The channel likely has gone away, do nothing.
2787 return true;
2788 }
2789
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002790 if (renderer)
2791 it->second->Start(renderer);
2792 else
2793 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002794
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002795 return true;
2796}
2797
2798bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2799 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002800 ChannelMap::iterator it = send_channels_.find(ssrc);
2801 if (it == send_channels_.end()) {
2802 if (renderer) {
2803 // Return an error if trying to set a valid renderer with an invalid ssrc.
2804 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2805 return false;
2806 }
2807
2808 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002809 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002810 }
2811
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002812 if (renderer)
2813 it->second->Start(renderer);
2814 else
2815 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002816
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002817 return true;
2818}
2819
2820bool WebRtcVoiceMediaChannel::GetActiveStreams(
2821 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002822 // In conference mode, the default channel should not be in
2823 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002824 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002825 for (ChannelMap::iterator it = receive_channels_.begin();
2826 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002827 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002828 if (level > 0) {
2829 actives->push_back(std::make_pair(it->first, level));
2830 }
2831 }
2832 return true;
2833}
2834
2835int WebRtcVoiceMediaChannel::GetOutputLevel() {
2836 // return the highest output level of all streams
2837 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002838 for (ChannelMap::iterator it = receive_channels_.begin();
2839 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002840 int level = GetOutputLevel(it->second->channel());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002841 highest = rtc::_max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002842 }
2843 return highest;
2844}
2845
2846int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2847 int ret;
2848 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2849 // In case of error, log the info and continue
2850 LOG_RTCERR0(TimeSinceLastTyping);
2851 ret = -1;
2852 } else {
2853 ret *= 1000; // We return ms, webrtc returns seconds.
2854 }
2855 return ret;
2856}
2857
2858void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2859 int cost_per_typing, int reporting_threshold, int penalty_decay,
2860 int type_event_delay) {
2861 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2862 time_window, cost_per_typing,
2863 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2864 // In case of error, log the info and continue
2865 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2866 cost_per_typing, reporting_threshold, penalty_decay,
2867 type_event_delay);
2868 }
2869}
2870
2871bool WebRtcVoiceMediaChannel::SetOutputScaling(
2872 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002873 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002874 // Collect the channels to scale the output volume.
2875 std::vector<int> channels;
2876 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002877 // Default channel is not in receive_channels_ if it is not being used for
2878 // playout.
2879 if (default_receive_ssrc_ == 0)
2880 channels.push_back(voe_channel());
2881 for (ChannelMap::const_iterator it = receive_channels_.begin();
2882 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002883 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002884 }
2885 } else { // Collect only the channel of the specified ssrc.
2886 int channel = GetReceiveChannelNum(ssrc);
2887 if (-1 == channel) {
2888 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2889 return false;
2890 }
2891 channels.push_back(channel);
2892 }
2893
2894 // Scale the output volume for the collected channels. We first normalize to
2895 // scale the volume and then set the left and right pan.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002896 float scale = static_cast<float>(rtc::_max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002897 if (scale > 0.0001f) {
2898 left /= scale;
2899 right /= scale;
2900 }
2901 for (std::vector<int>::const_iterator it = channels.begin();
2902 it != channels.end(); ++it) {
2903 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2904 *it, scale)) {
2905 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2906 return false;
2907 }
2908 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2909 *it, static_cast<float>(left), static_cast<float>(right))) {
2910 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2911 // Do not return if fails. SetOutputVolumePan is not available for all
2912 // pltforms.
2913 }
2914 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2915 << " right=" << right * scale
2916 << " for channel " << *it << " and ssrc " << ssrc;
2917 }
2918 return true;
2919}
2920
2921bool WebRtcVoiceMediaChannel::GetOutputScaling(
2922 uint32 ssrc, double* left, double* right) {
2923 if (!left || !right) return false;
2924
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002925 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002926 // Determine which channel based on ssrc.
2927 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2928 if (channel == -1) {
2929 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2930 return false;
2931 }
2932
2933 float scaling;
2934 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2935 channel, scaling)) {
2936 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2937 return false;
2938 }
2939
2940 float left_pan;
2941 float right_pan;
2942 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2943 channel, left_pan, right_pan)) {
2944 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2945 // If GetOutputVolumePan fails, we use the default left and right pan.
2946 left_pan = 1.0f;
2947 right_pan = 1.0f;
2948 }
2949
2950 *left = scaling * left_pan;
2951 *right = scaling * right_pan;
2952 return true;
2953}
2954
2955bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2956 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2957 return true;
2958}
2959
2960bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2961 bool play, bool loop) {
2962 if (!ringback_tone_) {
2963 return false;
2964 }
2965
2966 // The voe file api is not available in chrome.
2967 if (!engine()->voe()->file()) {
2968 return false;
2969 }
2970
2971 // Determine which VoiceEngine channel to play on.
2972 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2973 if (channel == -1) {
2974 return false;
2975 }
2976
2977 // Make sure the ringtone is cued properly, and play it out.
2978 if (play) {
2979 ringback_tone_->set_loop(loop);
2980 ringback_tone_->Rewind();
2981 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2982 ringback_tone_.get()) == -1) {
2983 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2984 LOG(LS_ERROR) << "Unable to start ringback tone";
2985 return false;
2986 }
2987 ringback_channels_.insert(channel);
2988 LOG(LS_INFO) << "Started ringback on channel " << channel;
2989 } else {
2990 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2991 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2992 LOG_RTCERR1(StopPlayingFileLocally, channel);
2993 return false;
2994 }
2995 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2996 ringback_channels_.erase(channel);
2997 }
2998
2999 return true;
3000}
3001
3002bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3003 return dtmf_allowed_;
3004}
3005
3006bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3007 int duration, int flags) {
3008 if (!dtmf_allowed_) {
3009 return false;
3010 }
3011
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003012 // Send the event.
3013 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003014 int channel = -1;
3015 if (ssrc == 0) {
3016 bool default_channel_is_inuse = false;
3017 for (ChannelMap::const_iterator iter = send_channels_.begin();
3018 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003019 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003020 default_channel_is_inuse = true;
3021 break;
3022 }
3023 }
3024 if (default_channel_is_inuse) {
3025 channel = voe_channel();
3026 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003027 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003028 }
3029 } else {
3030 channel = GetSendChannelNum(ssrc);
3031 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003032 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003033 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3034 << ssrc << " is not in use.";
3035 return false;
3036 }
3037 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003038 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3039 channel, event, true, duration) == -1) {
3040 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003041 return false;
3042 }
3043 }
3044
3045 // Play the event.
3046 if (flags & cricket::DF_PLAY) {
3047 // Play DTMF tone locally.
3048 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3049 LOG_RTCERR2(PlayDtmfTone, event, duration);
3050 return false;
3051 }
3052 }
3053
3054 return true;
3055}
3056
wu@webrtc.orga9890802013-12-13 00:21:03 +00003057void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003058 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003059 // Pick which channel to send this packet to. If this packet doesn't match
3060 // any multiplexed streams, just send it to the default channel. Otherwise,
3061 // send it to the specific decoder instance for that stream.
3062 int which_channel = GetReceiveChannelNum(
3063 ParseSsrc(packet->data(), packet->length(), false));
3064 if (which_channel == -1) {
3065 which_channel = voe_channel();
3066 }
3067
3068 // Stop any ringback that might be playing on the channel.
3069 // It's possible the ringback has already stopped, ih which case we'll just
3070 // use the opportunity to remove the channel from ringback_channels_.
3071 if (engine()->voe()->file()) {
3072 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3073 if (it != ringback_channels_.end()) {
3074 if (engine()->voe()->file()->IsPlayingFileLocally(
3075 which_channel) == 1) {
3076 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3077 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3078 << " due to incoming media";
3079 }
3080 ringback_channels_.erase(which_channel);
3081 }
3082 }
3083
3084 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003085 engine()->voe()->network()->ReceivedRTPPacket(
3086 which_channel,
3087 packet->data(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003088 static_cast<unsigned int>(packet->length()),
3089 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003090}
3091
wu@webrtc.orga9890802013-12-13 00:21:03 +00003092void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003093 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003094 // Sending channels need all RTCP packets with feedback information.
3095 // Even sender reports can contain attached report blocks.
3096 // Receiving channels need sender reports in order to create
3097 // correct receiver reports.
3098 int type = 0;
3099 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3100 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3101 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003102 }
3103
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003104 // If it is a sender report, find the channel that is listening.
3105 bool has_sent_to_default_channel = false;
3106 if (type == kRtcpTypeSR) {
3107 int which_channel = GetReceiveChannelNum(
3108 ParseSsrc(packet->data(), packet->length(), true));
3109 if (which_channel != -1) {
3110 engine()->voe()->network()->ReceivedRTCPPacket(
3111 which_channel,
3112 packet->data(),
3113 static_cast<unsigned int>(packet->length()));
3114
3115 if (IsDefaultChannel(which_channel))
3116 has_sent_to_default_channel = true;
3117 }
3118 }
3119
3120 // SR may continue RR and any RR entry may correspond to any one of the send
3121 // channels. So all RTCP packets must be forwarded all send channels. VoE
3122 // will filter out RR internally.
3123 for (ChannelMap::iterator iter = send_channels_.begin();
3124 iter != send_channels_.end(); ++iter) {
3125 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003126 if (IsDefaultChannel(iter->second->channel()) &&
3127 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003128 continue;
3129
3130 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003131 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003132 packet->data(),
3133 static_cast<unsigned int>(packet->length()));
3134 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003135}
3136
3137bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003138 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3139 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003140 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3141 return false;
3142 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003143 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3144 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003145 return false;
3146 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003147 // We set the AGC to mute state only when all the channels are muted.
3148 // This implementation is not ideal, instead we should signal the AGC when
3149 // the mic channel is muted/unmuted. We can't do it today because there
3150 // is no good way to know which stream is mapping to the mic channel.
3151 bool all_muted = muted;
3152 for (ChannelMap::const_iterator iter = send_channels_.begin();
3153 iter != send_channels_.end() && all_muted; ++iter) {
3154 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3155 all_muted)) {
3156 LOG_RTCERR1(GetInputMute, iter->second->channel());
3157 return false;
3158 }
3159 }
3160
3161 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3162 if (ap)
3163 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003164 return true;
3165}
3166
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003167bool WebRtcVoiceMediaChannel::SetStartSendBandwidth(int bps) {
3168 // TODO(andresp): Add support for setting an independent start bandwidth when
3169 // bandwidth estimation is enabled for voice engine.
3170 return false;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003171}
3172
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003173bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
3174 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
3175
3176 return SetSendBandwidthInternal(bps);
3177}
3178
3179bool WebRtcVoiceMediaChannel::SetSendBandwidthInternal(int bps) {
3180 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBandwidthInternal.";
3181
3182 send_bw_setting_ = true;
3183 send_bw_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003184
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003185 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003186 LOG(LS_INFO) << "The send codec has not been set up yet. "
3187 << "The send bandwidth setting will be applied later.";
3188 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003189 }
3190
3191 // Bandwidth is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003192 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3193 // SetMaxSendBandwith(0), the second call removes the previous limit.
3194 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003195 return true;
3196
3197 webrtc::CodecInst codec = *send_codec_;
3198 bool is_multi_rate = IsCodecMultiRate(codec);
3199
3200 if (is_multi_rate) {
3201 // If codec is multi-rate then just set the bitrate.
3202 codec.rate = bps;
3203 if (!SetSendCodec(codec)) {
3204 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3205 << " to bitrate " << bps << " bps.";
3206 return false;
3207 }
3208 return true;
3209 } else {
3210 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3211 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3212 // fixed bitrate then ignore.
3213 if (bps < codec.rate) {
3214 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3215 << " to bitrate " << bps << " bps"
3216 << ", requires at least " << codec.rate << " bps.";
3217 return false;
3218 }
3219 return true;
3220 }
3221}
3222
3223bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003224 bool echo_metrics_on = false;
3225 // These can take on valid negative values, so use the lowest possible level
3226 // as default rather than -1.
3227 int echo_return_loss = -100;
3228 int echo_return_loss_enhancement = -100;
3229 // These can also be negative, but in practice -1 is only used to signal
3230 // insufficient data, since the resolution is limited to multiples of 4 ms.
3231 int echo_delay_median_ms = -1;
3232 int echo_delay_std_ms = -1;
3233 if (engine()->voe()->processing()->GetEcMetricsStatus(
3234 echo_metrics_on) != -1 && echo_metrics_on) {
3235 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3236 // here, but it appears to be unsuitable currently. Revisit after this is
3237 // investigated: http://b/issue?id=5666755
3238 int erl, erle, rerl, anlp;
3239 if (engine()->voe()->processing()->GetEchoMetrics(
3240 erl, erle, rerl, anlp) != -1) {
3241 echo_return_loss = erl;
3242 echo_return_loss_enhancement = erle;
3243 }
3244
3245 int median, std;
3246 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3247 echo_delay_median_ms = median;
3248 echo_delay_std_ms = std;
3249 }
3250 }
3251
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003252 webrtc::CallStatistics cs;
3253 unsigned int ssrc;
3254 webrtc::CodecInst codec;
3255 unsigned int level;
3256
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003257 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3258 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003259 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003260
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003261 // Fill in the sender info, based on what we know, and what the
3262 // remote side told us it got from its RTCP report.
3263 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003264
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003265 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3266 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3267 continue;
3268 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003269
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003270 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003271 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3272 sinfo.bytes_sent = cs.bytesSent;
3273 sinfo.packets_sent = cs.packetsSent;
3274 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3275 // returns 0 to indicate an error value.
3276 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3277
3278 // Get data from the last remote RTCP report. Use default values if no data
3279 // available.
3280 sinfo.fraction_lost = -1.0;
3281 sinfo.jitter_ms = -1;
3282 sinfo.packets_lost = -1;
3283 sinfo.ext_seqnum = -1;
3284 std::vector<webrtc::ReportBlock> receive_blocks;
3285 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3286 channel, &receive_blocks) != -1 &&
3287 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3288 std::vector<webrtc::ReportBlock>::iterator iter;
3289 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3290 ++iter) {
3291 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003292 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003293 // Convert Q8 to floating point.
3294 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3295 // Convert samples to milliseconds.
3296 if (codec.plfreq / 1000 > 0) {
3297 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3298 }
3299 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3300 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3301 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003302 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003303 }
3304 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003305
3306 // Local speech level.
3307 sinfo.audio_level = (engine()->voe()->volume()->
3308 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3309
3310 // TODO(xians): We are injecting the same APM logging to all the send
3311 // channels here because there is no good way to know which send channel
3312 // is using the APM. The correct fix is to allow the send channels to have
3313 // their own APM so that we can feed the correct APM logging to different
3314 // send channels. See issue crbug/264611 .
3315 sinfo.echo_return_loss = echo_return_loss;
3316 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3317 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3318 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003319 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3320 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003321 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003322
3323 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003324 }
3325
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003326 // Build the list of receivers, one for each receiving channel, or 1 in
3327 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003328 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003329 for (ChannelMap::const_iterator it = receive_channels_.begin();
3330 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003331 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003332 }
3333 if (channels.empty()) {
3334 channels.push_back(voe_channel());
3335 }
3336
3337 // Get the SSRC and stats for each receiver, based on our own calculations.
3338 for (std::vector<int>::const_iterator it = channels.begin();
3339 it != channels.end(); ++it) {
3340 memset(&cs, 0, sizeof(cs));
3341 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3342 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3343 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3344 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003345 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003346 rinfo.bytes_rcvd = cs.bytesReceived;
3347 rinfo.packets_rcvd = cs.packetsReceived;
3348 // The next four fields are from the most recently sent RTCP report.
3349 // Convert Q8 to floating point.
3350 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3351 rinfo.packets_lost = cs.cumulativeLost;
3352 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003353#ifdef USE_WEBRTC_DEV_BRANCH
3354 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
3355#endif
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003356 if (codec.pltype != -1) {
3357 rinfo.codec_name = codec.plname;
3358 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003359 // Convert samples to milliseconds.
3360 if (codec.plfreq / 1000 > 0) {
3361 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3362 }
3363
3364 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3365 webrtc::NetworkStatistics ns;
3366 if (engine()->voe()->neteq() &&
3367 engine()->voe()->neteq()->GetNetworkStatistics(
3368 *it, ns) != -1) {
3369 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3370 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3371 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003372 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003373 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003374
3375 webrtc::AudioDecodingCallStats ds;
3376 if (engine()->voe()->neteq() &&
3377 engine()->voe()->neteq()->GetDecodingCallStatistics(
3378 *it, &ds) != -1) {
3379 rinfo.decoding_calls_to_silence_generator =
3380 ds.calls_to_silence_generator;
3381 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3382 rinfo.decoding_normal = ds.decoded_normal;
3383 rinfo.decoding_plc = ds.decoded_plc;
3384 rinfo.decoding_cng = ds.decoded_cng;
3385 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3386 }
3387
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003388 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003389 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003390 int playout_buffer_delay_ms = 0;
3391 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003392 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3393 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3394 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003395 }
3396
3397 // Get speech level.
3398 rinfo.audio_level = (engine()->voe()->volume()->
3399 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3400 info->receivers.push_back(rinfo);
3401 }
3402 }
3403
3404 return true;
3405}
3406
3407void WebRtcVoiceMediaChannel::GetLastMediaError(
3408 uint32* ssrc, VoiceMediaChannel::Error* error) {
3409 ASSERT(ssrc != NULL);
3410 ASSERT(error != NULL);
3411 FindSsrc(voe_channel(), ssrc);
3412 *error = WebRtcErrorToChannelError(GetLastEngineError());
3413}
3414
3415bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003416 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003417 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003418 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003419 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3420 // This means the error is not limited to a specific channel. Signal the
3421 // message using ssrc=0. If the current channel is sending, use this
3422 // channel for sending the message.
3423 *ssrc = 0;
3424 return true;
3425 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003426 // Check whether this is a sending channel.
3427 for (ChannelMap::const_iterator it = send_channels_.begin();
3428 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003429 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003430 // This is a sending channel.
3431 uint32 local_ssrc = 0;
3432 if (engine()->voe()->rtp()->GetLocalSSRC(
3433 channel_num, local_ssrc) != -1) {
3434 *ssrc = local_ssrc;
3435 }
3436 return true;
3437 }
3438 }
3439
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003440 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003441 for (ChannelMap::const_iterator it = receive_channels_.begin();
3442 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003443 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003444 *ssrc = it->first;
3445 return true;
3446 }
3447 }
3448 }
3449 return false;
3450}
3451
3452void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003453 if (error == VE_TYPING_NOISE_WARNING) {
3454 typing_noise_detected_ = true;
3455 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3456 typing_noise_detected_ = false;
3457 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003458 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3459}
3460
3461int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3462 unsigned int ulevel;
3463 int ret =
3464 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3465 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3466}
3467
3468int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003469 ChannelMap::iterator it = receive_channels_.find(ssrc);
3470 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003471 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003472 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3473}
3474
3475int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003476 ChannelMap::iterator it = send_channels_.find(ssrc);
3477 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003478 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003479
3480 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003481}
3482
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003483bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
3484 webrtc::VideoEngine* vie, int vie_channel) {
3485 shared_bwe_vie_ = vie;
3486 shared_bwe_vie_channel_ = vie_channel;
3487
3488 if (!SetupSharedBweOnChannel(voe_channel())) {
3489 return false;
3490 }
3491 for (ChannelMap::iterator it = receive_channels_.begin();
3492 it != receive_channels_.end(); ++it) {
3493 if (!SetupSharedBweOnChannel(it->second->channel())) {
3494 return false;
3495 }
3496 }
3497 return true;
3498}
3499
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003500bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3501 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3502 // Get the RED encodings from the parameter with no name. This may
3503 // change based on what is discussed on the Jingle list.
3504 // The encoding parameter is of the form "a/b"; we only support where
3505 // a == b. Verify this and parse out the value into red_pt.
3506 // If the parameter value is absent (as it will be until we wire up the
3507 // signaling of this message), use the second codec specified (i.e. the
3508 // one after "red") as the encoding parameter.
3509 int red_pt = -1;
3510 std::string red_params;
3511 CodecParameterMap::const_iterator it = red_codec.params.find("");
3512 if (it != red_codec.params.end()) {
3513 red_params = it->second;
3514 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003515 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003516 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003517 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003518 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3519 return false;
3520 }
3521 } else if (red_codec.params.empty()) {
3522 LOG(LS_WARNING) << "RED params not present, using defaults";
3523 if (all_codecs.size() > 1) {
3524 red_pt = all_codecs[1].id;
3525 }
3526 }
3527
3528 // Try to find red_pt in |codecs|.
3529 std::vector<AudioCodec>::const_iterator codec;
3530 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3531 if (codec->id == red_pt)
3532 break;
3533 }
3534
3535 // If we find the right codec, that will be the codec we pass to
3536 // SetSendCodec, with the desired payload type.
3537 if (codec != all_codecs.end() &&
3538 engine()->FindWebRtcCodec(*codec, send_codec)) {
3539 } else {
3540 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3541 return false;
3542 }
3543
3544 return true;
3545}
3546
3547bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3548 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003549 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003550 return false;
3551 }
3552 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3553 // what we want to do with them.
3554 // engine()->voe().EnableVQMon(voe_channel(), true);
3555 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3556 return true;
3557}
3558
3559bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3560 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3561 for (int i = 0; i < ncodecs; ++i) {
3562 webrtc::CodecInst voe_codec;
3563 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3564 voe_codec.pltype = -1;
3565 if (engine()->voe()->codec()->SetRecPayloadType(
3566 channel, voe_codec) == -1) {
3567 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3568 return false;
3569 }
3570 }
3571 }
3572 return true;
3573}
3574
3575bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3576 if (playout) {
3577 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3578 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3579 LOG_RTCERR1(StartPlayout, channel);
3580 return false;
3581 }
3582 } else {
3583 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3584 engine()->voe()->base()->StopPlayout(channel);
3585 }
3586 return true;
3587}
3588
3589uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3590 bool rtcp) {
3591 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3592 uint32 ssrc = 0;
3593 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003594 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003595 }
3596 return ssrc;
3597}
3598
3599// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3600VoiceMediaChannel::Error
3601 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3602 switch (err_code) {
3603 case 0:
3604 return ERROR_NONE;
3605 case VE_CANNOT_START_RECORDING:
3606 case VE_MIC_VOL_ERROR:
3607 case VE_GET_MIC_VOL_ERROR:
3608 case VE_CANNOT_ACCESS_MIC_VOL:
3609 return ERROR_REC_DEVICE_OPEN_FAILED;
3610 case VE_SATURATION_WARNING:
3611 return ERROR_REC_DEVICE_SATURATION;
3612 case VE_REC_DEVICE_REMOVED:
3613 return ERROR_REC_DEVICE_REMOVED;
3614 case VE_RUNTIME_REC_WARNING:
3615 case VE_RUNTIME_REC_ERROR:
3616 return ERROR_REC_RUNTIME_ERROR;
3617 case VE_CANNOT_START_PLAYOUT:
3618 case VE_SPEAKER_VOL_ERROR:
3619 case VE_GET_SPEAKER_VOL_ERROR:
3620 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3621 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3622 case VE_RUNTIME_PLAY_WARNING:
3623 case VE_RUNTIME_PLAY_ERROR:
3624 return ERROR_PLAY_RUNTIME_ERROR;
3625 case VE_TYPING_NOISE_WARNING:
3626 return ERROR_REC_TYPING_NOISE_DETECTED;
3627 default:
3628 return VoiceMediaChannel::ERROR_OTHER;
3629 }
3630}
3631
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003632bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3633 int channel_id, const RtpHeaderExtension* extension) {
3634 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003635 int id = 0;
3636 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003637 if (extension) {
3638 enable = true;
3639 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003640 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003641 }
3642 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003643 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003644 return false;
3645 }
3646 return true;
3647}
3648
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003649bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
3650 webrtc::ViENetwork* vie_network = NULL;
3651 int vie_channel = -1;
3652 if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
3653 shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
3654 vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
3655 vie_channel = shared_bwe_vie_channel_;
3656 }
3657 if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
3658 vie_channel) == -1) {
3659 LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
3660 if (vie_network != NULL) {
3661 // Don't fail if we're tearing down.
3662 return false;
3663 }
3664 }
3665 return true;
3666}
3667
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003668int WebRtcSoundclipStream::Read(void *buf, int len) {
3669 size_t res = 0;
3670 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003671 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003672}
3673
3674int WebRtcSoundclipStream::Rewind() {
3675 mem_.Rewind();
3676 // Return -1 to keep VoiceEngine from looping.
3677 return (loop_) ? 0 : -1;
3678}
3679
3680} // namespace cricket
3681
3682#endif // HAVE_WEBRTC_VOICE