blob: 3d5d9ee6603256f0ed41edb63c6429b703036cd3 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#ifdef HAVE_CONFIG_H
29#include <config.h>
30#endif
31
32#ifdef HAVE_WEBRTC_VOICE
33
34#include "talk/media/webrtc/webrtcvoiceengine.h"
35
36#include <algorithm>
37#include <cstdio>
38#include <string>
39#include <vector>
40
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000041#include "talk/media/base/audiorenderer.h"
42#include "talk/media/base/constants.h"
43#include "talk/media/base/streamparams.h"
44#include "talk/media/base/voiceprocessor.h"
45#include "talk/media/webrtc/webrtcvoe.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000046#include "webrtc/base/base64.h"
47#include "webrtc/base/byteorder.h"
48#include "webrtc/base/common.h"
49#include "webrtc/base/helpers.h"
50#include "webrtc/base/logging.h"
51#include "webrtc/base/stringencode.h"
52#include "webrtc/base/stringutils.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000053#include "webrtc/common.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054#include "webrtc/modules/audio_processing/include/audio_processing.h"
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +000055#include "webrtc/video_engine/include/vie_network.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056
57#ifdef WIN32
58#include <objbase.h> // NOLINT
59#endif
60
61namespace cricket {
62
63struct CodecPref {
64 const char* name;
65 int clockrate;
66 int channels;
67 int payload_type;
68 bool is_multi_rate;
69};
70
71static const CodecPref kCodecPrefs[] = {
72 { "OPUS", 48000, 2, 111, true },
73 { "ISAC", 16000, 1, 103, true },
74 { "ISAC", 32000, 1, 104, true },
75 { "CELT", 32000, 1, 109, true },
76 { "CELT", 32000, 2, 110, true },
77 { "G722", 16000, 1, 9, false },
78 { "ILBC", 8000, 1, 102, false },
79 { "PCMU", 8000, 1, 0, false },
80 { "PCMA", 8000, 1, 8, false },
81 { "CN", 48000, 1, 107, false },
82 { "CN", 32000, 1, 106, false },
83 { "CN", 16000, 1, 105, false },
84 { "CN", 8000, 1, 13, false },
85 { "red", 8000, 1, 127, false },
86 { "telephone-event", 8000, 1, 126, false },
87};
88
89// For Linux/Mac, using the default device is done by specifying index 0 for
90// VoE 4.0 and not -1 (which was the case for VoE 3.5).
91//
92// On Windows Vista and newer, Microsoft introduced the concept of "Default
93// Communications Device". This means that there are two types of default
94// devices (old Wave Audio style default and Default Communications Device).
95//
96// On Windows systems which only support Wave Audio style default, uses either
97// -1 or 0 to select the default device.
98//
99// On Windows systems which support both "Default Communication Device" and
100// old Wave Audio style default, use -1 for Default Communications Device and
101// -2 for Wave Audio style default, which is what we want to use for clips.
102// It's not clear yet whether the -2 index is handled properly on other OSes.
103
104#ifdef WIN32
105static const int kDefaultAudioDeviceId = -1;
106static const int kDefaultSoundclipDeviceId = -2;
107#else
108static const int kDefaultAudioDeviceId = 0;
109#endif
110
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111static const char kIsacCodecName[] = "ISAC";
112static const char kL16CodecName[] = "L16";
113// Codec parameters for Opus.
114static const int kOpusMonoBitrate = 32000;
115// Parameter used for NACK.
116// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
117static const int kNackMaxPackets = 250;
118static const int kOpusStereoBitrate = 64000;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000119// draft-spittka-payload-rtp-opus-03
120// Opus bitrate should be in the range between 6000 and 510000.
121static const int kOpusMinBitrate = 6000;
122static const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000123
wu@webrtc.orgde305012013-10-31 15:40:38 +0000124// Default audio dscp value.
125// See http://tools.ietf.org/html/rfc2474 for details.
126// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000127static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000128
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000129// Ensure we open the file in a writeable path on ChromeOS and Android. This
130// workaround can be removed when it's possible to specify a filename for audio
131// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000132//
133// TODO(grunell): Use a string in the options instead of hardcoding it here
134// and let the embedder choose the filename (crbug.com/264223).
135//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000136// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
137// below.
138#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000139static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000140#elif defined(ANDROID)
141static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000142#else
143static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
144#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000145
146// Dumps an AudioCodec in RFC 2327-ish format.
147static std::string ToString(const AudioCodec& codec) {
148 std::stringstream ss;
149 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
150 << " (" << codec.id << ")";
151 return ss.str();
152}
153static std::string ToString(const webrtc::CodecInst& codec) {
154 std::stringstream ss;
155 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
156 << " (" << codec.pltype << ")";
157 return ss.str();
158}
159
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000160static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000161 const char* delim = "\r\n";
162 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
163 LOG_V(sev) << tok;
164 }
165}
166
167// Severity is an integer because it comes is assumed to be from command line.
168static int SeverityToFilter(int severity) {
169 int filter = webrtc::kTraceNone;
170 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000171 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000172 filter |= webrtc::kTraceAll;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000173 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000174 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000175 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000176 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000177 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000178 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
179 }
180 return filter;
181}
182
183static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
184 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
185 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
186 kCodecPrefs[i].clockrate == codec.plfreq) {
187 return kCodecPrefs[i].is_multi_rate;
188 }
189 }
190 return false;
191}
192
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000193static bool IsTelephoneEventCodec(const std::string& name) {
194 return _stricmp(name.c_str(), "telephone-event") == 0;
195}
196
197static bool IsCNCodec(const std::string& name) {
198 return _stricmp(name.c_str(), "CN") == 0;
199}
200
201static bool IsRedCodec(const std::string& name) {
202 return _stricmp(name.c_str(), "red") == 0;
203}
204
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000205static bool FindCodec(const std::vector<AudioCodec>& codecs,
206 const AudioCodec& codec,
207 AudioCodec* found_codec) {
208 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
209 it != codecs.end(); ++it) {
210 if (it->Matches(codec)) {
211 if (found_codec != NULL) {
212 *found_codec = *it;
213 }
214 return true;
215 }
216 }
217 return false;
218}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000219
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000220static bool IsNackEnabled(const AudioCodec& codec) {
221 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
222 kParamValueEmpty));
223}
224
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000225// Gets the default set of options applied to the engine. Historically, these
226// were supplied as a combination of flags from the channel manager (ec, agc,
227// ns, and highpass) and the rest hardcoded in InitInternal.
228static AudioOptions GetDefaultEngineOptions() {
229 AudioOptions options;
230 options.echo_cancellation.Set(true);
231 options.auto_gain_control.Set(true);
232 options.noise_suppression.Set(true);
233 options.highpass_filter.Set(true);
234 options.stereo_swapping.Set(false);
235 options.typing_detection.Set(true);
236 options.conference_mode.Set(false);
237 options.adjust_agc_delta.Set(0);
238 options.experimental_agc.Set(false);
239 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000240 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000241 options.aec_dump.Set(false);
242 return options;
243}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000244
245class WebRtcSoundclipMedia : public SoundclipMedia {
246 public:
247 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
248 : engine_(engine), webrtc_channel_(-1) {
249 engine_->RegisterSoundclip(this);
250 }
251
252 virtual ~WebRtcSoundclipMedia() {
253 engine_->UnregisterSoundclip(this);
254 if (webrtc_channel_ != -1) {
255 // We shouldn't have to call Disable() here. DeleteChannel() should call
256 // StopPlayout() while deleting the channel. We should fix the bug
257 // inside WebRTC and remove the Disable() call bellow. This work is
258 // tracked by bug http://b/issue?id=5382855.
259 PlaySound(NULL, 0, 0);
260 Disable();
261 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
262 == -1) {
263 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
264 }
265 }
266 }
267
268 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000269 if (!engine_->voe_sc()) {
270 return false;
271 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000272 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000273 if (webrtc_channel_ == -1) {
274 LOG_RTCERR0(CreateChannel);
275 return false;
276 }
277 return true;
278 }
279
280 bool Enable() {
281 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
282 LOG_RTCERR1(StartPlayout, webrtc_channel_);
283 return false;
284 }
285 return true;
286 }
287
288 bool Disable() {
289 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
290 LOG_RTCERR1(StopPlayout, webrtc_channel_);
291 return false;
292 }
293 return true;
294 }
295
296 virtual bool PlaySound(const char *buf, int len, int flags) {
297 // The voe file api is not available in chrome.
298 if (!engine_->voe_sc()->file()) {
299 return false;
300 }
301 // Must stop playing the current sound (if any), because we are about to
302 // modify the stream.
303 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
304 == -1) {
305 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
306 return false;
307 }
308
309 if (buf) {
310 stream_.reset(new WebRtcSoundclipStream(buf, len));
311 stream_->set_loop((flags & SF_LOOP) != 0);
312 stream_->Rewind();
313
314 // Play it.
315 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
316 webrtc_channel_, stream_.get()) == -1) {
317 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
318 LOG(LS_ERROR) << "Unable to start soundclip";
319 return false;
320 }
321 } else {
322 stream_.reset();
323 }
324 return true;
325 }
326
327 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
328
329 private:
330 WebRtcVoiceEngine *engine_;
331 int webrtc_channel_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000332 rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000333};
334
335WebRtcVoiceEngine::WebRtcVoiceEngine()
336 : voe_wrapper_(new VoEWrapper()),
337 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000338 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000339 tracing_(new VoETraceWrapper()),
340 adm_(NULL),
341 adm_sc_(NULL),
342 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
343 is_dumping_aec_(false),
344 desired_local_monitor_enable_(false),
345 tx_processor_ssrc_(0),
346 rx_processor_ssrc_(0) {
347 Construct();
348}
349
350WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
351 VoEWrapper* voe_wrapper_sc,
352 VoETraceWrapper* tracing)
353 : voe_wrapper_(voe_wrapper),
354 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000355 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000356 tracing_(tracing),
357 adm_(NULL),
358 adm_sc_(NULL),
359 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
360 is_dumping_aec_(false),
361 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000362 tx_processor_ssrc_(0),
363 rx_processor_ssrc_(0) {
364 Construct();
365}
366
367void WebRtcVoiceEngine::Construct() {
368 SetTraceFilter(log_filter_);
369 initialized_ = false;
370 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
371 SetTraceOptions("");
372 if (tracing_->SetTraceCallback(this) == -1) {
373 LOG_RTCERR0(SetTraceCallback);
374 }
375 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
376 LOG_RTCERR0(RegisterVoiceEngineObserver);
377 }
378 // Clear the default agc state.
379 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
380
381 // Load our audio codec list.
382 ConstructCodecs();
383
384 // Load our RTP Header extensions.
385 rtp_header_extensions_.push_back(
386 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
387 kRtpAudioLevelHeaderExtensionDefaultId));
388 rtp_header_extensions_.push_back(
389 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
390 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
391 options_ = GetDefaultEngineOptions();
392}
393
394static bool IsOpus(const AudioCodec& codec) {
395 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
396}
397
398static bool IsIsac(const AudioCodec& codec) {
399 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
400}
401
402// True if params["stereo"] == "1"
403static bool IsOpusStereoEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000404 int value;
405 return codec.GetParam(kCodecParamStereo, &value) && value == 1;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000406}
407
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000408// TODO(minyue): Clamp bitrate when invalid.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000409static bool IsValidOpusBitrate(int bitrate) {
410 return (bitrate >= kOpusMinBitrate && bitrate <= kOpusMaxBitrate);
411}
412
413// Returns 0 if params[kCodecParamMaxAverageBitrate] is not defined or invalid.
414// Returns the value of params[kCodecParamMaxAverageBitrate] otherwise.
415static int GetOpusBitrateFromParams(const AudioCodec& codec) {
416 int bitrate = 0;
417 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
418 return 0;
419 }
420 if (!IsValidOpusBitrate(bitrate)) {
421 LOG(LS_WARNING) << "Codec parameter \"maxaveragebitrate\" has an "
422 << "invalid value: " << bitrate;
423 return 0;
424 }
425 return bitrate;
426}
427
buildbot@webrtc.orgfbd13282014-06-19 19:50:55 +0000428// Return true if params[kCodecParamUseInbandFec] == "1", false
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000429// otherwise.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000430static bool IsOpusFecEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000431 int value;
432 return codec.GetParam(kCodecParamUseInbandFec, &value) && value == 1;
433}
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000434
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000435// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
436// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
437static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
438 int value;
439 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
440 return value;
441 }
442 return kOpusDefaultMaxPlaybackRate;
443}
444
445static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
446 bool* enable_codec_fec, int* max_playback_rate) {
447 *enable_codec_fec = IsOpusFecEnabled(codec);
448 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
449
450 // If OPUS, change what we send according to the "stereo" codec
451 // parameter, and not the "channels" parameter. We set
452 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
453 // the bitrate is not specified, i.e. is zero, we set it to the
454 // appropriate default value for mono or stereo Opus.
455
456 // TODO(minyue): The determination of bit rate might take the maximum playback
457 // rate into account.
458
459 if (IsOpusStereoEnabled(codec)) {
460 voe_codec->channels = 2;
461 if (!IsValidOpusBitrate(codec.bitrate)) {
462 if (codec.bitrate != 0) {
463 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
464 << codec.bitrate
465 << ") with default opus stereo bitrate: "
466 << kOpusStereoBitrate;
467 }
468 voe_codec->rate = kOpusStereoBitrate;
469 }
470 } else {
471 voe_codec->channels = 1;
472 if (!IsValidOpusBitrate(codec.bitrate)) {
473 if (codec.bitrate != 0) {
474 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
475 << codec.bitrate
476 << ") with default opus mono bitrate: "
477 << kOpusMonoBitrate;
478 }
479 voe_codec->rate = kOpusMonoBitrate;
480 }
481 }
482 int bitrate_from_params = GetOpusBitrateFromParams(codec);
483 if (bitrate_from_params != 0) {
484 voe_codec->rate = bitrate_from_params;
485 }
486}
487
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000488void WebRtcVoiceEngine::ConstructCodecs() {
489 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
490 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
491 for (int i = 0; i < ncodecs; ++i) {
492 webrtc::CodecInst voe_codec;
493 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
494 // Skip uncompressed formats.
495 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
496 continue;
497 }
498
499 const CodecPref* pref = NULL;
500 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
501 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
502 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
503 kCodecPrefs[j].channels == voe_codec.channels) {
504 pref = &kCodecPrefs[j];
505 break;
506 }
507 }
508
509 if (pref) {
510 // Use the payload type that we've configured in our pref table;
511 // use the offset in our pref table to determine the sort order.
512 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
513 voe_codec.rate, voe_codec.channels,
514 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
515 LOG(LS_INFO) << ToString(codec);
516 if (IsIsac(codec)) {
517 // Indicate auto-bandwidth in signaling.
518 codec.bitrate = 0;
519 }
520 if (IsOpus(codec)) {
521 // Only add fmtp parameters that differ from the spec.
522 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
523 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000524 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000525 }
526 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
527 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000528 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000529 }
530 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
531 // when they can be set to values other than the default.
532 }
533 codecs_.push_back(codec);
534 } else {
535 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
536 }
537 }
538 }
539 // Make sure they are in local preference order.
540 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
541}
542
543WebRtcVoiceEngine::~WebRtcVoiceEngine() {
544 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
545 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
546 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
547 }
548 if (adm_) {
549 voe_wrapper_.reset();
550 adm_->Release();
551 adm_ = NULL;
552 }
553 if (adm_sc_) {
554 voe_wrapper_sc_.reset();
555 adm_sc_->Release();
556 adm_sc_ = NULL;
557 }
558
559 // Test to see if the media processor was deregistered properly
560 ASSERT(SignalRxMediaFrame.is_empty());
561 ASSERT(SignalTxMediaFrame.is_empty());
562
563 tracing_->SetTraceCallback(NULL);
564}
565
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000566bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000567 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
568 bool res = InitInternal();
569 if (res) {
570 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
571 } else {
572 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
573 Terminate();
574 }
575 return res;
576}
577
578bool WebRtcVoiceEngine::InitInternal() {
579 // Temporarily turn logging level up for the Init call
580 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000581 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000582 SetTraceFilter(extended_filter);
583 SetTraceOptions("");
584
585 // Init WebRtc VoiceEngine.
586 if (voe_wrapper_->base()->Init(adm_) == -1) {
587 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
588 SetTraceFilter(old_filter);
589 return false;
590 }
591
592 SetTraceFilter(old_filter);
593 SetTraceOptions(log_options_);
594
595 // Log the VoiceEngine version info
596 char buffer[1024] = "";
597 voe_wrapper_->base()->GetVersion(buffer);
598 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000599 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000600
601 // Save the default AGC configuration settings. This must happen before
602 // calling SetOptions or the default will be overwritten.
603 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
604 LOG_RTCERR0(GetAgcConfig);
605 return false;
606 }
607
608 // Set defaults for options, so that ApplyOptions applies them explicitly
609 // when we clear option (channel) overrides. External clients can still
610 // modify the defaults via SetOptions (on the media engine).
611 if (!SetOptions(GetDefaultEngineOptions())) {
612 return false;
613 }
614
615 // Print our codec list again for the call diagnostic log
616 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
617 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
618 it != codecs_.end(); ++it) {
619 LOG(LS_INFO) << ToString(*it);
620 }
621
622 // Disable the DTMF playout when a tone is sent.
623 // PlayDtmfTone will be used if local playout is needed.
624 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
625 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
626 }
627
628 initialized_ = true;
629 return true;
630}
631
632bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
633 if (voe_wrapper_sc_initialized_) {
634 return true;
635 }
636 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
637 // be false, so subsequent calls to EnsureSoundclipEngineInit will
638 // probably just fail again. That's acceptable behavior.
639#if defined(LINUX) && !defined(HAVE_LIBPULSE)
640 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
641#endif
642
643 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
644 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
645 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
646 return false;
647 }
648
649 // On Windows, tell it to use the default sound (not communication) devices.
650 // First check whether there is a valid sound device for playback.
651 // TODO(juberti): Clean this up when we support setting the soundclip device.
652#ifdef WIN32
653 // The SetPlayoutDevice may not be implemented in the case of external ADM.
654 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
655 // PeerConnection interface never set the adm_sc_, so need to check both
656 // in order to determine if the external adm is used.
657 if (!adm_ && !adm_sc_) {
658 int num_of_devices = 0;
659 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
660 num_of_devices > 0) {
661 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
662 == -1) {
663 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
664 voe_wrapper_sc_->error());
665 return false;
666 }
667 } else {
668 LOG(LS_WARNING) << "No valid sound playout device found.";
669 }
670 }
671#endif
672 voe_wrapper_sc_initialized_ = true;
673 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
674 return true;
675}
676
677void WebRtcVoiceEngine::Terminate() {
678 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
679 initialized_ = false;
680
681 StopAecDump();
682
683 if (voe_wrapper_sc_) {
684 voe_wrapper_sc_initialized_ = false;
685 voe_wrapper_sc_->base()->Terminate();
686 }
687 voe_wrapper_->base()->Terminate();
688 desired_local_monitor_enable_ = false;
689}
690
691int WebRtcVoiceEngine::GetCapabilities() {
692 return AUDIO_SEND | AUDIO_RECV;
693}
694
695VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
696 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
697 if (!ch->valid()) {
698 delete ch;
699 ch = NULL;
700 }
701 return ch;
702}
703
704SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
705 if (!EnsureSoundclipEngineInit()) {
706 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
707 << "initialize.";
708 return NULL;
709 }
710 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
711 if (!soundclip->Init() || !soundclip->Enable()) {
712 delete soundclip;
713 return NULL;
714 }
715 return soundclip;
716}
717
718bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
719 if (!ApplyOptions(options)) {
720 return false;
721 }
722 options_ = options;
723 return true;
724}
725
726bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
727 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
728 if (!ApplyOptions(overrides)) {
729 return false;
730 }
731 option_overrides_ = overrides;
732 return true;
733}
734
735bool WebRtcVoiceEngine::ClearOptionOverrides() {
736 LOG(LS_INFO) << "Clearing option overrides.";
737 AudioOptions options = options_;
738 // Only call ApplyOptions if |options_overrides_| contains overrided options.
739 // ApplyOptions affects NS, AGC other options that is shared between
740 // all WebRtcVoiceEngineChannels.
741 if (option_overrides_ == AudioOptions()) {
742 return true;
743 }
744
745 if (!ApplyOptions(options)) {
746 return false;
747 }
748 option_overrides_ = AudioOptions();
749 return true;
750}
751
752// AudioOptions defaults are set in InitInternal (for options with corresponding
753// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
754bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
755 AudioOptions options = options_in; // The options are modified below.
756 // kEcConference is AEC with high suppression.
757 webrtc::EcModes ec_mode = webrtc::kEcConference;
758 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
759 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
760 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
761 bool aecm_comfort_noise = false;
762 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
763 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
764 << aecm_comfort_noise << " (default is false).";
765 }
766
767#if defined(IOS)
768 // On iOS, VPIO provides built-in EC and AGC.
769 options.echo_cancellation.Set(false);
770 options.auto_gain_control.Set(false);
771#elif defined(ANDROID)
772 ec_mode = webrtc::kEcAecm;
773#endif
774
775#if defined(IOS) || defined(ANDROID)
776 // Set the AGC mode for iOS as well despite disabling it above, to avoid
777 // unsupported configuration errors from webrtc.
778 agc_mode = webrtc::kAgcFixedDigital;
779 options.typing_detection.Set(false);
780 options.experimental_agc.Set(false);
781 options.experimental_aec.Set(false);
782 options.experimental_ns.Set(false);
783#endif
784
785 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
786
787 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
788
789 bool echo_cancellation;
790 if (options.echo_cancellation.Get(&echo_cancellation)) {
791 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
792 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
793 return false;
794 } else {
795 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
796 << " with mode " << ec_mode;
797 }
798#if !defined(ANDROID)
799 // TODO(ajm): Remove the error return on Android from webrtc.
800 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
801 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
802 return false;
803 }
804#endif
805 if (ec_mode == webrtc::kEcAecm) {
806 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
807 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
808 return false;
809 }
810 }
811 }
812
813 bool auto_gain_control;
814 if (options.auto_gain_control.Get(&auto_gain_control)) {
815 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
816 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
817 return false;
818 } else {
819 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
820 << " with mode " << agc_mode;
821 }
822 }
823
824 if (options.tx_agc_target_dbov.IsSet() ||
825 options.tx_agc_digital_compression_gain.IsSet() ||
826 options.tx_agc_limiter.IsSet()) {
827 // Override default_agc_config_. Generally, an unset option means "leave
828 // the VoE bits alone" in this function, so we want whatever is set to be
829 // stored as the new "default". If we didn't, then setting e.g.
830 // tx_agc_target_dbov would reset digital compression gain and limiter
831 // settings.
832 // Also, if we don't update default_agc_config_, then adjust_agc_delta
833 // would be an offset from the original values, and not whatever was set
834 // explicitly.
835 default_agc_config_.targetLeveldBOv =
836 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
837 default_agc_config_.targetLeveldBOv);
838 default_agc_config_.digitalCompressionGaindB =
839 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
840 default_agc_config_.digitalCompressionGaindB);
841 default_agc_config_.limiterEnable =
842 options.tx_agc_limiter.GetWithDefaultIfUnset(
843 default_agc_config_.limiterEnable);
844 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
845 LOG_RTCERR3(SetAgcConfig,
846 default_agc_config_.targetLeveldBOv,
847 default_agc_config_.digitalCompressionGaindB,
848 default_agc_config_.limiterEnable);
849 return false;
850 }
851 }
852
853 bool noise_suppression;
854 if (options.noise_suppression.Get(&noise_suppression)) {
855 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
856 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
857 return false;
858 } else {
859 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
860 << " with mode " << ns_mode;
861 }
862 }
863
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000864 bool highpass_filter;
865 if (options.highpass_filter.Get(&highpass_filter)) {
866 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
867 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
868 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
869 return false;
870 }
871 }
872
873 bool stereo_swapping;
874 if (options.stereo_swapping.Get(&stereo_swapping)) {
875 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
876 voep->EnableStereoChannelSwapping(stereo_swapping);
877 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
878 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
879 return false;
880 }
881 }
882
883 bool typing_detection;
884 if (options.typing_detection.Get(&typing_detection)) {
885 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
886 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
887 // In case of error, log the info and continue
888 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
889 }
890 }
891
892 int adjust_agc_delta;
893 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
894 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
895 if (!AdjustAgcLevel(adjust_agc_delta)) {
896 return false;
897 }
898 }
899
900 bool aec_dump;
901 if (options.aec_dump.Get(&aec_dump)) {
902 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
903 if (aec_dump)
904 StartAecDump(kAecDumpByAudioOptionFilename);
905 else
906 StopAecDump();
907 }
908
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000909 webrtc::Config config;
910
911 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000912 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000913 if (experimental_aec_.Get(&experimental_aec)) {
914 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
915 config.Set<webrtc::DelayCorrection>(
916 new webrtc::DelayCorrection(experimental_aec));
917 }
918
919#ifdef USE_WEBRTC_DEV_BRANCH
920 experimental_ns_.SetFrom(options.experimental_ns);
921 bool experimental_ns;
922 if (experimental_ns_.Get(&experimental_ns)) {
923 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
924 config.Set<webrtc::ExperimentalNs>(
925 new webrtc::ExperimentalNs(experimental_ns));
926 }
927#endif
928
929 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
930 // returns NULL on audio_processing().
931 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
932 if (audioproc) {
933 audioproc->SetExtraOptions(config);
934 }
935
936#ifndef USE_WEBRTC_DEV_BRANCH
937 bool experimental_ns;
938 if (options.experimental_ns.Get(&experimental_ns)) {
939 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000940 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
941 // returns NULL on audio_processing().
942 if (audioproc) {
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000943 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
944 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
945 return false;
946 }
947 } else {
948 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
949 << experimental_ns;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000950 }
951 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000952#endif
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000953
954 uint32 recording_sample_rate;
955 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
956 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
957 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
958 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
959 }
960 }
961
962 uint32 playout_sample_rate;
963 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
964 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
965 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
966 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
967 }
968 }
969
970 return true;
971}
972
973bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
974 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
975 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
976 LOG_RTCERR1(SetDelayOffsetMs, offset);
977 return false;
978 }
979
980 return true;
981}
982
983struct ResumeEntry {
984 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
985 : channel(c),
986 playout(p),
987 send(s) {
988 }
989
990 WebRtcVoiceMediaChannel *channel;
991 bool playout;
992 SendFlags send;
993};
994
995// TODO(juberti): Refactor this so that the core logic can be used to set the
996// soundclip device. At that time, reinstate the soundclip pause/resume code.
997bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
998 const Device* out_device) {
999#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001000 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001001 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001002 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001003 kDefaultAudioDeviceId;
1004 // The device manager uses -1 as the default device, which was the case for
1005 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
1006#ifndef WIN32
1007 if (-1 == in_id) {
1008 in_id = kDefaultAudioDeviceId;
1009 }
1010 if (-1 == out_id) {
1011 out_id = kDefaultAudioDeviceId;
1012 }
1013#endif
1014
1015 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
1016 in_device->name : "Default device";
1017 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
1018 out_device->name : "Default device";
1019 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
1020 << ") and speaker to (id=" << out_id << ", name=" << out_name
1021 << ")";
1022
1023 // If we're running the local monitor, we need to stop it first.
1024 bool ret = true;
1025 if (!PauseLocalMonitor()) {
1026 LOG(LS_WARNING) << "Failed to pause local monitor";
1027 ret = false;
1028 }
1029
1030 // Must also pause all audio playback and capture.
1031 for (ChannelList::const_iterator i = channels_.begin();
1032 i != channels_.end(); ++i) {
1033 WebRtcVoiceMediaChannel *channel = *i;
1034 if (!channel->PausePlayout()) {
1035 LOG(LS_WARNING) << "Failed to pause playout";
1036 ret = false;
1037 }
1038 if (!channel->PauseSend()) {
1039 LOG(LS_WARNING) << "Failed to pause send";
1040 ret = false;
1041 }
1042 }
1043
1044 // Find the recording device id in VoiceEngine and set recording device.
1045 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1046 ret = false;
1047 }
1048 if (ret) {
1049 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
1050 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
1051 ret = false;
1052 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00001053 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
1054 if (ap)
1055 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001056 }
1057
1058 // Find the playout device id in VoiceEngine and set playout device.
1059 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1060 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1061 ret = false;
1062 }
1063 if (ret) {
1064 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001065 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001066 ret = false;
1067 }
1068 }
1069
1070 // Resume all audio playback and capture.
1071 for (ChannelList::const_iterator i = channels_.begin();
1072 i != channels_.end(); ++i) {
1073 WebRtcVoiceMediaChannel *channel = *i;
1074 if (!channel->ResumePlayout()) {
1075 LOG(LS_WARNING) << "Failed to resume playout";
1076 ret = false;
1077 }
1078 if (!channel->ResumeSend()) {
1079 LOG(LS_WARNING) << "Failed to resume send";
1080 ret = false;
1081 }
1082 }
1083
1084 // Resume local monitor.
1085 if (!ResumeLocalMonitor()) {
1086 LOG(LS_WARNING) << "Failed to resume local monitor";
1087 ret = false;
1088 }
1089
1090 if (ret) {
1091 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1092 << ") and speaker to (id="<< out_id << " name=" << out_name
1093 << ")";
1094 }
1095
1096 return ret;
1097#else
1098 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001099#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001100}
1101
1102bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1103 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1104 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001105#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001106 *rtc_id = dev_id;
1107 return true;
1108#else
1109 // In Windows and Mac, we need to find the VoiceEngine device id by name
1110 // unless the input dev_id is the default device id.
1111 if (kDefaultAudioDeviceId == dev_id) {
1112 *rtc_id = dev_id;
1113 return true;
1114 }
1115
1116 // Get the number of VoiceEngine audio devices.
1117 int count = 0;
1118 if (is_input) {
1119 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1120 LOG_RTCERR0(GetNumOfRecordingDevices);
1121 return false;
1122 }
1123 } else {
1124 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1125 LOG_RTCERR0(GetNumOfPlayoutDevices);
1126 return false;
1127 }
1128 }
1129
1130 for (int i = 0; i < count; ++i) {
1131 char name[128];
1132 char guid[128];
1133 if (is_input) {
1134 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1135 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1136 } else {
1137 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1138 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1139 }
1140
1141 std::string webrtc_name(name);
1142 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1143 *rtc_id = i;
1144 return true;
1145 }
1146 }
1147 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1148 return false;
1149#endif
1150}
1151
1152bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1153 unsigned int ulevel;
1154 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1155 LOG_RTCERR1(GetSpeakerVolume, level);
1156 return false;
1157 }
1158 *level = ulevel;
1159 return true;
1160}
1161
1162bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1163 ASSERT(level >= 0 && level <= 255);
1164 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1165 LOG_RTCERR1(SetSpeakerVolume, level);
1166 return false;
1167 }
1168 return true;
1169}
1170
1171int WebRtcVoiceEngine::GetInputLevel() {
1172 unsigned int ulevel;
1173 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1174 static_cast<int>(ulevel) : -1;
1175}
1176
1177bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1178 desired_local_monitor_enable_ = enable;
1179 return ChangeLocalMonitor(desired_local_monitor_enable_);
1180}
1181
1182bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1183 // The voe file api is not available in chrome.
1184 if (!voe_wrapper_->file()) {
1185 return false;
1186 }
1187 if (enable && !monitor_) {
1188 monitor_.reset(new WebRtcMonitorStream);
1189 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1190 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1191 // Must call Stop() because there are some cases where Start will report
1192 // failure but still change the state, and if we leave VE in the on state
1193 // then it could crash later when trying to invoke methods on our monitor.
1194 voe_wrapper_->file()->StopRecordingMicrophone();
1195 monitor_.reset();
1196 return false;
1197 }
1198 } else if (!enable && monitor_) {
1199 voe_wrapper_->file()->StopRecordingMicrophone();
1200 monitor_.reset();
1201 }
1202 return true;
1203}
1204
1205bool WebRtcVoiceEngine::PauseLocalMonitor() {
1206 return ChangeLocalMonitor(false);
1207}
1208
1209bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1210 return ChangeLocalMonitor(desired_local_monitor_enable_);
1211}
1212
1213const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1214 return codecs_;
1215}
1216
1217bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1218 return FindWebRtcCodec(in, NULL);
1219}
1220
1221// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1222bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1223 webrtc::CodecInst* out) {
1224 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1225 for (int i = 0; i < ncodecs; ++i) {
1226 webrtc::CodecInst voe_codec;
1227 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1228 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1229 voe_codec.rate, voe_codec.channels, 0);
1230 bool multi_rate = IsCodecMultiRate(voe_codec);
1231 // Allow arbitrary rates for ISAC to be specified.
1232 if (multi_rate) {
1233 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1234 codec.bitrate = 0;
1235 }
1236 if (codec.Matches(in)) {
1237 if (out) {
1238 // Fixup the payload type.
1239 voe_codec.pltype = in.id;
1240
1241 // Set bitrate if specified.
1242 if (multi_rate && in.bitrate != 0) {
1243 voe_codec.rate = in.bitrate;
1244 }
1245
1246 // Apply codec-specific settings.
1247 if (IsIsac(codec)) {
1248 // If ISAC and an explicit bitrate is not specified,
1249 // enable auto bandwidth adjustment.
1250 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1251 }
1252 *out = voe_codec;
1253 }
1254 return true;
1255 }
1256 }
1257 }
1258 return false;
1259}
1260const std::vector<RtpHeaderExtension>&
1261WebRtcVoiceEngine::rtp_header_extensions() const {
1262 return rtp_header_extensions_;
1263}
1264
1265void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1266 // if min_sev == -1, we keep the current log level.
1267 if (min_sev >= 0) {
1268 SetTraceFilter(SeverityToFilter(min_sev));
1269 }
1270 log_options_ = filter;
1271 SetTraceOptions(initialized_ ? log_options_ : "");
1272}
1273
1274int WebRtcVoiceEngine::GetLastEngineError() {
1275 return voe_wrapper_->error();
1276}
1277
1278void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1279 log_filter_ = filter;
1280 tracing_->SetTraceFilter(filter);
1281}
1282
1283// We suppport three different logging settings for VoiceEngine:
1284// 1. Observer callback that goes into talk diagnostic logfile.
1285// Use --logfile and --loglevel
1286//
1287// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1288// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1289//
1290// 3. EC log and dump for debugging QualityEngine.
1291// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1292//
1293// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1294// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1295void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1296 // Set encrypted trace file.
1297 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001298 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001299 std::vector<std::string>::iterator tracefile =
1300 std::find(opts.begin(), opts.end(), "tracefile");
1301 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1302 // Write encrypted debug output (at same loglevel) to file
1303 // EncryptedTraceFile no longer supported.
1304 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1305 LOG_RTCERR1(SetTraceFile, *tracefile);
1306 }
1307 }
1308
wu@webrtc.org97077a32013-10-25 21:18:33 +00001309 // Allow trace options to override the trace filter. We default
1310 // it to log_filter_ (as a translation of libjingle log levels)
1311 // elsewhere, but this allows clients to explicitly set webrtc
1312 // log levels.
1313 std::vector<std::string>::iterator tracefilter =
1314 std::find(opts.begin(), opts.end(), "tracefilter");
1315 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001316 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001317 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1318 }
1319 }
1320
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001321 // Set AEC dump file
1322 std::vector<std::string>::iterator recordEC =
1323 std::find(opts.begin(), opts.end(), "recordEC");
1324 if (recordEC != opts.end()) {
1325 ++recordEC;
1326 if (recordEC != opts.end())
1327 StartAecDump(recordEC->c_str());
1328 else
1329 StopAecDump();
1330 }
1331}
1332
1333// Ignore spammy trace messages, mostly from the stats API when we haven't
1334// gotten RTCP info yet from the remote side.
1335bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1336 static const char* kTracesToIgnore[] = {
1337 "\tfailed to GetReportBlockInformation",
1338 "GetRecCodec() failed to get received codec",
1339 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1340 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1341 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1342 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1343 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1344 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1345 "SenderInfoReceived No received SR",
1346 "StatisticsRTP() no statistics available",
1347 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1348 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1349 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1350 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1351 NULL
1352 };
1353 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1354 if (trace.find(*p) != std::string::npos) {
1355 return true;
1356 }
1357 }
1358 return false;
1359}
1360
1361void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1362 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001363 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001364 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001365 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001367 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001368 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001369 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001371 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001372
1373 // Skip past boilerplate prefix text
1374 if (length < 72) {
1375 std::string msg(trace, length);
1376 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1377 LOG_V(sev) << msg;
1378 } else {
1379 std::string msg(trace + 71, length - 72);
1380 if (!ShouldIgnoreTrace(msg)) {
1381 LOG_V(sev) << "webrtc: " << msg;
1382 }
1383 }
1384}
1385
1386void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001387 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001388 WebRtcVoiceMediaChannel* channel = NULL;
1389 uint32 ssrc = 0;
1390 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1391 << channel_num << ".";
1392 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1393 ASSERT(channel != NULL);
1394 channel->OnError(ssrc, err_code);
1395 } else {
1396 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1397 << " could not be found in channel list when error reported.";
1398 }
1399}
1400
1401bool WebRtcVoiceEngine::FindChannelAndSsrc(
1402 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1403 ASSERT(channel != NULL && ssrc != NULL);
1404
1405 *channel = NULL;
1406 *ssrc = 0;
1407 // Find corresponding channel and ssrc
1408 for (ChannelList::const_iterator it = channels_.begin();
1409 it != channels_.end(); ++it) {
1410 ASSERT(*it != NULL);
1411 if ((*it)->FindSsrc(channel_num, ssrc)) {
1412 *channel = *it;
1413 return true;
1414 }
1415 }
1416
1417 return false;
1418}
1419
1420// This method will search through the WebRtcVoiceMediaChannels and
1421// obtain the voice engine's channel number.
1422bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1423 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1424 ASSERT(channel_num != NULL);
1425 ASSERT(direction == MPD_RX || direction == MPD_TX);
1426
1427 *channel_num = -1;
1428 // Find corresponding channel for ssrc.
1429 for (ChannelList::const_iterator it = channels_.begin();
1430 it != channels_.end(); ++it) {
1431 ASSERT(*it != NULL);
1432 if (direction & MPD_RX) {
1433 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1434 }
1435 if (*channel_num == -1 && (direction & MPD_TX)) {
1436 *channel_num = (*it)->GetSendChannelNum(ssrc);
1437 }
1438 if (*channel_num != -1) {
1439 return true;
1440 }
1441 }
1442 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1443 return false;
1444}
1445
1446void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001447 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001448 channels_.push_back(channel);
1449}
1450
1451void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001452 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001453 ChannelList::iterator i = std::find(channels_.begin(),
1454 channels_.end(),
1455 channel);
1456 if (i != channels_.end()) {
1457 channels_.erase(i);
1458 }
1459}
1460
1461void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1462 soundclips_.push_back(soundclip);
1463}
1464
1465void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1466 SoundclipList::iterator i = std::find(soundclips_.begin(),
1467 soundclips_.end(),
1468 soundclip);
1469 if (i != soundclips_.end()) {
1470 soundclips_.erase(i);
1471 }
1472}
1473
1474// Adjusts the default AGC target level by the specified delta.
1475// NB: If we start messing with other config fields, we'll want
1476// to save the current webrtc::AgcConfig as well.
1477bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1478 webrtc::AgcConfig config = default_agc_config_;
1479 config.targetLeveldBOv -= delta;
1480
1481 LOG(LS_INFO) << "Adjusting AGC level from default -"
1482 << default_agc_config_.targetLeveldBOv << "dB to -"
1483 << config.targetLeveldBOv << "dB";
1484
1485 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1486 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1487 return false;
1488 }
1489 return true;
1490}
1491
1492bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1493 webrtc::AudioDeviceModule* adm_sc) {
1494 if (initialized_) {
1495 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1496 return false;
1497 }
1498 if (adm_) {
1499 adm_->Release();
1500 adm_ = NULL;
1501 }
1502 if (adm) {
1503 adm_ = adm;
1504 adm_->AddRef();
1505 }
1506
1507 if (adm_sc_) {
1508 adm_sc_->Release();
1509 adm_sc_ = NULL;
1510 }
1511 if (adm_sc) {
1512 adm_sc_ = adm_sc;
1513 adm_sc_->AddRef();
1514 }
1515 return true;
1516}
1517
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001518bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1519 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001520 if (!aec_dump_file_stream) {
1521 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001522 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001523 LOG(LS_WARNING) << "Could not close file.";
1524 return false;
1525 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001526 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001527 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001528 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001529 LOG_RTCERR0(StartDebugRecording);
1530 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001531 return false;
1532 }
1533 is_dumping_aec_ = true;
1534 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001535}
1536
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001537bool WebRtcVoiceEngine::RegisterProcessor(
1538 uint32 ssrc,
1539 VoiceProcessor* voice_processor,
1540 MediaProcessorDirection direction) {
1541 bool register_with_webrtc = false;
1542 int channel_id = -1;
1543 bool success = false;
1544 uint32* processor_ssrc = NULL;
1545 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1546 if (voice_processor == NULL || !found_channel) {
1547 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1548 << " foundChannel: " << found_channel;
1549 return false;
1550 }
1551
1552 webrtc::ProcessingTypes processing_type;
1553 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001554 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001555 if (direction == MPD_RX) {
1556 processing_type = webrtc::kPlaybackAllChannelsMixed;
1557 if (SignalRxMediaFrame.is_empty()) {
1558 register_with_webrtc = true;
1559 processor_ssrc = &rx_processor_ssrc_;
1560 }
1561 SignalRxMediaFrame.connect(voice_processor,
1562 &VoiceProcessor::OnFrame);
1563 } else {
1564 processing_type = webrtc::kRecordingPerChannel;
1565 if (SignalTxMediaFrame.is_empty()) {
1566 register_with_webrtc = true;
1567 processor_ssrc = &tx_processor_ssrc_;
1568 }
1569 SignalTxMediaFrame.connect(voice_processor,
1570 &VoiceProcessor::OnFrame);
1571 }
1572 }
1573 if (register_with_webrtc) {
1574 // TODO(janahan): when registering consider instantiating a
1575 // a VoeMediaProcess object and not make the engine extend the interface.
1576 if (voe()->media() && voe()->media()->
1577 RegisterExternalMediaProcessing(channel_id,
1578 processing_type,
1579 *this) != -1) {
1580 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1581 << channel_id;
1582 *processor_ssrc = ssrc;
1583 success = true;
1584 } else {
1585 LOG_RTCERR2(RegisterExternalMediaProcessing,
1586 channel_id,
1587 processing_type);
1588 success = false;
1589 }
1590 } else {
1591 // If we don't have to register with the engine, we just needed to
1592 // connect a new processor, set success to true;
1593 success = true;
1594 }
1595 return success;
1596}
1597
1598bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1599 MediaProcessorDirection channel_direction,
1600 uint32 ssrc,
1601 VoiceProcessor* voice_processor,
1602 MediaProcessorDirection processor_direction) {
1603 bool success = true;
1604 FrameSignal* signal;
1605 webrtc::ProcessingTypes processing_type;
1606 uint32* processor_ssrc = NULL;
1607 if (channel_direction == MPD_RX) {
1608 signal = &SignalRxMediaFrame;
1609 processing_type = webrtc::kPlaybackAllChannelsMixed;
1610 processor_ssrc = &rx_processor_ssrc_;
1611 } else {
1612 signal = &SignalTxMediaFrame;
1613 processing_type = webrtc::kRecordingPerChannel;
1614 processor_ssrc = &tx_processor_ssrc_;
1615 }
1616
1617 int deregister_id = -1;
1618 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001619 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001620 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1621 signal->disconnect(voice_processor);
1622 int channel_id = -1;
1623 bool found_channel = FindChannelNumFromSsrc(ssrc,
1624 channel_direction,
1625 &channel_id);
1626 if (signal->is_empty() && found_channel) {
1627 deregister_id = channel_id;
1628 }
1629 }
1630 }
1631 if (deregister_id != -1) {
1632 if (voe()->media() &&
1633 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1634 processing_type) != -1) {
1635 *processor_ssrc = 0;
1636 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1637 << deregister_id;
1638 } else {
1639 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1640 deregister_id,
1641 processing_type);
1642 success = false;
1643 }
1644 }
1645 return success;
1646}
1647
1648bool WebRtcVoiceEngine::UnregisterProcessor(
1649 uint32 ssrc,
1650 VoiceProcessor* voice_processor,
1651 MediaProcessorDirection direction) {
1652 bool success = true;
1653 if (voice_processor == NULL) {
1654 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1655 << ssrc;
1656 return false;
1657 }
1658 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1659 success = false;
1660 }
1661 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1662 success = false;
1663 }
1664 return success;
1665}
1666
1667// Implementing method from WebRtc VoEMediaProcess interface
1668// Do not lock mux_channel_cs_ in this callback.
1669void WebRtcVoiceEngine::Process(int channel,
1670 webrtc::ProcessingTypes type,
1671 int16_t audio10ms[],
1672 int length,
1673 int sampling_freq,
1674 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001675 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001676 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1677 if (type == webrtc::kPlaybackAllChannelsMixed) {
1678 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1679 } else if (type == webrtc::kRecordingPerChannel) {
1680 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1681 } else {
1682 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1683 << " channel: " << channel << " type: " << type
1684 << " tx_ssrc: " << tx_processor_ssrc_
1685 << " rx_ssrc: " << rx_processor_ssrc_;
1686 }
1687}
1688
1689void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1690 if (!is_dumping_aec_) {
1691 // Start dumping AEC when we are not dumping.
1692 if (voe_wrapper_->processing()->StartDebugRecording(
1693 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001694 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001695 } else {
1696 is_dumping_aec_ = true;
1697 }
1698 }
1699}
1700
1701void WebRtcVoiceEngine::StopAecDump() {
1702 if (is_dumping_aec_) {
1703 // Stop dumping AEC when we are dumping.
1704 if (voe_wrapper_->processing()->StopDebugRecording() !=
1705 webrtc::AudioProcessing::kNoError) {
1706 LOG_RTCERR0(StopDebugRecording);
1707 }
1708 is_dumping_aec_ = false;
1709 }
1710}
1711
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001712int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001713 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001714}
1715
1716int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1717 return CreateVoiceChannel(voe_wrapper_.get());
1718}
1719
1720int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1721 return CreateVoiceChannel(voe_wrapper_sc_.get());
1722}
1723
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001724class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1725 : public AudioRenderer::Sink {
1726 public:
1727 WebRtcVoiceChannelRenderer(int ch,
1728 webrtc::AudioTransport* voe_audio_transport)
1729 : channel_(ch),
1730 voe_audio_transport_(voe_audio_transport),
1731 renderer_(NULL) {
1732 }
1733 virtual ~WebRtcVoiceChannelRenderer() {
1734 Stop();
1735 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001736
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001737 // Starts the rendering by setting a sink to the renderer to get data
1738 // callback.
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 // TODO(xians): Make sure Start() is called only once.
1741 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001742 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001743 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001744 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001745 ASSERT(renderer_ == renderer);
1746 return;
1747 }
1748
1749 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1750 // in getUserMedia by default.
1751 renderer->AddChannel(channel_);
1752 renderer->SetSink(this);
1753 renderer_ = renderer;
1754 }
1755
1756 // Stops rendering by setting the sink of the renderer to NULL. No data
1757 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001758 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001759 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001760 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001761 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001762 return;
1763
1764 renderer_->RemoveChannel(channel_);
1765 renderer_->SetSink(NULL);
1766 renderer_ = NULL;
1767 }
1768
1769 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001770 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001771 virtual void OnData(const void* audio_data,
1772 int bits_per_sample,
1773 int sample_rate,
1774 int number_of_channels,
1775 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001776 voe_audio_transport_->OnData(channel_,
1777 audio_data,
1778 bits_per_sample,
1779 sample_rate,
1780 number_of_channels,
1781 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001782 }
1783
1784 // Callback from the |renderer_| when it is going away. In case Start() has
1785 // never been called, this callback won't be triggered.
1786 virtual void OnClose() OVERRIDE {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001787 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001788 // Set |renderer_| to NULL to make sure no more callback will get into
1789 // the renderer.
1790 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001791 }
1792
1793 // Accessor to the VoE channel ID.
1794 int channel() const { return channel_; }
1795
1796 private:
1797 const int channel_;
1798 webrtc::AudioTransport* const voe_audio_transport_;
1799
1800 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1801 // PeerConnection will make sure invalidating the pointer before the object
1802 // goes away.
1803 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001804
1805 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001806 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001807};
1808
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001809// WebRtcVoiceMediaChannel
1810WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1811 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1812 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001813 engine->CreateMediaVoiceChannel()),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001814 send_bw_setting_(false),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001815 send_bw_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001816 options_(),
1817 dtmf_allowed_(false),
1818 desired_playout_(false),
1819 nack_enabled_(false),
1820 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001821 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001822 desired_send_(SEND_NOTHING),
1823 send_(SEND_NOTHING),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001824 shared_bwe_vie_(NULL),
1825 shared_bwe_vie_channel_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001826 default_receive_ssrc_(0) {
1827 engine->RegisterChannel(this);
1828 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1829 << voe_channel();
1830
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001831 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001832}
1833
1834WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1835 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1836 << voe_channel();
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001837 ASSERT(shared_bwe_vie_ == NULL);
1838 ASSERT(shared_bwe_vie_channel_ == -1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001839
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001840 // Remove any remaining send streams, the default channel will be deleted
1841 // later.
1842 while (!send_channels_.empty())
1843 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001844
1845 // Unregister ourselves from the engine.
1846 engine()->UnregisterChannel(this);
1847 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001848 while (!receive_channels_.empty()) {
1849 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001850 }
1851
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001852 // Delete the default channel.
1853 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001854}
1855
1856bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1857 LOG(LS_INFO) << "Setting voice channel options: "
1858 << options.ToString();
1859
wu@webrtc.orgde305012013-10-31 15:40:38 +00001860 // Check if DSCP value is changed from previous.
1861 bool dscp_option_changed = (options_.dscp != options.dscp);
1862
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001863 // TODO(xians): Add support to set different options for different send
1864 // streams after we support multiple APMs.
1865
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001866 // We retain all of the existing options, and apply the given ones
1867 // on top. This means there is no way to "clear" options such that
1868 // they go back to the engine default.
1869 options_.SetAll(options);
1870
1871 if (send_ != SEND_NOTHING) {
1872 if (!engine()->SetOptionOverrides(options_)) {
1873 LOG(LS_WARNING) <<
1874 "Failed to engine SetOptionOverrides during channel SetOptions.";
1875 return false;
1876 }
1877 } else {
1878 // Will be interpreted when appropriate.
1879 }
1880
wu@webrtc.org97077a32013-10-25 21:18:33 +00001881 // Receiver-side auto gain control happens per channel, so set it here from
1882 // options. Note that, like conference mode, setting it on the engine won't
1883 // have the desired effect, since voice channels don't inherit options from
1884 // the media engine when those options are applied per-channel.
1885 bool rx_auto_gain_control;
1886 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1887 if (engine()->voe()->processing()->SetRxAgcStatus(
1888 voe_channel(), rx_auto_gain_control,
1889 webrtc::kAgcFixedDigital) == -1) {
1890 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1891 return false;
1892 } else {
1893 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1894 << " with mode " << webrtc::kAgcFixedDigital;
1895 }
1896 }
1897 if (options.rx_agc_target_dbov.IsSet() ||
1898 options.rx_agc_digital_compression_gain.IsSet() ||
1899 options.rx_agc_limiter.IsSet()) {
1900 webrtc::AgcConfig config;
1901 // If only some of the options are being overridden, get the current
1902 // settings for the channel and bail if they aren't available.
1903 if (!options.rx_agc_target_dbov.IsSet() ||
1904 !options.rx_agc_digital_compression_gain.IsSet() ||
1905 !options.rx_agc_limiter.IsSet()) {
1906 if (engine()->voe()->processing()->GetRxAgcConfig(
1907 voe_channel(), config) != 0) {
1908 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1909 << "channel " << voe_channel() << ". Since not all rx "
1910 << "agc options are specified, unable to safely set rx "
1911 << "agc options.";
1912 return false;
1913 }
1914 }
1915 config.targetLeveldBOv =
1916 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1917 config.targetLeveldBOv);
1918 config.digitalCompressionGaindB =
1919 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1920 config.digitalCompressionGaindB);
1921 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1922 config.limiterEnable);
1923 if (engine()->voe()->processing()->SetRxAgcConfig(
1924 voe_channel(), config) == -1) {
1925 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1926 config.digitalCompressionGaindB, config.limiterEnable);
1927 return false;
1928 }
1929 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001930 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001931 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001932 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001933 dscp = kAudioDscpValue;
1934 if (MediaChannel::SetDscp(dscp) != 0) {
1935 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1936 }
1937 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001938
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001939 // Force update of Video Engine BWE forwarding to reflect experiment setting.
1940 if (!SetupSharedBandwidthEstimation(shared_bwe_vie_,
1941 shared_bwe_vie_channel_)) {
1942 return false;
1943 }
1944
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001945 LOG(LS_INFO) << "Set voice channel options. Current options: "
1946 << options_.ToString();
1947 return true;
1948}
1949
1950bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1951 const std::vector<AudioCodec>& codecs) {
1952 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001953 LOG(LS_INFO) << "Setting receive voice codecs:";
1954
1955 std::vector<AudioCodec> new_codecs;
1956 // Find all new codecs. We allow adding new codecs but don't allow changing
1957 // the payload type of codecs that is already configured since we might
1958 // already be receiving packets with that payload type.
1959 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001960 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001961 AudioCodec old_codec;
1962 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1963 if (old_codec.id != it->id) {
1964 LOG(LS_ERROR) << it->name << " payload type changed.";
1965 return false;
1966 }
1967 } else {
1968 new_codecs.push_back(*it);
1969 }
1970 }
1971 if (new_codecs.empty()) {
1972 // There are no new codecs to configure. Already configured codecs are
1973 // never removed.
1974 return true;
1975 }
1976
1977 if (playout_) {
1978 // Receive codecs can not be changed while playing. So we temporarily
1979 // pause playout.
1980 PausePlayout();
1981 }
1982
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001983 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001984 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1985 it != new_codecs.end() && ret; ++it) {
1986 webrtc::CodecInst voe_codec;
1987 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1988 LOG(LS_INFO) << ToString(*it);
1989 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001990 if (default_receive_ssrc_ == 0) {
1991 // Set the receive codecs on the default channel explicitly if the
1992 // default channel is not used by |receive_channels_|, this happens in
1993 // conference mode or in non-conference mode when there is no playout
1994 // channel.
1995 // TODO(xians): Figure out how we use the default channel in conference
1996 // mode.
1997 if (engine()->voe()->codec()->SetRecPayloadType(
1998 voe_channel(), voe_codec) == -1) {
1999 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
2000 ret = false;
2001 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002002 }
2003
2004 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002005 for (ChannelMap::iterator it = receive_channels_.begin();
2006 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002007 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002008 it->second->channel(), voe_codec) == -1) {
2009 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002010 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002011 ret = false;
2012 }
2013 }
2014 } else {
2015 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2016 ret = false;
2017 }
2018 }
2019 if (ret) {
2020 recv_codecs_ = codecs;
2021 }
2022
2023 if (desired_playout_ && !playout_) {
2024 ResumePlayout();
2025 }
2026 return ret;
2027}
2028
2029bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002030 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002031 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002032 engine()->voe()->codec()->SetVADStatus(channel, false);
2033 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002034#ifdef USE_WEBRTC_DEV_BRANCH
2035 engine()->voe()->rtp()->SetREDStatus(channel, false);
2036 engine()->voe()->codec()->SetFECStatus(channel, false);
2037#else
2038 // TODO(minyue): Remove code under #else case after new WebRTC roll.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002039 engine()->voe()->rtp()->SetFECStatus(channel, false);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002040#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002041
2042 // Scan through the list to figure out the codec to use for sending, along
2043 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002044 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002045 webrtc::CodecInst send_codec;
2046 memset(&send_codec, 0, sizeof(send_codec));
2047
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002048 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002049 bool enable_codec_fec = false;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002050
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002051 // max_playback_rate <= 0 will not trigger setting of maximum encoding
2052 // bandwidth.
2053 int max_playback_rate = 0;
2054
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002055 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002056 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2057 it != codecs.end(); ++it) {
2058 // Ignore codecs we don't know about. The negotiation step should prevent
2059 // this, but double-check to be sure.
2060 webrtc::CodecInst voe_codec;
2061 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002062 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002063 continue;
2064 }
2065
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002066 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2067 // Skip telephone-event/CN codec, which will be handled later.
2068 continue;
2069 }
2070
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002071
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002072 // We'll use the first codec in the list to actually send audio data.
2073 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002074 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002075 // used is specified in params.
2076 if (IsRedCodec(it->name)) {
2077 // Parse out the RED parameters. If we fail, just ignore RED;
2078 // we don't support all possible params/usage scenarios.
2079 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2080 continue;
2081 }
2082
2083 // Enable redundant encoding of the specified codec. Treat any
2084 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002085#ifdef USE_WEBRTC_DEV_BRANCH
2086 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2087 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2088 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
2089#else
2090 // TODO(minyue): Remove code under #else case after new WebRTC roll.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002091 LOG(LS_INFO) << "Enabling FEC";
2092 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2093 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002094#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002095 return false;
2096 }
2097 } else {
2098 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002099 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002100 // For Opus as the send codec, we are to enable inband FEC if requested
2101 // and set maximum playback rate.
2102 if (IsOpus(*it)) {
2103 GetOpusConfig(*it, &send_codec, &enable_codec_fec, &max_playback_rate);
2104 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002105 }
2106 found_send_codec = true;
2107 break;
2108 }
2109
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002110 if (nack_enabled_ != nack_enabled) {
2111 SetNack(channel, nack_enabled);
2112 nack_enabled_ = nack_enabled;
2113 }
2114
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002115 if (!found_send_codec) {
2116 LOG(LS_WARNING) << "Received empty list of codecs.";
2117 return false;
2118 }
2119
2120 // Set the codec immediately, since SetVADStatus() depends on whether
2121 // the current codec is mono or stereo.
2122 if (!SetSendCodec(channel, send_codec))
2123 return false;
2124
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002125 // FEC should be enabled after SetSendCodec.
2126 if (enable_codec_fec) {
2127 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2128 << channel;
2129#ifdef USE_WEBRTC_DEV_BRANCH
2130 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2131 // Enable codec internal FEC. Treat any failure as fatal internal error.
2132 LOG_RTCERR2(SetFECStatus, channel, true);
2133 return false;
2134 }
2135#endif // USE_WEBRTC_DEV_BRANCH
2136 }
2137
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002138 // maxplaybackrate should be set after SetSendCodec.
2139 if (max_playback_rate > 0) {
2140 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
2141 << max_playback_rate
2142 << " Hz on channel "
2143 << channel;
2144#ifdef USE_WEBRTC_DEV_BRANCH
2145 // (max_playback_rate + 1) >> 1 is to obtain ceil(max_playback_rate / 2.0).
2146 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
2147 channel, max_playback_rate) == -1) {
2148 LOG(LS_WARNING) << "Could not set maximum playback rate.";
2149 }
2150#endif
2151 }
2152
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002153 // Always update the |send_codec_| to the currently set send codec.
2154 send_codec_.reset(new webrtc::CodecInst(send_codec));
2155
2156 if (send_bw_setting_) {
2157 SetSendBandwidthInternal(send_bw_bps_);
2158 }
2159
2160 // Loop through the codecs list again to config the telephone-event/CN codec.
2161 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2162 it != codecs.end(); ++it) {
2163 // Ignore codecs we don't know about. The negotiation step should prevent
2164 // this, but double-check to be sure.
2165 webrtc::CodecInst voe_codec;
2166 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2167 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2168 continue;
2169 }
2170
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002171 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2172 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002173 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002174 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2175 channel, it->id) == -1) {
2176 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2177 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002178 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002179 } else if (IsCNCodec(it->name)) {
2180 // Turn voice activity detection/comfort noise on if supported.
2181 // Set the wideband CN payload type appropriately.
2182 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002183 webrtc::PayloadFrequencies cn_freq;
2184 switch (it->clockrate) {
2185 case 8000:
2186 cn_freq = webrtc::kFreq8000Hz;
2187 break;
2188 case 16000:
2189 cn_freq = webrtc::kFreq16000Hz;
2190 break;
2191 case 32000:
2192 cn_freq = webrtc::kFreq32000Hz;
2193 break;
2194 default:
2195 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2196 << " not supported.";
2197 continue;
2198 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002199 // Set the CN payloadtype and the VAD status.
2200 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2201 if (cn_freq != webrtc::kFreq8000Hz) {
2202 if (engine()->voe()->codec()->SetSendCNPayloadType(
2203 channel, it->id, cn_freq) == -1) {
2204 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2205 // TODO(ajm): This failure condition will be removed from VoE.
2206 // Restore the return here when we update to a new enough webrtc.
2207 //
2208 // Not returning false because the SetSendCNPayloadType will fail if
2209 // the channel is already sending.
2210 // This can happen if the remote description is applied twice, for
2211 // example in the case of ROAP on top of JSEP, where both side will
2212 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002213 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002214 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002215 // Only turn on VAD if we have a CN payload type that matches the
2216 // clockrate for the codec we are going to use.
2217 if (it->clockrate == send_codec.plfreq) {
2218 LOG(LS_INFO) << "Enabling VAD";
2219 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2220 LOG_RTCERR2(SetVADStatus, channel, true);
2221 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002222 }
2223 }
2224 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002225 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002226 return true;
2227}
2228
2229bool WebRtcVoiceMediaChannel::SetSendCodecs(
2230 const std::vector<AudioCodec>& codecs) {
2231 dtmf_allowed_ = false;
2232 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2233 it != codecs.end(); ++it) {
2234 // Find the DTMF telephone event "codec".
2235 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2236 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2237 dtmf_allowed_ = true;
2238 }
2239 }
2240
2241 // Cache the codecs in order to configure the channel created later.
2242 send_codecs_ = codecs;
2243 for (ChannelMap::iterator iter = send_channels_.begin();
2244 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002245 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002246 return false;
2247 }
2248 }
2249
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002250 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002251 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002252 return true;
2253}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002254
2255void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2256 bool nack_enabled) {
2257 for (ChannelMap::const_iterator it = channels.begin();
2258 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002259 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002260 }
2261}
2262
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002263void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002264 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002265 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002266 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2267 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002268 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002269 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2270 }
2271}
2272
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002273bool WebRtcVoiceMediaChannel::SetSendCodec(
2274 const webrtc::CodecInst& send_codec) {
2275 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2276 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002277 for (ChannelMap::iterator iter = send_channels_.begin();
2278 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002279 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002280 return false;
2281 }
2282
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002283 return true;
2284}
2285
2286bool WebRtcVoiceMediaChannel::SetSendCodec(
2287 int channel, const webrtc::CodecInst& send_codec) {
2288 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2289 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2290
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002291 webrtc::CodecInst current_codec;
2292 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2293 (send_codec == current_codec)) {
2294 // Codec is already configured, we can return without setting it again.
2295 return true;
2296 }
2297
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002298 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2299 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002300 return false;
2301 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002302 return true;
2303}
2304
2305bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2306 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002307 if (receive_extensions_ == extensions) {
2308 return true;
2309 }
2310
2311 // The default channel may or may not be in |receive_channels_|. Set the rtp
2312 // header extensions for default channel regardless.
2313 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2314 return false;
2315 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002316
2317 // Loop through all receive channels and enable/disable the extensions.
2318 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2319 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002320 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2321 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002322 return false;
2323 }
2324 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002325
2326 receive_extensions_ = extensions;
2327 return true;
2328}
2329
2330bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2331 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002332 const RtpHeaderExtension* audio_level_extension =
2333 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2334 if (!SetHeaderExtension(
2335 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2336 audio_level_extension)) {
2337 return false;
2338 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002339
2340 const RtpHeaderExtension* send_time_extension =
2341 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2342 if (!SetHeaderExtension(
2343 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2344 send_time_extension)) {
2345 return false;
2346 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002347 return true;
2348}
2349
2350bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2351 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002352 if (send_extensions_ == extensions) {
2353 return true;
2354 }
2355
2356 // The default channel may or may not be in |send_channels_|. Set the rtp
2357 // header extensions for default channel regardless.
2358
2359 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2360 return false;
2361 }
2362
2363 // Loop through all send channels and enable/disable the extensions.
2364 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2365 channel_it != send_channels_.end(); ++channel_it) {
2366 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2367 extensions)) {
2368 return false;
2369 }
2370 }
2371
2372 send_extensions_ = extensions;
2373 return true;
2374}
2375
2376bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2377 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002378 const RtpHeaderExtension* audio_level_extension =
2379 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002380
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002381 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002382 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002383 audio_level_extension)) {
2384 return false;
2385 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002386
2387 const RtpHeaderExtension* send_time_extension =
2388 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002389 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002390 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002391 send_time_extension)) {
2392 return false;
2393 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002394
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002395 return true;
2396}
2397
2398bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2399 desired_playout_ = playout;
2400 return ChangePlayout(desired_playout_);
2401}
2402
2403bool WebRtcVoiceMediaChannel::PausePlayout() {
2404 return ChangePlayout(false);
2405}
2406
2407bool WebRtcVoiceMediaChannel::ResumePlayout() {
2408 return ChangePlayout(desired_playout_);
2409}
2410
2411bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2412 if (playout_ == playout) {
2413 return true;
2414 }
2415
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002416 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002417 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002418 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002419 // Only toggle the default channel if we don't have any other channels.
2420 result = SetPlayout(voe_channel(), playout);
2421 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002422 for (ChannelMap::iterator it = receive_channels_.begin();
2423 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002424 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002425 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002426 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002427 result = false;
2428 }
2429 }
2430
2431 if (result) {
2432 playout_ = playout;
2433 }
2434 return result;
2435}
2436
2437bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2438 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002439 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002440 return ChangeSend(desired_send_);
2441 return true;
2442}
2443
2444bool WebRtcVoiceMediaChannel::PauseSend() {
2445 return ChangeSend(SEND_NOTHING);
2446}
2447
2448bool WebRtcVoiceMediaChannel::ResumeSend() {
2449 return ChangeSend(desired_send_);
2450}
2451
2452bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2453 if (send_ == send) {
2454 return true;
2455 }
2456
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002457 // Change the settings on each send channel.
2458 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002459 engine()->SetOptionOverrides(options_);
2460
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002461 // Change the settings on each send channel.
2462 for (ChannelMap::iterator iter = send_channels_.begin();
2463 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002464 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002465 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002466 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002467
2468 // Clear up the options after stopping sending.
2469 if (send == SEND_NOTHING)
2470 engine()->ClearOptionOverrides();
2471
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002472 send_ = send;
2473 return true;
2474}
2475
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002476bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2477 if (send == SEND_MICROPHONE) {
2478 if (engine()->voe()->base()->StartSend(channel) == -1) {
2479 LOG_RTCERR1(StartSend, channel);
2480 return false;
2481 }
2482 if (engine()->voe()->file() &&
2483 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2484 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2485 return false;
2486 }
2487 } else { // SEND_NOTHING
2488 ASSERT(send == SEND_NOTHING);
2489 if (engine()->voe()->base()->StopSend(channel) == -1) {
2490 LOG_RTCERR1(StopSend, channel);
2491 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002492 }
2493 }
2494
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002495 return true;
2496}
2497
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002498// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002499void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2500 if (engine()->voe()->network()->RegisterExternalTransport(
2501 channel, *this) == -1) {
2502 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2503 }
2504
2505 // Enable RTCP (for quality stats and feedback messages)
2506 EnableRtcp(channel);
2507
2508 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2509 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002510
2511 // Set RTP header extension for the new channel.
2512 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002513}
2514
2515bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2516 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2517 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2518 }
2519
2520 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2521 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002522 return false;
2523 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002524
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002525 return true;
2526}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002527
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002528bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2529 // If the default channel is already used for sending create a new channel
2530 // otherwise use the default channel for sending.
2531 int channel = GetSendChannelNum(sp.first_ssrc());
2532 if (channel != -1) {
2533 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2534 return false;
2535 }
2536
2537 bool default_channel_is_available = true;
2538 for (ChannelMap::const_iterator iter = send_channels_.begin();
2539 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002540 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002541 default_channel_is_available = false;
2542 break;
2543 }
2544 }
2545 if (default_channel_is_available) {
2546 channel = voe_channel();
2547 } else {
2548 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002549 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002550 if (channel == -1) {
2551 LOG_RTCERR0(CreateChannel);
2552 return false;
2553 }
2554
2555 ConfigureSendChannel(channel);
2556 }
2557
2558 // Save the channel to send_channels_, so that RemoveSendStream() can still
2559 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002560 webrtc::AudioTransport* audio_transport =
2561 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002562 send_channels_.insert(std::make_pair(
2563 sp.first_ssrc(),
2564 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002565
2566 // Set the send (local) SSRC.
2567 // If there are multiple send SSRCs, we can only set the first one here, and
2568 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2569 // (with a codec requires multiple SSRC(s)).
2570 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2571 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2572 return false;
2573 }
2574
2575 // At this point the channel's local SSRC has been updated. If the channel is
2576 // the default channel make sure that all the receive channels are updated as
2577 // well. Receive channels have to have the same SSRC as the default channel in
2578 // order to send receiver reports with this SSRC.
2579 if (IsDefaultChannel(channel)) {
2580 for (ChannelMap::const_iterator it = receive_channels_.begin();
2581 it != receive_channels_.end(); ++it) {
2582 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002583 if (!IsDefaultChannel(it->second->channel())) {
2584 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002585 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002586 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002587 return false;
2588 }
2589 }
2590 }
2591 }
2592
2593 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002594 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2595 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002596 }
2597
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002598 // Set the current codecs to be used for the new channel.
2599 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002600 return false;
2601
2602 return ChangeSend(channel, desired_send_);
2603}
2604
2605bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2606 ChannelMap::iterator it = send_channels_.find(ssrc);
2607 if (it == send_channels_.end()) {
2608 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2609 << " which doesn't exist.";
2610 return false;
2611 }
2612
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002613 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002614 ChangeSend(channel, SEND_NOTHING);
2615
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002616 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2617 // this will disconnect the audio renderer with the send channel.
2618 delete it->second;
2619 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002620
2621 if (IsDefaultChannel(channel)) {
2622 // Do not delete the default channel since the receive channels depend on
2623 // the default channel, recycle it instead.
2624 ChangeSend(channel, SEND_NOTHING);
2625 } else {
2626 // Clean up and delete the send channel.
2627 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2628 << " with VoiceEngine channel #" << channel << ".";
2629 if (!DeleteChannel(channel))
2630 return false;
2631 }
2632
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002633 if (send_channels_.empty())
2634 ChangeSend(SEND_NOTHING);
2635
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002636 return true;
2637}
2638
2639bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002640 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002641
2642 if (!VERIFY(sp.ssrcs.size() == 1))
2643 return false;
2644 uint32 ssrc = sp.first_ssrc();
2645
wu@webrtc.org78187522013-10-07 23:32:02 +00002646 if (ssrc == 0) {
2647 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2648 return false;
2649 }
2650
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002651 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2652 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002653 return false;
2654 }
2655
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002656 // Reuse default channel for recv stream in non-conference mode call
2657 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002658 webrtc::AudioTransport* audio_transport =
2659 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002660 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2661 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2662 << " reuse default channel";
2663 default_receive_ssrc_ = sp.first_ssrc();
2664 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002665 default_receive_ssrc_,
2666 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002667 if (!SetupSharedBweOnChannel(voe_channel())) {
2668 return false;
2669 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002670 return SetPlayout(voe_channel(), playout_);
2671 }
2672
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002673 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002674 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002675 if (channel == -1) {
2676 LOG_RTCERR0(CreateChannel);
2677 return false;
2678 }
2679
wu@webrtc.org78187522013-10-07 23:32:02 +00002680 if (!ConfigureRecvChannel(channel)) {
2681 DeleteChannel(channel);
2682 return false;
2683 }
2684
2685 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002686 std::make_pair(
2687 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002688
2689 LOG(LS_INFO) << "New audio stream " << ssrc
2690 << " registered to VoiceEngine channel #"
2691 << channel << ".";
2692 return true;
2693}
2694
2695bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002696 // Configure to use external transport, like our default channel.
2697 if (engine()->voe()->network()->RegisterExternalTransport(
2698 channel, *this) == -1) {
2699 LOG_RTCERR2(SetExternalTransport, channel, this);
2700 return false;
2701 }
2702
2703 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002704 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002705 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2706 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002707 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002708 return false;
2709 }
2710 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002711 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002712 return false;
2713 }
2714
2715 // Use the same recv payload types as our default channel.
2716 ResetRecvCodecs(channel);
2717 if (!recv_codecs_.empty()) {
2718 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2719 it != recv_codecs_.end(); ++it) {
2720 webrtc::CodecInst voe_codec;
2721 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2722 voe_codec.pltype = it->id;
2723 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2724 if (engine()->voe()->codec()->GetRecPayloadType(
2725 voe_channel(), voe_codec) != -1) {
2726 if (engine()->voe()->codec()->SetRecPayloadType(
2727 channel, voe_codec) == -1) {
2728 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2729 return false;
2730 }
2731 }
2732 }
2733 }
2734 }
2735
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002736 if (InConferenceMode()) {
2737 // To be in par with the video, voe_channel() is not used for receiving in
2738 // a conference call.
2739 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2740 // This is the first stream in a multi user meeting. We can now
2741 // disable playback of the default stream. This since the default
2742 // stream will probably have received some initial packets before
2743 // the new stream was added. This will mean that the CN state from
2744 // the default channel will be mixed in with the other streams
2745 // throughout the whole meeting, which might be disturbing.
2746 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2747 SetPlayout(voe_channel(), false);
2748 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002749 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002750 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002751
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002752 // Set RTP header extension for the new channel.
2753 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2754 return false;
2755 }
2756
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002757 // Set up channel to be able to forward incoming packets to video engine BWE.
2758 if (!SetupSharedBweOnChannel(channel)) {
2759 return false;
2760 }
2761
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002762 return SetPlayout(channel, playout_);
2763}
2764
2765bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002766 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002767 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002768 if (it == receive_channels_.end()) {
2769 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2770 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002771 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002772 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002773
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002774 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2775 // will disconnect the audio renderer with the receive channel.
2776 // Cache the channel before the deletion.
2777 const int channel = it->second->channel();
2778 delete it->second;
2779 receive_channels_.erase(it);
2780
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002781 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002782 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002783 // Recycle the default channel is for recv stream.
2784 if (playout_)
2785 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002786
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002787 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002788 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002789 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002790
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002791 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002792 << " with VoiceEngine channel #" << channel << ".";
2793 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002794 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002795
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002796 bool enable_default_channel_playout = false;
2797 if (receive_channels_.empty()) {
2798 // The last stream was removed. We can now enable the default
2799 // channel for new channels to be played out immediately without
2800 // waiting for AddStream messages.
2801 // We do this for both conference mode and non-conference mode.
2802 // TODO(oja): Does the default channel still have it's CN state?
2803 enable_default_channel_playout = true;
2804 }
2805 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2806 default_receive_ssrc_ != 0) {
2807 // Only the default channel is active, enable the playout on default
2808 // channel.
2809 enable_default_channel_playout = true;
2810 }
2811 if (enable_default_channel_playout && playout_) {
2812 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2813 SetPlayout(voe_channel(), true);
2814 }
2815
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002816 return true;
2817}
2818
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002819bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2820 AudioRenderer* renderer) {
2821 ChannelMap::iterator it = receive_channels_.find(ssrc);
2822 if (it == receive_channels_.end()) {
2823 if (renderer) {
2824 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002825 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002826 return false;
2827 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002828
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002829 // The channel likely has gone away, do nothing.
2830 return true;
2831 }
2832
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002833 if (renderer)
2834 it->second->Start(renderer);
2835 else
2836 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002837
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002838 return true;
2839}
2840
2841bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2842 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002843 ChannelMap::iterator it = send_channels_.find(ssrc);
2844 if (it == send_channels_.end()) {
2845 if (renderer) {
2846 // Return an error if trying to set a valid renderer with an invalid ssrc.
2847 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2848 return false;
2849 }
2850
2851 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002852 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002853 }
2854
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002855 if (renderer)
2856 it->second->Start(renderer);
2857 else
2858 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002859
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002860 return true;
2861}
2862
2863bool WebRtcVoiceMediaChannel::GetActiveStreams(
2864 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002865 // In conference mode, the default channel should not be in
2866 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002867 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002868 for (ChannelMap::iterator it = receive_channels_.begin();
2869 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002870 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002871 if (level > 0) {
2872 actives->push_back(std::make_pair(it->first, level));
2873 }
2874 }
2875 return true;
2876}
2877
2878int WebRtcVoiceMediaChannel::GetOutputLevel() {
2879 // return the highest output level of all streams
2880 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002881 for (ChannelMap::iterator it = receive_channels_.begin();
2882 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002883 int level = GetOutputLevel(it->second->channel());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002884 highest = rtc::_max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002885 }
2886 return highest;
2887}
2888
2889int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2890 int ret;
2891 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2892 // In case of error, log the info and continue
2893 LOG_RTCERR0(TimeSinceLastTyping);
2894 ret = -1;
2895 } else {
2896 ret *= 1000; // We return ms, webrtc returns seconds.
2897 }
2898 return ret;
2899}
2900
2901void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2902 int cost_per_typing, int reporting_threshold, int penalty_decay,
2903 int type_event_delay) {
2904 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2905 time_window, cost_per_typing,
2906 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2907 // In case of error, log the info and continue
2908 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2909 cost_per_typing, reporting_threshold, penalty_decay,
2910 type_event_delay);
2911 }
2912}
2913
2914bool WebRtcVoiceMediaChannel::SetOutputScaling(
2915 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002916 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002917 // Collect the channels to scale the output volume.
2918 std::vector<int> channels;
2919 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002920 // Default channel is not in receive_channels_ if it is not being used for
2921 // playout.
2922 if (default_receive_ssrc_ == 0)
2923 channels.push_back(voe_channel());
2924 for (ChannelMap::const_iterator it = receive_channels_.begin();
2925 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002926 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002927 }
2928 } else { // Collect only the channel of the specified ssrc.
2929 int channel = GetReceiveChannelNum(ssrc);
2930 if (-1 == channel) {
2931 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2932 return false;
2933 }
2934 channels.push_back(channel);
2935 }
2936
2937 // Scale the output volume for the collected channels. We first normalize to
2938 // scale the volume and then set the left and right pan.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002939 float scale = static_cast<float>(rtc::_max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002940 if (scale > 0.0001f) {
2941 left /= scale;
2942 right /= scale;
2943 }
2944 for (std::vector<int>::const_iterator it = channels.begin();
2945 it != channels.end(); ++it) {
2946 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2947 *it, scale)) {
2948 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2949 return false;
2950 }
2951 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2952 *it, static_cast<float>(left), static_cast<float>(right))) {
2953 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2954 // Do not return if fails. SetOutputVolumePan is not available for all
2955 // pltforms.
2956 }
2957 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2958 << " right=" << right * scale
2959 << " for channel " << *it << " and ssrc " << ssrc;
2960 }
2961 return true;
2962}
2963
2964bool WebRtcVoiceMediaChannel::GetOutputScaling(
2965 uint32 ssrc, double* left, double* right) {
2966 if (!left || !right) return false;
2967
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002968 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002969 // Determine which channel based on ssrc.
2970 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2971 if (channel == -1) {
2972 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2973 return false;
2974 }
2975
2976 float scaling;
2977 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2978 channel, scaling)) {
2979 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2980 return false;
2981 }
2982
2983 float left_pan;
2984 float right_pan;
2985 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2986 channel, left_pan, right_pan)) {
2987 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2988 // If GetOutputVolumePan fails, we use the default left and right pan.
2989 left_pan = 1.0f;
2990 right_pan = 1.0f;
2991 }
2992
2993 *left = scaling * left_pan;
2994 *right = scaling * right_pan;
2995 return true;
2996}
2997
2998bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2999 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
3000 return true;
3001}
3002
3003bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
3004 bool play, bool loop) {
3005 if (!ringback_tone_) {
3006 return false;
3007 }
3008
3009 // The voe file api is not available in chrome.
3010 if (!engine()->voe()->file()) {
3011 return false;
3012 }
3013
3014 // Determine which VoiceEngine channel to play on.
3015 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
3016 if (channel == -1) {
3017 return false;
3018 }
3019
3020 // Make sure the ringtone is cued properly, and play it out.
3021 if (play) {
3022 ringback_tone_->set_loop(loop);
3023 ringback_tone_->Rewind();
3024 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
3025 ringback_tone_.get()) == -1) {
3026 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
3027 LOG(LS_ERROR) << "Unable to start ringback tone";
3028 return false;
3029 }
3030 ringback_channels_.insert(channel);
3031 LOG(LS_INFO) << "Started ringback on channel " << channel;
3032 } else {
3033 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
3034 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
3035 LOG_RTCERR1(StopPlayingFileLocally, channel);
3036 return false;
3037 }
3038 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
3039 ringback_channels_.erase(channel);
3040 }
3041
3042 return true;
3043}
3044
3045bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3046 return dtmf_allowed_;
3047}
3048
3049bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3050 int duration, int flags) {
3051 if (!dtmf_allowed_) {
3052 return false;
3053 }
3054
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003055 // Send the event.
3056 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003057 int channel = -1;
3058 if (ssrc == 0) {
3059 bool default_channel_is_inuse = false;
3060 for (ChannelMap::const_iterator iter = send_channels_.begin();
3061 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003062 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003063 default_channel_is_inuse = true;
3064 break;
3065 }
3066 }
3067 if (default_channel_is_inuse) {
3068 channel = voe_channel();
3069 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003070 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003071 }
3072 } else {
3073 channel = GetSendChannelNum(ssrc);
3074 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003075 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003076 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3077 << ssrc << " is not in use.";
3078 return false;
3079 }
3080 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003081 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3082 channel, event, true, duration) == -1) {
3083 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003084 return false;
3085 }
3086 }
3087
3088 // Play the event.
3089 if (flags & cricket::DF_PLAY) {
3090 // Play DTMF tone locally.
3091 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3092 LOG_RTCERR2(PlayDtmfTone, event, duration);
3093 return false;
3094 }
3095 }
3096
3097 return true;
3098}
3099
wu@webrtc.orga9890802013-12-13 00:21:03 +00003100void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003101 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003102 // Pick which channel to send this packet to. If this packet doesn't match
3103 // any multiplexed streams, just send it to the default channel. Otherwise,
3104 // send it to the specific decoder instance for that stream.
3105 int which_channel = GetReceiveChannelNum(
3106 ParseSsrc(packet->data(), packet->length(), false));
3107 if (which_channel == -1) {
3108 which_channel = voe_channel();
3109 }
3110
3111 // Stop any ringback that might be playing on the channel.
3112 // It's possible the ringback has already stopped, ih which case we'll just
3113 // use the opportunity to remove the channel from ringback_channels_.
3114 if (engine()->voe()->file()) {
3115 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3116 if (it != ringback_channels_.end()) {
3117 if (engine()->voe()->file()->IsPlayingFileLocally(
3118 which_channel) == 1) {
3119 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3120 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3121 << " due to incoming media";
3122 }
3123 ringback_channels_.erase(which_channel);
3124 }
3125 }
3126
3127 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003128 engine()->voe()->network()->ReceivedRTPPacket(
3129 which_channel,
3130 packet->data(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003131 static_cast<unsigned int>(packet->length()),
3132 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003133}
3134
wu@webrtc.orga9890802013-12-13 00:21:03 +00003135void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003136 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003137 // Sending channels need all RTCP packets with feedback information.
3138 // Even sender reports can contain attached report blocks.
3139 // Receiving channels need sender reports in order to create
3140 // correct receiver reports.
3141 int type = 0;
3142 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3143 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3144 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003145 }
3146
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003147 // If it is a sender report, find the channel that is listening.
3148 bool has_sent_to_default_channel = false;
3149 if (type == kRtcpTypeSR) {
3150 int which_channel = GetReceiveChannelNum(
3151 ParseSsrc(packet->data(), packet->length(), true));
3152 if (which_channel != -1) {
3153 engine()->voe()->network()->ReceivedRTCPPacket(
3154 which_channel,
3155 packet->data(),
3156 static_cast<unsigned int>(packet->length()));
3157
3158 if (IsDefaultChannel(which_channel))
3159 has_sent_to_default_channel = true;
3160 }
3161 }
3162
3163 // SR may continue RR and any RR entry may correspond to any one of the send
3164 // channels. So all RTCP packets must be forwarded all send channels. VoE
3165 // will filter out RR internally.
3166 for (ChannelMap::iterator iter = send_channels_.begin();
3167 iter != send_channels_.end(); ++iter) {
3168 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003169 if (IsDefaultChannel(iter->second->channel()) &&
3170 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003171 continue;
3172
3173 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003174 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003175 packet->data(),
3176 static_cast<unsigned int>(packet->length()));
3177 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003178}
3179
3180bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003181 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3182 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003183 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3184 return false;
3185 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003186 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3187 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003188 return false;
3189 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003190 // We set the AGC to mute state only when all the channels are muted.
3191 // This implementation is not ideal, instead we should signal the AGC when
3192 // the mic channel is muted/unmuted. We can't do it today because there
3193 // is no good way to know which stream is mapping to the mic channel.
3194 bool all_muted = muted;
3195 for (ChannelMap::const_iterator iter = send_channels_.begin();
3196 iter != send_channels_.end() && all_muted; ++iter) {
3197 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3198 all_muted)) {
3199 LOG_RTCERR1(GetInputMute, iter->second->channel());
3200 return false;
3201 }
3202 }
3203
3204 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3205 if (ap)
3206 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003207 return true;
3208}
3209
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003210bool WebRtcVoiceMediaChannel::SetStartSendBandwidth(int bps) {
3211 // TODO(andresp): Add support for setting an independent start bandwidth when
3212 // bandwidth estimation is enabled for voice engine.
3213 return false;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003214}
3215
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003216bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
3217 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
3218
3219 return SetSendBandwidthInternal(bps);
3220}
3221
3222bool WebRtcVoiceMediaChannel::SetSendBandwidthInternal(int bps) {
3223 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBandwidthInternal.";
3224
3225 send_bw_setting_ = true;
3226 send_bw_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003227
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003228 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003229 LOG(LS_INFO) << "The send codec has not been set up yet. "
3230 << "The send bandwidth setting will be applied later.";
3231 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003232 }
3233
3234 // Bandwidth is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003235 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3236 // SetMaxSendBandwith(0), the second call removes the previous limit.
3237 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003238 return true;
3239
3240 webrtc::CodecInst codec = *send_codec_;
3241 bool is_multi_rate = IsCodecMultiRate(codec);
3242
3243 if (is_multi_rate) {
3244 // If codec is multi-rate then just set the bitrate.
3245 codec.rate = bps;
3246 if (!SetSendCodec(codec)) {
3247 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3248 << " to bitrate " << bps << " bps.";
3249 return false;
3250 }
3251 return true;
3252 } else {
3253 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3254 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3255 // fixed bitrate then ignore.
3256 if (bps < codec.rate) {
3257 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3258 << " to bitrate " << bps << " bps"
3259 << ", requires at least " << codec.rate << " bps.";
3260 return false;
3261 }
3262 return true;
3263 }
3264}
3265
3266bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003267 bool echo_metrics_on = false;
3268 // These can take on valid negative values, so use the lowest possible level
3269 // as default rather than -1.
3270 int echo_return_loss = -100;
3271 int echo_return_loss_enhancement = -100;
3272 // These can also be negative, but in practice -1 is only used to signal
3273 // insufficient data, since the resolution is limited to multiples of 4 ms.
3274 int echo_delay_median_ms = -1;
3275 int echo_delay_std_ms = -1;
3276 if (engine()->voe()->processing()->GetEcMetricsStatus(
3277 echo_metrics_on) != -1 && echo_metrics_on) {
3278 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3279 // here, but it appears to be unsuitable currently. Revisit after this is
3280 // investigated: http://b/issue?id=5666755
3281 int erl, erle, rerl, anlp;
3282 if (engine()->voe()->processing()->GetEchoMetrics(
3283 erl, erle, rerl, anlp) != -1) {
3284 echo_return_loss = erl;
3285 echo_return_loss_enhancement = erle;
3286 }
3287
3288 int median, std;
3289 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3290 echo_delay_median_ms = median;
3291 echo_delay_std_ms = std;
3292 }
3293 }
3294
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003295 webrtc::CallStatistics cs;
3296 unsigned int ssrc;
3297 webrtc::CodecInst codec;
3298 unsigned int level;
3299
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003300 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3301 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003302 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003303
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003304 // Fill in the sender info, based on what we know, and what the
3305 // remote side told us it got from its RTCP report.
3306 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003307
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003308 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3309 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3310 continue;
3311 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003312
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003313 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003314 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3315 sinfo.bytes_sent = cs.bytesSent;
3316 sinfo.packets_sent = cs.packetsSent;
3317 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3318 // returns 0 to indicate an error value.
3319 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3320
3321 // Get data from the last remote RTCP report. Use default values if no data
3322 // available.
3323 sinfo.fraction_lost = -1.0;
3324 sinfo.jitter_ms = -1;
3325 sinfo.packets_lost = -1;
3326 sinfo.ext_seqnum = -1;
3327 std::vector<webrtc::ReportBlock> receive_blocks;
3328 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3329 channel, &receive_blocks) != -1 &&
3330 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3331 std::vector<webrtc::ReportBlock>::iterator iter;
3332 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3333 ++iter) {
3334 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003335 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003336 // Convert Q8 to floating point.
3337 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3338 // Convert samples to milliseconds.
3339 if (codec.plfreq / 1000 > 0) {
3340 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3341 }
3342 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3343 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3344 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003345 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003346 }
3347 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003348
3349 // Local speech level.
3350 sinfo.audio_level = (engine()->voe()->volume()->
3351 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3352
3353 // TODO(xians): We are injecting the same APM logging to all the send
3354 // channels here because there is no good way to know which send channel
3355 // is using the APM. The correct fix is to allow the send channels to have
3356 // their own APM so that we can feed the correct APM logging to different
3357 // send channels. See issue crbug/264611 .
3358 sinfo.echo_return_loss = echo_return_loss;
3359 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3360 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3361 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003362 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3363 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003364 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003365
3366 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003367 }
3368
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003369 // Build the list of receivers, one for each receiving channel, or 1 in
3370 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003371 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003372 for (ChannelMap::const_iterator it = receive_channels_.begin();
3373 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003374 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003375 }
3376 if (channels.empty()) {
3377 channels.push_back(voe_channel());
3378 }
3379
3380 // Get the SSRC and stats for each receiver, based on our own calculations.
3381 for (std::vector<int>::const_iterator it = channels.begin();
3382 it != channels.end(); ++it) {
3383 memset(&cs, 0, sizeof(cs));
3384 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3385 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3386 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3387 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003388 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003389 rinfo.bytes_rcvd = cs.bytesReceived;
3390 rinfo.packets_rcvd = cs.packetsReceived;
3391 // The next four fields are from the most recently sent RTCP report.
3392 // Convert Q8 to floating point.
3393 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3394 rinfo.packets_lost = cs.cumulativeLost;
3395 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003396#ifdef USE_WEBRTC_DEV_BRANCH
3397 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
3398#endif
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003399 if (codec.pltype != -1) {
3400 rinfo.codec_name = codec.plname;
3401 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003402 // Convert samples to milliseconds.
3403 if (codec.plfreq / 1000 > 0) {
3404 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3405 }
3406
3407 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3408 webrtc::NetworkStatistics ns;
3409 if (engine()->voe()->neteq() &&
3410 engine()->voe()->neteq()->GetNetworkStatistics(
3411 *it, ns) != -1) {
3412 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3413 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3414 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003415 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003416 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003417
3418 webrtc::AudioDecodingCallStats ds;
3419 if (engine()->voe()->neteq() &&
3420 engine()->voe()->neteq()->GetDecodingCallStatistics(
3421 *it, &ds) != -1) {
3422 rinfo.decoding_calls_to_silence_generator =
3423 ds.calls_to_silence_generator;
3424 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3425 rinfo.decoding_normal = ds.decoded_normal;
3426 rinfo.decoding_plc = ds.decoded_plc;
3427 rinfo.decoding_cng = ds.decoded_cng;
3428 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3429 }
3430
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003431 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003432 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003433 int playout_buffer_delay_ms = 0;
3434 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003435 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3436 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3437 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003438 }
3439
3440 // Get speech level.
3441 rinfo.audio_level = (engine()->voe()->volume()->
3442 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3443 info->receivers.push_back(rinfo);
3444 }
3445 }
3446
3447 return true;
3448}
3449
3450void WebRtcVoiceMediaChannel::GetLastMediaError(
3451 uint32* ssrc, VoiceMediaChannel::Error* error) {
3452 ASSERT(ssrc != NULL);
3453 ASSERT(error != NULL);
3454 FindSsrc(voe_channel(), ssrc);
3455 *error = WebRtcErrorToChannelError(GetLastEngineError());
3456}
3457
3458bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003459 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003460 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003461 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003462 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3463 // This means the error is not limited to a specific channel. Signal the
3464 // message using ssrc=0. If the current channel is sending, use this
3465 // channel for sending the message.
3466 *ssrc = 0;
3467 return true;
3468 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003469 // Check whether this is a sending channel.
3470 for (ChannelMap::const_iterator it = send_channels_.begin();
3471 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003472 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003473 // This is a sending channel.
3474 uint32 local_ssrc = 0;
3475 if (engine()->voe()->rtp()->GetLocalSSRC(
3476 channel_num, local_ssrc) != -1) {
3477 *ssrc = local_ssrc;
3478 }
3479 return true;
3480 }
3481 }
3482
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003483 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003484 for (ChannelMap::const_iterator it = receive_channels_.begin();
3485 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003486 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003487 *ssrc = it->first;
3488 return true;
3489 }
3490 }
3491 }
3492 return false;
3493}
3494
3495void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003496 if (error == VE_TYPING_NOISE_WARNING) {
3497 typing_noise_detected_ = true;
3498 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3499 typing_noise_detected_ = false;
3500 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003501 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3502}
3503
3504int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3505 unsigned int ulevel;
3506 int ret =
3507 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3508 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3509}
3510
3511int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003512 ChannelMap::iterator it = receive_channels_.find(ssrc);
3513 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003514 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003515 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3516}
3517
3518int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003519 ChannelMap::iterator it = send_channels_.find(ssrc);
3520 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003521 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003522
3523 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003524}
3525
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003526bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
3527 webrtc::VideoEngine* vie, int vie_channel) {
3528 shared_bwe_vie_ = vie;
3529 shared_bwe_vie_channel_ = vie_channel;
3530
3531 if (!SetupSharedBweOnChannel(voe_channel())) {
3532 return false;
3533 }
3534 for (ChannelMap::iterator it = receive_channels_.begin();
3535 it != receive_channels_.end(); ++it) {
3536 if (!SetupSharedBweOnChannel(it->second->channel())) {
3537 return false;
3538 }
3539 }
3540 return true;
3541}
3542
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003543bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3544 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3545 // Get the RED encodings from the parameter with no name. This may
3546 // change based on what is discussed on the Jingle list.
3547 // The encoding parameter is of the form "a/b"; we only support where
3548 // a == b. Verify this and parse out the value into red_pt.
3549 // If the parameter value is absent (as it will be until we wire up the
3550 // signaling of this message), use the second codec specified (i.e. the
3551 // one after "red") as the encoding parameter.
3552 int red_pt = -1;
3553 std::string red_params;
3554 CodecParameterMap::const_iterator it = red_codec.params.find("");
3555 if (it != red_codec.params.end()) {
3556 red_params = it->second;
3557 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003558 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003559 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003560 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003561 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3562 return false;
3563 }
3564 } else if (red_codec.params.empty()) {
3565 LOG(LS_WARNING) << "RED params not present, using defaults";
3566 if (all_codecs.size() > 1) {
3567 red_pt = all_codecs[1].id;
3568 }
3569 }
3570
3571 // Try to find red_pt in |codecs|.
3572 std::vector<AudioCodec>::const_iterator codec;
3573 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3574 if (codec->id == red_pt)
3575 break;
3576 }
3577
3578 // If we find the right codec, that will be the codec we pass to
3579 // SetSendCodec, with the desired payload type.
3580 if (codec != all_codecs.end() &&
3581 engine()->FindWebRtcCodec(*codec, send_codec)) {
3582 } else {
3583 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3584 return false;
3585 }
3586
3587 return true;
3588}
3589
3590bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3591 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003592 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003593 return false;
3594 }
3595 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3596 // what we want to do with them.
3597 // engine()->voe().EnableVQMon(voe_channel(), true);
3598 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3599 return true;
3600}
3601
3602bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3603 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3604 for (int i = 0; i < ncodecs; ++i) {
3605 webrtc::CodecInst voe_codec;
3606 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3607 voe_codec.pltype = -1;
3608 if (engine()->voe()->codec()->SetRecPayloadType(
3609 channel, voe_codec) == -1) {
3610 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3611 return false;
3612 }
3613 }
3614 }
3615 return true;
3616}
3617
3618bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3619 if (playout) {
3620 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3621 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3622 LOG_RTCERR1(StartPlayout, channel);
3623 return false;
3624 }
3625 } else {
3626 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3627 engine()->voe()->base()->StopPlayout(channel);
3628 }
3629 return true;
3630}
3631
3632uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3633 bool rtcp) {
3634 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3635 uint32 ssrc = 0;
3636 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003637 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003638 }
3639 return ssrc;
3640}
3641
3642// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3643VoiceMediaChannel::Error
3644 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3645 switch (err_code) {
3646 case 0:
3647 return ERROR_NONE;
3648 case VE_CANNOT_START_RECORDING:
3649 case VE_MIC_VOL_ERROR:
3650 case VE_GET_MIC_VOL_ERROR:
3651 case VE_CANNOT_ACCESS_MIC_VOL:
3652 return ERROR_REC_DEVICE_OPEN_FAILED;
3653 case VE_SATURATION_WARNING:
3654 return ERROR_REC_DEVICE_SATURATION;
3655 case VE_REC_DEVICE_REMOVED:
3656 return ERROR_REC_DEVICE_REMOVED;
3657 case VE_RUNTIME_REC_WARNING:
3658 case VE_RUNTIME_REC_ERROR:
3659 return ERROR_REC_RUNTIME_ERROR;
3660 case VE_CANNOT_START_PLAYOUT:
3661 case VE_SPEAKER_VOL_ERROR:
3662 case VE_GET_SPEAKER_VOL_ERROR:
3663 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3664 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3665 case VE_RUNTIME_PLAY_WARNING:
3666 case VE_RUNTIME_PLAY_ERROR:
3667 return ERROR_PLAY_RUNTIME_ERROR;
3668 case VE_TYPING_NOISE_WARNING:
3669 return ERROR_REC_TYPING_NOISE_DETECTED;
3670 default:
3671 return VoiceMediaChannel::ERROR_OTHER;
3672 }
3673}
3674
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003675bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3676 int channel_id, const RtpHeaderExtension* extension) {
3677 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003678 int id = 0;
3679 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003680 if (extension) {
3681 enable = true;
3682 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003683 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003684 }
3685 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003686 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003687 return false;
3688 }
3689 return true;
3690}
3691
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003692bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
3693 webrtc::ViENetwork* vie_network = NULL;
3694 int vie_channel = -1;
3695 if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
3696 shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
3697 vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
3698 vie_channel = shared_bwe_vie_channel_;
3699 }
3700 if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
3701 vie_channel) == -1) {
3702 LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
3703 if (vie_network != NULL) {
3704 // Don't fail if we're tearing down.
3705 return false;
3706 }
3707 }
3708 return true;
3709}
3710
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003711int WebRtcSoundclipStream::Read(void *buf, int len) {
3712 size_t res = 0;
3713 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003714 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003715}
3716
3717int WebRtcSoundclipStream::Rewind() {
3718 mem_.Rewind();
3719 // Return -1 to keep VoiceEngine from looping.
3720 return (loop_) ? 0 : -1;
3721}
3722
3723} // namespace cricket
3724
3725#endif // HAVE_WEBRTC_VOICE