blob: 19c23e7c77304464caed0d365b26323d79648d87 [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";
minyue@webrtc.org82195292014-10-30 08:23:54 +0000113// Codec parameters for Opus.
114static const int kOpusMonoBitrate = 32000;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000115// 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;
minyue@webrtc.org82195292014-10-30 08:23:54 +0000118static 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.
buildbot@webrtc.org879fac82014-10-30 07:50:13 +0000412static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
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) {
minyue@webrtc.org82195292014-10-30 08:23:54 +0000420 bitrate = IsOpusStereoEnabled(codec) ? kOpusStereoBitrate :
421 kOpusMonoBitrate;
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000422 } 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
minyue@webrtc.org82195292014-10-30 08:23:54 +0000462 // 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;
buildbot@webrtc.org879fac82014-10-30 07:50:13 +0000466 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
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)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000498 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000499 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,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001230 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001231 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()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001795 send_bitrate_setting_(false),
1796 send_bitrate_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
minyue@webrtc.org26236952014-10-29 02:27:08 +00002031 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002032
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002033 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002034 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2035 it != codecs.end(); ++it) {
2036 // Ignore codecs we don't know about. The negotiation step should prevent
2037 // this, but double-check to be sure.
2038 webrtc::CodecInst voe_codec;
2039 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002040 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002041 continue;
2042 }
2043
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002044 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2045 // Skip telephone-event/CN codec, which will be handled later.
2046 continue;
2047 }
2048
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002049 // We'll use the first codec in the list to actually send audio data.
2050 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002051 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002052 // used is specified in params.
2053 if (IsRedCodec(it->name)) {
2054 // Parse out the RED parameters. If we fail, just ignore RED;
2055 // we don't support all possible params/usage scenarios.
2056 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2057 continue;
2058 }
2059
2060 // Enable redundant encoding of the specified codec. Treat any
2061 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002062#ifdef USE_WEBRTC_DEV_BRANCH
2063 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2064 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2065 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
2066#else
2067 // TODO(minyue): Remove code under #else case after new WebRTC roll.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002068 LOG(LS_INFO) << "Enabling FEC";
2069 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2070 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002071#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002072 return false;
2073 }
2074 } else {
2075 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002076 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002077 // For Opus as the send codec, we are to enable inband FEC if requested
2078 // and set maximum playback rate.
2079 if (IsOpus(*it)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002080 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
2081 &opus_max_playback_rate);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002082 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002083 }
2084 found_send_codec = true;
2085 break;
2086 }
2087
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002088 if (nack_enabled_ != nack_enabled) {
2089 SetNack(channel, nack_enabled);
2090 nack_enabled_ = nack_enabled;
2091 }
2092
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002093 if (!found_send_codec) {
2094 LOG(LS_WARNING) << "Received empty list of codecs.";
2095 return false;
2096 }
2097
2098 // Set the codec immediately, since SetVADStatus() depends on whether
2099 // the current codec is mono or stereo.
2100 if (!SetSendCodec(channel, send_codec))
2101 return false;
2102
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002103 // FEC should be enabled after SetSendCodec.
2104 if (enable_codec_fec) {
2105 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2106 << channel;
2107#ifdef USE_WEBRTC_DEV_BRANCH
2108 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2109 // Enable codec internal FEC. Treat any failure as fatal internal error.
2110 LOG_RTCERR2(SetFECStatus, channel, true);
2111 return false;
2112 }
2113#endif // USE_WEBRTC_DEV_BRANCH
2114 }
2115
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002116 // maxplaybackrate should be set after SetSendCodec.
minyue@webrtc.org26236952014-10-29 02:27:08 +00002117 // If opus_max_playback_rate <= 0, the default maximum playback rate of 48 kHz
2118 // will be used.
2119 if (opus_max_playback_rate > 0) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002120 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002121 << opus_max_playback_rate
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002122 << " Hz on channel "
2123 << channel;
2124#ifdef USE_WEBRTC_DEV_BRANCH
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002125 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
minyue@webrtc.org26236952014-10-29 02:27:08 +00002126 channel, opus_max_playback_rate) == -1) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002127 LOG(LS_WARNING) << "Could not set maximum playback rate.";
2128 }
2129#endif
2130 }
2131
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002132 // Always update the |send_codec_| to the currently set send codec.
2133 send_codec_.reset(new webrtc::CodecInst(send_codec));
2134
minyue@webrtc.org26236952014-10-29 02:27:08 +00002135 if (send_bitrate_setting_) {
2136 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002137 }
2138
2139 // Loop through the codecs list again to config the telephone-event/CN codec.
2140 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2141 it != codecs.end(); ++it) {
2142 // Ignore codecs we don't know about. The negotiation step should prevent
2143 // this, but double-check to be sure.
2144 webrtc::CodecInst voe_codec;
2145 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2146 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2147 continue;
2148 }
2149
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002150 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2151 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002152 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002153 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2154 channel, it->id) == -1) {
2155 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2156 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002157 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002158 } else if (IsCNCodec(it->name)) {
2159 // Turn voice activity detection/comfort noise on if supported.
2160 // Set the wideband CN payload type appropriately.
2161 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002162 webrtc::PayloadFrequencies cn_freq;
2163 switch (it->clockrate) {
2164 case 8000:
2165 cn_freq = webrtc::kFreq8000Hz;
2166 break;
2167 case 16000:
2168 cn_freq = webrtc::kFreq16000Hz;
2169 break;
2170 case 32000:
2171 cn_freq = webrtc::kFreq32000Hz;
2172 break;
2173 default:
2174 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2175 << " not supported.";
2176 continue;
2177 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002178 // Set the CN payloadtype and the VAD status.
2179 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2180 if (cn_freq != webrtc::kFreq8000Hz) {
2181 if (engine()->voe()->codec()->SetSendCNPayloadType(
2182 channel, it->id, cn_freq) == -1) {
2183 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2184 // TODO(ajm): This failure condition will be removed from VoE.
2185 // Restore the return here when we update to a new enough webrtc.
2186 //
2187 // Not returning false because the SetSendCNPayloadType will fail if
2188 // the channel is already sending.
2189 // This can happen if the remote description is applied twice, for
2190 // example in the case of ROAP on top of JSEP, where both side will
2191 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002192 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002193 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002194 // Only turn on VAD if we have a CN payload type that matches the
2195 // clockrate for the codec we are going to use.
2196 if (it->clockrate == send_codec.plfreq) {
2197 LOG(LS_INFO) << "Enabling VAD";
2198 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2199 LOG_RTCERR2(SetVADStatus, channel, true);
2200 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002201 }
2202 }
2203 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002204 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002205 return true;
2206}
2207
2208bool WebRtcVoiceMediaChannel::SetSendCodecs(
2209 const std::vector<AudioCodec>& codecs) {
2210 dtmf_allowed_ = false;
2211 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2212 it != codecs.end(); ++it) {
2213 // Find the DTMF telephone event "codec".
2214 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2215 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2216 dtmf_allowed_ = true;
2217 }
2218 }
2219
2220 // Cache the codecs in order to configure the channel created later.
2221 send_codecs_ = codecs;
2222 for (ChannelMap::iterator iter = send_channels_.begin();
2223 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002224 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002225 return false;
2226 }
2227 }
2228
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002229 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002230 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002231 return true;
2232}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002233
2234void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2235 bool nack_enabled) {
2236 for (ChannelMap::const_iterator it = channels.begin();
2237 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002238 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002239 }
2240}
2241
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002242void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002243 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002244 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002245 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2246 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002247 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002248 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2249 }
2250}
2251
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002252bool WebRtcVoiceMediaChannel::SetSendCodec(
2253 const webrtc::CodecInst& send_codec) {
2254 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2255 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002256 for (ChannelMap::iterator iter = send_channels_.begin();
2257 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002258 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002259 return false;
2260 }
2261
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002262 return true;
2263}
2264
2265bool WebRtcVoiceMediaChannel::SetSendCodec(
2266 int channel, const webrtc::CodecInst& send_codec) {
2267 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2268 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2269
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002270 webrtc::CodecInst current_codec;
2271 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2272 (send_codec == current_codec)) {
2273 // Codec is already configured, we can return without setting it again.
2274 return true;
2275 }
2276
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002277 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2278 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002279 return false;
2280 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002281 return true;
2282}
2283
2284bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2285 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002286 if (receive_extensions_ == extensions) {
2287 return true;
2288 }
2289
2290 // The default channel may or may not be in |receive_channels_|. Set the rtp
2291 // header extensions for default channel regardless.
2292 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2293 return false;
2294 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002295
2296 // Loop through all receive channels and enable/disable the extensions.
2297 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2298 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002299 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2300 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002301 return false;
2302 }
2303 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002304
2305 receive_extensions_ = extensions;
2306 return true;
2307}
2308
2309bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2310 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002311 const RtpHeaderExtension* audio_level_extension =
2312 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2313 if (!SetHeaderExtension(
2314 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2315 audio_level_extension)) {
2316 return false;
2317 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002318
2319 const RtpHeaderExtension* send_time_extension =
2320 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2321 if (!SetHeaderExtension(
2322 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2323 send_time_extension)) {
2324 return false;
2325 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002326 return true;
2327}
2328
2329bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2330 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002331 if (send_extensions_ == extensions) {
2332 return true;
2333 }
2334
2335 // The default channel may or may not be in |send_channels_|. Set the rtp
2336 // header extensions for default channel regardless.
2337
2338 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2339 return false;
2340 }
2341
2342 // Loop through all send channels and enable/disable the extensions.
2343 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2344 channel_it != send_channels_.end(); ++channel_it) {
2345 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2346 extensions)) {
2347 return false;
2348 }
2349 }
2350
2351 send_extensions_ = extensions;
2352 return true;
2353}
2354
2355bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2356 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002357 const RtpHeaderExtension* audio_level_extension =
2358 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002359
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002360 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002361 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002362 audio_level_extension)) {
2363 return false;
2364 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002365
2366 const RtpHeaderExtension* send_time_extension =
2367 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002368 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002369 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002370 send_time_extension)) {
2371 return false;
2372 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002373
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002374 return true;
2375}
2376
2377bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2378 desired_playout_ = playout;
2379 return ChangePlayout(desired_playout_);
2380}
2381
2382bool WebRtcVoiceMediaChannel::PausePlayout() {
2383 return ChangePlayout(false);
2384}
2385
2386bool WebRtcVoiceMediaChannel::ResumePlayout() {
2387 return ChangePlayout(desired_playout_);
2388}
2389
2390bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2391 if (playout_ == playout) {
2392 return true;
2393 }
2394
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002395 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002396 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002397 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002398 // Only toggle the default channel if we don't have any other channels.
2399 result = SetPlayout(voe_channel(), playout);
2400 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002401 for (ChannelMap::iterator it = receive_channels_.begin();
2402 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002403 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002404 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002405 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002406 result = false;
2407 }
2408 }
2409
2410 if (result) {
2411 playout_ = playout;
2412 }
2413 return result;
2414}
2415
2416bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2417 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002418 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002419 return ChangeSend(desired_send_);
2420 return true;
2421}
2422
2423bool WebRtcVoiceMediaChannel::PauseSend() {
2424 return ChangeSend(SEND_NOTHING);
2425}
2426
2427bool WebRtcVoiceMediaChannel::ResumeSend() {
2428 return ChangeSend(desired_send_);
2429}
2430
2431bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2432 if (send_ == send) {
2433 return true;
2434 }
2435
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002436 // Change the settings on each send channel.
2437 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002438 engine()->SetOptionOverrides(options_);
2439
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002440 // Change the settings on each send channel.
2441 for (ChannelMap::iterator iter = send_channels_.begin();
2442 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002443 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002444 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002445 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002446
2447 // Clear up the options after stopping sending.
2448 if (send == SEND_NOTHING)
2449 engine()->ClearOptionOverrides();
2450
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002451 send_ = send;
2452 return true;
2453}
2454
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002455bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2456 if (send == SEND_MICROPHONE) {
2457 if (engine()->voe()->base()->StartSend(channel) == -1) {
2458 LOG_RTCERR1(StartSend, channel);
2459 return false;
2460 }
2461 if (engine()->voe()->file() &&
2462 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2463 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2464 return false;
2465 }
2466 } else { // SEND_NOTHING
2467 ASSERT(send == SEND_NOTHING);
2468 if (engine()->voe()->base()->StopSend(channel) == -1) {
2469 LOG_RTCERR1(StopSend, channel);
2470 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002471 }
2472 }
2473
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002474 return true;
2475}
2476
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002477// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002478void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2479 if (engine()->voe()->network()->RegisterExternalTransport(
2480 channel, *this) == -1) {
2481 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2482 }
2483
2484 // Enable RTCP (for quality stats and feedback messages)
2485 EnableRtcp(channel);
2486
2487 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2488 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002489
2490 // Set RTP header extension for the new channel.
2491 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002492}
2493
2494bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2495 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2496 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2497 }
2498
2499 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2500 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002501 return false;
2502 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002503
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002504 return true;
2505}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002506
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002507bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2508 // If the default channel is already used for sending create a new channel
2509 // otherwise use the default channel for sending.
2510 int channel = GetSendChannelNum(sp.first_ssrc());
2511 if (channel != -1) {
2512 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2513 return false;
2514 }
2515
2516 bool default_channel_is_available = true;
2517 for (ChannelMap::const_iterator iter = send_channels_.begin();
2518 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002519 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002520 default_channel_is_available = false;
2521 break;
2522 }
2523 }
2524 if (default_channel_is_available) {
2525 channel = voe_channel();
2526 } else {
2527 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002528 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002529 if (channel == -1) {
2530 LOG_RTCERR0(CreateChannel);
2531 return false;
2532 }
2533
2534 ConfigureSendChannel(channel);
2535 }
2536
2537 // Save the channel to send_channels_, so that RemoveSendStream() can still
2538 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002539 webrtc::AudioTransport* audio_transport =
2540 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002541 send_channels_.insert(std::make_pair(
2542 sp.first_ssrc(),
2543 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002544
2545 // Set the send (local) SSRC.
2546 // If there are multiple send SSRCs, we can only set the first one here, and
2547 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2548 // (with a codec requires multiple SSRC(s)).
2549 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2550 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2551 return false;
2552 }
2553
2554 // At this point the channel's local SSRC has been updated. If the channel is
2555 // the default channel make sure that all the receive channels are updated as
2556 // well. Receive channels have to have the same SSRC as the default channel in
2557 // order to send receiver reports with this SSRC.
2558 if (IsDefaultChannel(channel)) {
2559 for (ChannelMap::const_iterator it = receive_channels_.begin();
2560 it != receive_channels_.end(); ++it) {
2561 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002562 if (!IsDefaultChannel(it->second->channel())) {
2563 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002564 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002565 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002566 return false;
2567 }
2568 }
2569 }
2570 }
2571
2572 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002573 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2574 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002575 }
2576
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002577 // Set the current codecs to be used for the new channel.
2578 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002579 return false;
2580
2581 return ChangeSend(channel, desired_send_);
2582}
2583
2584bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2585 ChannelMap::iterator it = send_channels_.find(ssrc);
2586 if (it == send_channels_.end()) {
2587 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2588 << " which doesn't exist.";
2589 return false;
2590 }
2591
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002592 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002593 ChangeSend(channel, SEND_NOTHING);
2594
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002595 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2596 // this will disconnect the audio renderer with the send channel.
2597 delete it->second;
2598 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002599
2600 if (IsDefaultChannel(channel)) {
2601 // Do not delete the default channel since the receive channels depend on
2602 // the default channel, recycle it instead.
2603 ChangeSend(channel, SEND_NOTHING);
2604 } else {
2605 // Clean up and delete the send channel.
2606 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2607 << " with VoiceEngine channel #" << channel << ".";
2608 if (!DeleteChannel(channel))
2609 return false;
2610 }
2611
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002612 if (send_channels_.empty())
2613 ChangeSend(SEND_NOTHING);
2614
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002615 return true;
2616}
2617
2618bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002619 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002620
2621 if (!VERIFY(sp.ssrcs.size() == 1))
2622 return false;
2623 uint32 ssrc = sp.first_ssrc();
2624
wu@webrtc.org78187522013-10-07 23:32:02 +00002625 if (ssrc == 0) {
2626 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2627 return false;
2628 }
2629
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002630 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2631 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002632 return false;
2633 }
2634
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002635 // Reuse default channel for recv stream in non-conference mode call
2636 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002637 webrtc::AudioTransport* audio_transport =
2638 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002639 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2640 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2641 << " reuse default channel";
2642 default_receive_ssrc_ = sp.first_ssrc();
2643 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002644 default_receive_ssrc_,
2645 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002646 if (!SetupSharedBweOnChannel(voe_channel())) {
2647 return false;
2648 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002649 return SetPlayout(voe_channel(), playout_);
2650 }
2651
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002652 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002653 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002654 if (channel == -1) {
2655 LOG_RTCERR0(CreateChannel);
2656 return false;
2657 }
2658
wu@webrtc.org78187522013-10-07 23:32:02 +00002659 if (!ConfigureRecvChannel(channel)) {
2660 DeleteChannel(channel);
2661 return false;
2662 }
2663
2664 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002665 std::make_pair(
2666 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002667
2668 LOG(LS_INFO) << "New audio stream " << ssrc
2669 << " registered to VoiceEngine channel #"
2670 << channel << ".";
2671 return true;
2672}
2673
2674bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002675 // Configure to use external transport, like our default channel.
2676 if (engine()->voe()->network()->RegisterExternalTransport(
2677 channel, *this) == -1) {
2678 LOG_RTCERR2(SetExternalTransport, channel, this);
2679 return false;
2680 }
2681
2682 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002683 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002684 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2685 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002686 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002687 return false;
2688 }
2689 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002690 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002691 return false;
2692 }
2693
2694 // Use the same recv payload types as our default channel.
2695 ResetRecvCodecs(channel);
2696 if (!recv_codecs_.empty()) {
2697 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2698 it != recv_codecs_.end(); ++it) {
2699 webrtc::CodecInst voe_codec;
2700 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2701 voe_codec.pltype = it->id;
2702 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2703 if (engine()->voe()->codec()->GetRecPayloadType(
2704 voe_channel(), voe_codec) != -1) {
2705 if (engine()->voe()->codec()->SetRecPayloadType(
2706 channel, voe_codec) == -1) {
2707 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2708 return false;
2709 }
2710 }
2711 }
2712 }
2713 }
2714
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002715 if (InConferenceMode()) {
2716 // To be in par with the video, voe_channel() is not used for receiving in
2717 // a conference call.
2718 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2719 // This is the first stream in a multi user meeting. We can now
2720 // disable playback of the default stream. This since the default
2721 // stream will probably have received some initial packets before
2722 // the new stream was added. This will mean that the CN state from
2723 // the default channel will be mixed in with the other streams
2724 // throughout the whole meeting, which might be disturbing.
2725 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2726 SetPlayout(voe_channel(), false);
2727 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002728 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002729 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002730
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002731 // Set RTP header extension for the new channel.
2732 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2733 return false;
2734 }
2735
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002736 // Set up channel to be able to forward incoming packets to video engine BWE.
2737 if (!SetupSharedBweOnChannel(channel)) {
2738 return false;
2739 }
2740
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002741 return SetPlayout(channel, playout_);
2742}
2743
2744bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002745 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002746 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002747 if (it == receive_channels_.end()) {
2748 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2749 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002750 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002751 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002752
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002753 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2754 // will disconnect the audio renderer with the receive channel.
2755 // Cache the channel before the deletion.
2756 const int channel = it->second->channel();
2757 delete it->second;
2758 receive_channels_.erase(it);
2759
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002760 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002761 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002762 // Recycle the default channel is for recv stream.
2763 if (playout_)
2764 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002765
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002766 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002767 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002768 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002769
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002770 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002771 << " with VoiceEngine channel #" << channel << ".";
2772 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002773 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002774
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002775 bool enable_default_channel_playout = false;
2776 if (receive_channels_.empty()) {
2777 // The last stream was removed. We can now enable the default
2778 // channel for new channels to be played out immediately without
2779 // waiting for AddStream messages.
2780 // We do this for both conference mode and non-conference mode.
2781 // TODO(oja): Does the default channel still have it's CN state?
2782 enable_default_channel_playout = true;
2783 }
2784 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2785 default_receive_ssrc_ != 0) {
2786 // Only the default channel is active, enable the playout on default
2787 // channel.
2788 enable_default_channel_playout = true;
2789 }
2790 if (enable_default_channel_playout && playout_) {
2791 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2792 SetPlayout(voe_channel(), true);
2793 }
2794
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002795 return true;
2796}
2797
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002798bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2799 AudioRenderer* renderer) {
2800 ChannelMap::iterator it = receive_channels_.find(ssrc);
2801 if (it == receive_channels_.end()) {
2802 if (renderer) {
2803 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002804 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002805 return false;
2806 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002807
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002808 // The channel likely has gone away, do nothing.
2809 return true;
2810 }
2811
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002812 if (renderer)
2813 it->second->Start(renderer);
2814 else
2815 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002816
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002817 return true;
2818}
2819
2820bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2821 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002822 ChannelMap::iterator it = send_channels_.find(ssrc);
2823 if (it == send_channels_.end()) {
2824 if (renderer) {
2825 // Return an error if trying to set a valid renderer with an invalid ssrc.
2826 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2827 return false;
2828 }
2829
2830 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002831 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002832 }
2833
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002834 if (renderer)
2835 it->second->Start(renderer);
2836 else
2837 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002838
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002839 return true;
2840}
2841
2842bool WebRtcVoiceMediaChannel::GetActiveStreams(
2843 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002844 // In conference mode, the default channel should not be in
2845 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002846 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002847 for (ChannelMap::iterator it = receive_channels_.begin();
2848 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002849 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002850 if (level > 0) {
2851 actives->push_back(std::make_pair(it->first, level));
2852 }
2853 }
2854 return true;
2855}
2856
2857int WebRtcVoiceMediaChannel::GetOutputLevel() {
2858 // return the highest output level of all streams
2859 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002860 for (ChannelMap::iterator it = receive_channels_.begin();
2861 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002862 int level = GetOutputLevel(it->second->channel());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002863 highest = rtc::_max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002864 }
2865 return highest;
2866}
2867
2868int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2869 int ret;
2870 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2871 // In case of error, log the info and continue
2872 LOG_RTCERR0(TimeSinceLastTyping);
2873 ret = -1;
2874 } else {
2875 ret *= 1000; // We return ms, webrtc returns seconds.
2876 }
2877 return ret;
2878}
2879
2880void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2881 int cost_per_typing, int reporting_threshold, int penalty_decay,
2882 int type_event_delay) {
2883 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2884 time_window, cost_per_typing,
2885 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2886 // In case of error, log the info and continue
2887 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2888 cost_per_typing, reporting_threshold, penalty_decay,
2889 type_event_delay);
2890 }
2891}
2892
2893bool WebRtcVoiceMediaChannel::SetOutputScaling(
2894 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002895 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002896 // Collect the channels to scale the output volume.
2897 std::vector<int> channels;
2898 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002899 // Default channel is not in receive_channels_ if it is not being used for
2900 // playout.
2901 if (default_receive_ssrc_ == 0)
2902 channels.push_back(voe_channel());
2903 for (ChannelMap::const_iterator it = receive_channels_.begin();
2904 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002905 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002906 }
2907 } else { // Collect only the channel of the specified ssrc.
2908 int channel = GetReceiveChannelNum(ssrc);
2909 if (-1 == channel) {
2910 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2911 return false;
2912 }
2913 channels.push_back(channel);
2914 }
2915
2916 // Scale the output volume for the collected channels. We first normalize to
2917 // scale the volume and then set the left and right pan.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002918 float scale = static_cast<float>(rtc::_max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002919 if (scale > 0.0001f) {
2920 left /= scale;
2921 right /= scale;
2922 }
2923 for (std::vector<int>::const_iterator it = channels.begin();
2924 it != channels.end(); ++it) {
2925 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2926 *it, scale)) {
2927 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2928 return false;
2929 }
2930 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2931 *it, static_cast<float>(left), static_cast<float>(right))) {
2932 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2933 // Do not return if fails. SetOutputVolumePan is not available for all
2934 // pltforms.
2935 }
2936 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2937 << " right=" << right * scale
2938 << " for channel " << *it << " and ssrc " << ssrc;
2939 }
2940 return true;
2941}
2942
2943bool WebRtcVoiceMediaChannel::GetOutputScaling(
2944 uint32 ssrc, double* left, double* right) {
2945 if (!left || !right) return false;
2946
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002947 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002948 // Determine which channel based on ssrc.
2949 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2950 if (channel == -1) {
2951 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2952 return false;
2953 }
2954
2955 float scaling;
2956 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2957 channel, scaling)) {
2958 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2959 return false;
2960 }
2961
2962 float left_pan;
2963 float right_pan;
2964 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2965 channel, left_pan, right_pan)) {
2966 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2967 // If GetOutputVolumePan fails, we use the default left and right pan.
2968 left_pan = 1.0f;
2969 right_pan = 1.0f;
2970 }
2971
2972 *left = scaling * left_pan;
2973 *right = scaling * right_pan;
2974 return true;
2975}
2976
2977bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2978 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2979 return true;
2980}
2981
2982bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2983 bool play, bool loop) {
2984 if (!ringback_tone_) {
2985 return false;
2986 }
2987
2988 // The voe file api is not available in chrome.
2989 if (!engine()->voe()->file()) {
2990 return false;
2991 }
2992
2993 // Determine which VoiceEngine channel to play on.
2994 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2995 if (channel == -1) {
2996 return false;
2997 }
2998
2999 // Make sure the ringtone is cued properly, and play it out.
3000 if (play) {
3001 ringback_tone_->set_loop(loop);
3002 ringback_tone_->Rewind();
3003 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
3004 ringback_tone_.get()) == -1) {
3005 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
3006 LOG(LS_ERROR) << "Unable to start ringback tone";
3007 return false;
3008 }
3009 ringback_channels_.insert(channel);
3010 LOG(LS_INFO) << "Started ringback on channel " << channel;
3011 } else {
3012 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
3013 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
3014 LOG_RTCERR1(StopPlayingFileLocally, channel);
3015 return false;
3016 }
3017 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
3018 ringback_channels_.erase(channel);
3019 }
3020
3021 return true;
3022}
3023
3024bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3025 return dtmf_allowed_;
3026}
3027
3028bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3029 int duration, int flags) {
3030 if (!dtmf_allowed_) {
3031 return false;
3032 }
3033
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003034 // Send the event.
3035 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003036 int channel = -1;
3037 if (ssrc == 0) {
3038 bool default_channel_is_inuse = false;
3039 for (ChannelMap::const_iterator iter = send_channels_.begin();
3040 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003041 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003042 default_channel_is_inuse = true;
3043 break;
3044 }
3045 }
3046 if (default_channel_is_inuse) {
3047 channel = voe_channel();
3048 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003049 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003050 }
3051 } else {
3052 channel = GetSendChannelNum(ssrc);
3053 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003054 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003055 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3056 << ssrc << " is not in use.";
3057 return false;
3058 }
3059 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003060 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3061 channel, event, true, duration) == -1) {
3062 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003063 return false;
3064 }
3065 }
3066
3067 // Play the event.
3068 if (flags & cricket::DF_PLAY) {
3069 // Play DTMF tone locally.
3070 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3071 LOG_RTCERR2(PlayDtmfTone, event, duration);
3072 return false;
3073 }
3074 }
3075
3076 return true;
3077}
3078
wu@webrtc.orga9890802013-12-13 00:21:03 +00003079void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003080 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003081 // Pick which channel to send this packet to. If this packet doesn't match
3082 // any multiplexed streams, just send it to the default channel. Otherwise,
3083 // send it to the specific decoder instance for that stream.
3084 int which_channel = GetReceiveChannelNum(
3085 ParseSsrc(packet->data(), packet->length(), false));
3086 if (which_channel == -1) {
3087 which_channel = voe_channel();
3088 }
3089
3090 // Stop any ringback that might be playing on the channel.
3091 // It's possible the ringback has already stopped, ih which case we'll just
3092 // use the opportunity to remove the channel from ringback_channels_.
3093 if (engine()->voe()->file()) {
3094 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3095 if (it != ringback_channels_.end()) {
3096 if (engine()->voe()->file()->IsPlayingFileLocally(
3097 which_channel) == 1) {
3098 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3099 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3100 << " due to incoming media";
3101 }
3102 ringback_channels_.erase(which_channel);
3103 }
3104 }
3105
3106 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003107 engine()->voe()->network()->ReceivedRTPPacket(
3108 which_channel,
3109 packet->data(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003110 static_cast<unsigned int>(packet->length()),
3111 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003112}
3113
wu@webrtc.orga9890802013-12-13 00:21:03 +00003114void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003115 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003116 // Sending channels need all RTCP packets with feedback information.
3117 // Even sender reports can contain attached report blocks.
3118 // Receiving channels need sender reports in order to create
3119 // correct receiver reports.
3120 int type = 0;
3121 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3122 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3123 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003124 }
3125
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003126 // If it is a sender report, find the channel that is listening.
3127 bool has_sent_to_default_channel = false;
3128 if (type == kRtcpTypeSR) {
3129 int which_channel = GetReceiveChannelNum(
3130 ParseSsrc(packet->data(), packet->length(), true));
3131 if (which_channel != -1) {
3132 engine()->voe()->network()->ReceivedRTCPPacket(
3133 which_channel,
3134 packet->data(),
3135 static_cast<unsigned int>(packet->length()));
3136
3137 if (IsDefaultChannel(which_channel))
3138 has_sent_to_default_channel = true;
3139 }
3140 }
3141
3142 // SR may continue RR and any RR entry may correspond to any one of the send
3143 // channels. So all RTCP packets must be forwarded all send channels. VoE
3144 // will filter out RR internally.
3145 for (ChannelMap::iterator iter = send_channels_.begin();
3146 iter != send_channels_.end(); ++iter) {
3147 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003148 if (IsDefaultChannel(iter->second->channel()) &&
3149 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003150 continue;
3151
3152 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003153 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003154 packet->data(),
3155 static_cast<unsigned int>(packet->length()));
3156 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003157}
3158
3159bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003160 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3161 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003162 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3163 return false;
3164 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003165 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3166 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003167 return false;
3168 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003169 // We set the AGC to mute state only when all the channels are muted.
3170 // This implementation is not ideal, instead we should signal the AGC when
3171 // the mic channel is muted/unmuted. We can't do it today because there
3172 // is no good way to know which stream is mapping to the mic channel.
3173 bool all_muted = muted;
3174 for (ChannelMap::const_iterator iter = send_channels_.begin();
3175 iter != send_channels_.end() && all_muted; ++iter) {
3176 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3177 all_muted)) {
3178 LOG_RTCERR1(GetInputMute, iter->second->channel());
3179 return false;
3180 }
3181 }
3182
3183 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3184 if (ap)
3185 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003186 return true;
3187}
3188
minyue@webrtc.org26236952014-10-29 02:27:08 +00003189// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3190// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003191bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003192 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003193
minyue@webrtc.org26236952014-10-29 02:27:08 +00003194 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003195}
3196
minyue@webrtc.org26236952014-10-29 02:27:08 +00003197bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3198 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003199
minyue@webrtc.org26236952014-10-29 02:27:08 +00003200 send_bitrate_setting_ = true;
3201 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003202
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003203 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003204 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003205 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003206 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003207 }
3208
minyue@webrtc.org26236952014-10-29 02:27:08 +00003209 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003210 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3211 // SetMaxSendBandwith(0), the second call removes the previous limit.
3212 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003213 return true;
3214
3215 webrtc::CodecInst codec = *send_codec_;
3216 bool is_multi_rate = IsCodecMultiRate(codec);
3217
3218 if (is_multi_rate) {
3219 // If codec is multi-rate then just set the bitrate.
3220 codec.rate = bps;
3221 if (!SetSendCodec(codec)) {
3222 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3223 << " to bitrate " << bps << " bps.";
3224 return false;
3225 }
3226 return true;
3227 } else {
3228 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3229 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3230 // fixed bitrate then ignore.
3231 if (bps < codec.rate) {
3232 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3233 << " to bitrate " << bps << " bps"
3234 << ", requires at least " << codec.rate << " bps.";
3235 return false;
3236 }
3237 return true;
3238 }
3239}
3240
3241bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003242 bool echo_metrics_on = false;
3243 // These can take on valid negative values, so use the lowest possible level
3244 // as default rather than -1.
3245 int echo_return_loss = -100;
3246 int echo_return_loss_enhancement = -100;
3247 // These can also be negative, but in practice -1 is only used to signal
3248 // insufficient data, since the resolution is limited to multiples of 4 ms.
3249 int echo_delay_median_ms = -1;
3250 int echo_delay_std_ms = -1;
3251 if (engine()->voe()->processing()->GetEcMetricsStatus(
3252 echo_metrics_on) != -1 && echo_metrics_on) {
3253 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3254 // here, but it appears to be unsuitable currently. Revisit after this is
3255 // investigated: http://b/issue?id=5666755
3256 int erl, erle, rerl, anlp;
3257 if (engine()->voe()->processing()->GetEchoMetrics(
3258 erl, erle, rerl, anlp) != -1) {
3259 echo_return_loss = erl;
3260 echo_return_loss_enhancement = erle;
3261 }
3262
3263 int median, std;
3264 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3265 echo_delay_median_ms = median;
3266 echo_delay_std_ms = std;
3267 }
3268 }
3269
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003270 webrtc::CallStatistics cs;
3271 unsigned int ssrc;
3272 webrtc::CodecInst codec;
3273 unsigned int level;
3274
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003275 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3276 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003277 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003278
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003279 // Fill in the sender info, based on what we know, and what the
3280 // remote side told us it got from its RTCP report.
3281 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003282
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003283 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3284 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3285 continue;
3286 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003287
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003288 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003289 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3290 sinfo.bytes_sent = cs.bytesSent;
3291 sinfo.packets_sent = cs.packetsSent;
3292 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3293 // returns 0 to indicate an error value.
3294 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3295
3296 // Get data from the last remote RTCP report. Use default values if no data
3297 // available.
3298 sinfo.fraction_lost = -1.0;
3299 sinfo.jitter_ms = -1;
3300 sinfo.packets_lost = -1;
3301 sinfo.ext_seqnum = -1;
3302 std::vector<webrtc::ReportBlock> receive_blocks;
3303 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3304 channel, &receive_blocks) != -1 &&
3305 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3306 std::vector<webrtc::ReportBlock>::iterator iter;
3307 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3308 ++iter) {
3309 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003310 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003311 // Convert Q8 to floating point.
3312 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3313 // Convert samples to milliseconds.
3314 if (codec.plfreq / 1000 > 0) {
3315 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3316 }
3317 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3318 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3319 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003320 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003321 }
3322 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003323
3324 // Local speech level.
3325 sinfo.audio_level = (engine()->voe()->volume()->
3326 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3327
3328 // TODO(xians): We are injecting the same APM logging to all the send
3329 // channels here because there is no good way to know which send channel
3330 // is using the APM. The correct fix is to allow the send channels to have
3331 // their own APM so that we can feed the correct APM logging to different
3332 // send channels. See issue crbug/264611 .
3333 sinfo.echo_return_loss = echo_return_loss;
3334 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3335 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3336 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003337 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3338 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003339 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003340
3341 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003342 }
3343
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003344 // Build the list of receivers, one for each receiving channel, or 1 in
3345 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003346 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003347 for (ChannelMap::const_iterator it = receive_channels_.begin();
3348 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003349 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003350 }
3351 if (channels.empty()) {
3352 channels.push_back(voe_channel());
3353 }
3354
3355 // Get the SSRC and stats for each receiver, based on our own calculations.
3356 for (std::vector<int>::const_iterator it = channels.begin();
3357 it != channels.end(); ++it) {
3358 memset(&cs, 0, sizeof(cs));
3359 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3360 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3361 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3362 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003363 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003364 rinfo.bytes_rcvd = cs.bytesReceived;
3365 rinfo.packets_rcvd = cs.packetsReceived;
3366 // The next four fields are from the most recently sent RTCP report.
3367 // Convert Q8 to floating point.
3368 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3369 rinfo.packets_lost = cs.cumulativeLost;
3370 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003371#ifdef USE_WEBRTC_DEV_BRANCH
3372 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
3373#endif
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003374 if (codec.pltype != -1) {
3375 rinfo.codec_name = codec.plname;
3376 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003377 // Convert samples to milliseconds.
3378 if (codec.plfreq / 1000 > 0) {
3379 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3380 }
3381
3382 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3383 webrtc::NetworkStatistics ns;
3384 if (engine()->voe()->neteq() &&
3385 engine()->voe()->neteq()->GetNetworkStatistics(
3386 *it, ns) != -1) {
3387 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3388 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3389 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003390 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003391 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003392
3393 webrtc::AudioDecodingCallStats ds;
3394 if (engine()->voe()->neteq() &&
3395 engine()->voe()->neteq()->GetDecodingCallStatistics(
3396 *it, &ds) != -1) {
3397 rinfo.decoding_calls_to_silence_generator =
3398 ds.calls_to_silence_generator;
3399 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3400 rinfo.decoding_normal = ds.decoded_normal;
3401 rinfo.decoding_plc = ds.decoded_plc;
3402 rinfo.decoding_cng = ds.decoded_cng;
3403 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3404 }
3405
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003406 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003407 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003408 int playout_buffer_delay_ms = 0;
3409 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003410 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3411 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3412 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003413 }
3414
3415 // Get speech level.
3416 rinfo.audio_level = (engine()->voe()->volume()->
3417 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3418 info->receivers.push_back(rinfo);
3419 }
3420 }
3421
3422 return true;
3423}
3424
3425void WebRtcVoiceMediaChannel::GetLastMediaError(
3426 uint32* ssrc, VoiceMediaChannel::Error* error) {
3427 ASSERT(ssrc != NULL);
3428 ASSERT(error != NULL);
3429 FindSsrc(voe_channel(), ssrc);
3430 *error = WebRtcErrorToChannelError(GetLastEngineError());
3431}
3432
3433bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003434 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003435 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003436 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003437 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3438 // This means the error is not limited to a specific channel. Signal the
3439 // message using ssrc=0. If the current channel is sending, use this
3440 // channel for sending the message.
3441 *ssrc = 0;
3442 return true;
3443 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003444 // Check whether this is a sending channel.
3445 for (ChannelMap::const_iterator it = send_channels_.begin();
3446 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003447 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003448 // This is a sending channel.
3449 uint32 local_ssrc = 0;
3450 if (engine()->voe()->rtp()->GetLocalSSRC(
3451 channel_num, local_ssrc) != -1) {
3452 *ssrc = local_ssrc;
3453 }
3454 return true;
3455 }
3456 }
3457
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003458 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003459 for (ChannelMap::const_iterator it = receive_channels_.begin();
3460 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003461 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003462 *ssrc = it->first;
3463 return true;
3464 }
3465 }
3466 }
3467 return false;
3468}
3469
3470void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003471 if (error == VE_TYPING_NOISE_WARNING) {
3472 typing_noise_detected_ = true;
3473 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3474 typing_noise_detected_ = false;
3475 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003476 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3477}
3478
3479int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3480 unsigned int ulevel;
3481 int ret =
3482 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3483 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3484}
3485
3486int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003487 ChannelMap::iterator it = receive_channels_.find(ssrc);
3488 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003489 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003490 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3491}
3492
3493int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003494 ChannelMap::iterator it = send_channels_.find(ssrc);
3495 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003496 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003497
3498 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003499}
3500
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003501bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
3502 webrtc::VideoEngine* vie, int vie_channel) {
3503 shared_bwe_vie_ = vie;
3504 shared_bwe_vie_channel_ = vie_channel;
3505
3506 if (!SetupSharedBweOnChannel(voe_channel())) {
3507 return false;
3508 }
3509 for (ChannelMap::iterator it = receive_channels_.begin();
3510 it != receive_channels_.end(); ++it) {
3511 if (!SetupSharedBweOnChannel(it->second->channel())) {
3512 return false;
3513 }
3514 }
3515 return true;
3516}
3517
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003518bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3519 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3520 // Get the RED encodings from the parameter with no name. This may
3521 // change based on what is discussed on the Jingle list.
3522 // The encoding parameter is of the form "a/b"; we only support where
3523 // a == b. Verify this and parse out the value into red_pt.
3524 // If the parameter value is absent (as it will be until we wire up the
3525 // signaling of this message), use the second codec specified (i.e. the
3526 // one after "red") as the encoding parameter.
3527 int red_pt = -1;
3528 std::string red_params;
3529 CodecParameterMap::const_iterator it = red_codec.params.find("");
3530 if (it != red_codec.params.end()) {
3531 red_params = it->second;
3532 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003533 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003534 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003535 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003536 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3537 return false;
3538 }
3539 } else if (red_codec.params.empty()) {
3540 LOG(LS_WARNING) << "RED params not present, using defaults";
3541 if (all_codecs.size() > 1) {
3542 red_pt = all_codecs[1].id;
3543 }
3544 }
3545
3546 // Try to find red_pt in |codecs|.
3547 std::vector<AudioCodec>::const_iterator codec;
3548 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3549 if (codec->id == red_pt)
3550 break;
3551 }
3552
3553 // If we find the right codec, that will be the codec we pass to
3554 // SetSendCodec, with the desired payload type.
3555 if (codec != all_codecs.end() &&
3556 engine()->FindWebRtcCodec(*codec, send_codec)) {
3557 } else {
3558 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3559 return false;
3560 }
3561
3562 return true;
3563}
3564
3565bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3566 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003567 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003568 return false;
3569 }
3570 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3571 // what we want to do with them.
3572 // engine()->voe().EnableVQMon(voe_channel(), true);
3573 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3574 return true;
3575}
3576
3577bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3578 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3579 for (int i = 0; i < ncodecs; ++i) {
3580 webrtc::CodecInst voe_codec;
3581 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3582 voe_codec.pltype = -1;
3583 if (engine()->voe()->codec()->SetRecPayloadType(
3584 channel, voe_codec) == -1) {
3585 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3586 return false;
3587 }
3588 }
3589 }
3590 return true;
3591}
3592
3593bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3594 if (playout) {
3595 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3596 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3597 LOG_RTCERR1(StartPlayout, channel);
3598 return false;
3599 }
3600 } else {
3601 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3602 engine()->voe()->base()->StopPlayout(channel);
3603 }
3604 return true;
3605}
3606
3607uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3608 bool rtcp) {
3609 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3610 uint32 ssrc = 0;
3611 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003612 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003613 }
3614 return ssrc;
3615}
3616
3617// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3618VoiceMediaChannel::Error
3619 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3620 switch (err_code) {
3621 case 0:
3622 return ERROR_NONE;
3623 case VE_CANNOT_START_RECORDING:
3624 case VE_MIC_VOL_ERROR:
3625 case VE_GET_MIC_VOL_ERROR:
3626 case VE_CANNOT_ACCESS_MIC_VOL:
3627 return ERROR_REC_DEVICE_OPEN_FAILED;
3628 case VE_SATURATION_WARNING:
3629 return ERROR_REC_DEVICE_SATURATION;
3630 case VE_REC_DEVICE_REMOVED:
3631 return ERROR_REC_DEVICE_REMOVED;
3632 case VE_RUNTIME_REC_WARNING:
3633 case VE_RUNTIME_REC_ERROR:
3634 return ERROR_REC_RUNTIME_ERROR;
3635 case VE_CANNOT_START_PLAYOUT:
3636 case VE_SPEAKER_VOL_ERROR:
3637 case VE_GET_SPEAKER_VOL_ERROR:
3638 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3639 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3640 case VE_RUNTIME_PLAY_WARNING:
3641 case VE_RUNTIME_PLAY_ERROR:
3642 return ERROR_PLAY_RUNTIME_ERROR;
3643 case VE_TYPING_NOISE_WARNING:
3644 return ERROR_REC_TYPING_NOISE_DETECTED;
3645 default:
3646 return VoiceMediaChannel::ERROR_OTHER;
3647 }
3648}
3649
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003650bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3651 int channel_id, const RtpHeaderExtension* extension) {
3652 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003653 int id = 0;
3654 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003655 if (extension) {
3656 enable = true;
3657 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003658 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003659 }
3660 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003661 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003662 return false;
3663 }
3664 return true;
3665}
3666
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003667bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
3668 webrtc::ViENetwork* vie_network = NULL;
3669 int vie_channel = -1;
3670 if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
3671 shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
3672 vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
3673 vie_channel = shared_bwe_vie_channel_;
3674 }
3675 if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
3676 vie_channel) == -1) {
3677 LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
3678 if (vie_network != NULL) {
3679 // Don't fail if we're tearing down.
3680 return false;
3681 }
3682 }
3683 return true;
3684}
3685
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003686int WebRtcSoundclipStream::Read(void *buf, int len) {
3687 size_t res = 0;
3688 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003689 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003690}
3691
3692int WebRtcSoundclipStream::Rewind() {
3693 mem_.Rewind();
3694 // Return -1 to keep VoiceEngine from looping.
3695 return (loop_) ? 0 : -1;
3696}
3697
3698} // namespace cricket
3699
3700#endif // HAVE_WEBRTC_VOICE