blob: 5f2de4a2e8c286ad184663f1ab18e6ba79bfa0cc [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;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000123
wu@webrtc.orgde305012013-10-31 15:40:38 +0000124// Default audio dscp value.
125// See http://tools.ietf.org/html/rfc2474 for details.
126// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000127static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000128
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000129// Ensure we open the file in a writeable path on ChromeOS and Android. This
130// workaround can be removed when it's possible to specify a filename for audio
131// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000132//
133// TODO(grunell): Use a string in the options instead of hardcoding it here
134// and let the embedder choose the filename (crbug.com/264223).
135//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000136// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
137// below.
138#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000139static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000140#elif defined(ANDROID)
141static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000142#else
143static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
144#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000145
146// Dumps an AudioCodec in RFC 2327-ish format.
147static std::string ToString(const AudioCodec& codec) {
148 std::stringstream ss;
149 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
150 << " (" << codec.id << ")";
151 return ss.str();
152}
153static std::string ToString(const webrtc::CodecInst& codec) {
154 std::stringstream ss;
155 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
156 << " (" << codec.pltype << ")";
157 return ss.str();
158}
159
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000160static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000161 const char* delim = "\r\n";
162 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
163 LOG_V(sev) << tok;
164 }
165}
166
167// Severity is an integer because it comes is assumed to be from command line.
168static int SeverityToFilter(int severity) {
169 int filter = webrtc::kTraceNone;
170 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000171 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000172 filter |= webrtc::kTraceAll;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000173 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000174 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000175 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000176 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000177 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000178 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
179 }
180 return filter;
181}
182
183static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
184 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
185 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
186 kCodecPrefs[i].clockrate == codec.plfreq) {
187 return kCodecPrefs[i].is_multi_rate;
188 }
189 }
190 return false;
191}
192
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000193static bool IsTelephoneEventCodec(const std::string& name) {
194 return _stricmp(name.c_str(), "telephone-event") == 0;
195}
196
197static bool IsCNCodec(const std::string& name) {
198 return _stricmp(name.c_str(), "CN") == 0;
199}
200
201static bool IsRedCodec(const std::string& name) {
202 return _stricmp(name.c_str(), "red") == 0;
203}
204
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000205static bool FindCodec(const std::vector<AudioCodec>& codecs,
206 const AudioCodec& codec,
207 AudioCodec* found_codec) {
208 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
209 it != codecs.end(); ++it) {
210 if (it->Matches(codec)) {
211 if (found_codec != NULL) {
212 *found_codec = *it;
213 }
214 return true;
215 }
216 }
217 return false;
218}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000219
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000220static bool IsNackEnabled(const AudioCodec& codec) {
221 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
222 kParamValueEmpty));
223}
224
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000225// Gets the default set of options applied to the engine. Historically, these
226// were supplied as a combination of flags from the channel manager (ec, agc,
227// ns, and highpass) and the rest hardcoded in InitInternal.
228static AudioOptions GetDefaultEngineOptions() {
229 AudioOptions options;
230 options.echo_cancellation.Set(true);
231 options.auto_gain_control.Set(true);
232 options.noise_suppression.Set(true);
233 options.highpass_filter.Set(true);
234 options.stereo_swapping.Set(false);
235 options.typing_detection.Set(true);
236 options.conference_mode.Set(false);
237 options.adjust_agc_delta.Set(0);
238 options.experimental_agc.Set(false);
239 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000240 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000241 options.aec_dump.Set(false);
242 return options;
243}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000244
245class WebRtcSoundclipMedia : public SoundclipMedia {
246 public:
247 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
248 : engine_(engine), webrtc_channel_(-1) {
249 engine_->RegisterSoundclip(this);
250 }
251
252 virtual ~WebRtcSoundclipMedia() {
253 engine_->UnregisterSoundclip(this);
254 if (webrtc_channel_ != -1) {
255 // We shouldn't have to call Disable() here. DeleteChannel() should call
256 // StopPlayout() while deleting the channel. We should fix the bug
257 // inside WebRTC and remove the Disable() call bellow. This work is
258 // tracked by bug http://b/issue?id=5382855.
259 PlaySound(NULL, 0, 0);
260 Disable();
261 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
262 == -1) {
263 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
264 }
265 }
266 }
267
268 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000269 if (!engine_->voe_sc()) {
270 return false;
271 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000272 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000273 if (webrtc_channel_ == -1) {
274 LOG_RTCERR0(CreateChannel);
275 return false;
276 }
277 return true;
278 }
279
280 bool Enable() {
281 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
282 LOG_RTCERR1(StartPlayout, webrtc_channel_);
283 return false;
284 }
285 return true;
286 }
287
288 bool Disable() {
289 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
290 LOG_RTCERR1(StopPlayout, webrtc_channel_);
291 return false;
292 }
293 return true;
294 }
295
296 virtual bool PlaySound(const char *buf, int len, int flags) {
297 // The voe file api is not available in chrome.
298 if (!engine_->voe_sc()->file()) {
299 return false;
300 }
301 // Must stop playing the current sound (if any), because we are about to
302 // modify the stream.
303 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
304 == -1) {
305 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
306 return false;
307 }
308
309 if (buf) {
310 stream_.reset(new WebRtcSoundclipStream(buf, len));
311 stream_->set_loop((flags & SF_LOOP) != 0);
312 stream_->Rewind();
313
314 // Play it.
315 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
316 webrtc_channel_, stream_.get()) == -1) {
317 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
318 LOG(LS_ERROR) << "Unable to start soundclip";
319 return false;
320 }
321 } else {
322 stream_.reset();
323 }
324 return true;
325 }
326
327 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
328
329 private:
330 WebRtcVoiceEngine *engine_;
331 int webrtc_channel_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000332 rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000333};
334
335WebRtcVoiceEngine::WebRtcVoiceEngine()
336 : voe_wrapper_(new VoEWrapper()),
337 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000338 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000339 tracing_(new VoETraceWrapper()),
340 adm_(NULL),
341 adm_sc_(NULL),
342 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
343 is_dumping_aec_(false),
344 desired_local_monitor_enable_(false),
345 tx_processor_ssrc_(0),
346 rx_processor_ssrc_(0) {
347 Construct();
348}
349
350WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
351 VoEWrapper* voe_wrapper_sc,
352 VoETraceWrapper* tracing)
353 : voe_wrapper_(voe_wrapper),
354 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000355 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000356 tracing_(tracing),
357 adm_(NULL),
358 adm_sc_(NULL),
359 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
360 is_dumping_aec_(false),
361 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000362 tx_processor_ssrc_(0),
363 rx_processor_ssrc_(0) {
364 Construct();
365}
366
367void WebRtcVoiceEngine::Construct() {
368 SetTraceFilter(log_filter_);
369 initialized_ = false;
370 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
371 SetTraceOptions("");
372 if (tracing_->SetTraceCallback(this) == -1) {
373 LOG_RTCERR0(SetTraceCallback);
374 }
375 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
376 LOG_RTCERR0(RegisterVoiceEngineObserver);
377 }
378 // Clear the default agc state.
379 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
380
381 // Load our audio codec list.
382 ConstructCodecs();
383
384 // Load our RTP Header extensions.
385 rtp_header_extensions_.push_back(
386 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
387 kRtpAudioLevelHeaderExtensionDefaultId));
388 rtp_header_extensions_.push_back(
389 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
390 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
391 options_ = GetDefaultEngineOptions();
392}
393
394static bool IsOpus(const AudioCodec& codec) {
395 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
396}
397
398static bool IsIsac(const AudioCodec& codec) {
399 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
400}
401
402// True if params["stereo"] == "1"
403static bool IsOpusStereoEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000404 int value;
405 return codec.GetParam(kCodecParamStereo, &value) && value == 1;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000406}
407
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000408// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
409// otherwise. If the value (either from params or codec.bitrate) <=0, use the
410// default configuration. If the value is beyond feasible bit rate of Opus,
411// clamp it. Returns the Opus bit rate for operation.
412static int GetOpusBitrate(const AudioCodec& codec) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000413 int bitrate = 0;
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000414 bool use_param = true;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000415 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000416 bitrate = codec.bitrate;
417 use_param = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000418 }
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000419 if (bitrate <= 0) {
420 bitrate = IsOpusStereoEnabled(codec) ? kOpusStereoBitrate :
421 kOpusMonoBitrate;
422 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
423 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
424 std::string rate_source =
425 use_param ? "Codec parameter \"maxaveragebitrate\"" :
426 "Supplied Opus bitrate";
427 LOG(LS_WARNING) << rate_source
428 << " is invalid and is replaced by: "
429 << bitrate;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000430 }
431 return bitrate;
432}
433
buildbot@webrtc.orgfbd13282014-06-19 19:50:55 +0000434// Return true if params[kCodecParamUseInbandFec] == "1", false
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000435// otherwise.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000436static bool IsOpusFecEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000437 int value;
438 return codec.GetParam(kCodecParamUseInbandFec, &value) && value == 1;
439}
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000440
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000441// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
442// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
443static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
444 int value;
445 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
446 return value;
447 }
448 return kOpusDefaultMaxPlaybackRate;
449}
450
451static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
452 bool* enable_codec_fec, int* max_playback_rate) {
453 *enable_codec_fec = IsOpusFecEnabled(codec);
454 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
455
456 // If OPUS, change what we send according to the "stereo" codec
457 // parameter, and not the "channels" parameter. We set
458 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000459 // the bitrate is not specified, i.e. is <= zero, we set it to the
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000460 // appropriate default value for mono or stereo Opus.
461
462 // TODO(minyue): The determination of bit rate might take the maximum playback
463 // rate into account.
464
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000465 voe_codec->channels = IsOpusStereoEnabled(codec) ? 2 : 1;
466 voe_codec->rate = GetOpusBitrate(codec);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000467}
468
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000469void WebRtcVoiceEngine::ConstructCodecs() {
470 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
471 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
472 for (int i = 0; i < ncodecs; ++i) {
473 webrtc::CodecInst voe_codec;
474 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
475 // Skip uncompressed formats.
476 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
477 continue;
478 }
479
480 const CodecPref* pref = NULL;
481 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
482 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
483 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
484 kCodecPrefs[j].channels == voe_codec.channels) {
485 pref = &kCodecPrefs[j];
486 break;
487 }
488 }
489
490 if (pref) {
491 // Use the payload type that we've configured in our pref table;
492 // use the offset in our pref table to determine the sort order.
493 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
494 voe_codec.rate, voe_codec.channels,
495 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
496 LOG(LS_INFO) << ToString(codec);
497 if (IsIsac(codec)) {
498 // Indicate auto-bandwidth in signaling.
499 codec.bitrate = 0;
500 }
501 if (IsOpus(codec)) {
502 // Only add fmtp parameters that differ from the spec.
503 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
504 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000505 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000506 }
507 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
508 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000509 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000510 }
511 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
512 // when they can be set to values other than the default.
513 }
514 codecs_.push_back(codec);
515 } else {
516 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
517 }
518 }
519 }
520 // Make sure they are in local preference order.
521 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
522}
523
524WebRtcVoiceEngine::~WebRtcVoiceEngine() {
525 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
526 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
527 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
528 }
529 if (adm_) {
530 voe_wrapper_.reset();
531 adm_->Release();
532 adm_ = NULL;
533 }
534 if (adm_sc_) {
535 voe_wrapper_sc_.reset();
536 adm_sc_->Release();
537 adm_sc_ = NULL;
538 }
539
540 // Test to see if the media processor was deregistered properly
541 ASSERT(SignalRxMediaFrame.is_empty());
542 ASSERT(SignalTxMediaFrame.is_empty());
543
544 tracing_->SetTraceCallback(NULL);
545}
546
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000547bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000548 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
549 bool res = InitInternal();
550 if (res) {
551 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
552 } else {
553 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
554 Terminate();
555 }
556 return res;
557}
558
559bool WebRtcVoiceEngine::InitInternal() {
560 // Temporarily turn logging level up for the Init call
561 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000562 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000563 SetTraceFilter(extended_filter);
564 SetTraceOptions("");
565
566 // Init WebRtc VoiceEngine.
567 if (voe_wrapper_->base()->Init(adm_) == -1) {
568 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
569 SetTraceFilter(old_filter);
570 return false;
571 }
572
573 SetTraceFilter(old_filter);
574 SetTraceOptions(log_options_);
575
576 // Log the VoiceEngine version info
577 char buffer[1024] = "";
578 voe_wrapper_->base()->GetVersion(buffer);
579 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000580 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000581
582 // Save the default AGC configuration settings. This must happen before
583 // calling SetOptions or the default will be overwritten.
584 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
585 LOG_RTCERR0(GetAgcConfig);
586 return false;
587 }
588
589 // Set defaults for options, so that ApplyOptions applies them explicitly
590 // when we clear option (channel) overrides. External clients can still
591 // modify the defaults via SetOptions (on the media engine).
592 if (!SetOptions(GetDefaultEngineOptions())) {
593 return false;
594 }
595
596 // Print our codec list again for the call diagnostic log
597 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
598 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
599 it != codecs_.end(); ++it) {
600 LOG(LS_INFO) << ToString(*it);
601 }
602
603 // Disable the DTMF playout when a tone is sent.
604 // PlayDtmfTone will be used if local playout is needed.
605 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
606 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
607 }
608
609 initialized_ = true;
610 return true;
611}
612
613bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
614 if (voe_wrapper_sc_initialized_) {
615 return true;
616 }
617 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
618 // be false, so subsequent calls to EnsureSoundclipEngineInit will
619 // probably just fail again. That's acceptable behavior.
620#if defined(LINUX) && !defined(HAVE_LIBPULSE)
621 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
622#endif
623
624 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
625 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
626 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
627 return false;
628 }
629
630 // On Windows, tell it to use the default sound (not communication) devices.
631 // First check whether there is a valid sound device for playback.
632 // TODO(juberti): Clean this up when we support setting the soundclip device.
633#ifdef WIN32
634 // The SetPlayoutDevice may not be implemented in the case of external ADM.
635 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
636 // PeerConnection interface never set the adm_sc_, so need to check both
637 // in order to determine if the external adm is used.
638 if (!adm_ && !adm_sc_) {
639 int num_of_devices = 0;
640 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
641 num_of_devices > 0) {
642 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
643 == -1) {
644 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
645 voe_wrapper_sc_->error());
646 return false;
647 }
648 } else {
649 LOG(LS_WARNING) << "No valid sound playout device found.";
650 }
651 }
652#endif
653 voe_wrapper_sc_initialized_ = true;
654 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
655 return true;
656}
657
658void WebRtcVoiceEngine::Terminate() {
659 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
660 initialized_ = false;
661
662 StopAecDump();
663
664 if (voe_wrapper_sc_) {
665 voe_wrapper_sc_initialized_ = false;
666 voe_wrapper_sc_->base()->Terminate();
667 }
668 voe_wrapper_->base()->Terminate();
669 desired_local_monitor_enable_ = false;
670}
671
672int WebRtcVoiceEngine::GetCapabilities() {
673 return AUDIO_SEND | AUDIO_RECV;
674}
675
676VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
677 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
678 if (!ch->valid()) {
679 delete ch;
680 ch = NULL;
681 }
682 return ch;
683}
684
685SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
686 if (!EnsureSoundclipEngineInit()) {
687 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
688 << "initialize.";
689 return NULL;
690 }
691 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
692 if (!soundclip->Init() || !soundclip->Enable()) {
693 delete soundclip;
694 return NULL;
695 }
696 return soundclip;
697}
698
699bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
700 if (!ApplyOptions(options)) {
701 return false;
702 }
703 options_ = options;
704 return true;
705}
706
707bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
708 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
709 if (!ApplyOptions(overrides)) {
710 return false;
711 }
712 option_overrides_ = overrides;
713 return true;
714}
715
716bool WebRtcVoiceEngine::ClearOptionOverrides() {
717 LOG(LS_INFO) << "Clearing option overrides.";
718 AudioOptions options = options_;
719 // Only call ApplyOptions if |options_overrides_| contains overrided options.
720 // ApplyOptions affects NS, AGC other options that is shared between
721 // all WebRtcVoiceEngineChannels.
722 if (option_overrides_ == AudioOptions()) {
723 return true;
724 }
725
726 if (!ApplyOptions(options)) {
727 return false;
728 }
729 option_overrides_ = AudioOptions();
730 return true;
731}
732
733// AudioOptions defaults are set in InitInternal (for options with corresponding
734// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
735bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
736 AudioOptions options = options_in; // The options are modified below.
737 // kEcConference is AEC with high suppression.
738 webrtc::EcModes ec_mode = webrtc::kEcConference;
739 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
740 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
741 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
742 bool aecm_comfort_noise = false;
743 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
744 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
745 << aecm_comfort_noise << " (default is false).";
746 }
747
748#if defined(IOS)
749 // On iOS, VPIO provides built-in EC and AGC.
750 options.echo_cancellation.Set(false);
751 options.auto_gain_control.Set(false);
752#elif defined(ANDROID)
753 ec_mode = webrtc::kEcAecm;
754#endif
755
756#if defined(IOS) || defined(ANDROID)
757 // Set the AGC mode for iOS as well despite disabling it above, to avoid
758 // unsupported configuration errors from webrtc.
759 agc_mode = webrtc::kAgcFixedDigital;
760 options.typing_detection.Set(false);
761 options.experimental_agc.Set(false);
762 options.experimental_aec.Set(false);
763 options.experimental_ns.Set(false);
764#endif
765
766 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
767
768 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
769
770 bool echo_cancellation;
771 if (options.echo_cancellation.Get(&echo_cancellation)) {
772 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
773 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
774 return false;
775 } else {
776 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
777 << " with mode " << ec_mode;
778 }
779#if !defined(ANDROID)
780 // TODO(ajm): Remove the error return on Android from webrtc.
781 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
782 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
783 return false;
784 }
785#endif
786 if (ec_mode == webrtc::kEcAecm) {
787 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
788 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
789 return false;
790 }
791 }
792 }
793
794 bool auto_gain_control;
795 if (options.auto_gain_control.Get(&auto_gain_control)) {
796 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
797 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
798 return false;
799 } else {
800 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
801 << " with mode " << agc_mode;
802 }
803 }
804
805 if (options.tx_agc_target_dbov.IsSet() ||
806 options.tx_agc_digital_compression_gain.IsSet() ||
807 options.tx_agc_limiter.IsSet()) {
808 // Override default_agc_config_. Generally, an unset option means "leave
809 // the VoE bits alone" in this function, so we want whatever is set to be
810 // stored as the new "default". If we didn't, then setting e.g.
811 // tx_agc_target_dbov would reset digital compression gain and limiter
812 // settings.
813 // Also, if we don't update default_agc_config_, then adjust_agc_delta
814 // would be an offset from the original values, and not whatever was set
815 // explicitly.
816 default_agc_config_.targetLeveldBOv =
817 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
818 default_agc_config_.targetLeveldBOv);
819 default_agc_config_.digitalCompressionGaindB =
820 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
821 default_agc_config_.digitalCompressionGaindB);
822 default_agc_config_.limiterEnable =
823 options.tx_agc_limiter.GetWithDefaultIfUnset(
824 default_agc_config_.limiterEnable);
825 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
826 LOG_RTCERR3(SetAgcConfig,
827 default_agc_config_.targetLeveldBOv,
828 default_agc_config_.digitalCompressionGaindB,
829 default_agc_config_.limiterEnable);
830 return false;
831 }
832 }
833
834 bool noise_suppression;
835 if (options.noise_suppression.Get(&noise_suppression)) {
836 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
837 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
838 return false;
839 } else {
840 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
841 << " with mode " << ns_mode;
842 }
843 }
844
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000845 bool highpass_filter;
846 if (options.highpass_filter.Get(&highpass_filter)) {
847 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
848 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
849 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
850 return false;
851 }
852 }
853
854 bool stereo_swapping;
855 if (options.stereo_swapping.Get(&stereo_swapping)) {
856 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
857 voep->EnableStereoChannelSwapping(stereo_swapping);
858 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
859 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
860 return false;
861 }
862 }
863
864 bool typing_detection;
865 if (options.typing_detection.Get(&typing_detection)) {
866 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
867 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
868 // In case of error, log the info and continue
869 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
870 }
871 }
872
873 int adjust_agc_delta;
874 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
875 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
876 if (!AdjustAgcLevel(adjust_agc_delta)) {
877 return false;
878 }
879 }
880
881 bool aec_dump;
882 if (options.aec_dump.Get(&aec_dump)) {
883 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
884 if (aec_dump)
885 StartAecDump(kAecDumpByAudioOptionFilename);
886 else
887 StopAecDump();
888 }
889
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000890 webrtc::Config config;
891
892 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000893 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000894 if (experimental_aec_.Get(&experimental_aec)) {
895 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
896 config.Set<webrtc::DelayCorrection>(
897 new webrtc::DelayCorrection(experimental_aec));
898 }
899
900#ifdef USE_WEBRTC_DEV_BRANCH
901 experimental_ns_.SetFrom(options.experimental_ns);
902 bool experimental_ns;
903 if (experimental_ns_.Get(&experimental_ns)) {
904 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
905 config.Set<webrtc::ExperimentalNs>(
906 new webrtc::ExperimentalNs(experimental_ns));
907 }
908#endif
909
910 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
911 // returns NULL on audio_processing().
912 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
913 if (audioproc) {
914 audioproc->SetExtraOptions(config);
915 }
916
917#ifndef USE_WEBRTC_DEV_BRANCH
918 bool experimental_ns;
919 if (options.experimental_ns.Get(&experimental_ns)) {
920 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000921 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
922 // returns NULL on audio_processing().
923 if (audioproc) {
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000924 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
925 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
926 return false;
927 }
928 } else {
929 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
930 << experimental_ns;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000931 }
932 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000933#endif
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000934
935 uint32 recording_sample_rate;
936 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
937 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
938 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
939 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
940 }
941 }
942
943 uint32 playout_sample_rate;
944 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
945 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
946 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
947 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
948 }
949 }
950
951 return true;
952}
953
954bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
955 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
956 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
957 LOG_RTCERR1(SetDelayOffsetMs, offset);
958 return false;
959 }
960
961 return true;
962}
963
964struct ResumeEntry {
965 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
966 : channel(c),
967 playout(p),
968 send(s) {
969 }
970
971 WebRtcVoiceMediaChannel *channel;
972 bool playout;
973 SendFlags send;
974};
975
976// TODO(juberti): Refactor this so that the core logic can be used to set the
977// soundclip device. At that time, reinstate the soundclip pause/resume code.
978bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
979 const Device* out_device) {
980#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000981 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000982 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000983 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000984 kDefaultAudioDeviceId;
985 // The device manager uses -1 as the default device, which was the case for
986 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
987#ifndef WIN32
988 if (-1 == in_id) {
989 in_id = kDefaultAudioDeviceId;
990 }
991 if (-1 == out_id) {
992 out_id = kDefaultAudioDeviceId;
993 }
994#endif
995
996 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
997 in_device->name : "Default device";
998 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
999 out_device->name : "Default device";
1000 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
1001 << ") and speaker to (id=" << out_id << ", name=" << out_name
1002 << ")";
1003
1004 // If we're running the local monitor, we need to stop it first.
1005 bool ret = true;
1006 if (!PauseLocalMonitor()) {
1007 LOG(LS_WARNING) << "Failed to pause local monitor";
1008 ret = false;
1009 }
1010
1011 // Must also pause all audio playback and capture.
1012 for (ChannelList::const_iterator i = channels_.begin();
1013 i != channels_.end(); ++i) {
1014 WebRtcVoiceMediaChannel *channel = *i;
1015 if (!channel->PausePlayout()) {
1016 LOG(LS_WARNING) << "Failed to pause playout";
1017 ret = false;
1018 }
1019 if (!channel->PauseSend()) {
1020 LOG(LS_WARNING) << "Failed to pause send";
1021 ret = false;
1022 }
1023 }
1024
1025 // Find the recording device id in VoiceEngine and set recording device.
1026 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1027 ret = false;
1028 }
1029 if (ret) {
1030 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
1031 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
1032 ret = false;
1033 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00001034 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
1035 if (ap)
1036 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001037 }
1038
1039 // Find the playout device id in VoiceEngine and set playout device.
1040 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1041 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1042 ret = false;
1043 }
1044 if (ret) {
1045 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001046 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001047 ret = false;
1048 }
1049 }
1050
1051 // Resume all audio playback and capture.
1052 for (ChannelList::const_iterator i = channels_.begin();
1053 i != channels_.end(); ++i) {
1054 WebRtcVoiceMediaChannel *channel = *i;
1055 if (!channel->ResumePlayout()) {
1056 LOG(LS_WARNING) << "Failed to resume playout";
1057 ret = false;
1058 }
1059 if (!channel->ResumeSend()) {
1060 LOG(LS_WARNING) << "Failed to resume send";
1061 ret = false;
1062 }
1063 }
1064
1065 // Resume local monitor.
1066 if (!ResumeLocalMonitor()) {
1067 LOG(LS_WARNING) << "Failed to resume local monitor";
1068 ret = false;
1069 }
1070
1071 if (ret) {
1072 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1073 << ") and speaker to (id="<< out_id << " name=" << out_name
1074 << ")";
1075 }
1076
1077 return ret;
1078#else
1079 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001080#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001081}
1082
1083bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1084 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1085 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001086#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001087 *rtc_id = dev_id;
1088 return true;
1089#else
1090 // In Windows and Mac, we need to find the VoiceEngine device id by name
1091 // unless the input dev_id is the default device id.
1092 if (kDefaultAudioDeviceId == dev_id) {
1093 *rtc_id = dev_id;
1094 return true;
1095 }
1096
1097 // Get the number of VoiceEngine audio devices.
1098 int count = 0;
1099 if (is_input) {
1100 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1101 LOG_RTCERR0(GetNumOfRecordingDevices);
1102 return false;
1103 }
1104 } else {
1105 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1106 LOG_RTCERR0(GetNumOfPlayoutDevices);
1107 return false;
1108 }
1109 }
1110
1111 for (int i = 0; i < count; ++i) {
1112 char name[128];
1113 char guid[128];
1114 if (is_input) {
1115 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1116 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1117 } else {
1118 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1119 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1120 }
1121
1122 std::string webrtc_name(name);
1123 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1124 *rtc_id = i;
1125 return true;
1126 }
1127 }
1128 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1129 return false;
1130#endif
1131}
1132
1133bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1134 unsigned int ulevel;
1135 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1136 LOG_RTCERR1(GetSpeakerVolume, level);
1137 return false;
1138 }
1139 *level = ulevel;
1140 return true;
1141}
1142
1143bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1144 ASSERT(level >= 0 && level <= 255);
1145 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1146 LOG_RTCERR1(SetSpeakerVolume, level);
1147 return false;
1148 }
1149 return true;
1150}
1151
1152int WebRtcVoiceEngine::GetInputLevel() {
1153 unsigned int ulevel;
1154 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1155 static_cast<int>(ulevel) : -1;
1156}
1157
1158bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1159 desired_local_monitor_enable_ = enable;
1160 return ChangeLocalMonitor(desired_local_monitor_enable_);
1161}
1162
1163bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1164 // The voe file api is not available in chrome.
1165 if (!voe_wrapper_->file()) {
1166 return false;
1167 }
1168 if (enable && !monitor_) {
1169 monitor_.reset(new WebRtcMonitorStream);
1170 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1171 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1172 // Must call Stop() because there are some cases where Start will report
1173 // failure but still change the state, and if we leave VE in the on state
1174 // then it could crash later when trying to invoke methods on our monitor.
1175 voe_wrapper_->file()->StopRecordingMicrophone();
1176 monitor_.reset();
1177 return false;
1178 }
1179 } else if (!enable && monitor_) {
1180 voe_wrapper_->file()->StopRecordingMicrophone();
1181 monitor_.reset();
1182 }
1183 return true;
1184}
1185
1186bool WebRtcVoiceEngine::PauseLocalMonitor() {
1187 return ChangeLocalMonitor(false);
1188}
1189
1190bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1191 return ChangeLocalMonitor(desired_local_monitor_enable_);
1192}
1193
1194const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1195 return codecs_;
1196}
1197
1198bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1199 return FindWebRtcCodec(in, NULL);
1200}
1201
1202// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1203bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1204 webrtc::CodecInst* out) {
1205 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1206 for (int i = 0; i < ncodecs; ++i) {
1207 webrtc::CodecInst voe_codec;
1208 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1209 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1210 voe_codec.rate, voe_codec.channels, 0);
1211 bool multi_rate = IsCodecMultiRate(voe_codec);
1212 // Allow arbitrary rates for ISAC to be specified.
1213 if (multi_rate) {
1214 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1215 codec.bitrate = 0;
1216 }
1217 if (codec.Matches(in)) {
1218 if (out) {
1219 // Fixup the payload type.
1220 voe_codec.pltype = in.id;
1221
1222 // Set bitrate if specified.
1223 if (multi_rate && in.bitrate != 0) {
1224 voe_codec.rate = in.bitrate;
1225 }
1226
1227 // Apply codec-specific settings.
1228 if (IsIsac(codec)) {
1229 // If ISAC and an explicit bitrate is not specified,
1230 // enable auto bandwidth adjustment.
1231 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1232 }
1233 *out = voe_codec;
1234 }
1235 return true;
1236 }
1237 }
1238 }
1239 return false;
1240}
1241const std::vector<RtpHeaderExtension>&
1242WebRtcVoiceEngine::rtp_header_extensions() const {
1243 return rtp_header_extensions_;
1244}
1245
1246void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1247 // if min_sev == -1, we keep the current log level.
1248 if (min_sev >= 0) {
1249 SetTraceFilter(SeverityToFilter(min_sev));
1250 }
1251 log_options_ = filter;
1252 SetTraceOptions(initialized_ ? log_options_ : "");
1253}
1254
1255int WebRtcVoiceEngine::GetLastEngineError() {
1256 return voe_wrapper_->error();
1257}
1258
1259void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1260 log_filter_ = filter;
1261 tracing_->SetTraceFilter(filter);
1262}
1263
1264// We suppport three different logging settings for VoiceEngine:
1265// 1. Observer callback that goes into talk diagnostic logfile.
1266// Use --logfile and --loglevel
1267//
1268// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1269// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1270//
1271// 3. EC log and dump for debugging QualityEngine.
1272// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1273//
1274// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1275// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1276void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1277 // Set encrypted trace file.
1278 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001279 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280 std::vector<std::string>::iterator tracefile =
1281 std::find(opts.begin(), opts.end(), "tracefile");
1282 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1283 // Write encrypted debug output (at same loglevel) to file
1284 // EncryptedTraceFile no longer supported.
1285 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1286 LOG_RTCERR1(SetTraceFile, *tracefile);
1287 }
1288 }
1289
wu@webrtc.org97077a32013-10-25 21:18:33 +00001290 // Allow trace options to override the trace filter. We default
1291 // it to log_filter_ (as a translation of libjingle log levels)
1292 // elsewhere, but this allows clients to explicitly set webrtc
1293 // log levels.
1294 std::vector<std::string>::iterator tracefilter =
1295 std::find(opts.begin(), opts.end(), "tracefilter");
1296 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001297 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001298 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1299 }
1300 }
1301
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001302 // Set AEC dump file
1303 std::vector<std::string>::iterator recordEC =
1304 std::find(opts.begin(), opts.end(), "recordEC");
1305 if (recordEC != opts.end()) {
1306 ++recordEC;
1307 if (recordEC != opts.end())
1308 StartAecDump(recordEC->c_str());
1309 else
1310 StopAecDump();
1311 }
1312}
1313
1314// Ignore spammy trace messages, mostly from the stats API when we haven't
1315// gotten RTCP info yet from the remote side.
1316bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1317 static const char* kTracesToIgnore[] = {
1318 "\tfailed to GetReportBlockInformation",
1319 "GetRecCodec() failed to get received codec",
1320 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1321 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1322 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1323 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1324 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1325 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1326 "SenderInfoReceived No received SR",
1327 "StatisticsRTP() no statistics available",
1328 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1329 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1330 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1331 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1332 NULL
1333 };
1334 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1335 if (trace.find(*p) != std::string::npos) {
1336 return true;
1337 }
1338 }
1339 return false;
1340}
1341
1342void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1343 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001344 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001345 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001346 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001347 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001348 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001350 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001352 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001353
1354 // Skip past boilerplate prefix text
1355 if (length < 72) {
1356 std::string msg(trace, length);
1357 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1358 LOG_V(sev) << msg;
1359 } else {
1360 std::string msg(trace + 71, length - 72);
1361 if (!ShouldIgnoreTrace(msg)) {
1362 LOG_V(sev) << "webrtc: " << msg;
1363 }
1364 }
1365}
1366
1367void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001368 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369 WebRtcVoiceMediaChannel* channel = NULL;
1370 uint32 ssrc = 0;
1371 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1372 << channel_num << ".";
1373 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1374 ASSERT(channel != NULL);
1375 channel->OnError(ssrc, err_code);
1376 } else {
1377 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1378 << " could not be found in channel list when error reported.";
1379 }
1380}
1381
1382bool WebRtcVoiceEngine::FindChannelAndSsrc(
1383 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1384 ASSERT(channel != NULL && ssrc != NULL);
1385
1386 *channel = NULL;
1387 *ssrc = 0;
1388 // Find corresponding channel and ssrc
1389 for (ChannelList::const_iterator it = channels_.begin();
1390 it != channels_.end(); ++it) {
1391 ASSERT(*it != NULL);
1392 if ((*it)->FindSsrc(channel_num, ssrc)) {
1393 *channel = *it;
1394 return true;
1395 }
1396 }
1397
1398 return false;
1399}
1400
1401// This method will search through the WebRtcVoiceMediaChannels and
1402// obtain the voice engine's channel number.
1403bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1404 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1405 ASSERT(channel_num != NULL);
1406 ASSERT(direction == MPD_RX || direction == MPD_TX);
1407
1408 *channel_num = -1;
1409 // Find corresponding channel for ssrc.
1410 for (ChannelList::const_iterator it = channels_.begin();
1411 it != channels_.end(); ++it) {
1412 ASSERT(*it != NULL);
1413 if (direction & MPD_RX) {
1414 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1415 }
1416 if (*channel_num == -1 && (direction & MPD_TX)) {
1417 *channel_num = (*it)->GetSendChannelNum(ssrc);
1418 }
1419 if (*channel_num != -1) {
1420 return true;
1421 }
1422 }
1423 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1424 return false;
1425}
1426
1427void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001428 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001429 channels_.push_back(channel);
1430}
1431
1432void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001433 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001434 ChannelList::iterator i = std::find(channels_.begin(),
1435 channels_.end(),
1436 channel);
1437 if (i != channels_.end()) {
1438 channels_.erase(i);
1439 }
1440}
1441
1442void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1443 soundclips_.push_back(soundclip);
1444}
1445
1446void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1447 SoundclipList::iterator i = std::find(soundclips_.begin(),
1448 soundclips_.end(),
1449 soundclip);
1450 if (i != soundclips_.end()) {
1451 soundclips_.erase(i);
1452 }
1453}
1454
1455// Adjusts the default AGC target level by the specified delta.
1456// NB: If we start messing with other config fields, we'll want
1457// to save the current webrtc::AgcConfig as well.
1458bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1459 webrtc::AgcConfig config = default_agc_config_;
1460 config.targetLeveldBOv -= delta;
1461
1462 LOG(LS_INFO) << "Adjusting AGC level from default -"
1463 << default_agc_config_.targetLeveldBOv << "dB to -"
1464 << config.targetLeveldBOv << "dB";
1465
1466 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1467 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1468 return false;
1469 }
1470 return true;
1471}
1472
1473bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1474 webrtc::AudioDeviceModule* adm_sc) {
1475 if (initialized_) {
1476 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1477 return false;
1478 }
1479 if (adm_) {
1480 adm_->Release();
1481 adm_ = NULL;
1482 }
1483 if (adm) {
1484 adm_ = adm;
1485 adm_->AddRef();
1486 }
1487
1488 if (adm_sc_) {
1489 adm_sc_->Release();
1490 adm_sc_ = NULL;
1491 }
1492 if (adm_sc) {
1493 adm_sc_ = adm_sc;
1494 adm_sc_->AddRef();
1495 }
1496 return true;
1497}
1498
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001499bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1500 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001501 if (!aec_dump_file_stream) {
1502 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001503 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001504 LOG(LS_WARNING) << "Could not close file.";
1505 return false;
1506 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001507 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001508 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001509 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001510 LOG_RTCERR0(StartDebugRecording);
1511 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001512 return false;
1513 }
1514 is_dumping_aec_ = true;
1515 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001516}
1517
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001518bool WebRtcVoiceEngine::RegisterProcessor(
1519 uint32 ssrc,
1520 VoiceProcessor* voice_processor,
1521 MediaProcessorDirection direction) {
1522 bool register_with_webrtc = false;
1523 int channel_id = -1;
1524 bool success = false;
1525 uint32* processor_ssrc = NULL;
1526 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1527 if (voice_processor == NULL || !found_channel) {
1528 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1529 << " foundChannel: " << found_channel;
1530 return false;
1531 }
1532
1533 webrtc::ProcessingTypes processing_type;
1534 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001535 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001536 if (direction == MPD_RX) {
1537 processing_type = webrtc::kPlaybackAllChannelsMixed;
1538 if (SignalRxMediaFrame.is_empty()) {
1539 register_with_webrtc = true;
1540 processor_ssrc = &rx_processor_ssrc_;
1541 }
1542 SignalRxMediaFrame.connect(voice_processor,
1543 &VoiceProcessor::OnFrame);
1544 } else {
1545 processing_type = webrtc::kRecordingPerChannel;
1546 if (SignalTxMediaFrame.is_empty()) {
1547 register_with_webrtc = true;
1548 processor_ssrc = &tx_processor_ssrc_;
1549 }
1550 SignalTxMediaFrame.connect(voice_processor,
1551 &VoiceProcessor::OnFrame);
1552 }
1553 }
1554 if (register_with_webrtc) {
1555 // TODO(janahan): when registering consider instantiating a
1556 // a VoeMediaProcess object and not make the engine extend the interface.
1557 if (voe()->media() && voe()->media()->
1558 RegisterExternalMediaProcessing(channel_id,
1559 processing_type,
1560 *this) != -1) {
1561 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1562 << channel_id;
1563 *processor_ssrc = ssrc;
1564 success = true;
1565 } else {
1566 LOG_RTCERR2(RegisterExternalMediaProcessing,
1567 channel_id,
1568 processing_type);
1569 success = false;
1570 }
1571 } else {
1572 // If we don't have to register with the engine, we just needed to
1573 // connect a new processor, set success to true;
1574 success = true;
1575 }
1576 return success;
1577}
1578
1579bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1580 MediaProcessorDirection channel_direction,
1581 uint32 ssrc,
1582 VoiceProcessor* voice_processor,
1583 MediaProcessorDirection processor_direction) {
1584 bool success = true;
1585 FrameSignal* signal;
1586 webrtc::ProcessingTypes processing_type;
1587 uint32* processor_ssrc = NULL;
1588 if (channel_direction == MPD_RX) {
1589 signal = &SignalRxMediaFrame;
1590 processing_type = webrtc::kPlaybackAllChannelsMixed;
1591 processor_ssrc = &rx_processor_ssrc_;
1592 } else {
1593 signal = &SignalTxMediaFrame;
1594 processing_type = webrtc::kRecordingPerChannel;
1595 processor_ssrc = &tx_processor_ssrc_;
1596 }
1597
1598 int deregister_id = -1;
1599 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001600 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001601 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1602 signal->disconnect(voice_processor);
1603 int channel_id = -1;
1604 bool found_channel = FindChannelNumFromSsrc(ssrc,
1605 channel_direction,
1606 &channel_id);
1607 if (signal->is_empty() && found_channel) {
1608 deregister_id = channel_id;
1609 }
1610 }
1611 }
1612 if (deregister_id != -1) {
1613 if (voe()->media() &&
1614 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1615 processing_type) != -1) {
1616 *processor_ssrc = 0;
1617 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1618 << deregister_id;
1619 } else {
1620 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1621 deregister_id,
1622 processing_type);
1623 success = false;
1624 }
1625 }
1626 return success;
1627}
1628
1629bool WebRtcVoiceEngine::UnregisterProcessor(
1630 uint32 ssrc,
1631 VoiceProcessor* voice_processor,
1632 MediaProcessorDirection direction) {
1633 bool success = true;
1634 if (voice_processor == NULL) {
1635 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1636 << ssrc;
1637 return false;
1638 }
1639 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1640 success = false;
1641 }
1642 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1643 success = false;
1644 }
1645 return success;
1646}
1647
1648// Implementing method from WebRtc VoEMediaProcess interface
1649// Do not lock mux_channel_cs_ in this callback.
1650void WebRtcVoiceEngine::Process(int channel,
1651 webrtc::ProcessingTypes type,
1652 int16_t audio10ms[],
1653 int length,
1654 int sampling_freq,
1655 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001656 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001657 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1658 if (type == webrtc::kPlaybackAllChannelsMixed) {
1659 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1660 } else if (type == webrtc::kRecordingPerChannel) {
1661 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1662 } else {
1663 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1664 << " channel: " << channel << " type: " << type
1665 << " tx_ssrc: " << tx_processor_ssrc_
1666 << " rx_ssrc: " << rx_processor_ssrc_;
1667 }
1668}
1669
1670void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1671 if (!is_dumping_aec_) {
1672 // Start dumping AEC when we are not dumping.
1673 if (voe_wrapper_->processing()->StartDebugRecording(
1674 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001675 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001676 } else {
1677 is_dumping_aec_ = true;
1678 }
1679 }
1680}
1681
1682void WebRtcVoiceEngine::StopAecDump() {
1683 if (is_dumping_aec_) {
1684 // Stop dumping AEC when we are dumping.
1685 if (voe_wrapper_->processing()->StopDebugRecording() !=
1686 webrtc::AudioProcessing::kNoError) {
1687 LOG_RTCERR0(StopDebugRecording);
1688 }
1689 is_dumping_aec_ = false;
1690 }
1691}
1692
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001693int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001694 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001695}
1696
1697int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1698 return CreateVoiceChannel(voe_wrapper_.get());
1699}
1700
1701int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1702 return CreateVoiceChannel(voe_wrapper_sc_.get());
1703}
1704
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001705class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1706 : public AudioRenderer::Sink {
1707 public:
1708 WebRtcVoiceChannelRenderer(int ch,
1709 webrtc::AudioTransport* voe_audio_transport)
1710 : channel_(ch),
1711 voe_audio_transport_(voe_audio_transport),
1712 renderer_(NULL) {
1713 }
1714 virtual ~WebRtcVoiceChannelRenderer() {
1715 Stop();
1716 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001717
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001718 // Starts the rendering by setting a sink to the renderer to get data
1719 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001720 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001721 // TODO(xians): Make sure Start() is called only once.
1722 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001723 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001724 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001725 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001726 ASSERT(renderer_ == renderer);
1727 return;
1728 }
1729
1730 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1731 // in getUserMedia by default.
1732 renderer->AddChannel(channel_);
1733 renderer->SetSink(this);
1734 renderer_ = renderer;
1735 }
1736
1737 // Stops rendering by setting the sink of the renderer to NULL. No data
1738 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001739 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001740 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001741 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001742 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001743 return;
1744
1745 renderer_->RemoveChannel(channel_);
1746 renderer_->SetSink(NULL);
1747 renderer_ = NULL;
1748 }
1749
1750 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001751 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001752 virtual void OnData(const void* audio_data,
1753 int bits_per_sample,
1754 int sample_rate,
1755 int number_of_channels,
1756 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001757 voe_audio_transport_->OnData(channel_,
1758 audio_data,
1759 bits_per_sample,
1760 sample_rate,
1761 number_of_channels,
1762 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001763 }
1764
1765 // Callback from the |renderer_| when it is going away. In case Start() has
1766 // never been called, this callback won't be triggered.
1767 virtual void OnClose() OVERRIDE {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001768 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001769 // Set |renderer_| to NULL to make sure no more callback will get into
1770 // the renderer.
1771 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001772 }
1773
1774 // Accessor to the VoE channel ID.
1775 int channel() const { return channel_; }
1776
1777 private:
1778 const int channel_;
1779 webrtc::AudioTransport* const voe_audio_transport_;
1780
1781 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1782 // PeerConnection will make sure invalidating the pointer before the object
1783 // goes away.
1784 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001785
1786 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001787 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001788};
1789
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001790// WebRtcVoiceMediaChannel
1791WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1792 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1793 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001794 engine->CreateMediaVoiceChannel()),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001795 send_bw_setting_(false),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001796 send_bw_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001797 options_(),
1798 dtmf_allowed_(false),
1799 desired_playout_(false),
1800 nack_enabled_(false),
1801 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001802 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001803 desired_send_(SEND_NOTHING),
1804 send_(SEND_NOTHING),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001805 shared_bwe_vie_(NULL),
1806 shared_bwe_vie_channel_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001807 default_receive_ssrc_(0) {
1808 engine->RegisterChannel(this);
1809 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1810 << voe_channel();
1811
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001812 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001813}
1814
1815WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1816 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1817 << voe_channel();
buildbot@webrtc.org6e5c7842014-09-19 06:46:37 +00001818 SetupSharedBandwidthEstimation(NULL, -1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001819
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001820 // Remove any remaining send streams, the default channel will be deleted
1821 // later.
1822 while (!send_channels_.empty())
1823 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001824
1825 // Unregister ourselves from the engine.
1826 engine()->UnregisterChannel(this);
1827 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001828 while (!receive_channels_.empty()) {
1829 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001830 }
1831
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001832 // Delete the default channel.
1833 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001834}
1835
1836bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1837 LOG(LS_INFO) << "Setting voice channel options: "
1838 << options.ToString();
1839
wu@webrtc.orgde305012013-10-31 15:40:38 +00001840 // Check if DSCP value is changed from previous.
1841 bool dscp_option_changed = (options_.dscp != options.dscp);
1842
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001843 // TODO(xians): Add support to set different options for different send
1844 // streams after we support multiple APMs.
1845
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001846 // We retain all of the existing options, and apply the given ones
1847 // on top. This means there is no way to "clear" options such that
1848 // they go back to the engine default.
1849 options_.SetAll(options);
1850
1851 if (send_ != SEND_NOTHING) {
1852 if (!engine()->SetOptionOverrides(options_)) {
1853 LOG(LS_WARNING) <<
1854 "Failed to engine SetOptionOverrides during channel SetOptions.";
1855 return false;
1856 }
1857 } else {
1858 // Will be interpreted when appropriate.
1859 }
1860
wu@webrtc.org97077a32013-10-25 21:18:33 +00001861 // Receiver-side auto gain control happens per channel, so set it here from
1862 // options. Note that, like conference mode, setting it on the engine won't
1863 // have the desired effect, since voice channels don't inherit options from
1864 // the media engine when those options are applied per-channel.
1865 bool rx_auto_gain_control;
1866 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1867 if (engine()->voe()->processing()->SetRxAgcStatus(
1868 voe_channel(), rx_auto_gain_control,
1869 webrtc::kAgcFixedDigital) == -1) {
1870 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1871 return false;
1872 } else {
1873 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1874 << " with mode " << webrtc::kAgcFixedDigital;
1875 }
1876 }
1877 if (options.rx_agc_target_dbov.IsSet() ||
1878 options.rx_agc_digital_compression_gain.IsSet() ||
1879 options.rx_agc_limiter.IsSet()) {
1880 webrtc::AgcConfig config;
1881 // If only some of the options are being overridden, get the current
1882 // settings for the channel and bail if they aren't available.
1883 if (!options.rx_agc_target_dbov.IsSet() ||
1884 !options.rx_agc_digital_compression_gain.IsSet() ||
1885 !options.rx_agc_limiter.IsSet()) {
1886 if (engine()->voe()->processing()->GetRxAgcConfig(
1887 voe_channel(), config) != 0) {
1888 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1889 << "channel " << voe_channel() << ". Since not all rx "
1890 << "agc options are specified, unable to safely set rx "
1891 << "agc options.";
1892 return false;
1893 }
1894 }
1895 config.targetLeveldBOv =
1896 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1897 config.targetLeveldBOv);
1898 config.digitalCompressionGaindB =
1899 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1900 config.digitalCompressionGaindB);
1901 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1902 config.limiterEnable);
1903 if (engine()->voe()->processing()->SetRxAgcConfig(
1904 voe_channel(), config) == -1) {
1905 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1906 config.digitalCompressionGaindB, config.limiterEnable);
1907 return false;
1908 }
1909 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001910 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001911 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001912 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001913 dscp = kAudioDscpValue;
1914 if (MediaChannel::SetDscp(dscp) != 0) {
1915 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1916 }
1917 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001918
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001919 // Force update of Video Engine BWE forwarding to reflect experiment setting.
1920 if (!SetupSharedBandwidthEstimation(shared_bwe_vie_,
1921 shared_bwe_vie_channel_)) {
1922 return false;
1923 }
1924
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001925 LOG(LS_INFO) << "Set voice channel options. Current options: "
1926 << options_.ToString();
1927 return true;
1928}
1929
1930bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1931 const std::vector<AudioCodec>& codecs) {
1932 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001933 LOG(LS_INFO) << "Setting receive voice codecs:";
1934
1935 std::vector<AudioCodec> new_codecs;
1936 // Find all new codecs. We allow adding new codecs but don't allow changing
1937 // the payload type of codecs that is already configured since we might
1938 // already be receiving packets with that payload type.
1939 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001940 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001941 AudioCodec old_codec;
1942 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1943 if (old_codec.id != it->id) {
1944 LOG(LS_ERROR) << it->name << " payload type changed.";
1945 return false;
1946 }
1947 } else {
1948 new_codecs.push_back(*it);
1949 }
1950 }
1951 if (new_codecs.empty()) {
1952 // There are no new codecs to configure. Already configured codecs are
1953 // never removed.
1954 return true;
1955 }
1956
1957 if (playout_) {
1958 // Receive codecs can not be changed while playing. So we temporarily
1959 // pause playout.
1960 PausePlayout();
1961 }
1962
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001963 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001964 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1965 it != new_codecs.end() && ret; ++it) {
1966 webrtc::CodecInst voe_codec;
1967 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1968 LOG(LS_INFO) << ToString(*it);
1969 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001970 if (default_receive_ssrc_ == 0) {
1971 // Set the receive codecs on the default channel explicitly if the
1972 // default channel is not used by |receive_channels_|, this happens in
1973 // conference mode or in non-conference mode when there is no playout
1974 // channel.
1975 // TODO(xians): Figure out how we use the default channel in conference
1976 // mode.
1977 if (engine()->voe()->codec()->SetRecPayloadType(
1978 voe_channel(), voe_codec) == -1) {
1979 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1980 ret = false;
1981 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001982 }
1983
1984 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001985 for (ChannelMap::iterator it = receive_channels_.begin();
1986 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001987 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001988 it->second->channel(), voe_codec) == -1) {
1989 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001990 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001991 ret = false;
1992 }
1993 }
1994 } else {
1995 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1996 ret = false;
1997 }
1998 }
1999 if (ret) {
2000 recv_codecs_ = codecs;
2001 }
2002
2003 if (desired_playout_ && !playout_) {
2004 ResumePlayout();
2005 }
2006 return ret;
2007}
2008
2009bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002010 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002011 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002012 engine()->voe()->codec()->SetVADStatus(channel, false);
2013 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002014#ifdef USE_WEBRTC_DEV_BRANCH
2015 engine()->voe()->rtp()->SetREDStatus(channel, false);
2016 engine()->voe()->codec()->SetFECStatus(channel, false);
2017#else
2018 // TODO(minyue): Remove code under #else case after new WebRTC roll.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002019 engine()->voe()->rtp()->SetFECStatus(channel, false);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002020#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002021
2022 // Scan through the list to figure out the codec to use for sending, along
2023 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002024 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002025 webrtc::CodecInst send_codec;
2026 memset(&send_codec, 0, sizeof(send_codec));
2027
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002028 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002029 bool enable_codec_fec = false;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002030
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002031 // max_playback_rate <= 0 will not trigger setting of maximum encoding
2032 // bandwidth.
2033 int max_playback_rate = 0;
2034
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002035 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002036 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2037 it != codecs.end(); ++it) {
2038 // Ignore codecs we don't know about. The negotiation step should prevent
2039 // this, but double-check to be sure.
2040 webrtc::CodecInst voe_codec;
2041 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002042 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002043 continue;
2044 }
2045
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002046 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2047 // Skip telephone-event/CN codec, which will be handled later.
2048 continue;
2049 }
2050
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002051
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002052 // We'll use the first codec in the list to actually send audio data.
2053 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002054 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002055 // used is specified in params.
2056 if (IsRedCodec(it->name)) {
2057 // Parse out the RED parameters. If we fail, just ignore RED;
2058 // we don't support all possible params/usage scenarios.
2059 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2060 continue;
2061 }
2062
2063 // Enable redundant encoding of the specified codec. Treat any
2064 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002065#ifdef USE_WEBRTC_DEV_BRANCH
2066 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2067 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2068 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
2069#else
2070 // TODO(minyue): Remove code under #else case after new WebRTC roll.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002071 LOG(LS_INFO) << "Enabling FEC";
2072 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2073 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002074#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002075 return false;
2076 }
2077 } else {
2078 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002079 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002080 // For Opus as the send codec, we are to enable inband FEC if requested
2081 // and set maximum playback rate.
2082 if (IsOpus(*it)) {
2083 GetOpusConfig(*it, &send_codec, &enable_codec_fec, &max_playback_rate);
2084 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002085 }
2086 found_send_codec = true;
2087 break;
2088 }
2089
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002090 if (nack_enabled_ != nack_enabled) {
2091 SetNack(channel, nack_enabled);
2092 nack_enabled_ = nack_enabled;
2093 }
2094
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002095 if (!found_send_codec) {
2096 LOG(LS_WARNING) << "Received empty list of codecs.";
2097 return false;
2098 }
2099
2100 // Set the codec immediately, since SetVADStatus() depends on whether
2101 // the current codec is mono or stereo.
2102 if (!SetSendCodec(channel, send_codec))
2103 return false;
2104
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002105 // FEC should be enabled after SetSendCodec.
2106 if (enable_codec_fec) {
2107 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2108 << channel;
2109#ifdef USE_WEBRTC_DEV_BRANCH
2110 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2111 // Enable codec internal FEC. Treat any failure as fatal internal error.
2112 LOG_RTCERR2(SetFECStatus, channel, true);
2113 return false;
2114 }
2115#endif // USE_WEBRTC_DEV_BRANCH
2116 }
2117
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002118 // maxplaybackrate should be set after SetSendCodec.
2119 if (max_playback_rate > 0) {
2120 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
2121 << max_playback_rate
2122 << " Hz on channel "
2123 << channel;
2124#ifdef USE_WEBRTC_DEV_BRANCH
2125 // (max_playback_rate + 1) >> 1 is to obtain ceil(max_playback_rate / 2.0).
2126 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
2127 channel, max_playback_rate) == -1) {
2128 LOG(LS_WARNING) << "Could not set maximum playback rate.";
2129 }
2130#endif
2131 }
2132
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002133 // Always update the |send_codec_| to the currently set send codec.
2134 send_codec_.reset(new webrtc::CodecInst(send_codec));
2135
2136 if (send_bw_setting_) {
2137 SetSendBandwidthInternal(send_bw_bps_);
2138 }
2139
2140 // Loop through the codecs list again to config the telephone-event/CN codec.
2141 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2142 it != codecs.end(); ++it) {
2143 // Ignore codecs we don't know about. The negotiation step should prevent
2144 // this, but double-check to be sure.
2145 webrtc::CodecInst voe_codec;
2146 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2147 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2148 continue;
2149 }
2150
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002151 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2152 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002153 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002154 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2155 channel, it->id) == -1) {
2156 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2157 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002158 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002159 } else if (IsCNCodec(it->name)) {
2160 // Turn voice activity detection/comfort noise on if supported.
2161 // Set the wideband CN payload type appropriately.
2162 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002163 webrtc::PayloadFrequencies cn_freq;
2164 switch (it->clockrate) {
2165 case 8000:
2166 cn_freq = webrtc::kFreq8000Hz;
2167 break;
2168 case 16000:
2169 cn_freq = webrtc::kFreq16000Hz;
2170 break;
2171 case 32000:
2172 cn_freq = webrtc::kFreq32000Hz;
2173 break;
2174 default:
2175 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2176 << " not supported.";
2177 continue;
2178 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002179 // Set the CN payloadtype and the VAD status.
2180 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2181 if (cn_freq != webrtc::kFreq8000Hz) {
2182 if (engine()->voe()->codec()->SetSendCNPayloadType(
2183 channel, it->id, cn_freq) == -1) {
2184 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2185 // TODO(ajm): This failure condition will be removed from VoE.
2186 // Restore the return here when we update to a new enough webrtc.
2187 //
2188 // Not returning false because the SetSendCNPayloadType will fail if
2189 // the channel is already sending.
2190 // This can happen if the remote description is applied twice, for
2191 // example in the case of ROAP on top of JSEP, where both side will
2192 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002193 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002194 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002195 // Only turn on VAD if we have a CN payload type that matches the
2196 // clockrate for the codec we are going to use.
2197 if (it->clockrate == send_codec.plfreq) {
2198 LOG(LS_INFO) << "Enabling VAD";
2199 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2200 LOG_RTCERR2(SetVADStatus, channel, true);
2201 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002202 }
2203 }
2204 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002205 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002206 return true;
2207}
2208
2209bool WebRtcVoiceMediaChannel::SetSendCodecs(
2210 const std::vector<AudioCodec>& codecs) {
2211 dtmf_allowed_ = false;
2212 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2213 it != codecs.end(); ++it) {
2214 // Find the DTMF telephone event "codec".
2215 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2216 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2217 dtmf_allowed_ = true;
2218 }
2219 }
2220
2221 // Cache the codecs in order to configure the channel created later.
2222 send_codecs_ = codecs;
2223 for (ChannelMap::iterator iter = send_channels_.begin();
2224 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002225 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002226 return false;
2227 }
2228 }
2229
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002230 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002231 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002232 return true;
2233}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002234
2235void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2236 bool nack_enabled) {
2237 for (ChannelMap::const_iterator it = channels.begin();
2238 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002239 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002240 }
2241}
2242
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002243void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002244 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002245 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002246 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2247 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002248 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002249 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2250 }
2251}
2252
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002253bool WebRtcVoiceMediaChannel::SetSendCodec(
2254 const webrtc::CodecInst& send_codec) {
2255 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2256 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002257 for (ChannelMap::iterator iter = send_channels_.begin();
2258 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002259 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002260 return false;
2261 }
2262
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002263 return true;
2264}
2265
2266bool WebRtcVoiceMediaChannel::SetSendCodec(
2267 int channel, const webrtc::CodecInst& send_codec) {
2268 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2269 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2270
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002271 webrtc::CodecInst current_codec;
2272 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2273 (send_codec == current_codec)) {
2274 // Codec is already configured, we can return without setting it again.
2275 return true;
2276 }
2277
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002278 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2279 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002280 return false;
2281 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002282 return true;
2283}
2284
2285bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2286 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002287 if (receive_extensions_ == extensions) {
2288 return true;
2289 }
2290
2291 // The default channel may or may not be in |receive_channels_|. Set the rtp
2292 // header extensions for default channel regardless.
2293 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2294 return false;
2295 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002296
2297 // Loop through all receive channels and enable/disable the extensions.
2298 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2299 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002300 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2301 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002302 return false;
2303 }
2304 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002305
2306 receive_extensions_ = extensions;
2307 return true;
2308}
2309
2310bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2311 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002312 const RtpHeaderExtension* audio_level_extension =
2313 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2314 if (!SetHeaderExtension(
2315 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2316 audio_level_extension)) {
2317 return false;
2318 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002319
2320 const RtpHeaderExtension* send_time_extension =
2321 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2322 if (!SetHeaderExtension(
2323 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2324 send_time_extension)) {
2325 return false;
2326 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002327 return true;
2328}
2329
2330bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2331 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002332 if (send_extensions_ == extensions) {
2333 return true;
2334 }
2335
2336 // The default channel may or may not be in |send_channels_|. Set the rtp
2337 // header extensions for default channel regardless.
2338
2339 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2340 return false;
2341 }
2342
2343 // Loop through all send channels and enable/disable the extensions.
2344 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2345 channel_it != send_channels_.end(); ++channel_it) {
2346 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2347 extensions)) {
2348 return false;
2349 }
2350 }
2351
2352 send_extensions_ = extensions;
2353 return true;
2354}
2355
2356bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2357 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002358 const RtpHeaderExtension* audio_level_extension =
2359 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002360
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002361 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002362 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002363 audio_level_extension)) {
2364 return false;
2365 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002366
2367 const RtpHeaderExtension* send_time_extension =
2368 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002369 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002370 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002371 send_time_extension)) {
2372 return false;
2373 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002374
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002375 return true;
2376}
2377
2378bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2379 desired_playout_ = playout;
2380 return ChangePlayout(desired_playout_);
2381}
2382
2383bool WebRtcVoiceMediaChannel::PausePlayout() {
2384 return ChangePlayout(false);
2385}
2386
2387bool WebRtcVoiceMediaChannel::ResumePlayout() {
2388 return ChangePlayout(desired_playout_);
2389}
2390
2391bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2392 if (playout_ == playout) {
2393 return true;
2394 }
2395
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002396 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002397 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002398 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002399 // Only toggle the default channel if we don't have any other channels.
2400 result = SetPlayout(voe_channel(), playout);
2401 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002402 for (ChannelMap::iterator it = receive_channels_.begin();
2403 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002404 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002405 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002406 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002407 result = false;
2408 }
2409 }
2410
2411 if (result) {
2412 playout_ = playout;
2413 }
2414 return result;
2415}
2416
2417bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2418 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002419 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002420 return ChangeSend(desired_send_);
2421 return true;
2422}
2423
2424bool WebRtcVoiceMediaChannel::PauseSend() {
2425 return ChangeSend(SEND_NOTHING);
2426}
2427
2428bool WebRtcVoiceMediaChannel::ResumeSend() {
2429 return ChangeSend(desired_send_);
2430}
2431
2432bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2433 if (send_ == send) {
2434 return true;
2435 }
2436
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002437 // Change the settings on each send channel.
2438 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002439 engine()->SetOptionOverrides(options_);
2440
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002441 // Change the settings on each send channel.
2442 for (ChannelMap::iterator iter = send_channels_.begin();
2443 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002444 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002445 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002446 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002447
2448 // Clear up the options after stopping sending.
2449 if (send == SEND_NOTHING)
2450 engine()->ClearOptionOverrides();
2451
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002452 send_ = send;
2453 return true;
2454}
2455
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002456bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2457 if (send == SEND_MICROPHONE) {
2458 if (engine()->voe()->base()->StartSend(channel) == -1) {
2459 LOG_RTCERR1(StartSend, channel);
2460 return false;
2461 }
2462 if (engine()->voe()->file() &&
2463 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2464 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2465 return false;
2466 }
2467 } else { // SEND_NOTHING
2468 ASSERT(send == SEND_NOTHING);
2469 if (engine()->voe()->base()->StopSend(channel) == -1) {
2470 LOG_RTCERR1(StopSend, channel);
2471 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002472 }
2473 }
2474
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002475 return true;
2476}
2477
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002478// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002479void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2480 if (engine()->voe()->network()->RegisterExternalTransport(
2481 channel, *this) == -1) {
2482 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2483 }
2484
2485 // Enable RTCP (for quality stats and feedback messages)
2486 EnableRtcp(channel);
2487
2488 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2489 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002490
2491 // Set RTP header extension for the new channel.
2492 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002493}
2494
2495bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2496 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2497 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2498 }
2499
2500 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2501 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002502 return false;
2503 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002504
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002505 return true;
2506}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002507
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002508bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2509 // If the default channel is already used for sending create a new channel
2510 // otherwise use the default channel for sending.
2511 int channel = GetSendChannelNum(sp.first_ssrc());
2512 if (channel != -1) {
2513 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2514 return false;
2515 }
2516
2517 bool default_channel_is_available = true;
2518 for (ChannelMap::const_iterator iter = send_channels_.begin();
2519 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002520 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002521 default_channel_is_available = false;
2522 break;
2523 }
2524 }
2525 if (default_channel_is_available) {
2526 channel = voe_channel();
2527 } else {
2528 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002529 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002530 if (channel == -1) {
2531 LOG_RTCERR0(CreateChannel);
2532 return false;
2533 }
2534
2535 ConfigureSendChannel(channel);
2536 }
2537
2538 // Save the channel to send_channels_, so that RemoveSendStream() can still
2539 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002540 webrtc::AudioTransport* audio_transport =
2541 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002542 send_channels_.insert(std::make_pair(
2543 sp.first_ssrc(),
2544 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002545
2546 // Set the send (local) SSRC.
2547 // If there are multiple send SSRCs, we can only set the first one here, and
2548 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2549 // (with a codec requires multiple SSRC(s)).
2550 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2551 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2552 return false;
2553 }
2554
2555 // At this point the channel's local SSRC has been updated. If the channel is
2556 // the default channel make sure that all the receive channels are updated as
2557 // well. Receive channels have to have the same SSRC as the default channel in
2558 // order to send receiver reports with this SSRC.
2559 if (IsDefaultChannel(channel)) {
2560 for (ChannelMap::const_iterator it = receive_channels_.begin();
2561 it != receive_channels_.end(); ++it) {
2562 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002563 if (!IsDefaultChannel(it->second->channel())) {
2564 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002565 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002566 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002567 return false;
2568 }
2569 }
2570 }
2571 }
2572
2573 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002574 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2575 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002576 }
2577
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002578 // Set the current codecs to be used for the new channel.
2579 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002580 return false;
2581
2582 return ChangeSend(channel, desired_send_);
2583}
2584
2585bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2586 ChannelMap::iterator it = send_channels_.find(ssrc);
2587 if (it == send_channels_.end()) {
2588 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2589 << " which doesn't exist.";
2590 return false;
2591 }
2592
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002593 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002594 ChangeSend(channel, SEND_NOTHING);
2595
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002596 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2597 // this will disconnect the audio renderer with the send channel.
2598 delete it->second;
2599 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002600
2601 if (IsDefaultChannel(channel)) {
2602 // Do not delete the default channel since the receive channels depend on
2603 // the default channel, recycle it instead.
2604 ChangeSend(channel, SEND_NOTHING);
2605 } else {
2606 // Clean up and delete the send channel.
2607 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2608 << " with VoiceEngine channel #" << channel << ".";
2609 if (!DeleteChannel(channel))
2610 return false;
2611 }
2612
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002613 if (send_channels_.empty())
2614 ChangeSend(SEND_NOTHING);
2615
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002616 return true;
2617}
2618
2619bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002620 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002621
2622 if (!VERIFY(sp.ssrcs.size() == 1))
2623 return false;
2624 uint32 ssrc = sp.first_ssrc();
2625
wu@webrtc.org78187522013-10-07 23:32:02 +00002626 if (ssrc == 0) {
2627 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2628 return false;
2629 }
2630
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002631 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2632 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002633 return false;
2634 }
2635
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002636 // Reuse default channel for recv stream in non-conference mode call
2637 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002638 webrtc::AudioTransport* audio_transport =
2639 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002640 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2641 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2642 << " reuse default channel";
2643 default_receive_ssrc_ = sp.first_ssrc();
2644 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002645 default_receive_ssrc_,
2646 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002647 if (!SetupSharedBweOnChannel(voe_channel())) {
2648 return false;
2649 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002650 return SetPlayout(voe_channel(), playout_);
2651 }
2652
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002653 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002654 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002655 if (channel == -1) {
2656 LOG_RTCERR0(CreateChannel);
2657 return false;
2658 }
2659
wu@webrtc.org78187522013-10-07 23:32:02 +00002660 if (!ConfigureRecvChannel(channel)) {
2661 DeleteChannel(channel);
2662 return false;
2663 }
2664
2665 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002666 std::make_pair(
2667 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002668
2669 LOG(LS_INFO) << "New audio stream " << ssrc
2670 << " registered to VoiceEngine channel #"
2671 << channel << ".";
2672 return true;
2673}
2674
2675bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002676 // Configure to use external transport, like our default channel.
2677 if (engine()->voe()->network()->RegisterExternalTransport(
2678 channel, *this) == -1) {
2679 LOG_RTCERR2(SetExternalTransport, channel, this);
2680 return false;
2681 }
2682
2683 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002684 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002685 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2686 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002687 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002688 return false;
2689 }
2690 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002691 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002692 return false;
2693 }
2694
2695 // Use the same recv payload types as our default channel.
2696 ResetRecvCodecs(channel);
2697 if (!recv_codecs_.empty()) {
2698 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2699 it != recv_codecs_.end(); ++it) {
2700 webrtc::CodecInst voe_codec;
2701 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2702 voe_codec.pltype = it->id;
2703 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2704 if (engine()->voe()->codec()->GetRecPayloadType(
2705 voe_channel(), voe_codec) != -1) {
2706 if (engine()->voe()->codec()->SetRecPayloadType(
2707 channel, voe_codec) == -1) {
2708 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2709 return false;
2710 }
2711 }
2712 }
2713 }
2714 }
2715
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002716 if (InConferenceMode()) {
2717 // To be in par with the video, voe_channel() is not used for receiving in
2718 // a conference call.
2719 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2720 // This is the first stream in a multi user meeting. We can now
2721 // disable playback of the default stream. This since the default
2722 // stream will probably have received some initial packets before
2723 // the new stream was added. This will mean that the CN state from
2724 // the default channel will be mixed in with the other streams
2725 // throughout the whole meeting, which might be disturbing.
2726 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2727 SetPlayout(voe_channel(), false);
2728 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002729 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002730 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002731
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002732 // Set RTP header extension for the new channel.
2733 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2734 return false;
2735 }
2736
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002737 // Set up channel to be able to forward incoming packets to video engine BWE.
2738 if (!SetupSharedBweOnChannel(channel)) {
2739 return false;
2740 }
2741
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002742 return SetPlayout(channel, playout_);
2743}
2744
2745bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002746 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002747 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002748 if (it == receive_channels_.end()) {
2749 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2750 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002751 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002752 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002753
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002754 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2755 // will disconnect the audio renderer with the receive channel.
2756 // Cache the channel before the deletion.
2757 const int channel = it->second->channel();
2758 delete it->second;
2759 receive_channels_.erase(it);
2760
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002761 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002762 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002763 // Recycle the default channel is for recv stream.
2764 if (playout_)
2765 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002766
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002767 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002768 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002769 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002770
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002771 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002772 << " with VoiceEngine channel #" << channel << ".";
2773 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002774 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002775
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002776 bool enable_default_channel_playout = false;
2777 if (receive_channels_.empty()) {
2778 // The last stream was removed. We can now enable the default
2779 // channel for new channels to be played out immediately without
2780 // waiting for AddStream messages.
2781 // We do this for both conference mode and non-conference mode.
2782 // TODO(oja): Does the default channel still have it's CN state?
2783 enable_default_channel_playout = true;
2784 }
2785 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2786 default_receive_ssrc_ != 0) {
2787 // Only the default channel is active, enable the playout on default
2788 // channel.
2789 enable_default_channel_playout = true;
2790 }
2791 if (enable_default_channel_playout && playout_) {
2792 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2793 SetPlayout(voe_channel(), true);
2794 }
2795
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002796 return true;
2797}
2798
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002799bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2800 AudioRenderer* renderer) {
2801 ChannelMap::iterator it = receive_channels_.find(ssrc);
2802 if (it == receive_channels_.end()) {
2803 if (renderer) {
2804 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002805 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002806 return false;
2807 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002808
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002809 // The channel likely has gone away, do nothing.
2810 return true;
2811 }
2812
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002813 if (renderer)
2814 it->second->Start(renderer);
2815 else
2816 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002817
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002818 return true;
2819}
2820
2821bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2822 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002823 ChannelMap::iterator it = send_channels_.find(ssrc);
2824 if (it == send_channels_.end()) {
2825 if (renderer) {
2826 // Return an error if trying to set a valid renderer with an invalid ssrc.
2827 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2828 return false;
2829 }
2830
2831 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002832 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002833 }
2834
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002835 if (renderer)
2836 it->second->Start(renderer);
2837 else
2838 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002839
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002840 return true;
2841}
2842
2843bool WebRtcVoiceMediaChannel::GetActiveStreams(
2844 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002845 // In conference mode, the default channel should not be in
2846 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002847 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002848 for (ChannelMap::iterator it = receive_channels_.begin();
2849 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002850 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002851 if (level > 0) {
2852 actives->push_back(std::make_pair(it->first, level));
2853 }
2854 }
2855 return true;
2856}
2857
2858int WebRtcVoiceMediaChannel::GetOutputLevel() {
2859 // return the highest output level of all streams
2860 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002861 for (ChannelMap::iterator it = receive_channels_.begin();
2862 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002863 int level = GetOutputLevel(it->second->channel());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002864 highest = rtc::_max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002865 }
2866 return highest;
2867}
2868
2869int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2870 int ret;
2871 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2872 // In case of error, log the info and continue
2873 LOG_RTCERR0(TimeSinceLastTyping);
2874 ret = -1;
2875 } else {
2876 ret *= 1000; // We return ms, webrtc returns seconds.
2877 }
2878 return ret;
2879}
2880
2881void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2882 int cost_per_typing, int reporting_threshold, int penalty_decay,
2883 int type_event_delay) {
2884 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2885 time_window, cost_per_typing,
2886 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2887 // In case of error, log the info and continue
2888 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2889 cost_per_typing, reporting_threshold, penalty_decay,
2890 type_event_delay);
2891 }
2892}
2893
2894bool WebRtcVoiceMediaChannel::SetOutputScaling(
2895 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002896 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002897 // Collect the channels to scale the output volume.
2898 std::vector<int> channels;
2899 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002900 // Default channel is not in receive_channels_ if it is not being used for
2901 // playout.
2902 if (default_receive_ssrc_ == 0)
2903 channels.push_back(voe_channel());
2904 for (ChannelMap::const_iterator it = receive_channels_.begin();
2905 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002906 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002907 }
2908 } else { // Collect only the channel of the specified ssrc.
2909 int channel = GetReceiveChannelNum(ssrc);
2910 if (-1 == channel) {
2911 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2912 return false;
2913 }
2914 channels.push_back(channel);
2915 }
2916
2917 // Scale the output volume for the collected channels. We first normalize to
2918 // scale the volume and then set the left and right pan.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002919 float scale = static_cast<float>(rtc::_max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002920 if (scale > 0.0001f) {
2921 left /= scale;
2922 right /= scale;
2923 }
2924 for (std::vector<int>::const_iterator it = channels.begin();
2925 it != channels.end(); ++it) {
2926 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2927 *it, scale)) {
2928 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2929 return false;
2930 }
2931 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2932 *it, static_cast<float>(left), static_cast<float>(right))) {
2933 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2934 // Do not return if fails. SetOutputVolumePan is not available for all
2935 // pltforms.
2936 }
2937 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2938 << " right=" << right * scale
2939 << " for channel " << *it << " and ssrc " << ssrc;
2940 }
2941 return true;
2942}
2943
2944bool WebRtcVoiceMediaChannel::GetOutputScaling(
2945 uint32 ssrc, double* left, double* right) {
2946 if (!left || !right) return false;
2947
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002948 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002949 // Determine which channel based on ssrc.
2950 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2951 if (channel == -1) {
2952 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2953 return false;
2954 }
2955
2956 float scaling;
2957 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2958 channel, scaling)) {
2959 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2960 return false;
2961 }
2962
2963 float left_pan;
2964 float right_pan;
2965 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2966 channel, left_pan, right_pan)) {
2967 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2968 // If GetOutputVolumePan fails, we use the default left and right pan.
2969 left_pan = 1.0f;
2970 right_pan = 1.0f;
2971 }
2972
2973 *left = scaling * left_pan;
2974 *right = scaling * right_pan;
2975 return true;
2976}
2977
2978bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2979 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2980 return true;
2981}
2982
2983bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2984 bool play, bool loop) {
2985 if (!ringback_tone_) {
2986 return false;
2987 }
2988
2989 // The voe file api is not available in chrome.
2990 if (!engine()->voe()->file()) {
2991 return false;
2992 }
2993
2994 // Determine which VoiceEngine channel to play on.
2995 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2996 if (channel == -1) {
2997 return false;
2998 }
2999
3000 // Make sure the ringtone is cued properly, and play it out.
3001 if (play) {
3002 ringback_tone_->set_loop(loop);
3003 ringback_tone_->Rewind();
3004 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
3005 ringback_tone_.get()) == -1) {
3006 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
3007 LOG(LS_ERROR) << "Unable to start ringback tone";
3008 return false;
3009 }
3010 ringback_channels_.insert(channel);
3011 LOG(LS_INFO) << "Started ringback on channel " << channel;
3012 } else {
3013 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
3014 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
3015 LOG_RTCERR1(StopPlayingFileLocally, channel);
3016 return false;
3017 }
3018 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
3019 ringback_channels_.erase(channel);
3020 }
3021
3022 return true;
3023}
3024
3025bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3026 return dtmf_allowed_;
3027}
3028
3029bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3030 int duration, int flags) {
3031 if (!dtmf_allowed_) {
3032 return false;
3033 }
3034
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003035 // Send the event.
3036 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003037 int channel = -1;
3038 if (ssrc == 0) {
3039 bool default_channel_is_inuse = false;
3040 for (ChannelMap::const_iterator iter = send_channels_.begin();
3041 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003042 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003043 default_channel_is_inuse = true;
3044 break;
3045 }
3046 }
3047 if (default_channel_is_inuse) {
3048 channel = voe_channel();
3049 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003050 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003051 }
3052 } else {
3053 channel = GetSendChannelNum(ssrc);
3054 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003055 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003056 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3057 << ssrc << " is not in use.";
3058 return false;
3059 }
3060 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003061 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3062 channel, event, true, duration) == -1) {
3063 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003064 return false;
3065 }
3066 }
3067
3068 // Play the event.
3069 if (flags & cricket::DF_PLAY) {
3070 // Play DTMF tone locally.
3071 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3072 LOG_RTCERR2(PlayDtmfTone, event, duration);
3073 return false;
3074 }
3075 }
3076
3077 return true;
3078}
3079
wu@webrtc.orga9890802013-12-13 00:21:03 +00003080void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003081 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003082 // Pick which channel to send this packet to. If this packet doesn't match
3083 // any multiplexed streams, just send it to the default channel. Otherwise,
3084 // send it to the specific decoder instance for that stream.
3085 int which_channel = GetReceiveChannelNum(
3086 ParseSsrc(packet->data(), packet->length(), false));
3087 if (which_channel == -1) {
3088 which_channel = voe_channel();
3089 }
3090
3091 // Stop any ringback that might be playing on the channel.
3092 // It's possible the ringback has already stopped, ih which case we'll just
3093 // use the opportunity to remove the channel from ringback_channels_.
3094 if (engine()->voe()->file()) {
3095 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3096 if (it != ringback_channels_.end()) {
3097 if (engine()->voe()->file()->IsPlayingFileLocally(
3098 which_channel) == 1) {
3099 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3100 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3101 << " due to incoming media";
3102 }
3103 ringback_channels_.erase(which_channel);
3104 }
3105 }
3106
3107 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003108 engine()->voe()->network()->ReceivedRTPPacket(
3109 which_channel,
3110 packet->data(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003111 static_cast<unsigned int>(packet->length()),
3112 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003113}
3114
wu@webrtc.orga9890802013-12-13 00:21:03 +00003115void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003116 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003117 // Sending channels need all RTCP packets with feedback information.
3118 // Even sender reports can contain attached report blocks.
3119 // Receiving channels need sender reports in order to create
3120 // correct receiver reports.
3121 int type = 0;
3122 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3123 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3124 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003125 }
3126
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003127 // If it is a sender report, find the channel that is listening.
3128 bool has_sent_to_default_channel = false;
3129 if (type == kRtcpTypeSR) {
3130 int which_channel = GetReceiveChannelNum(
3131 ParseSsrc(packet->data(), packet->length(), true));
3132 if (which_channel != -1) {
3133 engine()->voe()->network()->ReceivedRTCPPacket(
3134 which_channel,
3135 packet->data(),
3136 static_cast<unsigned int>(packet->length()));
3137
3138 if (IsDefaultChannel(which_channel))
3139 has_sent_to_default_channel = true;
3140 }
3141 }
3142
3143 // SR may continue RR and any RR entry may correspond to any one of the send
3144 // channels. So all RTCP packets must be forwarded all send channels. VoE
3145 // will filter out RR internally.
3146 for (ChannelMap::iterator iter = send_channels_.begin();
3147 iter != send_channels_.end(); ++iter) {
3148 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003149 if (IsDefaultChannel(iter->second->channel()) &&
3150 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003151 continue;
3152
3153 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003154 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003155 packet->data(),
3156 static_cast<unsigned int>(packet->length()));
3157 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003158}
3159
3160bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003161 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3162 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003163 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3164 return false;
3165 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003166 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3167 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003168 return false;
3169 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003170 // We set the AGC to mute state only when all the channels are muted.
3171 // This implementation is not ideal, instead we should signal the AGC when
3172 // the mic channel is muted/unmuted. We can't do it today because there
3173 // is no good way to know which stream is mapping to the mic channel.
3174 bool all_muted = muted;
3175 for (ChannelMap::const_iterator iter = send_channels_.begin();
3176 iter != send_channels_.end() && all_muted; ++iter) {
3177 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3178 all_muted)) {
3179 LOG_RTCERR1(GetInputMute, iter->second->channel());
3180 return false;
3181 }
3182 }
3183
3184 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3185 if (ap)
3186 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003187 return true;
3188}
3189
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003190bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
3191 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
3192
3193 return SetSendBandwidthInternal(bps);
3194}
3195
3196bool WebRtcVoiceMediaChannel::SetSendBandwidthInternal(int bps) {
3197 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBandwidthInternal.";
3198
3199 send_bw_setting_ = true;
3200 send_bw_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003201
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003202 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003203 LOG(LS_INFO) << "The send codec has not been set up yet. "
3204 << "The send bandwidth setting will be applied later.";
3205 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003206 }
3207
3208 // Bandwidth is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003209 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3210 // SetMaxSendBandwith(0), the second call removes the previous limit.
3211 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003212 return true;
3213
3214 webrtc::CodecInst codec = *send_codec_;
3215 bool is_multi_rate = IsCodecMultiRate(codec);
3216
3217 if (is_multi_rate) {
3218 // If codec is multi-rate then just set the bitrate.
3219 codec.rate = bps;
3220 if (!SetSendCodec(codec)) {
3221 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3222 << " to bitrate " << bps << " bps.";
3223 return false;
3224 }
3225 return true;
3226 } else {
3227 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3228 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3229 // fixed bitrate then ignore.
3230 if (bps < codec.rate) {
3231 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3232 << " to bitrate " << bps << " bps"
3233 << ", requires at least " << codec.rate << " bps.";
3234 return false;
3235 }
3236 return true;
3237 }
3238}
3239
3240bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003241 bool echo_metrics_on = false;
3242 // These can take on valid negative values, so use the lowest possible level
3243 // as default rather than -1.
3244 int echo_return_loss = -100;
3245 int echo_return_loss_enhancement = -100;
3246 // These can also be negative, but in practice -1 is only used to signal
3247 // insufficient data, since the resolution is limited to multiples of 4 ms.
3248 int echo_delay_median_ms = -1;
3249 int echo_delay_std_ms = -1;
3250 if (engine()->voe()->processing()->GetEcMetricsStatus(
3251 echo_metrics_on) != -1 && echo_metrics_on) {
3252 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3253 // here, but it appears to be unsuitable currently. Revisit after this is
3254 // investigated: http://b/issue?id=5666755
3255 int erl, erle, rerl, anlp;
3256 if (engine()->voe()->processing()->GetEchoMetrics(
3257 erl, erle, rerl, anlp) != -1) {
3258 echo_return_loss = erl;
3259 echo_return_loss_enhancement = erle;
3260 }
3261
3262 int median, std;
3263 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3264 echo_delay_median_ms = median;
3265 echo_delay_std_ms = std;
3266 }
3267 }
3268
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003269 webrtc::CallStatistics cs;
3270 unsigned int ssrc;
3271 webrtc::CodecInst codec;
3272 unsigned int level;
3273
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003274 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3275 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003276 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003277
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003278 // Fill in the sender info, based on what we know, and what the
3279 // remote side told us it got from its RTCP report.
3280 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003281
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003282 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3283 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3284 continue;
3285 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003286
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003287 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003288 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3289 sinfo.bytes_sent = cs.bytesSent;
3290 sinfo.packets_sent = cs.packetsSent;
3291 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3292 // returns 0 to indicate an error value.
3293 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3294
3295 // Get data from the last remote RTCP report. Use default values if no data
3296 // available.
3297 sinfo.fraction_lost = -1.0;
3298 sinfo.jitter_ms = -1;
3299 sinfo.packets_lost = -1;
3300 sinfo.ext_seqnum = -1;
3301 std::vector<webrtc::ReportBlock> receive_blocks;
3302 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3303 channel, &receive_blocks) != -1 &&
3304 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3305 std::vector<webrtc::ReportBlock>::iterator iter;
3306 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3307 ++iter) {
3308 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003309 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003310 // Convert Q8 to floating point.
3311 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3312 // Convert samples to milliseconds.
3313 if (codec.plfreq / 1000 > 0) {
3314 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3315 }
3316 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3317 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3318 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003319 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003320 }
3321 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003322
3323 // Local speech level.
3324 sinfo.audio_level = (engine()->voe()->volume()->
3325 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3326
3327 // TODO(xians): We are injecting the same APM logging to all the send
3328 // channels here because there is no good way to know which send channel
3329 // is using the APM. The correct fix is to allow the send channels to have
3330 // their own APM so that we can feed the correct APM logging to different
3331 // send channels. See issue crbug/264611 .
3332 sinfo.echo_return_loss = echo_return_loss;
3333 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3334 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3335 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003336 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3337 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003338 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003339
3340 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003341 }
3342
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003343 // Build the list of receivers, one for each receiving channel, or 1 in
3344 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003345 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003346 for (ChannelMap::const_iterator it = receive_channels_.begin();
3347 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003348 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003349 }
3350 if (channels.empty()) {
3351 channels.push_back(voe_channel());
3352 }
3353
3354 // Get the SSRC and stats for each receiver, based on our own calculations.
3355 for (std::vector<int>::const_iterator it = channels.begin();
3356 it != channels.end(); ++it) {
3357 memset(&cs, 0, sizeof(cs));
3358 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3359 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3360 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3361 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003362 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003363 rinfo.bytes_rcvd = cs.bytesReceived;
3364 rinfo.packets_rcvd = cs.packetsReceived;
3365 // The next four fields are from the most recently sent RTCP report.
3366 // Convert Q8 to floating point.
3367 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3368 rinfo.packets_lost = cs.cumulativeLost;
3369 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003370#ifdef USE_WEBRTC_DEV_BRANCH
3371 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
3372#endif
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003373 if (codec.pltype != -1) {
3374 rinfo.codec_name = codec.plname;
3375 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003376 // Convert samples to milliseconds.
3377 if (codec.plfreq / 1000 > 0) {
3378 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3379 }
3380
3381 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3382 webrtc::NetworkStatistics ns;
3383 if (engine()->voe()->neteq() &&
3384 engine()->voe()->neteq()->GetNetworkStatistics(
3385 *it, ns) != -1) {
3386 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3387 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3388 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003389 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003390 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003391
3392 webrtc::AudioDecodingCallStats ds;
3393 if (engine()->voe()->neteq() &&
3394 engine()->voe()->neteq()->GetDecodingCallStatistics(
3395 *it, &ds) != -1) {
3396 rinfo.decoding_calls_to_silence_generator =
3397 ds.calls_to_silence_generator;
3398 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3399 rinfo.decoding_normal = ds.decoded_normal;
3400 rinfo.decoding_plc = ds.decoded_plc;
3401 rinfo.decoding_cng = ds.decoded_cng;
3402 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3403 }
3404
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003405 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003406 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003407 int playout_buffer_delay_ms = 0;
3408 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003409 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3410 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3411 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003412 }
3413
3414 // Get speech level.
3415 rinfo.audio_level = (engine()->voe()->volume()->
3416 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3417 info->receivers.push_back(rinfo);
3418 }
3419 }
3420
3421 return true;
3422}
3423
3424void WebRtcVoiceMediaChannel::GetLastMediaError(
3425 uint32* ssrc, VoiceMediaChannel::Error* error) {
3426 ASSERT(ssrc != NULL);
3427 ASSERT(error != NULL);
3428 FindSsrc(voe_channel(), ssrc);
3429 *error = WebRtcErrorToChannelError(GetLastEngineError());
3430}
3431
3432bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003433 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003434 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003435 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003436 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3437 // This means the error is not limited to a specific channel. Signal the
3438 // message using ssrc=0. If the current channel is sending, use this
3439 // channel for sending the message.
3440 *ssrc = 0;
3441 return true;
3442 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003443 // Check whether this is a sending channel.
3444 for (ChannelMap::const_iterator it = send_channels_.begin();
3445 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003446 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003447 // This is a sending channel.
3448 uint32 local_ssrc = 0;
3449 if (engine()->voe()->rtp()->GetLocalSSRC(
3450 channel_num, local_ssrc) != -1) {
3451 *ssrc = local_ssrc;
3452 }
3453 return true;
3454 }
3455 }
3456
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003457 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003458 for (ChannelMap::const_iterator it = receive_channels_.begin();
3459 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003460 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003461 *ssrc = it->first;
3462 return true;
3463 }
3464 }
3465 }
3466 return false;
3467}
3468
3469void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003470 if (error == VE_TYPING_NOISE_WARNING) {
3471 typing_noise_detected_ = true;
3472 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3473 typing_noise_detected_ = false;
3474 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003475 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3476}
3477
3478int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3479 unsigned int ulevel;
3480 int ret =
3481 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3482 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3483}
3484
3485int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003486 ChannelMap::iterator it = receive_channels_.find(ssrc);
3487 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003488 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003489 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3490}
3491
3492int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003493 ChannelMap::iterator it = send_channels_.find(ssrc);
3494 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003495 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003496
3497 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003498}
3499
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003500bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
3501 webrtc::VideoEngine* vie, int vie_channel) {
3502 shared_bwe_vie_ = vie;
3503 shared_bwe_vie_channel_ = vie_channel;
3504
3505 if (!SetupSharedBweOnChannel(voe_channel())) {
3506 return false;
3507 }
3508 for (ChannelMap::iterator it = receive_channels_.begin();
3509 it != receive_channels_.end(); ++it) {
3510 if (!SetupSharedBweOnChannel(it->second->channel())) {
3511 return false;
3512 }
3513 }
3514 return true;
3515}
3516
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003517bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3518 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3519 // Get the RED encodings from the parameter with no name. This may
3520 // change based on what is discussed on the Jingle list.
3521 // The encoding parameter is of the form "a/b"; we only support where
3522 // a == b. Verify this and parse out the value into red_pt.
3523 // If the parameter value is absent (as it will be until we wire up the
3524 // signaling of this message), use the second codec specified (i.e. the
3525 // one after "red") as the encoding parameter.
3526 int red_pt = -1;
3527 std::string red_params;
3528 CodecParameterMap::const_iterator it = red_codec.params.find("");
3529 if (it != red_codec.params.end()) {
3530 red_params = it->second;
3531 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003532 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003533 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003534 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003535 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3536 return false;
3537 }
3538 } else if (red_codec.params.empty()) {
3539 LOG(LS_WARNING) << "RED params not present, using defaults";
3540 if (all_codecs.size() > 1) {
3541 red_pt = all_codecs[1].id;
3542 }
3543 }
3544
3545 // Try to find red_pt in |codecs|.
3546 std::vector<AudioCodec>::const_iterator codec;
3547 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3548 if (codec->id == red_pt)
3549 break;
3550 }
3551
3552 // If we find the right codec, that will be the codec we pass to
3553 // SetSendCodec, with the desired payload type.
3554 if (codec != all_codecs.end() &&
3555 engine()->FindWebRtcCodec(*codec, send_codec)) {
3556 } else {
3557 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3558 return false;
3559 }
3560
3561 return true;
3562}
3563
3564bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3565 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003566 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003567 return false;
3568 }
3569 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3570 // what we want to do with them.
3571 // engine()->voe().EnableVQMon(voe_channel(), true);
3572 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3573 return true;
3574}
3575
3576bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3577 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3578 for (int i = 0; i < ncodecs; ++i) {
3579 webrtc::CodecInst voe_codec;
3580 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3581 voe_codec.pltype = -1;
3582 if (engine()->voe()->codec()->SetRecPayloadType(
3583 channel, voe_codec) == -1) {
3584 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3585 return false;
3586 }
3587 }
3588 }
3589 return true;
3590}
3591
3592bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3593 if (playout) {
3594 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3595 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3596 LOG_RTCERR1(StartPlayout, channel);
3597 return false;
3598 }
3599 } else {
3600 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3601 engine()->voe()->base()->StopPlayout(channel);
3602 }
3603 return true;
3604}
3605
3606uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3607 bool rtcp) {
3608 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3609 uint32 ssrc = 0;
3610 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003611 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003612 }
3613 return ssrc;
3614}
3615
3616// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3617VoiceMediaChannel::Error
3618 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3619 switch (err_code) {
3620 case 0:
3621 return ERROR_NONE;
3622 case VE_CANNOT_START_RECORDING:
3623 case VE_MIC_VOL_ERROR:
3624 case VE_GET_MIC_VOL_ERROR:
3625 case VE_CANNOT_ACCESS_MIC_VOL:
3626 return ERROR_REC_DEVICE_OPEN_FAILED;
3627 case VE_SATURATION_WARNING:
3628 return ERROR_REC_DEVICE_SATURATION;
3629 case VE_REC_DEVICE_REMOVED:
3630 return ERROR_REC_DEVICE_REMOVED;
3631 case VE_RUNTIME_REC_WARNING:
3632 case VE_RUNTIME_REC_ERROR:
3633 return ERROR_REC_RUNTIME_ERROR;
3634 case VE_CANNOT_START_PLAYOUT:
3635 case VE_SPEAKER_VOL_ERROR:
3636 case VE_GET_SPEAKER_VOL_ERROR:
3637 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3638 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3639 case VE_RUNTIME_PLAY_WARNING:
3640 case VE_RUNTIME_PLAY_ERROR:
3641 return ERROR_PLAY_RUNTIME_ERROR;
3642 case VE_TYPING_NOISE_WARNING:
3643 return ERROR_REC_TYPING_NOISE_DETECTED;
3644 default:
3645 return VoiceMediaChannel::ERROR_OTHER;
3646 }
3647}
3648
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003649bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3650 int channel_id, const RtpHeaderExtension* extension) {
3651 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003652 int id = 0;
3653 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003654 if (extension) {
3655 enable = true;
3656 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003657 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003658 }
3659 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003660 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003661 return false;
3662 }
3663 return true;
3664}
3665
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003666bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
3667 webrtc::ViENetwork* vie_network = NULL;
3668 int vie_channel = -1;
3669 if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
3670 shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
3671 vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
3672 vie_channel = shared_bwe_vie_channel_;
3673 }
3674 if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
3675 vie_channel) == -1) {
3676 LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
3677 if (vie_network != NULL) {
3678 // Don't fail if we're tearing down.
3679 return false;
3680 }
3681 }
3682 return true;
3683}
3684
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003685int WebRtcSoundclipStream::Read(void *buf, int len) {
3686 size_t res = 0;
3687 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003688 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003689}
3690
3691int WebRtcSoundclipStream::Rewind() {
3692 mem_.Rewind();
3693 // Return -1 to keep VoiceEngine from looping.
3694 return (loop_) ? 0 : -1;
3695}
3696
3697} // namespace cricket
3698
3699#endif // HAVE_WEBRTC_VOICE