blob: 8cb85b6af127324f31209b33a110ec034f0fed0b [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
809 bool experimental_ns;
810 if (options.experimental_ns.Get(&experimental_ns)) {
811 webrtc::AudioProcessing* audioproc =
812 voe_wrapper_->base()->audio_processing();
buildbot@webrtc.orga8d8ad22014-07-16 14:23:08 +0000813#ifdef USE_WEBRTC_DEV_BRANCH
814 webrtc::Config config;
815 config.Set<webrtc::ExperimentalNs>(new webrtc::ExperimentalNs(
816 experimental_ns));
817 audioproc->SetExtraOptions(config);
818#else
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000819 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
820 // returns NULL on audio_processing().
821 if (audioproc) {
822 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
823 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
824 return false;
825 }
826 } else {
827 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
828 << experimental_ns;
829 }
buildbot@webrtc.orga8d8ad22014-07-16 14:23:08 +0000830#endif
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000831 }
832
833 bool highpass_filter;
834 if (options.highpass_filter.Get(&highpass_filter)) {
835 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
836 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
837 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
838 return false;
839 }
840 }
841
842 bool stereo_swapping;
843 if (options.stereo_swapping.Get(&stereo_swapping)) {
844 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
845 voep->EnableStereoChannelSwapping(stereo_swapping);
846 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
847 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
848 return false;
849 }
850 }
851
852 bool typing_detection;
853 if (options.typing_detection.Get(&typing_detection)) {
854 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
855 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
856 // In case of error, log the info and continue
857 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
858 }
859 }
860
861 int adjust_agc_delta;
862 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
863 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
864 if (!AdjustAgcLevel(adjust_agc_delta)) {
865 return false;
866 }
867 }
868
869 bool aec_dump;
870 if (options.aec_dump.Get(&aec_dump)) {
871 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
872 if (aec_dump)
873 StartAecDump(kAecDumpByAudioOptionFilename);
874 else
875 StopAecDump();
876 }
877
878 bool experimental_aec;
879 if (options.experimental_aec.Get(&experimental_aec)) {
880 LOG(LS_INFO) << "Experimental aec is " << experimental_aec;
881 webrtc::AudioProcessing* audioproc =
882 voe_wrapper_->base()->audio_processing();
883 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
884 // returns NULL on audio_processing().
885 if (audioproc) {
886 webrtc::Config config;
887 config.Set<webrtc::DelayCorrection>(
888 new webrtc::DelayCorrection(experimental_aec));
889 audioproc->SetExtraOptions(config);
890 }
891 }
892
893 uint32 recording_sample_rate;
894 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
895 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
896 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
897 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
898 }
899 }
900
901 uint32 playout_sample_rate;
902 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
903 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
904 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
905 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
906 }
907 }
908
909 return true;
910}
911
912bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
913 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
914 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
915 LOG_RTCERR1(SetDelayOffsetMs, offset);
916 return false;
917 }
918
919 return true;
920}
921
922struct ResumeEntry {
923 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
924 : channel(c),
925 playout(p),
926 send(s) {
927 }
928
929 WebRtcVoiceMediaChannel *channel;
930 bool playout;
931 SendFlags send;
932};
933
934// TODO(juberti): Refactor this so that the core logic can be used to set the
935// soundclip device. At that time, reinstate the soundclip pause/resume code.
936bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
937 const Device* out_device) {
938#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000939 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000940 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000941 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000942 kDefaultAudioDeviceId;
943 // The device manager uses -1 as the default device, which was the case for
944 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
945#ifndef WIN32
946 if (-1 == in_id) {
947 in_id = kDefaultAudioDeviceId;
948 }
949 if (-1 == out_id) {
950 out_id = kDefaultAudioDeviceId;
951 }
952#endif
953
954 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
955 in_device->name : "Default device";
956 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
957 out_device->name : "Default device";
958 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
959 << ") and speaker to (id=" << out_id << ", name=" << out_name
960 << ")";
961
962 // If we're running the local monitor, we need to stop it first.
963 bool ret = true;
964 if (!PauseLocalMonitor()) {
965 LOG(LS_WARNING) << "Failed to pause local monitor";
966 ret = false;
967 }
968
969 // Must also pause all audio playback and capture.
970 for (ChannelList::const_iterator i = channels_.begin();
971 i != channels_.end(); ++i) {
972 WebRtcVoiceMediaChannel *channel = *i;
973 if (!channel->PausePlayout()) {
974 LOG(LS_WARNING) << "Failed to pause playout";
975 ret = false;
976 }
977 if (!channel->PauseSend()) {
978 LOG(LS_WARNING) << "Failed to pause send";
979 ret = false;
980 }
981 }
982
983 // Find the recording device id in VoiceEngine and set recording device.
984 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
985 ret = false;
986 }
987 if (ret) {
988 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
989 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
990 ret = false;
991 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +0000992 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
993 if (ap)
994 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000995 }
996
997 // Find the playout device id in VoiceEngine and set playout device.
998 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
999 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1000 ret = false;
1001 }
1002 if (ret) {
1003 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001004 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001005 ret = false;
1006 }
1007 }
1008
1009 // Resume all audio playback and capture.
1010 for (ChannelList::const_iterator i = channels_.begin();
1011 i != channels_.end(); ++i) {
1012 WebRtcVoiceMediaChannel *channel = *i;
1013 if (!channel->ResumePlayout()) {
1014 LOG(LS_WARNING) << "Failed to resume playout";
1015 ret = false;
1016 }
1017 if (!channel->ResumeSend()) {
1018 LOG(LS_WARNING) << "Failed to resume send";
1019 ret = false;
1020 }
1021 }
1022
1023 // Resume local monitor.
1024 if (!ResumeLocalMonitor()) {
1025 LOG(LS_WARNING) << "Failed to resume local monitor";
1026 ret = false;
1027 }
1028
1029 if (ret) {
1030 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1031 << ") and speaker to (id="<< out_id << " name=" << out_name
1032 << ")";
1033 }
1034
1035 return ret;
1036#else
1037 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001038#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039}
1040
1041bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1042 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1043 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001044#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001045 *rtc_id = dev_id;
1046 return true;
1047#else
1048 // In Windows and Mac, we need to find the VoiceEngine device id by name
1049 // unless the input dev_id is the default device id.
1050 if (kDefaultAudioDeviceId == dev_id) {
1051 *rtc_id = dev_id;
1052 return true;
1053 }
1054
1055 // Get the number of VoiceEngine audio devices.
1056 int count = 0;
1057 if (is_input) {
1058 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1059 LOG_RTCERR0(GetNumOfRecordingDevices);
1060 return false;
1061 }
1062 } else {
1063 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1064 LOG_RTCERR0(GetNumOfPlayoutDevices);
1065 return false;
1066 }
1067 }
1068
1069 for (int i = 0; i < count; ++i) {
1070 char name[128];
1071 char guid[128];
1072 if (is_input) {
1073 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1074 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1075 } else {
1076 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1077 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1078 }
1079
1080 std::string webrtc_name(name);
1081 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1082 *rtc_id = i;
1083 return true;
1084 }
1085 }
1086 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1087 return false;
1088#endif
1089}
1090
1091bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1092 unsigned int ulevel;
1093 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1094 LOG_RTCERR1(GetSpeakerVolume, level);
1095 return false;
1096 }
1097 *level = ulevel;
1098 return true;
1099}
1100
1101bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1102 ASSERT(level >= 0 && level <= 255);
1103 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1104 LOG_RTCERR1(SetSpeakerVolume, level);
1105 return false;
1106 }
1107 return true;
1108}
1109
1110int WebRtcVoiceEngine::GetInputLevel() {
1111 unsigned int ulevel;
1112 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1113 static_cast<int>(ulevel) : -1;
1114}
1115
1116bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1117 desired_local_monitor_enable_ = enable;
1118 return ChangeLocalMonitor(desired_local_monitor_enable_);
1119}
1120
1121bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1122 // The voe file api is not available in chrome.
1123 if (!voe_wrapper_->file()) {
1124 return false;
1125 }
1126 if (enable && !monitor_) {
1127 monitor_.reset(new WebRtcMonitorStream);
1128 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1129 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1130 // Must call Stop() because there are some cases where Start will report
1131 // failure but still change the state, and if we leave VE in the on state
1132 // then it could crash later when trying to invoke methods on our monitor.
1133 voe_wrapper_->file()->StopRecordingMicrophone();
1134 monitor_.reset();
1135 return false;
1136 }
1137 } else if (!enable && monitor_) {
1138 voe_wrapper_->file()->StopRecordingMicrophone();
1139 monitor_.reset();
1140 }
1141 return true;
1142}
1143
1144bool WebRtcVoiceEngine::PauseLocalMonitor() {
1145 return ChangeLocalMonitor(false);
1146}
1147
1148bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1149 return ChangeLocalMonitor(desired_local_monitor_enable_);
1150}
1151
1152const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1153 return codecs_;
1154}
1155
1156bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1157 return FindWebRtcCodec(in, NULL);
1158}
1159
1160// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1161bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1162 webrtc::CodecInst* out) {
1163 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1164 for (int i = 0; i < ncodecs; ++i) {
1165 webrtc::CodecInst voe_codec;
1166 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1167 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1168 voe_codec.rate, voe_codec.channels, 0);
1169 bool multi_rate = IsCodecMultiRate(voe_codec);
1170 // Allow arbitrary rates for ISAC to be specified.
1171 if (multi_rate) {
1172 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1173 codec.bitrate = 0;
1174 }
1175 if (codec.Matches(in)) {
1176 if (out) {
1177 // Fixup the payload type.
1178 voe_codec.pltype = in.id;
1179
1180 // Set bitrate if specified.
1181 if (multi_rate && in.bitrate != 0) {
1182 voe_codec.rate = in.bitrate;
1183 }
1184
1185 // Apply codec-specific settings.
1186 if (IsIsac(codec)) {
1187 // If ISAC and an explicit bitrate is not specified,
1188 // enable auto bandwidth adjustment.
1189 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1190 }
1191 *out = voe_codec;
1192 }
1193 return true;
1194 }
1195 }
1196 }
1197 return false;
1198}
1199const std::vector<RtpHeaderExtension>&
1200WebRtcVoiceEngine::rtp_header_extensions() const {
1201 return rtp_header_extensions_;
1202}
1203
1204void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1205 // if min_sev == -1, we keep the current log level.
1206 if (min_sev >= 0) {
1207 SetTraceFilter(SeverityToFilter(min_sev));
1208 }
1209 log_options_ = filter;
1210 SetTraceOptions(initialized_ ? log_options_ : "");
1211}
1212
1213int WebRtcVoiceEngine::GetLastEngineError() {
1214 return voe_wrapper_->error();
1215}
1216
1217void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1218 log_filter_ = filter;
1219 tracing_->SetTraceFilter(filter);
1220}
1221
1222// We suppport three different logging settings for VoiceEngine:
1223// 1. Observer callback that goes into talk diagnostic logfile.
1224// Use --logfile and --loglevel
1225//
1226// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1227// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1228//
1229// 3. EC log and dump for debugging QualityEngine.
1230// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1231//
1232// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1233// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1234void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1235 // Set encrypted trace file.
1236 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001237 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001238 std::vector<std::string>::iterator tracefile =
1239 std::find(opts.begin(), opts.end(), "tracefile");
1240 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1241 // Write encrypted debug output (at same loglevel) to file
1242 // EncryptedTraceFile no longer supported.
1243 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1244 LOG_RTCERR1(SetTraceFile, *tracefile);
1245 }
1246 }
1247
wu@webrtc.org97077a32013-10-25 21:18:33 +00001248 // Allow trace options to override the trace filter. We default
1249 // it to log_filter_ (as a translation of libjingle log levels)
1250 // elsewhere, but this allows clients to explicitly set webrtc
1251 // log levels.
1252 std::vector<std::string>::iterator tracefilter =
1253 std::find(opts.begin(), opts.end(), "tracefilter");
1254 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001255 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001256 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1257 }
1258 }
1259
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001260 // Set AEC dump file
1261 std::vector<std::string>::iterator recordEC =
1262 std::find(opts.begin(), opts.end(), "recordEC");
1263 if (recordEC != opts.end()) {
1264 ++recordEC;
1265 if (recordEC != opts.end())
1266 StartAecDump(recordEC->c_str());
1267 else
1268 StopAecDump();
1269 }
1270}
1271
1272// Ignore spammy trace messages, mostly from the stats API when we haven't
1273// gotten RTCP info yet from the remote side.
1274bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1275 static const char* kTracesToIgnore[] = {
1276 "\tfailed to GetReportBlockInformation",
1277 "GetRecCodec() failed to get received codec",
1278 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1279 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1280 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1281 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1282 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1283 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1284 "SenderInfoReceived No received SR",
1285 "StatisticsRTP() no statistics available",
1286 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1287 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1288 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1289 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1290 NULL
1291 };
1292 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1293 if (trace.find(*p) != std::string::npos) {
1294 return true;
1295 }
1296 }
1297 return false;
1298}
1299
1300void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1301 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001302 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001303 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001304 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001305 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001306 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001307 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001308 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001309 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001310 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311
1312 // Skip past boilerplate prefix text
1313 if (length < 72) {
1314 std::string msg(trace, length);
1315 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1316 LOG_V(sev) << msg;
1317 } else {
1318 std::string msg(trace + 71, length - 72);
1319 if (!ShouldIgnoreTrace(msg)) {
1320 LOG_V(sev) << "webrtc: " << msg;
1321 }
1322 }
1323}
1324
1325void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001326 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001327 WebRtcVoiceMediaChannel* channel = NULL;
1328 uint32 ssrc = 0;
1329 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1330 << channel_num << ".";
1331 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1332 ASSERT(channel != NULL);
1333 channel->OnError(ssrc, err_code);
1334 } else {
1335 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1336 << " could not be found in channel list when error reported.";
1337 }
1338}
1339
1340bool WebRtcVoiceEngine::FindChannelAndSsrc(
1341 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1342 ASSERT(channel != NULL && ssrc != NULL);
1343
1344 *channel = NULL;
1345 *ssrc = 0;
1346 // Find corresponding channel and ssrc
1347 for (ChannelList::const_iterator it = channels_.begin();
1348 it != channels_.end(); ++it) {
1349 ASSERT(*it != NULL);
1350 if ((*it)->FindSsrc(channel_num, ssrc)) {
1351 *channel = *it;
1352 return true;
1353 }
1354 }
1355
1356 return false;
1357}
1358
1359// This method will search through the WebRtcVoiceMediaChannels and
1360// obtain the voice engine's channel number.
1361bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1362 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1363 ASSERT(channel_num != NULL);
1364 ASSERT(direction == MPD_RX || direction == MPD_TX);
1365
1366 *channel_num = -1;
1367 // Find corresponding channel for ssrc.
1368 for (ChannelList::const_iterator it = channels_.begin();
1369 it != channels_.end(); ++it) {
1370 ASSERT(*it != NULL);
1371 if (direction & MPD_RX) {
1372 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1373 }
1374 if (*channel_num == -1 && (direction & MPD_TX)) {
1375 *channel_num = (*it)->GetSendChannelNum(ssrc);
1376 }
1377 if (*channel_num != -1) {
1378 return true;
1379 }
1380 }
1381 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1382 return false;
1383}
1384
1385void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001386 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001387 channels_.push_back(channel);
1388}
1389
1390void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001391 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392 ChannelList::iterator i = std::find(channels_.begin(),
1393 channels_.end(),
1394 channel);
1395 if (i != channels_.end()) {
1396 channels_.erase(i);
1397 }
1398}
1399
1400void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1401 soundclips_.push_back(soundclip);
1402}
1403
1404void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1405 SoundclipList::iterator i = std::find(soundclips_.begin(),
1406 soundclips_.end(),
1407 soundclip);
1408 if (i != soundclips_.end()) {
1409 soundclips_.erase(i);
1410 }
1411}
1412
1413// Adjusts the default AGC target level by the specified delta.
1414// NB: If we start messing with other config fields, we'll want
1415// to save the current webrtc::AgcConfig as well.
1416bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1417 webrtc::AgcConfig config = default_agc_config_;
1418 config.targetLeveldBOv -= delta;
1419
1420 LOG(LS_INFO) << "Adjusting AGC level from default -"
1421 << default_agc_config_.targetLeveldBOv << "dB to -"
1422 << config.targetLeveldBOv << "dB";
1423
1424 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1425 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1426 return false;
1427 }
1428 return true;
1429}
1430
1431bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1432 webrtc::AudioDeviceModule* adm_sc) {
1433 if (initialized_) {
1434 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1435 return false;
1436 }
1437 if (adm_) {
1438 adm_->Release();
1439 adm_ = NULL;
1440 }
1441 if (adm) {
1442 adm_ = adm;
1443 adm_->AddRef();
1444 }
1445
1446 if (adm_sc_) {
1447 adm_sc_->Release();
1448 adm_sc_ = NULL;
1449 }
1450 if (adm_sc) {
1451 adm_sc_ = adm_sc;
1452 adm_sc_->AddRef();
1453 }
1454 return true;
1455}
1456
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001457bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1458 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001459 if (!aec_dump_file_stream) {
1460 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001461 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001462 LOG(LS_WARNING) << "Could not close file.";
1463 return false;
1464 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001465 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001466 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001467 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001468 LOG_RTCERR0(StartDebugRecording);
1469 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001470 return false;
1471 }
1472 is_dumping_aec_ = true;
1473 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001474}
1475
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001476bool WebRtcVoiceEngine::RegisterProcessor(
1477 uint32 ssrc,
1478 VoiceProcessor* voice_processor,
1479 MediaProcessorDirection direction) {
1480 bool register_with_webrtc = false;
1481 int channel_id = -1;
1482 bool success = false;
1483 uint32* processor_ssrc = NULL;
1484 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1485 if (voice_processor == NULL || !found_channel) {
1486 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1487 << " foundChannel: " << found_channel;
1488 return false;
1489 }
1490
1491 webrtc::ProcessingTypes processing_type;
1492 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001493 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001494 if (direction == MPD_RX) {
1495 processing_type = webrtc::kPlaybackAllChannelsMixed;
1496 if (SignalRxMediaFrame.is_empty()) {
1497 register_with_webrtc = true;
1498 processor_ssrc = &rx_processor_ssrc_;
1499 }
1500 SignalRxMediaFrame.connect(voice_processor,
1501 &VoiceProcessor::OnFrame);
1502 } else {
1503 processing_type = webrtc::kRecordingPerChannel;
1504 if (SignalTxMediaFrame.is_empty()) {
1505 register_with_webrtc = true;
1506 processor_ssrc = &tx_processor_ssrc_;
1507 }
1508 SignalTxMediaFrame.connect(voice_processor,
1509 &VoiceProcessor::OnFrame);
1510 }
1511 }
1512 if (register_with_webrtc) {
1513 // TODO(janahan): when registering consider instantiating a
1514 // a VoeMediaProcess object and not make the engine extend the interface.
1515 if (voe()->media() && voe()->media()->
1516 RegisterExternalMediaProcessing(channel_id,
1517 processing_type,
1518 *this) != -1) {
1519 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1520 << channel_id;
1521 *processor_ssrc = ssrc;
1522 success = true;
1523 } else {
1524 LOG_RTCERR2(RegisterExternalMediaProcessing,
1525 channel_id,
1526 processing_type);
1527 success = false;
1528 }
1529 } else {
1530 // If we don't have to register with the engine, we just needed to
1531 // connect a new processor, set success to true;
1532 success = true;
1533 }
1534 return success;
1535}
1536
1537bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1538 MediaProcessorDirection channel_direction,
1539 uint32 ssrc,
1540 VoiceProcessor* voice_processor,
1541 MediaProcessorDirection processor_direction) {
1542 bool success = true;
1543 FrameSignal* signal;
1544 webrtc::ProcessingTypes processing_type;
1545 uint32* processor_ssrc = NULL;
1546 if (channel_direction == MPD_RX) {
1547 signal = &SignalRxMediaFrame;
1548 processing_type = webrtc::kPlaybackAllChannelsMixed;
1549 processor_ssrc = &rx_processor_ssrc_;
1550 } else {
1551 signal = &SignalTxMediaFrame;
1552 processing_type = webrtc::kRecordingPerChannel;
1553 processor_ssrc = &tx_processor_ssrc_;
1554 }
1555
1556 int deregister_id = -1;
1557 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001558 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001559 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1560 signal->disconnect(voice_processor);
1561 int channel_id = -1;
1562 bool found_channel = FindChannelNumFromSsrc(ssrc,
1563 channel_direction,
1564 &channel_id);
1565 if (signal->is_empty() && found_channel) {
1566 deregister_id = channel_id;
1567 }
1568 }
1569 }
1570 if (deregister_id != -1) {
1571 if (voe()->media() &&
1572 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1573 processing_type) != -1) {
1574 *processor_ssrc = 0;
1575 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1576 << deregister_id;
1577 } else {
1578 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1579 deregister_id,
1580 processing_type);
1581 success = false;
1582 }
1583 }
1584 return success;
1585}
1586
1587bool WebRtcVoiceEngine::UnregisterProcessor(
1588 uint32 ssrc,
1589 VoiceProcessor* voice_processor,
1590 MediaProcessorDirection direction) {
1591 bool success = true;
1592 if (voice_processor == NULL) {
1593 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1594 << ssrc;
1595 return false;
1596 }
1597 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1598 success = false;
1599 }
1600 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1601 success = false;
1602 }
1603 return success;
1604}
1605
1606// Implementing method from WebRtc VoEMediaProcess interface
1607// Do not lock mux_channel_cs_ in this callback.
1608void WebRtcVoiceEngine::Process(int channel,
1609 webrtc::ProcessingTypes type,
1610 int16_t audio10ms[],
1611 int length,
1612 int sampling_freq,
1613 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001614 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001615 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1616 if (type == webrtc::kPlaybackAllChannelsMixed) {
1617 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1618 } else if (type == webrtc::kRecordingPerChannel) {
1619 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1620 } else {
1621 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1622 << " channel: " << channel << " type: " << type
1623 << " tx_ssrc: " << tx_processor_ssrc_
1624 << " rx_ssrc: " << rx_processor_ssrc_;
1625 }
1626}
1627
1628void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1629 if (!is_dumping_aec_) {
1630 // Start dumping AEC when we are not dumping.
1631 if (voe_wrapper_->processing()->StartDebugRecording(
1632 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001633 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001634 } else {
1635 is_dumping_aec_ = true;
1636 }
1637 }
1638}
1639
1640void WebRtcVoiceEngine::StopAecDump() {
1641 if (is_dumping_aec_) {
1642 // Stop dumping AEC when we are dumping.
1643 if (voe_wrapper_->processing()->StopDebugRecording() !=
1644 webrtc::AudioProcessing::kNoError) {
1645 LOG_RTCERR0(StopDebugRecording);
1646 }
1647 is_dumping_aec_ = false;
1648 }
1649}
1650
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001651int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001652 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001653}
1654
1655int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1656 return CreateVoiceChannel(voe_wrapper_.get());
1657}
1658
1659int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1660 return CreateVoiceChannel(voe_wrapper_sc_.get());
1661}
1662
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001663class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1664 : public AudioRenderer::Sink {
1665 public:
1666 WebRtcVoiceChannelRenderer(int ch,
1667 webrtc::AudioTransport* voe_audio_transport)
1668 : channel_(ch),
1669 voe_audio_transport_(voe_audio_transport),
1670 renderer_(NULL) {
1671 }
1672 virtual ~WebRtcVoiceChannelRenderer() {
1673 Stop();
1674 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001675
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001676 // Starts the rendering by setting a sink to the renderer to get data
1677 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001678 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001679 // TODO(xians): Make sure Start() is called only once.
1680 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001681 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001682 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001683 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001684 ASSERT(renderer_ == renderer);
1685 return;
1686 }
1687
1688 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1689 // in getUserMedia by default.
1690 renderer->AddChannel(channel_);
1691 renderer->SetSink(this);
1692 renderer_ = renderer;
1693 }
1694
1695 // Stops rendering by setting the sink of the renderer to NULL. No data
1696 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001697 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001698 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001699 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001700 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001701 return;
1702
1703 renderer_->RemoveChannel(channel_);
1704 renderer_->SetSink(NULL);
1705 renderer_ = NULL;
1706 }
1707
1708 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001709 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001710 virtual void OnData(const void* audio_data,
1711 int bits_per_sample,
1712 int sample_rate,
1713 int number_of_channels,
1714 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001715 voe_audio_transport_->OnData(channel_,
1716 audio_data,
1717 bits_per_sample,
1718 sample_rate,
1719 number_of_channels,
1720 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001721 }
1722
1723 // Callback from the |renderer_| when it is going away. In case Start() has
1724 // never been called, this callback won't be triggered.
1725 virtual void OnClose() OVERRIDE {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001726 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001727 // Set |renderer_| to NULL to make sure no more callback will get into
1728 // the renderer.
1729 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001730 }
1731
1732 // Accessor to the VoE channel ID.
1733 int channel() const { return channel_; }
1734
1735 private:
1736 const int channel_;
1737 webrtc::AudioTransport* const voe_audio_transport_;
1738
1739 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1740 // PeerConnection will make sure invalidating the pointer before the object
1741 // goes away.
1742 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001743
1744 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001745 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001746};
1747
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001748// WebRtcVoiceMediaChannel
1749WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1750 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1751 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001752 engine->CreateMediaVoiceChannel()),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001753 send_bw_setting_(false),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001754 send_bw_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001755 options_(),
1756 dtmf_allowed_(false),
1757 desired_playout_(false),
1758 nack_enabled_(false),
1759 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001760 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001761 desired_send_(SEND_NOTHING),
1762 send_(SEND_NOTHING),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001763 shared_bwe_vie_(NULL),
1764 shared_bwe_vie_channel_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001765 default_receive_ssrc_(0) {
1766 engine->RegisterChannel(this);
1767 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1768 << voe_channel();
1769
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001770 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001771}
1772
1773WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1774 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1775 << voe_channel();
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001776 ASSERT(shared_bwe_vie_ == NULL);
1777 ASSERT(shared_bwe_vie_channel_ == -1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001778
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001779 // Remove any remaining send streams, the default channel will be deleted
1780 // later.
1781 while (!send_channels_.empty())
1782 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001783
1784 // Unregister ourselves from the engine.
1785 engine()->UnregisterChannel(this);
1786 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001787 while (!receive_channels_.empty()) {
1788 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001789 }
1790
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001791 // Delete the default channel.
1792 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001793}
1794
1795bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1796 LOG(LS_INFO) << "Setting voice channel options: "
1797 << options.ToString();
1798
wu@webrtc.orgde305012013-10-31 15:40:38 +00001799 // Check if DSCP value is changed from previous.
1800 bool dscp_option_changed = (options_.dscp != options.dscp);
1801
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001802 // TODO(xians): Add support to set different options for different send
1803 // streams after we support multiple APMs.
1804
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001805 // We retain all of the existing options, and apply the given ones
1806 // on top. This means there is no way to "clear" options such that
1807 // they go back to the engine default.
1808 options_.SetAll(options);
1809
1810 if (send_ != SEND_NOTHING) {
1811 if (!engine()->SetOptionOverrides(options_)) {
1812 LOG(LS_WARNING) <<
1813 "Failed to engine SetOptionOverrides during channel SetOptions.";
1814 return false;
1815 }
1816 } else {
1817 // Will be interpreted when appropriate.
1818 }
1819
wu@webrtc.org97077a32013-10-25 21:18:33 +00001820 // Receiver-side auto gain control happens per channel, so set it here from
1821 // options. Note that, like conference mode, setting it on the engine won't
1822 // have the desired effect, since voice channels don't inherit options from
1823 // the media engine when those options are applied per-channel.
1824 bool rx_auto_gain_control;
1825 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1826 if (engine()->voe()->processing()->SetRxAgcStatus(
1827 voe_channel(), rx_auto_gain_control,
1828 webrtc::kAgcFixedDigital) == -1) {
1829 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1830 return false;
1831 } else {
1832 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1833 << " with mode " << webrtc::kAgcFixedDigital;
1834 }
1835 }
1836 if (options.rx_agc_target_dbov.IsSet() ||
1837 options.rx_agc_digital_compression_gain.IsSet() ||
1838 options.rx_agc_limiter.IsSet()) {
1839 webrtc::AgcConfig config;
1840 // If only some of the options are being overridden, get the current
1841 // settings for the channel and bail if they aren't available.
1842 if (!options.rx_agc_target_dbov.IsSet() ||
1843 !options.rx_agc_digital_compression_gain.IsSet() ||
1844 !options.rx_agc_limiter.IsSet()) {
1845 if (engine()->voe()->processing()->GetRxAgcConfig(
1846 voe_channel(), config) != 0) {
1847 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1848 << "channel " << voe_channel() << ". Since not all rx "
1849 << "agc options are specified, unable to safely set rx "
1850 << "agc options.";
1851 return false;
1852 }
1853 }
1854 config.targetLeveldBOv =
1855 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1856 config.targetLeveldBOv);
1857 config.digitalCompressionGaindB =
1858 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1859 config.digitalCompressionGaindB);
1860 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1861 config.limiterEnable);
1862 if (engine()->voe()->processing()->SetRxAgcConfig(
1863 voe_channel(), config) == -1) {
1864 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1865 config.digitalCompressionGaindB, config.limiterEnable);
1866 return false;
1867 }
1868 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001869 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001870 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001871 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001872 dscp = kAudioDscpValue;
1873 if (MediaChannel::SetDscp(dscp) != 0) {
1874 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1875 }
1876 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001877
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001878 // Force update of Video Engine BWE forwarding to reflect experiment setting.
1879 if (!SetupSharedBandwidthEstimation(shared_bwe_vie_,
1880 shared_bwe_vie_channel_)) {
1881 return false;
1882 }
1883
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001884 LOG(LS_INFO) << "Set voice channel options. Current options: "
1885 << options_.ToString();
1886 return true;
1887}
1888
1889bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1890 const std::vector<AudioCodec>& codecs) {
1891 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001892 LOG(LS_INFO) << "Setting receive voice codecs:";
1893
1894 std::vector<AudioCodec> new_codecs;
1895 // Find all new codecs. We allow adding new codecs but don't allow changing
1896 // the payload type of codecs that is already configured since we might
1897 // already be receiving packets with that payload type.
1898 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001899 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001900 AudioCodec old_codec;
1901 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1902 if (old_codec.id != it->id) {
1903 LOG(LS_ERROR) << it->name << " payload type changed.";
1904 return false;
1905 }
1906 } else {
1907 new_codecs.push_back(*it);
1908 }
1909 }
1910 if (new_codecs.empty()) {
1911 // There are no new codecs to configure. Already configured codecs are
1912 // never removed.
1913 return true;
1914 }
1915
1916 if (playout_) {
1917 // Receive codecs can not be changed while playing. So we temporarily
1918 // pause playout.
1919 PausePlayout();
1920 }
1921
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001922 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001923 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1924 it != new_codecs.end() && ret; ++it) {
1925 webrtc::CodecInst voe_codec;
1926 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1927 LOG(LS_INFO) << ToString(*it);
1928 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001929 if (default_receive_ssrc_ == 0) {
1930 // Set the receive codecs on the default channel explicitly if the
1931 // default channel is not used by |receive_channels_|, this happens in
1932 // conference mode or in non-conference mode when there is no playout
1933 // channel.
1934 // TODO(xians): Figure out how we use the default channel in conference
1935 // mode.
1936 if (engine()->voe()->codec()->SetRecPayloadType(
1937 voe_channel(), voe_codec) == -1) {
1938 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1939 ret = false;
1940 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001941 }
1942
1943 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001944 for (ChannelMap::iterator it = receive_channels_.begin();
1945 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001946 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001947 it->second->channel(), voe_codec) == -1) {
1948 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001949 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001950 ret = false;
1951 }
1952 }
1953 } else {
1954 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1955 ret = false;
1956 }
1957 }
1958 if (ret) {
1959 recv_codecs_ = codecs;
1960 }
1961
1962 if (desired_playout_ && !playout_) {
1963 ResumePlayout();
1964 }
1965 return ret;
1966}
1967
1968bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001969 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001970 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001971 engine()->voe()->codec()->SetVADStatus(channel, false);
1972 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001973#ifdef USE_WEBRTC_DEV_BRANCH
1974 engine()->voe()->rtp()->SetREDStatus(channel, false);
1975 engine()->voe()->codec()->SetFECStatus(channel, false);
1976#else
1977 // TODO(minyue): Remove code under #else case after new WebRTC roll.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001978 engine()->voe()->rtp()->SetFECStatus(channel, false);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001979#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001980
1981 // Scan through the list to figure out the codec to use for sending, along
1982 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001983 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001984 webrtc::CodecInst send_codec;
1985 memset(&send_codec, 0, sizeof(send_codec));
1986
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001987 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001988 bool enable_codec_fec = false;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001989
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001990 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001991 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1992 it != codecs.end(); ++it) {
1993 // Ignore codecs we don't know about. The negotiation step should prevent
1994 // this, but double-check to be sure.
1995 webrtc::CodecInst voe_codec;
1996 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001997 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001998 continue;
1999 }
2000
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002001 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2002 // Skip telephone-event/CN codec, which will be handled later.
2003 continue;
2004 }
2005
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002006 // If OPUS, change what we send according to the "stereo" codec
2007 // parameter, and not the "channels" parameter. We set
2008 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
2009 // the bitrate is not specified, i.e. is zero, we set it to the
2010 // appropriate default value for mono or stereo Opus.
2011 if (IsOpus(*it)) {
2012 if (IsOpusStereoEnabled(*it)) {
2013 voe_codec.channels = 2;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002014 if (!IsValidOpusBitrate(it->bitrate)) {
2015 if (it->bitrate != 0) {
2016 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2017 << it->bitrate
2018 << ") with default opus stereo bitrate: "
2019 << kOpusStereoBitrate;
2020 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002021 voe_codec.rate = kOpusStereoBitrate;
2022 }
2023 } else {
2024 voe_codec.channels = 1;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002025 if (!IsValidOpusBitrate(it->bitrate)) {
2026 if (it->bitrate != 0) {
2027 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2028 << it->bitrate
2029 << ") with default opus mono bitrate: "
2030 << kOpusMonoBitrate;
2031 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002032 voe_codec.rate = kOpusMonoBitrate;
2033 }
2034 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002035 int bitrate_from_params = GetOpusBitrateFromParams(*it);
2036 if (bitrate_from_params != 0) {
2037 voe_codec.rate = bitrate_from_params;
2038 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002039 }
2040
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002041 // We'll use the first codec in the list to actually send audio data.
2042 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002043 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002044 // used is specified in params.
2045 if (IsRedCodec(it->name)) {
2046 // Parse out the RED parameters. If we fail, just ignore RED;
2047 // we don't support all possible params/usage scenarios.
2048 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2049 continue;
2050 }
2051
2052 // Enable redundant encoding of the specified codec. Treat any
2053 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002054#ifdef USE_WEBRTC_DEV_BRANCH
2055 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2056 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2057 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
2058#else
2059 // TODO(minyue): Remove code under #else case after new WebRTC roll.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002060 LOG(LS_INFO) << "Enabling FEC";
2061 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2062 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002063#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002064 return false;
2065 }
2066 } else {
2067 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002068 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002069 // For Opus as the send codec, we enable inband FEC if requested.
2070 enable_codec_fec = IsOpus(*it) && IsOpusFecEnabled(*it);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002071 }
2072 found_send_codec = true;
2073 break;
2074 }
2075
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002076 if (nack_enabled_ != nack_enabled) {
2077 SetNack(channel, nack_enabled);
2078 nack_enabled_ = nack_enabled;
2079 }
2080
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002081 if (!found_send_codec) {
2082 LOG(LS_WARNING) << "Received empty list of codecs.";
2083 return false;
2084 }
2085
2086 // Set the codec immediately, since SetVADStatus() depends on whether
2087 // the current codec is mono or stereo.
2088 if (!SetSendCodec(channel, send_codec))
2089 return false;
2090
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002091 // FEC should be enabled after SetSendCodec.
2092 if (enable_codec_fec) {
2093 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2094 << channel;
2095#ifdef USE_WEBRTC_DEV_BRANCH
2096 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2097 // Enable codec internal FEC. Treat any failure as fatal internal error.
2098 LOG_RTCERR2(SetFECStatus, channel, true);
2099 return false;
2100 }
2101#endif // USE_WEBRTC_DEV_BRANCH
2102 }
2103
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002104 // Always update the |send_codec_| to the currently set send codec.
2105 send_codec_.reset(new webrtc::CodecInst(send_codec));
2106
2107 if (send_bw_setting_) {
2108 SetSendBandwidthInternal(send_bw_bps_);
2109 }
2110
2111 // Loop through the codecs list again to config the telephone-event/CN codec.
2112 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2113 it != codecs.end(); ++it) {
2114 // Ignore codecs we don't know about. The negotiation step should prevent
2115 // this, but double-check to be sure.
2116 webrtc::CodecInst voe_codec;
2117 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2118 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2119 continue;
2120 }
2121
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002122 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2123 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002124 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002125 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2126 channel, it->id) == -1) {
2127 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2128 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002129 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002130 } else if (IsCNCodec(it->name)) {
2131 // Turn voice activity detection/comfort noise on if supported.
2132 // Set the wideband CN payload type appropriately.
2133 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002134 webrtc::PayloadFrequencies cn_freq;
2135 switch (it->clockrate) {
2136 case 8000:
2137 cn_freq = webrtc::kFreq8000Hz;
2138 break;
2139 case 16000:
2140 cn_freq = webrtc::kFreq16000Hz;
2141 break;
2142 case 32000:
2143 cn_freq = webrtc::kFreq32000Hz;
2144 break;
2145 default:
2146 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2147 << " not supported.";
2148 continue;
2149 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002150 // Set the CN payloadtype and the VAD status.
2151 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2152 if (cn_freq != webrtc::kFreq8000Hz) {
2153 if (engine()->voe()->codec()->SetSendCNPayloadType(
2154 channel, it->id, cn_freq) == -1) {
2155 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2156 // TODO(ajm): This failure condition will be removed from VoE.
2157 // Restore the return here when we update to a new enough webrtc.
2158 //
2159 // Not returning false because the SetSendCNPayloadType will fail if
2160 // the channel is already sending.
2161 // This can happen if the remote description is applied twice, for
2162 // example in the case of ROAP on top of JSEP, where both side will
2163 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002164 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002165 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002166 // Only turn on VAD if we have a CN payload type that matches the
2167 // clockrate for the codec we are going to use.
2168 if (it->clockrate == send_codec.plfreq) {
2169 LOG(LS_INFO) << "Enabling VAD";
2170 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2171 LOG_RTCERR2(SetVADStatus, channel, true);
2172 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002173 }
2174 }
2175 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002176 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002177 return true;
2178}
2179
2180bool WebRtcVoiceMediaChannel::SetSendCodecs(
2181 const std::vector<AudioCodec>& codecs) {
2182 dtmf_allowed_ = false;
2183 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2184 it != codecs.end(); ++it) {
2185 // Find the DTMF telephone event "codec".
2186 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2187 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2188 dtmf_allowed_ = true;
2189 }
2190 }
2191
2192 // Cache the codecs in order to configure the channel created later.
2193 send_codecs_ = codecs;
2194 for (ChannelMap::iterator iter = send_channels_.begin();
2195 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002196 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002197 return false;
2198 }
2199 }
2200
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002201 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002202 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002203 return true;
2204}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002205
2206void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2207 bool nack_enabled) {
2208 for (ChannelMap::const_iterator it = channels.begin();
2209 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002210 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002211 }
2212}
2213
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002214void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002215 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002216 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002217 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2218 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002219 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002220 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2221 }
2222}
2223
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002224bool WebRtcVoiceMediaChannel::SetSendCodec(
2225 const webrtc::CodecInst& send_codec) {
2226 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2227 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002228 for (ChannelMap::iterator iter = send_channels_.begin();
2229 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002230 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002231 return false;
2232 }
2233
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002234 return true;
2235}
2236
2237bool WebRtcVoiceMediaChannel::SetSendCodec(
2238 int channel, const webrtc::CodecInst& send_codec) {
2239 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2240 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2241
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002242 webrtc::CodecInst current_codec;
2243 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2244 (send_codec == current_codec)) {
2245 // Codec is already configured, we can return without setting it again.
2246 return true;
2247 }
2248
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002249 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2250 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002251 return false;
2252 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002253 return true;
2254}
2255
2256bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2257 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002258 if (receive_extensions_ == extensions) {
2259 return true;
2260 }
2261
2262 // The default channel may or may not be in |receive_channels_|. Set the rtp
2263 // header extensions for default channel regardless.
2264 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2265 return false;
2266 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002267
2268 // Loop through all receive channels and enable/disable the extensions.
2269 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2270 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002271 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2272 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002273 return false;
2274 }
2275 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002276
2277 receive_extensions_ = extensions;
2278 return true;
2279}
2280
2281bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2282 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002283 const RtpHeaderExtension* audio_level_extension =
2284 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2285 if (!SetHeaderExtension(
2286 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2287 audio_level_extension)) {
2288 return false;
2289 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002290
2291 const RtpHeaderExtension* send_time_extension =
2292 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2293 if (!SetHeaderExtension(
2294 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2295 send_time_extension)) {
2296 return false;
2297 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002298 return true;
2299}
2300
2301bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2302 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002303 if (send_extensions_ == extensions) {
2304 return true;
2305 }
2306
2307 // The default channel may or may not be in |send_channels_|. Set the rtp
2308 // header extensions for default channel regardless.
2309
2310 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2311 return false;
2312 }
2313
2314 // Loop through all send channels and enable/disable the extensions.
2315 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2316 channel_it != send_channels_.end(); ++channel_it) {
2317 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2318 extensions)) {
2319 return false;
2320 }
2321 }
2322
2323 send_extensions_ = extensions;
2324 return true;
2325}
2326
2327bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2328 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002329 const RtpHeaderExtension* audio_level_extension =
2330 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002331
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002332 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002333 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002334 audio_level_extension)) {
2335 return false;
2336 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002337
2338 const RtpHeaderExtension* send_time_extension =
2339 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002340 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002341 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002342 send_time_extension)) {
2343 return false;
2344 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002345
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002346 return true;
2347}
2348
2349bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2350 desired_playout_ = playout;
2351 return ChangePlayout(desired_playout_);
2352}
2353
2354bool WebRtcVoiceMediaChannel::PausePlayout() {
2355 return ChangePlayout(false);
2356}
2357
2358bool WebRtcVoiceMediaChannel::ResumePlayout() {
2359 return ChangePlayout(desired_playout_);
2360}
2361
2362bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2363 if (playout_ == playout) {
2364 return true;
2365 }
2366
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002367 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002368 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002369 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002370 // Only toggle the default channel if we don't have any other channels.
2371 result = SetPlayout(voe_channel(), playout);
2372 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002373 for (ChannelMap::iterator it = receive_channels_.begin();
2374 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002375 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002376 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002377 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002378 result = false;
2379 }
2380 }
2381
2382 if (result) {
2383 playout_ = playout;
2384 }
2385 return result;
2386}
2387
2388bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2389 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002390 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002391 return ChangeSend(desired_send_);
2392 return true;
2393}
2394
2395bool WebRtcVoiceMediaChannel::PauseSend() {
2396 return ChangeSend(SEND_NOTHING);
2397}
2398
2399bool WebRtcVoiceMediaChannel::ResumeSend() {
2400 return ChangeSend(desired_send_);
2401}
2402
2403bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2404 if (send_ == send) {
2405 return true;
2406 }
2407
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002408 // Change the settings on each send channel.
2409 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002410 engine()->SetOptionOverrides(options_);
2411
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002412 // Change the settings on each send channel.
2413 for (ChannelMap::iterator iter = send_channels_.begin();
2414 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002415 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002416 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002417 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002418
2419 // Clear up the options after stopping sending.
2420 if (send == SEND_NOTHING)
2421 engine()->ClearOptionOverrides();
2422
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002423 send_ = send;
2424 return true;
2425}
2426
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002427bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2428 if (send == SEND_MICROPHONE) {
2429 if (engine()->voe()->base()->StartSend(channel) == -1) {
2430 LOG_RTCERR1(StartSend, channel);
2431 return false;
2432 }
2433 if (engine()->voe()->file() &&
2434 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2435 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2436 return false;
2437 }
2438 } else { // SEND_NOTHING
2439 ASSERT(send == SEND_NOTHING);
2440 if (engine()->voe()->base()->StopSend(channel) == -1) {
2441 LOG_RTCERR1(StopSend, channel);
2442 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002443 }
2444 }
2445
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002446 return true;
2447}
2448
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002449// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002450void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2451 if (engine()->voe()->network()->RegisterExternalTransport(
2452 channel, *this) == -1) {
2453 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2454 }
2455
2456 // Enable RTCP (for quality stats and feedback messages)
2457 EnableRtcp(channel);
2458
2459 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2460 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002461
2462 // Set RTP header extension for the new channel.
2463 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002464}
2465
2466bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2467 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2468 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2469 }
2470
2471 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2472 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002473 return false;
2474 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002475
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002476 return true;
2477}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002478
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002479bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2480 // If the default channel is already used for sending create a new channel
2481 // otherwise use the default channel for sending.
2482 int channel = GetSendChannelNum(sp.first_ssrc());
2483 if (channel != -1) {
2484 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2485 return false;
2486 }
2487
2488 bool default_channel_is_available = true;
2489 for (ChannelMap::const_iterator iter = send_channels_.begin();
2490 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002491 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002492 default_channel_is_available = false;
2493 break;
2494 }
2495 }
2496 if (default_channel_is_available) {
2497 channel = voe_channel();
2498 } else {
2499 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002500 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002501 if (channel == -1) {
2502 LOG_RTCERR0(CreateChannel);
2503 return false;
2504 }
2505
2506 ConfigureSendChannel(channel);
2507 }
2508
2509 // Save the channel to send_channels_, so that RemoveSendStream() can still
2510 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002511 webrtc::AudioTransport* audio_transport =
2512 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002513 send_channels_.insert(std::make_pair(
2514 sp.first_ssrc(),
2515 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002516
2517 // Set the send (local) SSRC.
2518 // If there are multiple send SSRCs, we can only set the first one here, and
2519 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2520 // (with a codec requires multiple SSRC(s)).
2521 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2522 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2523 return false;
2524 }
2525
2526 // At this point the channel's local SSRC has been updated. If the channel is
2527 // the default channel make sure that all the receive channels are updated as
2528 // well. Receive channels have to have the same SSRC as the default channel in
2529 // order to send receiver reports with this SSRC.
2530 if (IsDefaultChannel(channel)) {
2531 for (ChannelMap::const_iterator it = receive_channels_.begin();
2532 it != receive_channels_.end(); ++it) {
2533 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002534 if (!IsDefaultChannel(it->second->channel())) {
2535 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002536 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002537 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002538 return false;
2539 }
2540 }
2541 }
2542 }
2543
2544 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002545 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2546 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002547 }
2548
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002549 // Set the current codecs to be used for the new channel.
2550 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002551 return false;
2552
2553 return ChangeSend(channel, desired_send_);
2554}
2555
2556bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2557 ChannelMap::iterator it = send_channels_.find(ssrc);
2558 if (it == send_channels_.end()) {
2559 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2560 << " which doesn't exist.";
2561 return false;
2562 }
2563
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002564 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002565 ChangeSend(channel, SEND_NOTHING);
2566
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002567 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2568 // this will disconnect the audio renderer with the send channel.
2569 delete it->second;
2570 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002571
2572 if (IsDefaultChannel(channel)) {
2573 // Do not delete the default channel since the receive channels depend on
2574 // the default channel, recycle it instead.
2575 ChangeSend(channel, SEND_NOTHING);
2576 } else {
2577 // Clean up and delete the send channel.
2578 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2579 << " with VoiceEngine channel #" << channel << ".";
2580 if (!DeleteChannel(channel))
2581 return false;
2582 }
2583
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002584 if (send_channels_.empty())
2585 ChangeSend(SEND_NOTHING);
2586
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002587 return true;
2588}
2589
2590bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002591 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002592
2593 if (!VERIFY(sp.ssrcs.size() == 1))
2594 return false;
2595 uint32 ssrc = sp.first_ssrc();
2596
wu@webrtc.org78187522013-10-07 23:32:02 +00002597 if (ssrc == 0) {
2598 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2599 return false;
2600 }
2601
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002602 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2603 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002604 return false;
2605 }
2606
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002607 // Reuse default channel for recv stream in non-conference mode call
2608 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002609 webrtc::AudioTransport* audio_transport =
2610 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002611 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2612 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2613 << " reuse default channel";
2614 default_receive_ssrc_ = sp.first_ssrc();
2615 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002616 default_receive_ssrc_,
2617 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002618 if (!SetupSharedBweOnChannel(voe_channel())) {
2619 return false;
2620 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002621 return SetPlayout(voe_channel(), playout_);
2622 }
2623
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002624 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002625 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002626 if (channel == -1) {
2627 LOG_RTCERR0(CreateChannel);
2628 return false;
2629 }
2630
wu@webrtc.org78187522013-10-07 23:32:02 +00002631 if (!ConfigureRecvChannel(channel)) {
2632 DeleteChannel(channel);
2633 return false;
2634 }
2635
2636 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002637 std::make_pair(
2638 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002639
2640 LOG(LS_INFO) << "New audio stream " << ssrc
2641 << " registered to VoiceEngine channel #"
2642 << channel << ".";
2643 return true;
2644}
2645
2646bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002647 // Configure to use external transport, like our default channel.
2648 if (engine()->voe()->network()->RegisterExternalTransport(
2649 channel, *this) == -1) {
2650 LOG_RTCERR2(SetExternalTransport, channel, this);
2651 return false;
2652 }
2653
2654 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002655 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002656 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2657 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002658 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002659 return false;
2660 }
2661 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002662 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002663 return false;
2664 }
2665
2666 // Use the same recv payload types as our default channel.
2667 ResetRecvCodecs(channel);
2668 if (!recv_codecs_.empty()) {
2669 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2670 it != recv_codecs_.end(); ++it) {
2671 webrtc::CodecInst voe_codec;
2672 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2673 voe_codec.pltype = it->id;
2674 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2675 if (engine()->voe()->codec()->GetRecPayloadType(
2676 voe_channel(), voe_codec) != -1) {
2677 if (engine()->voe()->codec()->SetRecPayloadType(
2678 channel, voe_codec) == -1) {
2679 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2680 return false;
2681 }
2682 }
2683 }
2684 }
2685 }
2686
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002687 if (InConferenceMode()) {
2688 // To be in par with the video, voe_channel() is not used for receiving in
2689 // a conference call.
2690 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2691 // This is the first stream in a multi user meeting. We can now
2692 // disable playback of the default stream. This since the default
2693 // stream will probably have received some initial packets before
2694 // the new stream was added. This will mean that the CN state from
2695 // the default channel will be mixed in with the other streams
2696 // throughout the whole meeting, which might be disturbing.
2697 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2698 SetPlayout(voe_channel(), false);
2699 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002700 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002701 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002702
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002703 // Set RTP header extension for the new channel.
2704 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2705 return false;
2706 }
2707
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002708 // Set up channel to be able to forward incoming packets to video engine BWE.
2709 if (!SetupSharedBweOnChannel(channel)) {
2710 return false;
2711 }
2712
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002713 return SetPlayout(channel, playout_);
2714}
2715
2716bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002717 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002718 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002719 if (it == receive_channels_.end()) {
2720 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2721 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002722 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002723 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002724
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002725 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2726 // will disconnect the audio renderer with the receive channel.
2727 // Cache the channel before the deletion.
2728 const int channel = it->second->channel();
2729 delete it->second;
2730 receive_channels_.erase(it);
2731
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002732 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002733 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002734 // Recycle the default channel is for recv stream.
2735 if (playout_)
2736 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002737
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002738 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002739 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002740 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002741
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002742 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002743 << " with VoiceEngine channel #" << channel << ".";
2744 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002745 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002746
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002747 bool enable_default_channel_playout = false;
2748 if (receive_channels_.empty()) {
2749 // The last stream was removed. We can now enable the default
2750 // channel for new channels to be played out immediately without
2751 // waiting for AddStream messages.
2752 // We do this for both conference mode and non-conference mode.
2753 // TODO(oja): Does the default channel still have it's CN state?
2754 enable_default_channel_playout = true;
2755 }
2756 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2757 default_receive_ssrc_ != 0) {
2758 // Only the default channel is active, enable the playout on default
2759 // channel.
2760 enable_default_channel_playout = true;
2761 }
2762 if (enable_default_channel_playout && playout_) {
2763 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2764 SetPlayout(voe_channel(), true);
2765 }
2766
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002767 return true;
2768}
2769
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002770bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2771 AudioRenderer* renderer) {
2772 ChannelMap::iterator it = receive_channels_.find(ssrc);
2773 if (it == receive_channels_.end()) {
2774 if (renderer) {
2775 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002776 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002777 return false;
2778 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002779
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002780 // The channel likely has gone away, do nothing.
2781 return true;
2782 }
2783
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002784 if (renderer)
2785 it->second->Start(renderer);
2786 else
2787 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002788
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002789 return true;
2790}
2791
2792bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2793 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002794 ChannelMap::iterator it = send_channels_.find(ssrc);
2795 if (it == send_channels_.end()) {
2796 if (renderer) {
2797 // Return an error if trying to set a valid renderer with an invalid ssrc.
2798 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2799 return false;
2800 }
2801
2802 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002803 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002804 }
2805
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002806 if (renderer)
2807 it->second->Start(renderer);
2808 else
2809 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002810
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002811 return true;
2812}
2813
2814bool WebRtcVoiceMediaChannel::GetActiveStreams(
2815 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002816 // In conference mode, the default channel should not be in
2817 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002818 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002819 for (ChannelMap::iterator it = receive_channels_.begin();
2820 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002821 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002822 if (level > 0) {
2823 actives->push_back(std::make_pair(it->first, level));
2824 }
2825 }
2826 return true;
2827}
2828
2829int WebRtcVoiceMediaChannel::GetOutputLevel() {
2830 // return the highest output level of all streams
2831 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002832 for (ChannelMap::iterator it = receive_channels_.begin();
2833 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002834 int level = GetOutputLevel(it->second->channel());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002835 highest = rtc::_max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002836 }
2837 return highest;
2838}
2839
2840int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2841 int ret;
2842 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2843 // In case of error, log the info and continue
2844 LOG_RTCERR0(TimeSinceLastTyping);
2845 ret = -1;
2846 } else {
2847 ret *= 1000; // We return ms, webrtc returns seconds.
2848 }
2849 return ret;
2850}
2851
2852void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2853 int cost_per_typing, int reporting_threshold, int penalty_decay,
2854 int type_event_delay) {
2855 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2856 time_window, cost_per_typing,
2857 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2858 // In case of error, log the info and continue
2859 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2860 cost_per_typing, reporting_threshold, penalty_decay,
2861 type_event_delay);
2862 }
2863}
2864
2865bool WebRtcVoiceMediaChannel::SetOutputScaling(
2866 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002867 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002868 // Collect the channels to scale the output volume.
2869 std::vector<int> channels;
2870 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002871 // Default channel is not in receive_channels_ if it is not being used for
2872 // playout.
2873 if (default_receive_ssrc_ == 0)
2874 channels.push_back(voe_channel());
2875 for (ChannelMap::const_iterator it = receive_channels_.begin();
2876 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002877 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002878 }
2879 } else { // Collect only the channel of the specified ssrc.
2880 int channel = GetReceiveChannelNum(ssrc);
2881 if (-1 == channel) {
2882 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2883 return false;
2884 }
2885 channels.push_back(channel);
2886 }
2887
2888 // Scale the output volume for the collected channels. We first normalize to
2889 // scale the volume and then set the left and right pan.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002890 float scale = static_cast<float>(rtc::_max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002891 if (scale > 0.0001f) {
2892 left /= scale;
2893 right /= scale;
2894 }
2895 for (std::vector<int>::const_iterator it = channels.begin();
2896 it != channels.end(); ++it) {
2897 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2898 *it, scale)) {
2899 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2900 return false;
2901 }
2902 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2903 *it, static_cast<float>(left), static_cast<float>(right))) {
2904 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2905 // Do not return if fails. SetOutputVolumePan is not available for all
2906 // pltforms.
2907 }
2908 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2909 << " right=" << right * scale
2910 << " for channel " << *it << " and ssrc " << ssrc;
2911 }
2912 return true;
2913}
2914
2915bool WebRtcVoiceMediaChannel::GetOutputScaling(
2916 uint32 ssrc, double* left, double* right) {
2917 if (!left || !right) return false;
2918
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002919 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002920 // Determine which channel based on ssrc.
2921 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2922 if (channel == -1) {
2923 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2924 return false;
2925 }
2926
2927 float scaling;
2928 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2929 channel, scaling)) {
2930 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2931 return false;
2932 }
2933
2934 float left_pan;
2935 float right_pan;
2936 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2937 channel, left_pan, right_pan)) {
2938 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2939 // If GetOutputVolumePan fails, we use the default left and right pan.
2940 left_pan = 1.0f;
2941 right_pan = 1.0f;
2942 }
2943
2944 *left = scaling * left_pan;
2945 *right = scaling * right_pan;
2946 return true;
2947}
2948
2949bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2950 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2951 return true;
2952}
2953
2954bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2955 bool play, bool loop) {
2956 if (!ringback_tone_) {
2957 return false;
2958 }
2959
2960 // The voe file api is not available in chrome.
2961 if (!engine()->voe()->file()) {
2962 return false;
2963 }
2964
2965 // Determine which VoiceEngine channel to play on.
2966 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2967 if (channel == -1) {
2968 return false;
2969 }
2970
2971 // Make sure the ringtone is cued properly, and play it out.
2972 if (play) {
2973 ringback_tone_->set_loop(loop);
2974 ringback_tone_->Rewind();
2975 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2976 ringback_tone_.get()) == -1) {
2977 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2978 LOG(LS_ERROR) << "Unable to start ringback tone";
2979 return false;
2980 }
2981 ringback_channels_.insert(channel);
2982 LOG(LS_INFO) << "Started ringback on channel " << channel;
2983 } else {
2984 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2985 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2986 LOG_RTCERR1(StopPlayingFileLocally, channel);
2987 return false;
2988 }
2989 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2990 ringback_channels_.erase(channel);
2991 }
2992
2993 return true;
2994}
2995
2996bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2997 return dtmf_allowed_;
2998}
2999
3000bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3001 int duration, int flags) {
3002 if (!dtmf_allowed_) {
3003 return false;
3004 }
3005
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003006 // Send the event.
3007 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003008 int channel = -1;
3009 if (ssrc == 0) {
3010 bool default_channel_is_inuse = false;
3011 for (ChannelMap::const_iterator iter = send_channels_.begin();
3012 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003013 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003014 default_channel_is_inuse = true;
3015 break;
3016 }
3017 }
3018 if (default_channel_is_inuse) {
3019 channel = voe_channel();
3020 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003021 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003022 }
3023 } else {
3024 channel = GetSendChannelNum(ssrc);
3025 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003026 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003027 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3028 << ssrc << " is not in use.";
3029 return false;
3030 }
3031 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003032 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3033 channel, event, true, duration) == -1) {
3034 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003035 return false;
3036 }
3037 }
3038
3039 // Play the event.
3040 if (flags & cricket::DF_PLAY) {
3041 // Play DTMF tone locally.
3042 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3043 LOG_RTCERR2(PlayDtmfTone, event, duration);
3044 return false;
3045 }
3046 }
3047
3048 return true;
3049}
3050
wu@webrtc.orga9890802013-12-13 00:21:03 +00003051void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003052 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003053 // Pick which channel to send this packet to. If this packet doesn't match
3054 // any multiplexed streams, just send it to the default channel. Otherwise,
3055 // send it to the specific decoder instance for that stream.
3056 int which_channel = GetReceiveChannelNum(
3057 ParseSsrc(packet->data(), packet->length(), false));
3058 if (which_channel == -1) {
3059 which_channel = voe_channel();
3060 }
3061
3062 // Stop any ringback that might be playing on the channel.
3063 // It's possible the ringback has already stopped, ih which case we'll just
3064 // use the opportunity to remove the channel from ringback_channels_.
3065 if (engine()->voe()->file()) {
3066 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3067 if (it != ringback_channels_.end()) {
3068 if (engine()->voe()->file()->IsPlayingFileLocally(
3069 which_channel) == 1) {
3070 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3071 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3072 << " due to incoming media";
3073 }
3074 ringback_channels_.erase(which_channel);
3075 }
3076 }
3077
3078 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003079 engine()->voe()->network()->ReceivedRTPPacket(
3080 which_channel,
3081 packet->data(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003082 static_cast<unsigned int>(packet->length()),
3083 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003084}
3085
wu@webrtc.orga9890802013-12-13 00:21:03 +00003086void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003087 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003088 // Sending channels need all RTCP packets with feedback information.
3089 // Even sender reports can contain attached report blocks.
3090 // Receiving channels need sender reports in order to create
3091 // correct receiver reports.
3092 int type = 0;
3093 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3094 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3095 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003096 }
3097
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003098 // If it is a sender report, find the channel that is listening.
3099 bool has_sent_to_default_channel = false;
3100 if (type == kRtcpTypeSR) {
3101 int which_channel = GetReceiveChannelNum(
3102 ParseSsrc(packet->data(), packet->length(), true));
3103 if (which_channel != -1) {
3104 engine()->voe()->network()->ReceivedRTCPPacket(
3105 which_channel,
3106 packet->data(),
3107 static_cast<unsigned int>(packet->length()));
3108
3109 if (IsDefaultChannel(which_channel))
3110 has_sent_to_default_channel = true;
3111 }
3112 }
3113
3114 // SR may continue RR and any RR entry may correspond to any one of the send
3115 // channels. So all RTCP packets must be forwarded all send channels. VoE
3116 // will filter out RR internally.
3117 for (ChannelMap::iterator iter = send_channels_.begin();
3118 iter != send_channels_.end(); ++iter) {
3119 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003120 if (IsDefaultChannel(iter->second->channel()) &&
3121 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003122 continue;
3123
3124 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003125 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003126 packet->data(),
3127 static_cast<unsigned int>(packet->length()));
3128 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003129}
3130
3131bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003132 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3133 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003134 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3135 return false;
3136 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003137 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3138 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003139 return false;
3140 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003141 // We set the AGC to mute state only when all the channels are muted.
3142 // This implementation is not ideal, instead we should signal the AGC when
3143 // the mic channel is muted/unmuted. We can't do it today because there
3144 // is no good way to know which stream is mapping to the mic channel.
3145 bool all_muted = muted;
3146 for (ChannelMap::const_iterator iter = send_channels_.begin();
3147 iter != send_channels_.end() && all_muted; ++iter) {
3148 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3149 all_muted)) {
3150 LOG_RTCERR1(GetInputMute, iter->second->channel());
3151 return false;
3152 }
3153 }
3154
3155 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3156 if (ap)
3157 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003158 return true;
3159}
3160
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003161bool WebRtcVoiceMediaChannel::SetStartSendBandwidth(int bps) {
3162 // TODO(andresp): Add support for setting an independent start bandwidth when
3163 // bandwidth estimation is enabled for voice engine.
3164 return false;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003165}
3166
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003167bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
3168 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
3169
3170 return SetSendBandwidthInternal(bps);
3171}
3172
3173bool WebRtcVoiceMediaChannel::SetSendBandwidthInternal(int bps) {
3174 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBandwidthInternal.";
3175
3176 send_bw_setting_ = true;
3177 send_bw_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003178
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003179 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003180 LOG(LS_INFO) << "The send codec has not been set up yet. "
3181 << "The send bandwidth setting will be applied later.";
3182 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003183 }
3184
3185 // Bandwidth is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003186 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3187 // SetMaxSendBandwith(0), the second call removes the previous limit.
3188 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003189 return true;
3190
3191 webrtc::CodecInst codec = *send_codec_;
3192 bool is_multi_rate = IsCodecMultiRate(codec);
3193
3194 if (is_multi_rate) {
3195 // If codec is multi-rate then just set the bitrate.
3196 codec.rate = bps;
3197 if (!SetSendCodec(codec)) {
3198 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3199 << " to bitrate " << bps << " bps.";
3200 return false;
3201 }
3202 return true;
3203 } else {
3204 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3205 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3206 // fixed bitrate then ignore.
3207 if (bps < codec.rate) {
3208 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3209 << " to bitrate " << bps << " bps"
3210 << ", requires at least " << codec.rate << " bps.";
3211 return false;
3212 }
3213 return true;
3214 }
3215}
3216
3217bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003218 bool echo_metrics_on = false;
3219 // These can take on valid negative values, so use the lowest possible level
3220 // as default rather than -1.
3221 int echo_return_loss = -100;
3222 int echo_return_loss_enhancement = -100;
3223 // These can also be negative, but in practice -1 is only used to signal
3224 // insufficient data, since the resolution is limited to multiples of 4 ms.
3225 int echo_delay_median_ms = -1;
3226 int echo_delay_std_ms = -1;
3227 if (engine()->voe()->processing()->GetEcMetricsStatus(
3228 echo_metrics_on) != -1 && echo_metrics_on) {
3229 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3230 // here, but it appears to be unsuitable currently. Revisit after this is
3231 // investigated: http://b/issue?id=5666755
3232 int erl, erle, rerl, anlp;
3233 if (engine()->voe()->processing()->GetEchoMetrics(
3234 erl, erle, rerl, anlp) != -1) {
3235 echo_return_loss = erl;
3236 echo_return_loss_enhancement = erle;
3237 }
3238
3239 int median, std;
3240 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3241 echo_delay_median_ms = median;
3242 echo_delay_std_ms = std;
3243 }
3244 }
3245
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003246 webrtc::CallStatistics cs;
3247 unsigned int ssrc;
3248 webrtc::CodecInst codec;
3249 unsigned int level;
3250
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003251 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3252 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003253 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003254
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003255 // Fill in the sender info, based on what we know, and what the
3256 // remote side told us it got from its RTCP report.
3257 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003258
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003259 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3260 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3261 continue;
3262 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003263
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003264 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003265 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3266 sinfo.bytes_sent = cs.bytesSent;
3267 sinfo.packets_sent = cs.packetsSent;
3268 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3269 // returns 0 to indicate an error value.
3270 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3271
3272 // Get data from the last remote RTCP report. Use default values if no data
3273 // available.
3274 sinfo.fraction_lost = -1.0;
3275 sinfo.jitter_ms = -1;
3276 sinfo.packets_lost = -1;
3277 sinfo.ext_seqnum = -1;
3278 std::vector<webrtc::ReportBlock> receive_blocks;
3279 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3280 channel, &receive_blocks) != -1 &&
3281 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3282 std::vector<webrtc::ReportBlock>::iterator iter;
3283 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3284 ++iter) {
3285 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003286 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003287 // Convert Q8 to floating point.
3288 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3289 // Convert samples to milliseconds.
3290 if (codec.plfreq / 1000 > 0) {
3291 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3292 }
3293 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3294 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3295 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003296 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003297 }
3298 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003299
3300 // Local speech level.
3301 sinfo.audio_level = (engine()->voe()->volume()->
3302 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3303
3304 // TODO(xians): We are injecting the same APM logging to all the send
3305 // channels here because there is no good way to know which send channel
3306 // is using the APM. The correct fix is to allow the send channels to have
3307 // their own APM so that we can feed the correct APM logging to different
3308 // send channels. See issue crbug/264611 .
3309 sinfo.echo_return_loss = echo_return_loss;
3310 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3311 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3312 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003313 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3314 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003315 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003316
3317 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003318 }
3319
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003320 // Build the list of receivers, one for each receiving channel, or 1 in
3321 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003322 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003323 for (ChannelMap::const_iterator it = receive_channels_.begin();
3324 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003325 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003326 }
3327 if (channels.empty()) {
3328 channels.push_back(voe_channel());
3329 }
3330
3331 // Get the SSRC and stats for each receiver, based on our own calculations.
3332 for (std::vector<int>::const_iterator it = channels.begin();
3333 it != channels.end(); ++it) {
3334 memset(&cs, 0, sizeof(cs));
3335 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3336 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3337 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3338 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003339 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003340 rinfo.bytes_rcvd = cs.bytesReceived;
3341 rinfo.packets_rcvd = cs.packetsReceived;
3342 // The next four fields are from the most recently sent RTCP report.
3343 // Convert Q8 to floating point.
3344 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3345 rinfo.packets_lost = cs.cumulativeLost;
3346 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003347#ifdef USE_WEBRTC_DEV_BRANCH
3348 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
3349#endif
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003350 if (codec.pltype != -1) {
3351 rinfo.codec_name = codec.plname;
3352 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003353 // Convert samples to milliseconds.
3354 if (codec.plfreq / 1000 > 0) {
3355 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3356 }
3357
3358 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3359 webrtc::NetworkStatistics ns;
3360 if (engine()->voe()->neteq() &&
3361 engine()->voe()->neteq()->GetNetworkStatistics(
3362 *it, ns) != -1) {
3363 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3364 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3365 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003366 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003367 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003368
3369 webrtc::AudioDecodingCallStats ds;
3370 if (engine()->voe()->neteq() &&
3371 engine()->voe()->neteq()->GetDecodingCallStatistics(
3372 *it, &ds) != -1) {
3373 rinfo.decoding_calls_to_silence_generator =
3374 ds.calls_to_silence_generator;
3375 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3376 rinfo.decoding_normal = ds.decoded_normal;
3377 rinfo.decoding_plc = ds.decoded_plc;
3378 rinfo.decoding_cng = ds.decoded_cng;
3379 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3380 }
3381
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003382 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003383 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003384 int playout_buffer_delay_ms = 0;
3385 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003386 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3387 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3388 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003389 }
3390
3391 // Get speech level.
3392 rinfo.audio_level = (engine()->voe()->volume()->
3393 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3394 info->receivers.push_back(rinfo);
3395 }
3396 }
3397
3398 return true;
3399}
3400
3401void WebRtcVoiceMediaChannel::GetLastMediaError(
3402 uint32* ssrc, VoiceMediaChannel::Error* error) {
3403 ASSERT(ssrc != NULL);
3404 ASSERT(error != NULL);
3405 FindSsrc(voe_channel(), ssrc);
3406 *error = WebRtcErrorToChannelError(GetLastEngineError());
3407}
3408
3409bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003410 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003411 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003412 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003413 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3414 // This means the error is not limited to a specific channel. Signal the
3415 // message using ssrc=0. If the current channel is sending, use this
3416 // channel for sending the message.
3417 *ssrc = 0;
3418 return true;
3419 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003420 // Check whether this is a sending channel.
3421 for (ChannelMap::const_iterator it = send_channels_.begin();
3422 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003423 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003424 // This is a sending channel.
3425 uint32 local_ssrc = 0;
3426 if (engine()->voe()->rtp()->GetLocalSSRC(
3427 channel_num, local_ssrc) != -1) {
3428 *ssrc = local_ssrc;
3429 }
3430 return true;
3431 }
3432 }
3433
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003434 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003435 for (ChannelMap::const_iterator it = receive_channels_.begin();
3436 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003437 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003438 *ssrc = it->first;
3439 return true;
3440 }
3441 }
3442 }
3443 return false;
3444}
3445
3446void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003447 if (error == VE_TYPING_NOISE_WARNING) {
3448 typing_noise_detected_ = true;
3449 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3450 typing_noise_detected_ = false;
3451 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003452 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3453}
3454
3455int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3456 unsigned int ulevel;
3457 int ret =
3458 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3459 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3460}
3461
3462int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003463 ChannelMap::iterator it = receive_channels_.find(ssrc);
3464 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003465 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003466 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3467}
3468
3469int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003470 ChannelMap::iterator it = send_channels_.find(ssrc);
3471 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003472 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003473
3474 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003475}
3476
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003477bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
3478 webrtc::VideoEngine* vie, int vie_channel) {
3479 shared_bwe_vie_ = vie;
3480 shared_bwe_vie_channel_ = vie_channel;
3481
3482 if (!SetupSharedBweOnChannel(voe_channel())) {
3483 return false;
3484 }
3485 for (ChannelMap::iterator it = receive_channels_.begin();
3486 it != receive_channels_.end(); ++it) {
3487 if (!SetupSharedBweOnChannel(it->second->channel())) {
3488 return false;
3489 }
3490 }
3491 return true;
3492}
3493
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003494bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3495 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3496 // Get the RED encodings from the parameter with no name. This may
3497 // change based on what is discussed on the Jingle list.
3498 // The encoding parameter is of the form "a/b"; we only support where
3499 // a == b. Verify this and parse out the value into red_pt.
3500 // If the parameter value is absent (as it will be until we wire up the
3501 // signaling of this message), use the second codec specified (i.e. the
3502 // one after "red") as the encoding parameter.
3503 int red_pt = -1;
3504 std::string red_params;
3505 CodecParameterMap::const_iterator it = red_codec.params.find("");
3506 if (it != red_codec.params.end()) {
3507 red_params = it->second;
3508 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003509 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003510 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003511 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003512 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3513 return false;
3514 }
3515 } else if (red_codec.params.empty()) {
3516 LOG(LS_WARNING) << "RED params not present, using defaults";
3517 if (all_codecs.size() > 1) {
3518 red_pt = all_codecs[1].id;
3519 }
3520 }
3521
3522 // Try to find red_pt in |codecs|.
3523 std::vector<AudioCodec>::const_iterator codec;
3524 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3525 if (codec->id == red_pt)
3526 break;
3527 }
3528
3529 // If we find the right codec, that will be the codec we pass to
3530 // SetSendCodec, with the desired payload type.
3531 if (codec != all_codecs.end() &&
3532 engine()->FindWebRtcCodec(*codec, send_codec)) {
3533 } else {
3534 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3535 return false;
3536 }
3537
3538 return true;
3539}
3540
3541bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3542 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003543 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003544 return false;
3545 }
3546 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3547 // what we want to do with them.
3548 // engine()->voe().EnableVQMon(voe_channel(), true);
3549 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3550 return true;
3551}
3552
3553bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3554 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3555 for (int i = 0; i < ncodecs; ++i) {
3556 webrtc::CodecInst voe_codec;
3557 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3558 voe_codec.pltype = -1;
3559 if (engine()->voe()->codec()->SetRecPayloadType(
3560 channel, voe_codec) == -1) {
3561 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3562 return false;
3563 }
3564 }
3565 }
3566 return true;
3567}
3568
3569bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3570 if (playout) {
3571 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3572 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3573 LOG_RTCERR1(StartPlayout, channel);
3574 return false;
3575 }
3576 } else {
3577 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3578 engine()->voe()->base()->StopPlayout(channel);
3579 }
3580 return true;
3581}
3582
3583uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3584 bool rtcp) {
3585 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3586 uint32 ssrc = 0;
3587 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003588 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003589 }
3590 return ssrc;
3591}
3592
3593// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3594VoiceMediaChannel::Error
3595 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3596 switch (err_code) {
3597 case 0:
3598 return ERROR_NONE;
3599 case VE_CANNOT_START_RECORDING:
3600 case VE_MIC_VOL_ERROR:
3601 case VE_GET_MIC_VOL_ERROR:
3602 case VE_CANNOT_ACCESS_MIC_VOL:
3603 return ERROR_REC_DEVICE_OPEN_FAILED;
3604 case VE_SATURATION_WARNING:
3605 return ERROR_REC_DEVICE_SATURATION;
3606 case VE_REC_DEVICE_REMOVED:
3607 return ERROR_REC_DEVICE_REMOVED;
3608 case VE_RUNTIME_REC_WARNING:
3609 case VE_RUNTIME_REC_ERROR:
3610 return ERROR_REC_RUNTIME_ERROR;
3611 case VE_CANNOT_START_PLAYOUT:
3612 case VE_SPEAKER_VOL_ERROR:
3613 case VE_GET_SPEAKER_VOL_ERROR:
3614 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3615 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3616 case VE_RUNTIME_PLAY_WARNING:
3617 case VE_RUNTIME_PLAY_ERROR:
3618 return ERROR_PLAY_RUNTIME_ERROR;
3619 case VE_TYPING_NOISE_WARNING:
3620 return ERROR_REC_TYPING_NOISE_DETECTED;
3621 default:
3622 return VoiceMediaChannel::ERROR_OTHER;
3623 }
3624}
3625
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003626bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3627 int channel_id, const RtpHeaderExtension* extension) {
3628 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003629 int id = 0;
3630 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003631 if (extension) {
3632 enable = true;
3633 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003634 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003635 }
3636 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003637 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003638 return false;
3639 }
3640 return true;
3641}
3642
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003643bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
3644 webrtc::ViENetwork* vie_network = NULL;
3645 int vie_channel = -1;
3646 if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
3647 shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
3648 vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
3649 vie_channel = shared_bwe_vie_channel_;
3650 }
3651 if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
3652 vie_channel) == -1) {
3653 LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
3654 if (vie_network != NULL) {
3655 // Don't fail if we're tearing down.
3656 return false;
3657 }
3658 }
3659 return true;
3660}
3661
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003662int WebRtcSoundclipStream::Read(void *buf, int len) {
3663 size_t res = 0;
3664 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003665 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003666}
3667
3668int WebRtcSoundclipStream::Rewind() {
3669 mem_.Rewind();
3670 // Return -1 to keep VoiceEngine from looping.
3671 return (loop_) ? 0 : -1;
3672}
3673
3674} // namespace cricket
3675
3676#endif // HAVE_WEBRTC_VOICE