blob: 81a6cdc3e342dfc4907f8ff9fad7fe9e6cecb9f7 [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"
55
56#ifdef WIN32
57#include <objbase.h> // NOLINT
58#endif
59
60namespace cricket {
61
62struct CodecPref {
63 const char* name;
64 int clockrate;
65 int channels;
66 int payload_type;
67 bool is_multi_rate;
68};
69
70static const CodecPref kCodecPrefs[] = {
71 { "OPUS", 48000, 2, 111, true },
72 { "ISAC", 16000, 1, 103, true },
73 { "ISAC", 32000, 1, 104, true },
74 { "CELT", 32000, 1, 109, true },
75 { "CELT", 32000, 2, 110, true },
76 { "G722", 16000, 1, 9, false },
77 { "ILBC", 8000, 1, 102, false },
78 { "PCMU", 8000, 1, 0, false },
79 { "PCMA", 8000, 1, 8, false },
80 { "CN", 48000, 1, 107, false },
81 { "CN", 32000, 1, 106, false },
82 { "CN", 16000, 1, 105, false },
83 { "CN", 8000, 1, 13, false },
84 { "red", 8000, 1, 127, false },
85 { "telephone-event", 8000, 1, 126, false },
86};
87
88// For Linux/Mac, using the default device is done by specifying index 0 for
89// VoE 4.0 and not -1 (which was the case for VoE 3.5).
90//
91// On Windows Vista and newer, Microsoft introduced the concept of "Default
92// Communications Device". This means that there are two types of default
93// devices (old Wave Audio style default and Default Communications Device).
94//
95// On Windows systems which only support Wave Audio style default, uses either
96// -1 or 0 to select the default device.
97//
98// On Windows systems which support both "Default Communication Device" and
99// old Wave Audio style default, use -1 for Default Communications Device and
100// -2 for Wave Audio style default, which is what we want to use for clips.
101// It's not clear yet whether the -2 index is handled properly on other OSes.
102
103#ifdef WIN32
104static const int kDefaultAudioDeviceId = -1;
105static const int kDefaultSoundclipDeviceId = -2;
106#else
107static const int kDefaultAudioDeviceId = 0;
108#endif
109
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110static const char kIsacCodecName[] = "ISAC";
111static const char kL16CodecName[] = "L16";
112// Codec parameters for Opus.
113static const int kOpusMonoBitrate = 32000;
114// Parameter used for NACK.
115// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
116static const int kNackMaxPackets = 250;
117static const int kOpusStereoBitrate = 64000;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000118// draft-spittka-payload-rtp-opus-03
119// Opus bitrate should be in the range between 6000 and 510000.
120static const int kOpusMinBitrate = 6000;
121static const int kOpusMaxBitrate = 510000;
wu@webrtc.orgde305012013-10-31 15:40:38 +0000122// Default audio dscp value.
123// See http://tools.ietf.org/html/rfc2474 for details.
124// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000125static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000126
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000127// Ensure we open the file in a writeable path on ChromeOS and Android. This
128// workaround can be removed when it's possible to specify a filename for audio
129// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000130//
131// TODO(grunell): Use a string in the options instead of hardcoding it here
132// and let the embedder choose the filename (crbug.com/264223).
133//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000134// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
135// below.
136#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000137static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000138#elif defined(ANDROID)
139static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000140#else
141static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
142#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000143
144// Dumps an AudioCodec in RFC 2327-ish format.
145static std::string ToString(const AudioCodec& codec) {
146 std::stringstream ss;
147 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
148 << " (" << codec.id << ")";
149 return ss.str();
150}
151static std::string ToString(const webrtc::CodecInst& codec) {
152 std::stringstream ss;
153 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
154 << " (" << codec.pltype << ")";
155 return ss.str();
156}
157
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000158static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000159 const char* delim = "\r\n";
160 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
161 LOG_V(sev) << tok;
162 }
163}
164
165// Severity is an integer because it comes is assumed to be from command line.
166static int SeverityToFilter(int severity) {
167 int filter = webrtc::kTraceNone;
168 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000169 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000170 filter |= webrtc::kTraceAll;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000171 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000172 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000173 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000174 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000175 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000176 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
177 }
178 return filter;
179}
180
181static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
182 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
183 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
184 kCodecPrefs[i].clockrate == codec.plfreq) {
185 return kCodecPrefs[i].is_multi_rate;
186 }
187 }
188 return false;
189}
190
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000191static bool IsTelephoneEventCodec(const std::string& name) {
192 return _stricmp(name.c_str(), "telephone-event") == 0;
193}
194
195static bool IsCNCodec(const std::string& name) {
196 return _stricmp(name.c_str(), "CN") == 0;
197}
198
199static bool IsRedCodec(const std::string& name) {
200 return _stricmp(name.c_str(), "red") == 0;
201}
202
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000203static bool FindCodec(const std::vector<AudioCodec>& codecs,
204 const AudioCodec& codec,
205 AudioCodec* found_codec) {
206 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
207 it != codecs.end(); ++it) {
208 if (it->Matches(codec)) {
209 if (found_codec != NULL) {
210 *found_codec = *it;
211 }
212 return true;
213 }
214 }
215 return false;
216}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000217
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000218static bool IsNackEnabled(const AudioCodec& codec) {
219 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
220 kParamValueEmpty));
221}
222
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000223// Gets the default set of options applied to the engine. Historically, these
224// were supplied as a combination of flags from the channel manager (ec, agc,
225// ns, and highpass) and the rest hardcoded in InitInternal.
226static AudioOptions GetDefaultEngineOptions() {
227 AudioOptions options;
228 options.echo_cancellation.Set(true);
229 options.auto_gain_control.Set(true);
230 options.noise_suppression.Set(true);
231 options.highpass_filter.Set(true);
232 options.stereo_swapping.Set(false);
233 options.typing_detection.Set(true);
234 options.conference_mode.Set(false);
235 options.adjust_agc_delta.Set(0);
236 options.experimental_agc.Set(false);
237 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000238 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000239 options.aec_dump.Set(false);
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000240 options.opus_fec.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000241 return options;
242}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000243
244class WebRtcSoundclipMedia : public SoundclipMedia {
245 public:
246 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
247 : engine_(engine), webrtc_channel_(-1) {
248 engine_->RegisterSoundclip(this);
249 }
250
251 virtual ~WebRtcSoundclipMedia() {
252 engine_->UnregisterSoundclip(this);
253 if (webrtc_channel_ != -1) {
254 // We shouldn't have to call Disable() here. DeleteChannel() should call
255 // StopPlayout() while deleting the channel. We should fix the bug
256 // inside WebRTC and remove the Disable() call bellow. This work is
257 // tracked by bug http://b/issue?id=5382855.
258 PlaySound(NULL, 0, 0);
259 Disable();
260 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
261 == -1) {
262 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
263 }
264 }
265 }
266
267 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000268 if (!engine_->voe_sc()) {
269 return false;
270 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000271 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000272 if (webrtc_channel_ == -1) {
273 LOG_RTCERR0(CreateChannel);
274 return false;
275 }
276 return true;
277 }
278
279 bool Enable() {
280 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
281 LOG_RTCERR1(StartPlayout, webrtc_channel_);
282 return false;
283 }
284 return true;
285 }
286
287 bool Disable() {
288 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
289 LOG_RTCERR1(StopPlayout, webrtc_channel_);
290 return false;
291 }
292 return true;
293 }
294
295 virtual bool PlaySound(const char *buf, int len, int flags) {
296 // The voe file api is not available in chrome.
297 if (!engine_->voe_sc()->file()) {
298 return false;
299 }
300 // Must stop playing the current sound (if any), because we are about to
301 // modify the stream.
302 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
303 == -1) {
304 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
305 return false;
306 }
307
308 if (buf) {
309 stream_.reset(new WebRtcSoundclipStream(buf, len));
310 stream_->set_loop((flags & SF_LOOP) != 0);
311 stream_->Rewind();
312
313 // Play it.
314 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
315 webrtc_channel_, stream_.get()) == -1) {
316 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
317 LOG(LS_ERROR) << "Unable to start soundclip";
318 return false;
319 }
320 } else {
321 stream_.reset();
322 }
323 return true;
324 }
325
326 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
327
328 private:
329 WebRtcVoiceEngine *engine_;
330 int webrtc_channel_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000331 rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000332};
333
334WebRtcVoiceEngine::WebRtcVoiceEngine()
335 : voe_wrapper_(new VoEWrapper()),
336 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000337 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000338 tracing_(new VoETraceWrapper()),
339 adm_(NULL),
340 adm_sc_(NULL),
341 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
342 is_dumping_aec_(false),
343 desired_local_monitor_enable_(false),
344 tx_processor_ssrc_(0),
345 rx_processor_ssrc_(0) {
346 Construct();
347}
348
349WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
350 VoEWrapper* voe_wrapper_sc,
351 VoETraceWrapper* tracing)
352 : voe_wrapper_(voe_wrapper),
353 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000354 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000355 tracing_(tracing),
356 adm_(NULL),
357 adm_sc_(NULL),
358 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
359 is_dumping_aec_(false),
360 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000361 tx_processor_ssrc_(0),
362 rx_processor_ssrc_(0) {
363 Construct();
364}
365
366void WebRtcVoiceEngine::Construct() {
367 SetTraceFilter(log_filter_);
368 initialized_ = false;
369 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
370 SetTraceOptions("");
371 if (tracing_->SetTraceCallback(this) == -1) {
372 LOG_RTCERR0(SetTraceCallback);
373 }
374 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
375 LOG_RTCERR0(RegisterVoiceEngineObserver);
376 }
377 // Clear the default agc state.
378 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
379
380 // Load our audio codec list.
381 ConstructCodecs();
382
383 // Load our RTP Header extensions.
384 rtp_header_extensions_.push_back(
385 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
386 kRtpAudioLevelHeaderExtensionDefaultId));
387 rtp_header_extensions_.push_back(
388 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
389 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
390 options_ = GetDefaultEngineOptions();
391}
392
393static bool IsOpus(const AudioCodec& codec) {
394 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
395}
396
397static bool IsIsac(const AudioCodec& codec) {
398 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
399}
400
401// True if params["stereo"] == "1"
402static bool IsOpusStereoEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000403 int value;
404 return codec.GetParam(kCodecParamStereo, &value) && value == 1;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000405}
406
407static bool IsValidOpusBitrate(int bitrate) {
408 return (bitrate >= kOpusMinBitrate && bitrate <= kOpusMaxBitrate);
409}
410
411// Returns 0 if params[kCodecParamMaxAverageBitrate] is not defined or invalid.
412// Returns the value of params[kCodecParamMaxAverageBitrate] otherwise.
413static int GetOpusBitrateFromParams(const AudioCodec& codec) {
414 int bitrate = 0;
415 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
416 return 0;
417 }
418 if (!IsValidOpusBitrate(bitrate)) {
419 LOG(LS_WARNING) << "Codec parameter \"maxaveragebitrate\" has an "
420 << "invalid value: " << bitrate;
421 return 0;
422 }
423 return bitrate;
424}
425
buildbot@webrtc.orgfbd13282014-06-19 19:50:55 +0000426// Return true if params[kCodecParamUseInbandFec] == "1", false
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000427// otherwise.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000428static bool IsOpusFecEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000429 int value;
430 return codec.GetParam(kCodecParamUseInbandFec, &value) && value == 1;
431}
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000432
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000433// Set params[kCodecParamUseInbandFec]. Caller should make sure codec is Opus.
buildbot@webrtc.orgfbd13282014-06-19 19:50:55 +0000434static void SetOpusFec(AudioCodec* codec, bool opus_fec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000435 if (opus_fec) {
buildbot@webrtc.orgfbd13282014-06-19 19:50:55 +0000436 codec->SetParam(kCodecParamUseInbandFec, 1);
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000437 } else {
buildbot@webrtc.orgfbd13282014-06-19 19:50:55 +0000438 codec->RemoveParam(kCodecParamUseInbandFec);
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000439 }
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000440}
441
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000442void WebRtcVoiceEngine::ConstructCodecs() {
443 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
444 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
445 for (int i = 0; i < ncodecs; ++i) {
446 webrtc::CodecInst voe_codec;
447 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
448 // Skip uncompressed formats.
449 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
450 continue;
451 }
452
453 const CodecPref* pref = NULL;
454 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
455 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
456 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
457 kCodecPrefs[j].channels == voe_codec.channels) {
458 pref = &kCodecPrefs[j];
459 break;
460 }
461 }
462
463 if (pref) {
464 // Use the payload type that we've configured in our pref table;
465 // use the offset in our pref table to determine the sort order.
466 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
467 voe_codec.rate, voe_codec.channels,
468 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
469 LOG(LS_INFO) << ToString(codec);
470 if (IsIsac(codec)) {
471 // Indicate auto-bandwidth in signaling.
472 codec.bitrate = 0;
473 }
474 if (IsOpus(codec)) {
475 // Only add fmtp parameters that differ from the spec.
476 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
477 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000478 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000479 }
480 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
481 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000482 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000483 }
484 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
485 // when they can be set to values other than the default.
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000486 SetOpusFec(&codec, false);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000487 }
488 codecs_.push_back(codec);
489 } else {
490 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
491 }
492 }
493 }
494 // Make sure they are in local preference order.
495 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
496}
497
498WebRtcVoiceEngine::~WebRtcVoiceEngine() {
499 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
500 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
501 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
502 }
503 if (adm_) {
504 voe_wrapper_.reset();
505 adm_->Release();
506 adm_ = NULL;
507 }
508 if (adm_sc_) {
509 voe_wrapper_sc_.reset();
510 adm_sc_->Release();
511 adm_sc_ = NULL;
512 }
513
514 // Test to see if the media processor was deregistered properly
515 ASSERT(SignalRxMediaFrame.is_empty());
516 ASSERT(SignalTxMediaFrame.is_empty());
517
518 tracing_->SetTraceCallback(NULL);
519}
520
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000521bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000522 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
523 bool res = InitInternal();
524 if (res) {
525 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
526 } else {
527 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
528 Terminate();
529 }
530 return res;
531}
532
533bool WebRtcVoiceEngine::InitInternal() {
534 // Temporarily turn logging level up for the Init call
535 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000536 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000537 SetTraceFilter(extended_filter);
538 SetTraceOptions("");
539
540 // Init WebRtc VoiceEngine.
541 if (voe_wrapper_->base()->Init(adm_) == -1) {
542 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
543 SetTraceFilter(old_filter);
544 return false;
545 }
546
547 SetTraceFilter(old_filter);
548 SetTraceOptions(log_options_);
549
550 // Log the VoiceEngine version info
551 char buffer[1024] = "";
552 voe_wrapper_->base()->GetVersion(buffer);
553 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000554 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000555
556 // Save the default AGC configuration settings. This must happen before
557 // calling SetOptions or the default will be overwritten.
558 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
559 LOG_RTCERR0(GetAgcConfig);
560 return false;
561 }
562
563 // Set defaults for options, so that ApplyOptions applies them explicitly
564 // when we clear option (channel) overrides. External clients can still
565 // modify the defaults via SetOptions (on the media engine).
566 if (!SetOptions(GetDefaultEngineOptions())) {
567 return false;
568 }
569
570 // Print our codec list again for the call diagnostic log
571 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
572 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
573 it != codecs_.end(); ++it) {
574 LOG(LS_INFO) << ToString(*it);
575 }
576
577 // Disable the DTMF playout when a tone is sent.
578 // PlayDtmfTone will be used if local playout is needed.
579 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
580 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
581 }
582
583 initialized_ = true;
584 return true;
585}
586
587bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
588 if (voe_wrapper_sc_initialized_) {
589 return true;
590 }
591 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
592 // be false, so subsequent calls to EnsureSoundclipEngineInit will
593 // probably just fail again. That's acceptable behavior.
594#if defined(LINUX) && !defined(HAVE_LIBPULSE)
595 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
596#endif
597
598 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
599 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
600 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
601 return false;
602 }
603
604 // On Windows, tell it to use the default sound (not communication) devices.
605 // First check whether there is a valid sound device for playback.
606 // TODO(juberti): Clean this up when we support setting the soundclip device.
607#ifdef WIN32
608 // The SetPlayoutDevice may not be implemented in the case of external ADM.
609 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
610 // PeerConnection interface never set the adm_sc_, so need to check both
611 // in order to determine if the external adm is used.
612 if (!adm_ && !adm_sc_) {
613 int num_of_devices = 0;
614 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
615 num_of_devices > 0) {
616 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
617 == -1) {
618 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
619 voe_wrapper_sc_->error());
620 return false;
621 }
622 } else {
623 LOG(LS_WARNING) << "No valid sound playout device found.";
624 }
625 }
626#endif
627 voe_wrapper_sc_initialized_ = true;
628 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
629 return true;
630}
631
632void WebRtcVoiceEngine::Terminate() {
633 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
634 initialized_ = false;
635
636 StopAecDump();
637
638 if (voe_wrapper_sc_) {
639 voe_wrapper_sc_initialized_ = false;
640 voe_wrapper_sc_->base()->Terminate();
641 }
642 voe_wrapper_->base()->Terminate();
643 desired_local_monitor_enable_ = false;
644}
645
646int WebRtcVoiceEngine::GetCapabilities() {
647 return AUDIO_SEND | AUDIO_RECV;
648}
649
650VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
651 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
652 if (!ch->valid()) {
653 delete ch;
654 ch = NULL;
655 }
656 return ch;
657}
658
659SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
660 if (!EnsureSoundclipEngineInit()) {
661 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
662 << "initialize.";
663 return NULL;
664 }
665 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
666 if (!soundclip->Init() || !soundclip->Enable()) {
667 delete soundclip;
668 return NULL;
669 }
670 return soundclip;
671}
672
673bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
674 if (!ApplyOptions(options)) {
675 return false;
676 }
677 options_ = options;
678 return true;
679}
680
681bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
682 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
683 if (!ApplyOptions(overrides)) {
684 return false;
685 }
686 option_overrides_ = overrides;
687 return true;
688}
689
690bool WebRtcVoiceEngine::ClearOptionOverrides() {
691 LOG(LS_INFO) << "Clearing option overrides.";
692 AudioOptions options = options_;
693 // Only call ApplyOptions if |options_overrides_| contains overrided options.
694 // ApplyOptions affects NS, AGC other options that is shared between
695 // all WebRtcVoiceEngineChannels.
696 if (option_overrides_ == AudioOptions()) {
697 return true;
698 }
699
700 if (!ApplyOptions(options)) {
701 return false;
702 }
703 option_overrides_ = AudioOptions();
704 return true;
705}
706
707// AudioOptions defaults are set in InitInternal (for options with corresponding
708// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
709bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
710 AudioOptions options = options_in; // The options are modified below.
711 // kEcConference is AEC with high suppression.
712 webrtc::EcModes ec_mode = webrtc::kEcConference;
713 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
714 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
715 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
716 bool aecm_comfort_noise = false;
717 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
718 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
719 << aecm_comfort_noise << " (default is false).";
720 }
721
722#if defined(IOS)
723 // On iOS, VPIO provides built-in EC and AGC.
724 options.echo_cancellation.Set(false);
725 options.auto_gain_control.Set(false);
726#elif defined(ANDROID)
727 ec_mode = webrtc::kEcAecm;
728#endif
729
730#if defined(IOS) || defined(ANDROID)
731 // Set the AGC mode for iOS as well despite disabling it above, to avoid
732 // unsupported configuration errors from webrtc.
733 agc_mode = webrtc::kAgcFixedDigital;
734 options.typing_detection.Set(false);
735 options.experimental_agc.Set(false);
736 options.experimental_aec.Set(false);
737 options.experimental_ns.Set(false);
738#endif
739
740 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
741
742 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
743
744 bool echo_cancellation;
745 if (options.echo_cancellation.Get(&echo_cancellation)) {
746 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
747 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
748 return false;
749 } else {
750 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
751 << " with mode " << ec_mode;
752 }
753#if !defined(ANDROID)
754 // TODO(ajm): Remove the error return on Android from webrtc.
755 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
756 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
757 return false;
758 }
759#endif
760 if (ec_mode == webrtc::kEcAecm) {
761 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
762 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
763 return false;
764 }
765 }
766 }
767
768 bool auto_gain_control;
769 if (options.auto_gain_control.Get(&auto_gain_control)) {
770 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
771 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
772 return false;
773 } else {
774 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
775 << " with mode " << agc_mode;
776 }
777 }
778
779 if (options.tx_agc_target_dbov.IsSet() ||
780 options.tx_agc_digital_compression_gain.IsSet() ||
781 options.tx_agc_limiter.IsSet()) {
782 // Override default_agc_config_. Generally, an unset option means "leave
783 // the VoE bits alone" in this function, so we want whatever is set to be
784 // stored as the new "default". If we didn't, then setting e.g.
785 // tx_agc_target_dbov would reset digital compression gain and limiter
786 // settings.
787 // Also, if we don't update default_agc_config_, then adjust_agc_delta
788 // would be an offset from the original values, and not whatever was set
789 // explicitly.
790 default_agc_config_.targetLeveldBOv =
791 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
792 default_agc_config_.targetLeveldBOv);
793 default_agc_config_.digitalCompressionGaindB =
794 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
795 default_agc_config_.digitalCompressionGaindB);
796 default_agc_config_.limiterEnable =
797 options.tx_agc_limiter.GetWithDefaultIfUnset(
798 default_agc_config_.limiterEnable);
799 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
800 LOG_RTCERR3(SetAgcConfig,
801 default_agc_config_.targetLeveldBOv,
802 default_agc_config_.digitalCompressionGaindB,
803 default_agc_config_.limiterEnable);
804 return false;
805 }
806 }
807
808 bool noise_suppression;
809 if (options.noise_suppression.Get(&noise_suppression)) {
810 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
811 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
812 return false;
813 } else {
814 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
815 << " with mode " << ns_mode;
816 }
817 }
818
819 bool experimental_ns;
820 if (options.experimental_ns.Get(&experimental_ns)) {
821 webrtc::AudioProcessing* audioproc =
822 voe_wrapper_->base()->audio_processing();
buildbot@webrtc.orga8d8ad22014-07-16 14:23:08 +0000823#ifdef USE_WEBRTC_DEV_BRANCH
824 webrtc::Config config;
825 config.Set<webrtc::ExperimentalNs>(new webrtc::ExperimentalNs(
826 experimental_ns));
827 audioproc->SetExtraOptions(config);
828#else
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000829 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
830 // returns NULL on audio_processing().
831 if (audioproc) {
832 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
833 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
834 return false;
835 }
836 } else {
837 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
838 << experimental_ns;
839 }
buildbot@webrtc.orga8d8ad22014-07-16 14:23:08 +0000840#endif
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000841 }
842
843 bool highpass_filter;
844 if (options.highpass_filter.Get(&highpass_filter)) {
845 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
846 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
847 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
848 return false;
849 }
850 }
851
852 bool stereo_swapping;
853 if (options.stereo_swapping.Get(&stereo_swapping)) {
854 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
855 voep->EnableStereoChannelSwapping(stereo_swapping);
856 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
857 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
858 return false;
859 }
860 }
861
862 bool typing_detection;
863 if (options.typing_detection.Get(&typing_detection)) {
864 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
865 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
866 // In case of error, log the info and continue
867 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
868 }
869 }
870
871 int adjust_agc_delta;
872 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
873 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
874 if (!AdjustAgcLevel(adjust_agc_delta)) {
875 return false;
876 }
877 }
878
879 bool aec_dump;
880 if (options.aec_dump.Get(&aec_dump)) {
881 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
882 if (aec_dump)
883 StartAecDump(kAecDumpByAudioOptionFilename);
884 else
885 StopAecDump();
886 }
887
888 bool experimental_aec;
889 if (options.experimental_aec.Get(&experimental_aec)) {
890 LOG(LS_INFO) << "Experimental aec is " << experimental_aec;
891 webrtc::AudioProcessing* audioproc =
892 voe_wrapper_->base()->audio_processing();
893 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
894 // returns NULL on audio_processing().
895 if (audioproc) {
896 webrtc::Config config;
897 config.Set<webrtc::DelayCorrection>(
898 new webrtc::DelayCorrection(experimental_aec));
899 audioproc->SetExtraOptions(config);
900 }
901 }
902
903 uint32 recording_sample_rate;
904 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
905 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
906 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
907 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
908 }
909 }
910
911 uint32 playout_sample_rate;
912 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
913 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
914 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
915 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
916 }
917 }
918
buildbot@webrtc.orgfbd13282014-06-19 19:50:55 +0000919 bool opus_fec;
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000920 if (options.opus_fec.Get(&opus_fec)) {
921 LOG(LS_INFO) << "Opus FEC is enabled? " << opus_fec;
922 for (std::vector<AudioCodec>::iterator it = codecs_.begin();
923 it != codecs_.end(); ++it) {
924 if (IsOpus(*it))
925 SetOpusFec(&(*it), opus_fec);
926 }
927 }
928
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000929 return true;
930}
931
932bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
933 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
934 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
935 LOG_RTCERR1(SetDelayOffsetMs, offset);
936 return false;
937 }
938
939 return true;
940}
941
942struct ResumeEntry {
943 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
944 : channel(c),
945 playout(p),
946 send(s) {
947 }
948
949 WebRtcVoiceMediaChannel *channel;
950 bool playout;
951 SendFlags send;
952};
953
954// TODO(juberti): Refactor this so that the core logic can be used to set the
955// soundclip device. At that time, reinstate the soundclip pause/resume code.
956bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
957 const Device* out_device) {
958#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000959 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000960 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000961 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000962 kDefaultAudioDeviceId;
963 // The device manager uses -1 as the default device, which was the case for
964 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
965#ifndef WIN32
966 if (-1 == in_id) {
967 in_id = kDefaultAudioDeviceId;
968 }
969 if (-1 == out_id) {
970 out_id = kDefaultAudioDeviceId;
971 }
972#endif
973
974 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
975 in_device->name : "Default device";
976 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
977 out_device->name : "Default device";
978 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
979 << ") and speaker to (id=" << out_id << ", name=" << out_name
980 << ")";
981
982 // If we're running the local monitor, we need to stop it first.
983 bool ret = true;
984 if (!PauseLocalMonitor()) {
985 LOG(LS_WARNING) << "Failed to pause local monitor";
986 ret = false;
987 }
988
989 // Must also pause all audio playback and capture.
990 for (ChannelList::const_iterator i = channels_.begin();
991 i != channels_.end(); ++i) {
992 WebRtcVoiceMediaChannel *channel = *i;
993 if (!channel->PausePlayout()) {
994 LOG(LS_WARNING) << "Failed to pause playout";
995 ret = false;
996 }
997 if (!channel->PauseSend()) {
998 LOG(LS_WARNING) << "Failed to pause send";
999 ret = false;
1000 }
1001 }
1002
1003 // Find the recording device id in VoiceEngine and set recording device.
1004 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1005 ret = false;
1006 }
1007 if (ret) {
1008 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
1009 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
1010 ret = false;
1011 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00001012 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
1013 if (ap)
1014 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001015 }
1016
1017 // Find the playout device id in VoiceEngine and set playout device.
1018 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1019 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1020 ret = false;
1021 }
1022 if (ret) {
1023 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001024 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001025 ret = false;
1026 }
1027 }
1028
1029 // Resume all audio playback and capture.
1030 for (ChannelList::const_iterator i = channels_.begin();
1031 i != channels_.end(); ++i) {
1032 WebRtcVoiceMediaChannel *channel = *i;
1033 if (!channel->ResumePlayout()) {
1034 LOG(LS_WARNING) << "Failed to resume playout";
1035 ret = false;
1036 }
1037 if (!channel->ResumeSend()) {
1038 LOG(LS_WARNING) << "Failed to resume send";
1039 ret = false;
1040 }
1041 }
1042
1043 // Resume local monitor.
1044 if (!ResumeLocalMonitor()) {
1045 LOG(LS_WARNING) << "Failed to resume local monitor";
1046 ret = false;
1047 }
1048
1049 if (ret) {
1050 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1051 << ") and speaker to (id="<< out_id << " name=" << out_name
1052 << ")";
1053 }
1054
1055 return ret;
1056#else
1057 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001058#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001059}
1060
1061bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1062 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1063 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001064#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001065 *rtc_id = dev_id;
1066 return true;
1067#else
1068 // In Windows and Mac, we need to find the VoiceEngine device id by name
1069 // unless the input dev_id is the default device id.
1070 if (kDefaultAudioDeviceId == dev_id) {
1071 *rtc_id = dev_id;
1072 return true;
1073 }
1074
1075 // Get the number of VoiceEngine audio devices.
1076 int count = 0;
1077 if (is_input) {
1078 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1079 LOG_RTCERR0(GetNumOfRecordingDevices);
1080 return false;
1081 }
1082 } else {
1083 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1084 LOG_RTCERR0(GetNumOfPlayoutDevices);
1085 return false;
1086 }
1087 }
1088
1089 for (int i = 0; i < count; ++i) {
1090 char name[128];
1091 char guid[128];
1092 if (is_input) {
1093 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1094 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1095 } else {
1096 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1097 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1098 }
1099
1100 std::string webrtc_name(name);
1101 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1102 *rtc_id = i;
1103 return true;
1104 }
1105 }
1106 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1107 return false;
1108#endif
1109}
1110
1111bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1112 unsigned int ulevel;
1113 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1114 LOG_RTCERR1(GetSpeakerVolume, level);
1115 return false;
1116 }
1117 *level = ulevel;
1118 return true;
1119}
1120
1121bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1122 ASSERT(level >= 0 && level <= 255);
1123 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1124 LOG_RTCERR1(SetSpeakerVolume, level);
1125 return false;
1126 }
1127 return true;
1128}
1129
1130int WebRtcVoiceEngine::GetInputLevel() {
1131 unsigned int ulevel;
1132 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1133 static_cast<int>(ulevel) : -1;
1134}
1135
1136bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1137 desired_local_monitor_enable_ = enable;
1138 return ChangeLocalMonitor(desired_local_monitor_enable_);
1139}
1140
1141bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1142 // The voe file api is not available in chrome.
1143 if (!voe_wrapper_->file()) {
1144 return false;
1145 }
1146 if (enable && !monitor_) {
1147 monitor_.reset(new WebRtcMonitorStream);
1148 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1149 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1150 // Must call Stop() because there are some cases where Start will report
1151 // failure but still change the state, and if we leave VE in the on state
1152 // then it could crash later when trying to invoke methods on our monitor.
1153 voe_wrapper_->file()->StopRecordingMicrophone();
1154 monitor_.reset();
1155 return false;
1156 }
1157 } else if (!enable && monitor_) {
1158 voe_wrapper_->file()->StopRecordingMicrophone();
1159 monitor_.reset();
1160 }
1161 return true;
1162}
1163
1164bool WebRtcVoiceEngine::PauseLocalMonitor() {
1165 return ChangeLocalMonitor(false);
1166}
1167
1168bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1169 return ChangeLocalMonitor(desired_local_monitor_enable_);
1170}
1171
1172const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1173 return codecs_;
1174}
1175
1176bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1177 return FindWebRtcCodec(in, NULL);
1178}
1179
1180// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1181bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1182 webrtc::CodecInst* out) {
1183 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1184 for (int i = 0; i < ncodecs; ++i) {
1185 webrtc::CodecInst voe_codec;
1186 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1187 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1188 voe_codec.rate, voe_codec.channels, 0);
1189 bool multi_rate = IsCodecMultiRate(voe_codec);
1190 // Allow arbitrary rates for ISAC to be specified.
1191 if (multi_rate) {
1192 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1193 codec.bitrate = 0;
1194 }
1195 if (codec.Matches(in)) {
1196 if (out) {
1197 // Fixup the payload type.
1198 voe_codec.pltype = in.id;
1199
1200 // Set bitrate if specified.
1201 if (multi_rate && in.bitrate != 0) {
1202 voe_codec.rate = in.bitrate;
1203 }
1204
1205 // Apply codec-specific settings.
1206 if (IsIsac(codec)) {
1207 // If ISAC and an explicit bitrate is not specified,
1208 // enable auto bandwidth adjustment.
1209 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1210 }
1211 *out = voe_codec;
1212 }
1213 return true;
1214 }
1215 }
1216 }
1217 return false;
1218}
1219const std::vector<RtpHeaderExtension>&
1220WebRtcVoiceEngine::rtp_header_extensions() const {
1221 return rtp_header_extensions_;
1222}
1223
1224void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1225 // if min_sev == -1, we keep the current log level.
1226 if (min_sev >= 0) {
1227 SetTraceFilter(SeverityToFilter(min_sev));
1228 }
1229 log_options_ = filter;
1230 SetTraceOptions(initialized_ ? log_options_ : "");
1231}
1232
1233int WebRtcVoiceEngine::GetLastEngineError() {
1234 return voe_wrapper_->error();
1235}
1236
1237void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1238 log_filter_ = filter;
1239 tracing_->SetTraceFilter(filter);
1240}
1241
1242// We suppport three different logging settings for VoiceEngine:
1243// 1. Observer callback that goes into talk diagnostic logfile.
1244// Use --logfile and --loglevel
1245//
1246// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1247// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1248//
1249// 3. EC log and dump for debugging QualityEngine.
1250// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1251//
1252// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1253// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1254void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1255 // Set encrypted trace file.
1256 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001257 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001258 std::vector<std::string>::iterator tracefile =
1259 std::find(opts.begin(), opts.end(), "tracefile");
1260 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1261 // Write encrypted debug output (at same loglevel) to file
1262 // EncryptedTraceFile no longer supported.
1263 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1264 LOG_RTCERR1(SetTraceFile, *tracefile);
1265 }
1266 }
1267
wu@webrtc.org97077a32013-10-25 21:18:33 +00001268 // Allow trace options to override the trace filter. We default
1269 // it to log_filter_ (as a translation of libjingle log levels)
1270 // elsewhere, but this allows clients to explicitly set webrtc
1271 // log levels.
1272 std::vector<std::string>::iterator tracefilter =
1273 std::find(opts.begin(), opts.end(), "tracefilter");
1274 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001275 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001276 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1277 }
1278 }
1279
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280 // Set AEC dump file
1281 std::vector<std::string>::iterator recordEC =
1282 std::find(opts.begin(), opts.end(), "recordEC");
1283 if (recordEC != opts.end()) {
1284 ++recordEC;
1285 if (recordEC != opts.end())
1286 StartAecDump(recordEC->c_str());
1287 else
1288 StopAecDump();
1289 }
1290}
1291
1292// Ignore spammy trace messages, mostly from the stats API when we haven't
1293// gotten RTCP info yet from the remote side.
1294bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1295 static const char* kTracesToIgnore[] = {
1296 "\tfailed to GetReportBlockInformation",
1297 "GetRecCodec() failed to get received codec",
1298 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1299 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1300 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1301 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1302 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1303 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1304 "SenderInfoReceived No received SR",
1305 "StatisticsRTP() no statistics available",
1306 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1307 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1308 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1309 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1310 NULL
1311 };
1312 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1313 if (trace.find(*p) != std::string::npos) {
1314 return true;
1315 }
1316 }
1317 return false;
1318}
1319
1320void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1321 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001322 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001323 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001324 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001325 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001326 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001327 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001328 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001329 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001330 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001331
1332 // Skip past boilerplate prefix text
1333 if (length < 72) {
1334 std::string msg(trace, length);
1335 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1336 LOG_V(sev) << msg;
1337 } else {
1338 std::string msg(trace + 71, length - 72);
1339 if (!ShouldIgnoreTrace(msg)) {
1340 LOG_V(sev) << "webrtc: " << msg;
1341 }
1342 }
1343}
1344
1345void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001346 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001347 WebRtcVoiceMediaChannel* channel = NULL;
1348 uint32 ssrc = 0;
1349 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1350 << channel_num << ".";
1351 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1352 ASSERT(channel != NULL);
1353 channel->OnError(ssrc, err_code);
1354 } else {
1355 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1356 << " could not be found in channel list when error reported.";
1357 }
1358}
1359
1360bool WebRtcVoiceEngine::FindChannelAndSsrc(
1361 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1362 ASSERT(channel != NULL && ssrc != NULL);
1363
1364 *channel = NULL;
1365 *ssrc = 0;
1366 // Find corresponding channel and ssrc
1367 for (ChannelList::const_iterator it = channels_.begin();
1368 it != channels_.end(); ++it) {
1369 ASSERT(*it != NULL);
1370 if ((*it)->FindSsrc(channel_num, ssrc)) {
1371 *channel = *it;
1372 return true;
1373 }
1374 }
1375
1376 return false;
1377}
1378
1379// This method will search through the WebRtcVoiceMediaChannels and
1380// obtain the voice engine's channel number.
1381bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1382 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1383 ASSERT(channel_num != NULL);
1384 ASSERT(direction == MPD_RX || direction == MPD_TX);
1385
1386 *channel_num = -1;
1387 // Find corresponding channel for ssrc.
1388 for (ChannelList::const_iterator it = channels_.begin();
1389 it != channels_.end(); ++it) {
1390 ASSERT(*it != NULL);
1391 if (direction & MPD_RX) {
1392 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1393 }
1394 if (*channel_num == -1 && (direction & MPD_TX)) {
1395 *channel_num = (*it)->GetSendChannelNum(ssrc);
1396 }
1397 if (*channel_num != -1) {
1398 return true;
1399 }
1400 }
1401 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1402 return false;
1403}
1404
1405void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001406 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001407 channels_.push_back(channel);
1408}
1409
1410void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001411 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001412 ChannelList::iterator i = std::find(channels_.begin(),
1413 channels_.end(),
1414 channel);
1415 if (i != channels_.end()) {
1416 channels_.erase(i);
1417 }
1418}
1419
1420void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1421 soundclips_.push_back(soundclip);
1422}
1423
1424void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1425 SoundclipList::iterator i = std::find(soundclips_.begin(),
1426 soundclips_.end(),
1427 soundclip);
1428 if (i != soundclips_.end()) {
1429 soundclips_.erase(i);
1430 }
1431}
1432
1433// Adjusts the default AGC target level by the specified delta.
1434// NB: If we start messing with other config fields, we'll want
1435// to save the current webrtc::AgcConfig as well.
1436bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1437 webrtc::AgcConfig config = default_agc_config_;
1438 config.targetLeveldBOv -= delta;
1439
1440 LOG(LS_INFO) << "Adjusting AGC level from default -"
1441 << default_agc_config_.targetLeveldBOv << "dB to -"
1442 << config.targetLeveldBOv << "dB";
1443
1444 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1445 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1446 return false;
1447 }
1448 return true;
1449}
1450
1451bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1452 webrtc::AudioDeviceModule* adm_sc) {
1453 if (initialized_) {
1454 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1455 return false;
1456 }
1457 if (adm_) {
1458 adm_->Release();
1459 adm_ = NULL;
1460 }
1461 if (adm) {
1462 adm_ = adm;
1463 adm_->AddRef();
1464 }
1465
1466 if (adm_sc_) {
1467 adm_sc_->Release();
1468 adm_sc_ = NULL;
1469 }
1470 if (adm_sc) {
1471 adm_sc_ = adm_sc;
1472 adm_sc_->AddRef();
1473 }
1474 return true;
1475}
1476
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001477bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1478 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001479 if (!aec_dump_file_stream) {
1480 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001481 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001482 LOG(LS_WARNING) << "Could not close file.";
1483 return false;
1484 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001485 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001486 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001487 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001488 LOG_RTCERR0(StartDebugRecording);
1489 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001490 return false;
1491 }
1492 is_dumping_aec_ = true;
1493 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001494}
1495
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001496bool WebRtcVoiceEngine::RegisterProcessor(
1497 uint32 ssrc,
1498 VoiceProcessor* voice_processor,
1499 MediaProcessorDirection direction) {
1500 bool register_with_webrtc = false;
1501 int channel_id = -1;
1502 bool success = false;
1503 uint32* processor_ssrc = NULL;
1504 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1505 if (voice_processor == NULL || !found_channel) {
1506 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1507 << " foundChannel: " << found_channel;
1508 return false;
1509 }
1510
1511 webrtc::ProcessingTypes processing_type;
1512 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001513 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001514 if (direction == MPD_RX) {
1515 processing_type = webrtc::kPlaybackAllChannelsMixed;
1516 if (SignalRxMediaFrame.is_empty()) {
1517 register_with_webrtc = true;
1518 processor_ssrc = &rx_processor_ssrc_;
1519 }
1520 SignalRxMediaFrame.connect(voice_processor,
1521 &VoiceProcessor::OnFrame);
1522 } else {
1523 processing_type = webrtc::kRecordingPerChannel;
1524 if (SignalTxMediaFrame.is_empty()) {
1525 register_with_webrtc = true;
1526 processor_ssrc = &tx_processor_ssrc_;
1527 }
1528 SignalTxMediaFrame.connect(voice_processor,
1529 &VoiceProcessor::OnFrame);
1530 }
1531 }
1532 if (register_with_webrtc) {
1533 // TODO(janahan): when registering consider instantiating a
1534 // a VoeMediaProcess object and not make the engine extend the interface.
1535 if (voe()->media() && voe()->media()->
1536 RegisterExternalMediaProcessing(channel_id,
1537 processing_type,
1538 *this) != -1) {
1539 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1540 << channel_id;
1541 *processor_ssrc = ssrc;
1542 success = true;
1543 } else {
1544 LOG_RTCERR2(RegisterExternalMediaProcessing,
1545 channel_id,
1546 processing_type);
1547 success = false;
1548 }
1549 } else {
1550 // If we don't have to register with the engine, we just needed to
1551 // connect a new processor, set success to true;
1552 success = true;
1553 }
1554 return success;
1555}
1556
1557bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1558 MediaProcessorDirection channel_direction,
1559 uint32 ssrc,
1560 VoiceProcessor* voice_processor,
1561 MediaProcessorDirection processor_direction) {
1562 bool success = true;
1563 FrameSignal* signal;
1564 webrtc::ProcessingTypes processing_type;
1565 uint32* processor_ssrc = NULL;
1566 if (channel_direction == MPD_RX) {
1567 signal = &SignalRxMediaFrame;
1568 processing_type = webrtc::kPlaybackAllChannelsMixed;
1569 processor_ssrc = &rx_processor_ssrc_;
1570 } else {
1571 signal = &SignalTxMediaFrame;
1572 processing_type = webrtc::kRecordingPerChannel;
1573 processor_ssrc = &tx_processor_ssrc_;
1574 }
1575
1576 int deregister_id = -1;
1577 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001578 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001579 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1580 signal->disconnect(voice_processor);
1581 int channel_id = -1;
1582 bool found_channel = FindChannelNumFromSsrc(ssrc,
1583 channel_direction,
1584 &channel_id);
1585 if (signal->is_empty() && found_channel) {
1586 deregister_id = channel_id;
1587 }
1588 }
1589 }
1590 if (deregister_id != -1) {
1591 if (voe()->media() &&
1592 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1593 processing_type) != -1) {
1594 *processor_ssrc = 0;
1595 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1596 << deregister_id;
1597 } else {
1598 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1599 deregister_id,
1600 processing_type);
1601 success = false;
1602 }
1603 }
1604 return success;
1605}
1606
1607bool WebRtcVoiceEngine::UnregisterProcessor(
1608 uint32 ssrc,
1609 VoiceProcessor* voice_processor,
1610 MediaProcessorDirection direction) {
1611 bool success = true;
1612 if (voice_processor == NULL) {
1613 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1614 << ssrc;
1615 return false;
1616 }
1617 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1618 success = false;
1619 }
1620 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1621 success = false;
1622 }
1623 return success;
1624}
1625
1626// Implementing method from WebRtc VoEMediaProcess interface
1627// Do not lock mux_channel_cs_ in this callback.
1628void WebRtcVoiceEngine::Process(int channel,
1629 webrtc::ProcessingTypes type,
1630 int16_t audio10ms[],
1631 int length,
1632 int sampling_freq,
1633 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001634 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001635 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1636 if (type == webrtc::kPlaybackAllChannelsMixed) {
1637 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1638 } else if (type == webrtc::kRecordingPerChannel) {
1639 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1640 } else {
1641 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1642 << " channel: " << channel << " type: " << type
1643 << " tx_ssrc: " << tx_processor_ssrc_
1644 << " rx_ssrc: " << rx_processor_ssrc_;
1645 }
1646}
1647
1648void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1649 if (!is_dumping_aec_) {
1650 // Start dumping AEC when we are not dumping.
1651 if (voe_wrapper_->processing()->StartDebugRecording(
1652 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001653 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001654 } else {
1655 is_dumping_aec_ = true;
1656 }
1657 }
1658}
1659
1660void WebRtcVoiceEngine::StopAecDump() {
1661 if (is_dumping_aec_) {
1662 // Stop dumping AEC when we are dumping.
1663 if (voe_wrapper_->processing()->StopDebugRecording() !=
1664 webrtc::AudioProcessing::kNoError) {
1665 LOG_RTCERR0(StopDebugRecording);
1666 }
1667 is_dumping_aec_ = false;
1668 }
1669}
1670
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001671int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001672 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001673}
1674
1675int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1676 return CreateVoiceChannel(voe_wrapper_.get());
1677}
1678
1679int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1680 return CreateVoiceChannel(voe_wrapper_sc_.get());
1681}
1682
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001683class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1684 : public AudioRenderer::Sink {
1685 public:
1686 WebRtcVoiceChannelRenderer(int ch,
1687 webrtc::AudioTransport* voe_audio_transport)
1688 : channel_(ch),
1689 voe_audio_transport_(voe_audio_transport),
1690 renderer_(NULL) {
1691 }
1692 virtual ~WebRtcVoiceChannelRenderer() {
1693 Stop();
1694 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001695
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001696 // Starts the rendering by setting a sink to the renderer to get data
1697 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001698 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001699 // TODO(xians): Make sure Start() is called only once.
1700 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001701 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001702 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001703 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001704 ASSERT(renderer_ == renderer);
1705 return;
1706 }
1707
1708 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1709 // in getUserMedia by default.
1710 renderer->AddChannel(channel_);
1711 renderer->SetSink(this);
1712 renderer_ = renderer;
1713 }
1714
1715 // Stops rendering by setting the sink of the renderer to NULL. No data
1716 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001717 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001718 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001719 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001720 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001721 return;
1722
1723 renderer_->RemoveChannel(channel_);
1724 renderer_->SetSink(NULL);
1725 renderer_ = NULL;
1726 }
1727
1728 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001729 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001730 virtual void OnData(const void* audio_data,
1731 int bits_per_sample,
1732 int sample_rate,
1733 int number_of_channels,
1734 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001735 voe_audio_transport_->OnData(channel_,
1736 audio_data,
1737 bits_per_sample,
1738 sample_rate,
1739 number_of_channels,
1740 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001741 }
1742
1743 // Callback from the |renderer_| when it is going away. In case Start() has
1744 // never been called, this callback won't be triggered.
1745 virtual void OnClose() OVERRIDE {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001746 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001747 // Set |renderer_| to NULL to make sure no more callback will get into
1748 // the renderer.
1749 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001750 }
1751
1752 // Accessor to the VoE channel ID.
1753 int channel() const { return channel_; }
1754
1755 private:
1756 const int channel_;
1757 webrtc::AudioTransport* const voe_audio_transport_;
1758
1759 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1760 // PeerConnection will make sure invalidating the pointer before the object
1761 // goes away.
1762 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001763
1764 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001765 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001766};
1767
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001768// WebRtcVoiceMediaChannel
1769WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1770 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1771 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001772 engine->CreateMediaVoiceChannel()),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001773 send_bw_setting_(false),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001774 send_bw_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001775 options_(),
1776 dtmf_allowed_(false),
1777 desired_playout_(false),
1778 nack_enabled_(false),
1779 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001780 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001781 desired_send_(SEND_NOTHING),
1782 send_(SEND_NOTHING),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001783 default_receive_ssrc_(0) {
1784 engine->RegisterChannel(this);
1785 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1786 << voe_channel();
1787
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001788 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001789}
1790
1791WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1792 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1793 << voe_channel();
1794
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001795 // Remove any remaining send streams, the default channel will be deleted
1796 // later.
1797 while (!send_channels_.empty())
1798 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001799
1800 // Unregister ourselves from the engine.
1801 engine()->UnregisterChannel(this);
1802 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001803 while (!receive_channels_.empty()) {
1804 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001805 }
1806
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001807 // Delete the default channel.
1808 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001809}
1810
1811bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1812 LOG(LS_INFO) << "Setting voice channel options: "
1813 << options.ToString();
1814
wu@webrtc.orgde305012013-10-31 15:40:38 +00001815 // Check if DSCP value is changed from previous.
1816 bool dscp_option_changed = (options_.dscp != options.dscp);
1817
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001818 // TODO(xians): Add support to set different options for different send
1819 // streams after we support multiple APMs.
1820
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001821 // We retain all of the existing options, and apply the given ones
1822 // on top. This means there is no way to "clear" options such that
1823 // they go back to the engine default.
1824 options_.SetAll(options);
1825
1826 if (send_ != SEND_NOTHING) {
1827 if (!engine()->SetOptionOverrides(options_)) {
1828 LOG(LS_WARNING) <<
1829 "Failed to engine SetOptionOverrides during channel SetOptions.";
1830 return false;
1831 }
1832 } else {
1833 // Will be interpreted when appropriate.
1834 }
1835
wu@webrtc.org97077a32013-10-25 21:18:33 +00001836 // Receiver-side auto gain control happens per channel, so set it here from
1837 // options. Note that, like conference mode, setting it on the engine won't
1838 // have the desired effect, since voice channels don't inherit options from
1839 // the media engine when those options are applied per-channel.
1840 bool rx_auto_gain_control;
1841 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1842 if (engine()->voe()->processing()->SetRxAgcStatus(
1843 voe_channel(), rx_auto_gain_control,
1844 webrtc::kAgcFixedDigital) == -1) {
1845 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1846 return false;
1847 } else {
1848 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1849 << " with mode " << webrtc::kAgcFixedDigital;
1850 }
1851 }
1852 if (options.rx_agc_target_dbov.IsSet() ||
1853 options.rx_agc_digital_compression_gain.IsSet() ||
1854 options.rx_agc_limiter.IsSet()) {
1855 webrtc::AgcConfig config;
1856 // If only some of the options are being overridden, get the current
1857 // settings for the channel and bail if they aren't available.
1858 if (!options.rx_agc_target_dbov.IsSet() ||
1859 !options.rx_agc_digital_compression_gain.IsSet() ||
1860 !options.rx_agc_limiter.IsSet()) {
1861 if (engine()->voe()->processing()->GetRxAgcConfig(
1862 voe_channel(), config) != 0) {
1863 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1864 << "channel " << voe_channel() << ". Since not all rx "
1865 << "agc options are specified, unable to safely set rx "
1866 << "agc options.";
1867 return false;
1868 }
1869 }
1870 config.targetLeveldBOv =
1871 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1872 config.targetLeveldBOv);
1873 config.digitalCompressionGaindB =
1874 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1875 config.digitalCompressionGaindB);
1876 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1877 config.limiterEnable);
1878 if (engine()->voe()->processing()->SetRxAgcConfig(
1879 voe_channel(), config) == -1) {
1880 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1881 config.digitalCompressionGaindB, config.limiterEnable);
1882 return false;
1883 }
1884 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001885 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001886 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001887 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001888 dscp = kAudioDscpValue;
1889 if (MediaChannel::SetDscp(dscp) != 0) {
1890 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1891 }
1892 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001893
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001894 LOG(LS_INFO) << "Set voice channel options. Current options: "
1895 << options_.ToString();
1896 return true;
1897}
1898
1899bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1900 const std::vector<AudioCodec>& codecs) {
1901 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001902 LOG(LS_INFO) << "Setting receive voice codecs:";
1903
1904 std::vector<AudioCodec> new_codecs;
1905 // Find all new codecs. We allow adding new codecs but don't allow changing
1906 // the payload type of codecs that is already configured since we might
1907 // already be receiving packets with that payload type.
1908 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001909 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001910 AudioCodec old_codec;
1911 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1912 if (old_codec.id != it->id) {
1913 LOG(LS_ERROR) << it->name << " payload type changed.";
1914 return false;
1915 }
1916 } else {
1917 new_codecs.push_back(*it);
1918 }
1919 }
1920 if (new_codecs.empty()) {
1921 // There are no new codecs to configure. Already configured codecs are
1922 // never removed.
1923 return true;
1924 }
1925
1926 if (playout_) {
1927 // Receive codecs can not be changed while playing. So we temporarily
1928 // pause playout.
1929 PausePlayout();
1930 }
1931
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001932 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001933 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1934 it != new_codecs.end() && ret; ++it) {
1935 webrtc::CodecInst voe_codec;
1936 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1937 LOG(LS_INFO) << ToString(*it);
1938 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001939 if (default_receive_ssrc_ == 0) {
1940 // Set the receive codecs on the default channel explicitly if the
1941 // default channel is not used by |receive_channels_|, this happens in
1942 // conference mode or in non-conference mode when there is no playout
1943 // channel.
1944 // TODO(xians): Figure out how we use the default channel in conference
1945 // mode.
1946 if (engine()->voe()->codec()->SetRecPayloadType(
1947 voe_channel(), voe_codec) == -1) {
1948 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1949 ret = false;
1950 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001951 }
1952
1953 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001954 for (ChannelMap::iterator it = receive_channels_.begin();
1955 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001956 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001957 it->second->channel(), voe_codec) == -1) {
1958 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001959 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001960 ret = false;
1961 }
1962 }
1963 } else {
1964 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1965 ret = false;
1966 }
1967 }
1968 if (ret) {
1969 recv_codecs_ = codecs;
1970 }
1971
1972 if (desired_playout_ && !playout_) {
1973 ResumePlayout();
1974 }
1975 return ret;
1976}
1977
1978bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001979 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001980 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001981 engine()->voe()->codec()->SetVADStatus(channel, false);
1982 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001983#ifdef USE_WEBRTC_DEV_BRANCH
1984 engine()->voe()->rtp()->SetREDStatus(channel, false);
1985 engine()->voe()->codec()->SetFECStatus(channel, false);
1986#else
1987 // TODO(minyue): Remove code under #else case after new WebRTC roll.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001988 engine()->voe()->rtp()->SetFECStatus(channel, false);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001989#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001990
1991 // Scan through the list to figure out the codec to use for sending, along
1992 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001993 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001994 webrtc::CodecInst send_codec;
1995 memset(&send_codec, 0, sizeof(send_codec));
1996
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001997 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001998 bool enable_codec_fec = false;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001999
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002000 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002001 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2002 it != codecs.end(); ++it) {
2003 // Ignore codecs we don't know about. The negotiation step should prevent
2004 // this, but double-check to be sure.
2005 webrtc::CodecInst voe_codec;
2006 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002007 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002008 continue;
2009 }
2010
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002011 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2012 // Skip telephone-event/CN codec, which will be handled later.
2013 continue;
2014 }
2015
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002016 // If OPUS, change what we send according to the "stereo" codec
2017 // parameter, and not the "channels" parameter. We set
2018 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
2019 // the bitrate is not specified, i.e. is zero, we set it to the
2020 // appropriate default value for mono or stereo Opus.
2021 if (IsOpus(*it)) {
2022 if (IsOpusStereoEnabled(*it)) {
2023 voe_codec.channels = 2;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002024 if (!IsValidOpusBitrate(it->bitrate)) {
2025 if (it->bitrate != 0) {
2026 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2027 << it->bitrate
2028 << ") with default opus stereo bitrate: "
2029 << kOpusStereoBitrate;
2030 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002031 voe_codec.rate = kOpusStereoBitrate;
2032 }
2033 } else {
2034 voe_codec.channels = 1;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002035 if (!IsValidOpusBitrate(it->bitrate)) {
2036 if (it->bitrate != 0) {
2037 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2038 << it->bitrate
2039 << ") with default opus mono bitrate: "
2040 << kOpusMonoBitrate;
2041 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002042 voe_codec.rate = kOpusMonoBitrate;
2043 }
2044 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002045 int bitrate_from_params = GetOpusBitrateFromParams(*it);
2046 if (bitrate_from_params != 0) {
2047 voe_codec.rate = bitrate_from_params;
2048 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002049 }
2050
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002051 // We'll use the first codec in the list to actually send audio data.
2052 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002053 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002054 // used is specified in params.
2055 if (IsRedCodec(it->name)) {
2056 // Parse out the RED parameters. If we fail, just ignore RED;
2057 // we don't support all possible params/usage scenarios.
2058 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2059 continue;
2060 }
2061
2062 // Enable redundant encoding of the specified codec. Treat any
2063 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002064#ifdef USE_WEBRTC_DEV_BRANCH
2065 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2066 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2067 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
2068#else
2069 // TODO(minyue): Remove code under #else case after new WebRTC roll.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002070 LOG(LS_INFO) << "Enabling FEC";
2071 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2072 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002073#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002074 return false;
2075 }
2076 } else {
2077 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002078 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002079 // For Opus as the send codec, we enable inband FEC if requested.
2080 enable_codec_fec = IsOpus(*it) && IsOpusFecEnabled(*it);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002081 }
2082 found_send_codec = true;
2083 break;
2084 }
2085
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002086 if (nack_enabled_ != nack_enabled) {
2087 SetNack(channel, nack_enabled);
2088 nack_enabled_ = nack_enabled;
2089 }
2090
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002091 if (!found_send_codec) {
2092 LOG(LS_WARNING) << "Received empty list of codecs.";
2093 return false;
2094 }
2095
2096 // Set the codec immediately, since SetVADStatus() depends on whether
2097 // the current codec is mono or stereo.
2098 if (!SetSendCodec(channel, send_codec))
2099 return false;
2100
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002101 // FEC should be enabled after SetSendCodec.
2102 if (enable_codec_fec) {
2103 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2104 << channel;
2105#ifdef USE_WEBRTC_DEV_BRANCH
2106 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2107 // Enable codec internal FEC. Treat any failure as fatal internal error.
2108 LOG_RTCERR2(SetFECStatus, channel, true);
2109 return false;
2110 }
2111#endif // USE_WEBRTC_DEV_BRANCH
2112 }
2113
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002114 // Always update the |send_codec_| to the currently set send codec.
2115 send_codec_.reset(new webrtc::CodecInst(send_codec));
2116
2117 if (send_bw_setting_) {
2118 SetSendBandwidthInternal(send_bw_bps_);
2119 }
2120
2121 // Loop through the codecs list again to config the telephone-event/CN codec.
2122 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2123 it != codecs.end(); ++it) {
2124 // Ignore codecs we don't know about. The negotiation step should prevent
2125 // this, but double-check to be sure.
2126 webrtc::CodecInst voe_codec;
2127 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2128 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2129 continue;
2130 }
2131
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002132 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2133 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002134 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002135 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2136 channel, it->id) == -1) {
2137 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2138 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002139 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002140 } else if (IsCNCodec(it->name)) {
2141 // Turn voice activity detection/comfort noise on if supported.
2142 // Set the wideband CN payload type appropriately.
2143 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002144 webrtc::PayloadFrequencies cn_freq;
2145 switch (it->clockrate) {
2146 case 8000:
2147 cn_freq = webrtc::kFreq8000Hz;
2148 break;
2149 case 16000:
2150 cn_freq = webrtc::kFreq16000Hz;
2151 break;
2152 case 32000:
2153 cn_freq = webrtc::kFreq32000Hz;
2154 break;
2155 default:
2156 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2157 << " not supported.";
2158 continue;
2159 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002160 // Set the CN payloadtype and the VAD status.
2161 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2162 if (cn_freq != webrtc::kFreq8000Hz) {
2163 if (engine()->voe()->codec()->SetSendCNPayloadType(
2164 channel, it->id, cn_freq) == -1) {
2165 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2166 // TODO(ajm): This failure condition will be removed from VoE.
2167 // Restore the return here when we update to a new enough webrtc.
2168 //
2169 // Not returning false because the SetSendCNPayloadType will fail if
2170 // the channel is already sending.
2171 // This can happen if the remote description is applied twice, for
2172 // example in the case of ROAP on top of JSEP, where both side will
2173 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002174 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002175 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002176 // Only turn on VAD if we have a CN payload type that matches the
2177 // clockrate for the codec we are going to use.
2178 if (it->clockrate == send_codec.plfreq) {
2179 LOG(LS_INFO) << "Enabling VAD";
2180 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2181 LOG_RTCERR2(SetVADStatus, channel, true);
2182 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002183 }
2184 }
2185 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002186 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002187 return true;
2188}
2189
2190bool WebRtcVoiceMediaChannel::SetSendCodecs(
2191 const std::vector<AudioCodec>& codecs) {
2192 dtmf_allowed_ = false;
2193 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2194 it != codecs.end(); ++it) {
2195 // Find the DTMF telephone event "codec".
2196 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2197 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2198 dtmf_allowed_ = true;
2199 }
2200 }
2201
2202 // Cache the codecs in order to configure the channel created later.
2203 send_codecs_ = codecs;
2204 for (ChannelMap::iterator iter = send_channels_.begin();
2205 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002206 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002207 return false;
2208 }
2209 }
2210
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002211 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002212 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002213 return true;
2214}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002215
2216void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2217 bool nack_enabled) {
2218 for (ChannelMap::const_iterator it = channels.begin();
2219 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002220 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002221 }
2222}
2223
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002224void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002225 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002226 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002227 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2228 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002229 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002230 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2231 }
2232}
2233
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002234bool WebRtcVoiceMediaChannel::SetSendCodec(
2235 const webrtc::CodecInst& send_codec) {
2236 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2237 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002238 for (ChannelMap::iterator iter = send_channels_.begin();
2239 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002240 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002241 return false;
2242 }
2243
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002244 return true;
2245}
2246
2247bool WebRtcVoiceMediaChannel::SetSendCodec(
2248 int channel, const webrtc::CodecInst& send_codec) {
2249 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2250 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2251
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002252 webrtc::CodecInst current_codec;
2253 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2254 (send_codec == current_codec)) {
2255 // Codec is already configured, we can return without setting it again.
2256 return true;
2257 }
2258
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002259 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2260 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002261 return false;
2262 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002263 return true;
2264}
2265
2266bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2267 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002268 if (receive_extensions_ == extensions) {
2269 return true;
2270 }
2271
2272 // The default channel may or may not be in |receive_channels_|. Set the rtp
2273 // header extensions for default channel regardless.
2274 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2275 return false;
2276 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002277
2278 // Loop through all receive channels and enable/disable the extensions.
2279 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2280 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002281 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2282 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002283 return false;
2284 }
2285 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002286
2287 receive_extensions_ = extensions;
2288 return true;
2289}
2290
2291bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2292 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002293 const RtpHeaderExtension* audio_level_extension =
2294 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2295 if (!SetHeaderExtension(
2296 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2297 audio_level_extension)) {
2298 return false;
2299 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002300
2301 const RtpHeaderExtension* send_time_extension =
2302 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2303 if (!SetHeaderExtension(
2304 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2305 send_time_extension)) {
2306 return false;
2307 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002308 return true;
2309}
2310
2311bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2312 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002313 if (send_extensions_ == extensions) {
2314 return true;
2315 }
2316
2317 // The default channel may or may not be in |send_channels_|. Set the rtp
2318 // header extensions for default channel regardless.
2319
2320 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2321 return false;
2322 }
2323
2324 // Loop through all send channels and enable/disable the extensions.
2325 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2326 channel_it != send_channels_.end(); ++channel_it) {
2327 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2328 extensions)) {
2329 return false;
2330 }
2331 }
2332
2333 send_extensions_ = extensions;
2334 return true;
2335}
2336
2337bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2338 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002339 const RtpHeaderExtension* audio_level_extension =
2340 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002341
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002342 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002343 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002344 audio_level_extension)) {
2345 return false;
2346 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002347
2348 const RtpHeaderExtension* send_time_extension =
2349 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002350 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002351 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002352 send_time_extension)) {
2353 return false;
2354 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002355
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002356 return true;
2357}
2358
2359bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2360 desired_playout_ = playout;
2361 return ChangePlayout(desired_playout_);
2362}
2363
2364bool WebRtcVoiceMediaChannel::PausePlayout() {
2365 return ChangePlayout(false);
2366}
2367
2368bool WebRtcVoiceMediaChannel::ResumePlayout() {
2369 return ChangePlayout(desired_playout_);
2370}
2371
2372bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2373 if (playout_ == playout) {
2374 return true;
2375 }
2376
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002377 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002378 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002379 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002380 // Only toggle the default channel if we don't have any other channels.
2381 result = SetPlayout(voe_channel(), playout);
2382 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002383 for (ChannelMap::iterator it = receive_channels_.begin();
2384 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002385 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002386 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002387 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002388 result = false;
2389 }
2390 }
2391
2392 if (result) {
2393 playout_ = playout;
2394 }
2395 return result;
2396}
2397
2398bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2399 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002400 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002401 return ChangeSend(desired_send_);
2402 return true;
2403}
2404
2405bool WebRtcVoiceMediaChannel::PauseSend() {
2406 return ChangeSend(SEND_NOTHING);
2407}
2408
2409bool WebRtcVoiceMediaChannel::ResumeSend() {
2410 return ChangeSend(desired_send_);
2411}
2412
2413bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2414 if (send_ == send) {
2415 return true;
2416 }
2417
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002418 // Change the settings on each send channel.
2419 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002420 engine()->SetOptionOverrides(options_);
2421
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002422 // Change the settings on each send channel.
2423 for (ChannelMap::iterator iter = send_channels_.begin();
2424 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002425 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002426 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002427 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002428
2429 // Clear up the options after stopping sending.
2430 if (send == SEND_NOTHING)
2431 engine()->ClearOptionOverrides();
2432
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002433 send_ = send;
2434 return true;
2435}
2436
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002437bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2438 if (send == SEND_MICROPHONE) {
2439 if (engine()->voe()->base()->StartSend(channel) == -1) {
2440 LOG_RTCERR1(StartSend, channel);
2441 return false;
2442 }
2443 if (engine()->voe()->file() &&
2444 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2445 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2446 return false;
2447 }
2448 } else { // SEND_NOTHING
2449 ASSERT(send == SEND_NOTHING);
2450 if (engine()->voe()->base()->StopSend(channel) == -1) {
2451 LOG_RTCERR1(StopSend, channel);
2452 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002453 }
2454 }
2455
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002456 return true;
2457}
2458
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002459// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002460void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2461 if (engine()->voe()->network()->RegisterExternalTransport(
2462 channel, *this) == -1) {
2463 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2464 }
2465
2466 // Enable RTCP (for quality stats and feedback messages)
2467 EnableRtcp(channel);
2468
2469 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2470 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002471
2472 // Set RTP header extension for the new channel.
2473 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002474}
2475
2476bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2477 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2478 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2479 }
2480
2481 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2482 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002483 return false;
2484 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002485
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002486 return true;
2487}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002488
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002489bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2490 // If the default channel is already used for sending create a new channel
2491 // otherwise use the default channel for sending.
2492 int channel = GetSendChannelNum(sp.first_ssrc());
2493 if (channel != -1) {
2494 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2495 return false;
2496 }
2497
2498 bool default_channel_is_available = true;
2499 for (ChannelMap::const_iterator iter = send_channels_.begin();
2500 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002501 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002502 default_channel_is_available = false;
2503 break;
2504 }
2505 }
2506 if (default_channel_is_available) {
2507 channel = voe_channel();
2508 } else {
2509 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002510 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002511 if (channel == -1) {
2512 LOG_RTCERR0(CreateChannel);
2513 return false;
2514 }
2515
2516 ConfigureSendChannel(channel);
2517 }
2518
2519 // Save the channel to send_channels_, so that RemoveSendStream() can still
2520 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002521 webrtc::AudioTransport* audio_transport =
2522 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002523 send_channels_.insert(std::make_pair(
2524 sp.first_ssrc(),
2525 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002526
2527 // Set the send (local) SSRC.
2528 // If there are multiple send SSRCs, we can only set the first one here, and
2529 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2530 // (with a codec requires multiple SSRC(s)).
2531 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2532 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2533 return false;
2534 }
2535
2536 // At this point the channel's local SSRC has been updated. If the channel is
2537 // the default channel make sure that all the receive channels are updated as
2538 // well. Receive channels have to have the same SSRC as the default channel in
2539 // order to send receiver reports with this SSRC.
2540 if (IsDefaultChannel(channel)) {
2541 for (ChannelMap::const_iterator it = receive_channels_.begin();
2542 it != receive_channels_.end(); ++it) {
2543 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002544 if (!IsDefaultChannel(it->second->channel())) {
2545 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002546 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002547 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002548 return false;
2549 }
2550 }
2551 }
2552 }
2553
2554 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
2555 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2556 return false;
2557 }
2558
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002559 // Set the current codecs to be used for the new channel.
2560 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002561 return false;
2562
2563 return ChangeSend(channel, desired_send_);
2564}
2565
2566bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2567 ChannelMap::iterator it = send_channels_.find(ssrc);
2568 if (it == send_channels_.end()) {
2569 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2570 << " which doesn't exist.";
2571 return false;
2572 }
2573
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002574 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002575 ChangeSend(channel, SEND_NOTHING);
2576
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002577 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2578 // this will disconnect the audio renderer with the send channel.
2579 delete it->second;
2580 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002581
2582 if (IsDefaultChannel(channel)) {
2583 // Do not delete the default channel since the receive channels depend on
2584 // the default channel, recycle it instead.
2585 ChangeSend(channel, SEND_NOTHING);
2586 } else {
2587 // Clean up and delete the send channel.
2588 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2589 << " with VoiceEngine channel #" << channel << ".";
2590 if (!DeleteChannel(channel))
2591 return false;
2592 }
2593
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002594 if (send_channels_.empty())
2595 ChangeSend(SEND_NOTHING);
2596
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002597 return true;
2598}
2599
2600bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002601 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002602
2603 if (!VERIFY(sp.ssrcs.size() == 1))
2604 return false;
2605 uint32 ssrc = sp.first_ssrc();
2606
wu@webrtc.org78187522013-10-07 23:32:02 +00002607 if (ssrc == 0) {
2608 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2609 return false;
2610 }
2611
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002612 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2613 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002614 return false;
2615 }
2616
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002617 // Reuse default channel for recv stream in non-conference mode call
2618 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002619 webrtc::AudioTransport* audio_transport =
2620 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002621 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2622 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2623 << " reuse default channel";
2624 default_receive_ssrc_ = sp.first_ssrc();
2625 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002626 default_receive_ssrc_,
2627 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002628 return SetPlayout(voe_channel(), playout_);
2629 }
2630
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002631 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002632 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002633 if (channel == -1) {
2634 LOG_RTCERR0(CreateChannel);
2635 return false;
2636 }
2637
wu@webrtc.org78187522013-10-07 23:32:02 +00002638 if (!ConfigureRecvChannel(channel)) {
2639 DeleteChannel(channel);
2640 return false;
2641 }
2642
2643 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002644 std::make_pair(
2645 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002646
2647 LOG(LS_INFO) << "New audio stream " << ssrc
2648 << " registered to VoiceEngine channel #"
2649 << channel << ".";
2650 return true;
2651}
2652
2653bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002654 // Configure to use external transport, like our default channel.
2655 if (engine()->voe()->network()->RegisterExternalTransport(
2656 channel, *this) == -1) {
2657 LOG_RTCERR2(SetExternalTransport, channel, this);
2658 return false;
2659 }
2660
2661 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002662 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002663 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2664 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002665 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002666 return false;
2667 }
2668 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002669 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002670 return false;
2671 }
2672
2673 // Use the same recv payload types as our default channel.
2674 ResetRecvCodecs(channel);
2675 if (!recv_codecs_.empty()) {
2676 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2677 it != recv_codecs_.end(); ++it) {
2678 webrtc::CodecInst voe_codec;
2679 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2680 voe_codec.pltype = it->id;
2681 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2682 if (engine()->voe()->codec()->GetRecPayloadType(
2683 voe_channel(), voe_codec) != -1) {
2684 if (engine()->voe()->codec()->SetRecPayloadType(
2685 channel, voe_codec) == -1) {
2686 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2687 return false;
2688 }
2689 }
2690 }
2691 }
2692 }
2693
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002694 if (InConferenceMode()) {
2695 // To be in par with the video, voe_channel() is not used for receiving in
2696 // a conference call.
2697 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2698 // This is the first stream in a multi user meeting. We can now
2699 // disable playback of the default stream. This since the default
2700 // stream will probably have received some initial packets before
2701 // the new stream was added. This will mean that the CN state from
2702 // the default channel will be mixed in with the other streams
2703 // throughout the whole meeting, which might be disturbing.
2704 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2705 SetPlayout(voe_channel(), false);
2706 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002707 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002708 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002709
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002710 // Set RTP header extension for the new channel.
2711 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2712 return false;
2713 }
2714
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002715 return SetPlayout(channel, playout_);
2716}
2717
2718bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002719 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002720 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002721 if (it == receive_channels_.end()) {
2722 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2723 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002724 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002725 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002726
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002727 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2728 // will disconnect the audio renderer with the receive channel.
2729 // Cache the channel before the deletion.
2730 const int channel = it->second->channel();
2731 delete it->second;
2732 receive_channels_.erase(it);
2733
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002734 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002735 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002736 // Recycle the default channel is for recv stream.
2737 if (playout_)
2738 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002739
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002740 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002741 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002742 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002743
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002744 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002745 << " with VoiceEngine channel #" << channel << ".";
2746 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002747 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002748
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002749 bool enable_default_channel_playout = false;
2750 if (receive_channels_.empty()) {
2751 // The last stream was removed. We can now enable the default
2752 // channel for new channels to be played out immediately without
2753 // waiting for AddStream messages.
2754 // We do this for both conference mode and non-conference mode.
2755 // TODO(oja): Does the default channel still have it's CN state?
2756 enable_default_channel_playout = true;
2757 }
2758 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2759 default_receive_ssrc_ != 0) {
2760 // Only the default channel is active, enable the playout on default
2761 // channel.
2762 enable_default_channel_playout = true;
2763 }
2764 if (enable_default_channel_playout && playout_) {
2765 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2766 SetPlayout(voe_channel(), true);
2767 }
2768
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002769 return true;
2770}
2771
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002772bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2773 AudioRenderer* renderer) {
2774 ChannelMap::iterator it = receive_channels_.find(ssrc);
2775 if (it == receive_channels_.end()) {
2776 if (renderer) {
2777 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002778 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002779 return false;
2780 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002781
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002782 // The channel likely has gone away, do nothing.
2783 return true;
2784 }
2785
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002786 if (renderer)
2787 it->second->Start(renderer);
2788 else
2789 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002790
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002791 return true;
2792}
2793
2794bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2795 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002796 ChannelMap::iterator it = send_channels_.find(ssrc);
2797 if (it == send_channels_.end()) {
2798 if (renderer) {
2799 // Return an error if trying to set a valid renderer with an invalid ssrc.
2800 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2801 return false;
2802 }
2803
2804 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002805 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002806 }
2807
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002808 if (renderer)
2809 it->second->Start(renderer);
2810 else
2811 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002812
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002813 return true;
2814}
2815
2816bool WebRtcVoiceMediaChannel::GetActiveStreams(
2817 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002818 // In conference mode, the default channel should not be in
2819 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002820 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002821 for (ChannelMap::iterator it = receive_channels_.begin();
2822 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002823 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002824 if (level > 0) {
2825 actives->push_back(std::make_pair(it->first, level));
2826 }
2827 }
2828 return true;
2829}
2830
2831int WebRtcVoiceMediaChannel::GetOutputLevel() {
2832 // return the highest output level of all streams
2833 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002834 for (ChannelMap::iterator it = receive_channels_.begin();
2835 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002836 int level = GetOutputLevel(it->second->channel());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002837 highest = rtc::_max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002838 }
2839 return highest;
2840}
2841
2842int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2843 int ret;
2844 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2845 // In case of error, log the info and continue
2846 LOG_RTCERR0(TimeSinceLastTyping);
2847 ret = -1;
2848 } else {
2849 ret *= 1000; // We return ms, webrtc returns seconds.
2850 }
2851 return ret;
2852}
2853
2854void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2855 int cost_per_typing, int reporting_threshold, int penalty_decay,
2856 int type_event_delay) {
2857 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2858 time_window, cost_per_typing,
2859 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2860 // In case of error, log the info and continue
2861 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2862 cost_per_typing, reporting_threshold, penalty_decay,
2863 type_event_delay);
2864 }
2865}
2866
2867bool WebRtcVoiceMediaChannel::SetOutputScaling(
2868 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002869 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002870 // Collect the channels to scale the output volume.
2871 std::vector<int> channels;
2872 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002873 // Default channel is not in receive_channels_ if it is not being used for
2874 // playout.
2875 if (default_receive_ssrc_ == 0)
2876 channels.push_back(voe_channel());
2877 for (ChannelMap::const_iterator it = receive_channels_.begin();
2878 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002879 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002880 }
2881 } else { // Collect only the channel of the specified ssrc.
2882 int channel = GetReceiveChannelNum(ssrc);
2883 if (-1 == channel) {
2884 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2885 return false;
2886 }
2887 channels.push_back(channel);
2888 }
2889
2890 // Scale the output volume for the collected channels. We first normalize to
2891 // scale the volume and then set the left and right pan.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002892 float scale = static_cast<float>(rtc::_max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002893 if (scale > 0.0001f) {
2894 left /= scale;
2895 right /= scale;
2896 }
2897 for (std::vector<int>::const_iterator it = channels.begin();
2898 it != channels.end(); ++it) {
2899 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2900 *it, scale)) {
2901 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2902 return false;
2903 }
2904 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2905 *it, static_cast<float>(left), static_cast<float>(right))) {
2906 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2907 // Do not return if fails. SetOutputVolumePan is not available for all
2908 // pltforms.
2909 }
2910 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2911 << " right=" << right * scale
2912 << " for channel " << *it << " and ssrc " << ssrc;
2913 }
2914 return true;
2915}
2916
2917bool WebRtcVoiceMediaChannel::GetOutputScaling(
2918 uint32 ssrc, double* left, double* right) {
2919 if (!left || !right) return false;
2920
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002921 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002922 // Determine which channel based on ssrc.
2923 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2924 if (channel == -1) {
2925 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2926 return false;
2927 }
2928
2929 float scaling;
2930 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2931 channel, scaling)) {
2932 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2933 return false;
2934 }
2935
2936 float left_pan;
2937 float right_pan;
2938 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2939 channel, left_pan, right_pan)) {
2940 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2941 // If GetOutputVolumePan fails, we use the default left and right pan.
2942 left_pan = 1.0f;
2943 right_pan = 1.0f;
2944 }
2945
2946 *left = scaling * left_pan;
2947 *right = scaling * right_pan;
2948 return true;
2949}
2950
2951bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2952 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2953 return true;
2954}
2955
2956bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2957 bool play, bool loop) {
2958 if (!ringback_tone_) {
2959 return false;
2960 }
2961
2962 // The voe file api is not available in chrome.
2963 if (!engine()->voe()->file()) {
2964 return false;
2965 }
2966
2967 // Determine which VoiceEngine channel to play on.
2968 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2969 if (channel == -1) {
2970 return false;
2971 }
2972
2973 // Make sure the ringtone is cued properly, and play it out.
2974 if (play) {
2975 ringback_tone_->set_loop(loop);
2976 ringback_tone_->Rewind();
2977 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2978 ringback_tone_.get()) == -1) {
2979 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2980 LOG(LS_ERROR) << "Unable to start ringback tone";
2981 return false;
2982 }
2983 ringback_channels_.insert(channel);
2984 LOG(LS_INFO) << "Started ringback on channel " << channel;
2985 } else {
2986 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2987 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2988 LOG_RTCERR1(StopPlayingFileLocally, channel);
2989 return false;
2990 }
2991 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2992 ringback_channels_.erase(channel);
2993 }
2994
2995 return true;
2996}
2997
2998bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2999 return dtmf_allowed_;
3000}
3001
3002bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3003 int duration, int flags) {
3004 if (!dtmf_allowed_) {
3005 return false;
3006 }
3007
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003008 // Send the event.
3009 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003010 int channel = -1;
3011 if (ssrc == 0) {
3012 bool default_channel_is_inuse = false;
3013 for (ChannelMap::const_iterator iter = send_channels_.begin();
3014 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003015 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003016 default_channel_is_inuse = true;
3017 break;
3018 }
3019 }
3020 if (default_channel_is_inuse) {
3021 channel = voe_channel();
3022 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003023 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003024 }
3025 } else {
3026 channel = GetSendChannelNum(ssrc);
3027 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003028 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003029 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3030 << ssrc << " is not in use.";
3031 return false;
3032 }
3033 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003034 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3035 channel, event, true, duration) == -1) {
3036 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003037 return false;
3038 }
3039 }
3040
3041 // Play the event.
3042 if (flags & cricket::DF_PLAY) {
3043 // Play DTMF tone locally.
3044 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3045 LOG_RTCERR2(PlayDtmfTone, event, duration);
3046 return false;
3047 }
3048 }
3049
3050 return true;
3051}
3052
wu@webrtc.orga9890802013-12-13 00:21:03 +00003053void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003054 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003055 // Pick which channel to send this packet to. If this packet doesn't match
3056 // any multiplexed streams, just send it to the default channel. Otherwise,
3057 // send it to the specific decoder instance for that stream.
3058 int which_channel = GetReceiveChannelNum(
3059 ParseSsrc(packet->data(), packet->length(), false));
3060 if (which_channel == -1) {
3061 which_channel = voe_channel();
3062 }
3063
3064 // Stop any ringback that might be playing on the channel.
3065 // It's possible the ringback has already stopped, ih which case we'll just
3066 // use the opportunity to remove the channel from ringback_channels_.
3067 if (engine()->voe()->file()) {
3068 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3069 if (it != ringback_channels_.end()) {
3070 if (engine()->voe()->file()->IsPlayingFileLocally(
3071 which_channel) == 1) {
3072 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3073 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3074 << " due to incoming media";
3075 }
3076 ringback_channels_.erase(which_channel);
3077 }
3078 }
3079
3080 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003081 engine()->voe()->network()->ReceivedRTPPacket(
3082 which_channel,
3083 packet->data(),
3084 static_cast<unsigned int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003085}
3086
wu@webrtc.orga9890802013-12-13 00:21:03 +00003087void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003088 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003089 // Sending channels need all RTCP packets with feedback information.
3090 // Even sender reports can contain attached report blocks.
3091 // Receiving channels need sender reports in order to create
3092 // correct receiver reports.
3093 int type = 0;
3094 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3095 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3096 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003097 }
3098
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003099 // If it is a sender report, find the channel that is listening.
3100 bool has_sent_to_default_channel = false;
3101 if (type == kRtcpTypeSR) {
3102 int which_channel = GetReceiveChannelNum(
3103 ParseSsrc(packet->data(), packet->length(), true));
3104 if (which_channel != -1) {
3105 engine()->voe()->network()->ReceivedRTCPPacket(
3106 which_channel,
3107 packet->data(),
3108 static_cast<unsigned int>(packet->length()));
3109
3110 if (IsDefaultChannel(which_channel))
3111 has_sent_to_default_channel = true;
3112 }
3113 }
3114
3115 // SR may continue RR and any RR entry may correspond to any one of the send
3116 // channels. So all RTCP packets must be forwarded all send channels. VoE
3117 // will filter out RR internally.
3118 for (ChannelMap::iterator iter = send_channels_.begin();
3119 iter != send_channels_.end(); ++iter) {
3120 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003121 if (IsDefaultChannel(iter->second->channel()) &&
3122 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003123 continue;
3124
3125 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003126 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003127 packet->data(),
3128 static_cast<unsigned int>(packet->length()));
3129 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003130}
3131
3132bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003133 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3134 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003135 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3136 return false;
3137 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003138 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3139 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003140 return false;
3141 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003142 // We set the AGC to mute state only when all the channels are muted.
3143 // This implementation is not ideal, instead we should signal the AGC when
3144 // the mic channel is muted/unmuted. We can't do it today because there
3145 // is no good way to know which stream is mapping to the mic channel.
3146 bool all_muted = muted;
3147 for (ChannelMap::const_iterator iter = send_channels_.begin();
3148 iter != send_channels_.end() && all_muted; ++iter) {
3149 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3150 all_muted)) {
3151 LOG_RTCERR1(GetInputMute, iter->second->channel());
3152 return false;
3153 }
3154 }
3155
3156 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3157 if (ap)
3158 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003159 return true;
3160}
3161
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003162bool WebRtcVoiceMediaChannel::SetStartSendBandwidth(int bps) {
3163 // TODO(andresp): Add support for setting an independent start bandwidth when
3164 // bandwidth estimation is enabled for voice engine.
3165 return false;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003166}
3167
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003168bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
3169 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
3170
3171 return SetSendBandwidthInternal(bps);
3172}
3173
3174bool WebRtcVoiceMediaChannel::SetSendBandwidthInternal(int bps) {
3175 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBandwidthInternal.";
3176
3177 send_bw_setting_ = true;
3178 send_bw_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003179
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003180 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003181 LOG(LS_INFO) << "The send codec has not been set up yet. "
3182 << "The send bandwidth setting will be applied later.";
3183 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003184 }
3185
3186 // Bandwidth is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003187 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3188 // SetMaxSendBandwith(0), the second call removes the previous limit.
3189 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003190 return true;
3191
3192 webrtc::CodecInst codec = *send_codec_;
3193 bool is_multi_rate = IsCodecMultiRate(codec);
3194
3195 if (is_multi_rate) {
3196 // If codec is multi-rate then just set the bitrate.
3197 codec.rate = bps;
3198 if (!SetSendCodec(codec)) {
3199 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3200 << " to bitrate " << bps << " bps.";
3201 return false;
3202 }
3203 return true;
3204 } else {
3205 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3206 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3207 // fixed bitrate then ignore.
3208 if (bps < codec.rate) {
3209 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3210 << " to bitrate " << bps << " bps"
3211 << ", requires at least " << codec.rate << " bps.";
3212 return false;
3213 }
3214 return true;
3215 }
3216}
3217
3218bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003219 bool echo_metrics_on = false;
3220 // These can take on valid negative values, so use the lowest possible level
3221 // as default rather than -1.
3222 int echo_return_loss = -100;
3223 int echo_return_loss_enhancement = -100;
3224 // These can also be negative, but in practice -1 is only used to signal
3225 // insufficient data, since the resolution is limited to multiples of 4 ms.
3226 int echo_delay_median_ms = -1;
3227 int echo_delay_std_ms = -1;
3228 if (engine()->voe()->processing()->GetEcMetricsStatus(
3229 echo_metrics_on) != -1 && echo_metrics_on) {
3230 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3231 // here, but it appears to be unsuitable currently. Revisit after this is
3232 // investigated: http://b/issue?id=5666755
3233 int erl, erle, rerl, anlp;
3234 if (engine()->voe()->processing()->GetEchoMetrics(
3235 erl, erle, rerl, anlp) != -1) {
3236 echo_return_loss = erl;
3237 echo_return_loss_enhancement = erle;
3238 }
3239
3240 int median, std;
3241 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3242 echo_delay_median_ms = median;
3243 echo_delay_std_ms = std;
3244 }
3245 }
3246
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003247 webrtc::CallStatistics cs;
3248 unsigned int ssrc;
3249 webrtc::CodecInst codec;
3250 unsigned int level;
3251
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003252 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3253 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003254 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003255
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003256 // Fill in the sender info, based on what we know, and what the
3257 // remote side told us it got from its RTCP report.
3258 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003259
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003260 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3261 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3262 continue;
3263 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003264
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003265 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003266 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3267 sinfo.bytes_sent = cs.bytesSent;
3268 sinfo.packets_sent = cs.packetsSent;
3269 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3270 // returns 0 to indicate an error value.
3271 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3272
3273 // Get data from the last remote RTCP report. Use default values if no data
3274 // available.
3275 sinfo.fraction_lost = -1.0;
3276 sinfo.jitter_ms = -1;
3277 sinfo.packets_lost = -1;
3278 sinfo.ext_seqnum = -1;
3279 std::vector<webrtc::ReportBlock> receive_blocks;
3280 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3281 channel, &receive_blocks) != -1 &&
3282 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3283 std::vector<webrtc::ReportBlock>::iterator iter;
3284 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3285 ++iter) {
3286 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003287 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003288 // Convert Q8 to floating point.
3289 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3290 // Convert samples to milliseconds.
3291 if (codec.plfreq / 1000 > 0) {
3292 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3293 }
3294 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3295 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3296 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003297 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003298 }
3299 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003300
3301 // Local speech level.
3302 sinfo.audio_level = (engine()->voe()->volume()->
3303 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3304
3305 // TODO(xians): We are injecting the same APM logging to all the send
3306 // channels here because there is no good way to know which send channel
3307 // is using the APM. The correct fix is to allow the send channels to have
3308 // their own APM so that we can feed the correct APM logging to different
3309 // send channels. See issue crbug/264611 .
3310 sinfo.echo_return_loss = echo_return_loss;
3311 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3312 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3313 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003314 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3315 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003316 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003317
3318 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003319 }
3320
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003321 // Build the list of receivers, one for each receiving channel, or 1 in
3322 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003323 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003324 for (ChannelMap::const_iterator it = receive_channels_.begin();
3325 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003326 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003327 }
3328 if (channels.empty()) {
3329 channels.push_back(voe_channel());
3330 }
3331
3332 // Get the SSRC and stats for each receiver, based on our own calculations.
3333 for (std::vector<int>::const_iterator it = channels.begin();
3334 it != channels.end(); ++it) {
3335 memset(&cs, 0, sizeof(cs));
3336 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3337 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3338 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3339 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003340 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003341 rinfo.bytes_rcvd = cs.bytesReceived;
3342 rinfo.packets_rcvd = cs.packetsReceived;
3343 // The next four fields are from the most recently sent RTCP report.
3344 // Convert Q8 to floating point.
3345 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3346 rinfo.packets_lost = cs.cumulativeLost;
3347 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003348#ifdef USE_WEBRTC_DEV_BRANCH
3349 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
3350#endif
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003351 if (codec.pltype != -1) {
3352 rinfo.codec_name = codec.plname;
3353 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003354 // Convert samples to milliseconds.
3355 if (codec.plfreq / 1000 > 0) {
3356 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3357 }
3358
3359 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3360 webrtc::NetworkStatistics ns;
3361 if (engine()->voe()->neteq() &&
3362 engine()->voe()->neteq()->GetNetworkStatistics(
3363 *it, ns) != -1) {
3364 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3365 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3366 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003367 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003368 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003369
3370 webrtc::AudioDecodingCallStats ds;
3371 if (engine()->voe()->neteq() &&
3372 engine()->voe()->neteq()->GetDecodingCallStatistics(
3373 *it, &ds) != -1) {
3374 rinfo.decoding_calls_to_silence_generator =
3375 ds.calls_to_silence_generator;
3376 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3377 rinfo.decoding_normal = ds.decoded_normal;
3378 rinfo.decoding_plc = ds.decoded_plc;
3379 rinfo.decoding_cng = ds.decoded_cng;
3380 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3381 }
3382
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003383 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003384 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003385 int playout_buffer_delay_ms = 0;
3386 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003387 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3388 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3389 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003390 }
3391
3392 // Get speech level.
3393 rinfo.audio_level = (engine()->voe()->volume()->
3394 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3395 info->receivers.push_back(rinfo);
3396 }
3397 }
3398
3399 return true;
3400}
3401
3402void WebRtcVoiceMediaChannel::GetLastMediaError(
3403 uint32* ssrc, VoiceMediaChannel::Error* error) {
3404 ASSERT(ssrc != NULL);
3405 ASSERT(error != NULL);
3406 FindSsrc(voe_channel(), ssrc);
3407 *error = WebRtcErrorToChannelError(GetLastEngineError());
3408}
3409
3410bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003411 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003412 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003413 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003414 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3415 // This means the error is not limited to a specific channel. Signal the
3416 // message using ssrc=0. If the current channel is sending, use this
3417 // channel for sending the message.
3418 *ssrc = 0;
3419 return true;
3420 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003421 // Check whether this is a sending channel.
3422 for (ChannelMap::const_iterator it = send_channels_.begin();
3423 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003424 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003425 // This is a sending channel.
3426 uint32 local_ssrc = 0;
3427 if (engine()->voe()->rtp()->GetLocalSSRC(
3428 channel_num, local_ssrc) != -1) {
3429 *ssrc = local_ssrc;
3430 }
3431 return true;
3432 }
3433 }
3434
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003435 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003436 for (ChannelMap::const_iterator it = receive_channels_.begin();
3437 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003438 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003439 *ssrc = it->first;
3440 return true;
3441 }
3442 }
3443 }
3444 return false;
3445}
3446
3447void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003448 if (error == VE_TYPING_NOISE_WARNING) {
3449 typing_noise_detected_ = true;
3450 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3451 typing_noise_detected_ = false;
3452 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003453 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3454}
3455
3456int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3457 unsigned int ulevel;
3458 int ret =
3459 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3460 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3461}
3462
3463int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003464 ChannelMap::iterator it = receive_channels_.find(ssrc);
3465 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003466 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003467 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3468}
3469
3470int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003471 ChannelMap::iterator it = send_channels_.find(ssrc);
3472 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003473 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003474
3475 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003476}
3477
3478bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3479 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3480 // Get the RED encodings from the parameter with no name. This may
3481 // change based on what is discussed on the Jingle list.
3482 // The encoding parameter is of the form "a/b"; we only support where
3483 // a == b. Verify this and parse out the value into red_pt.
3484 // If the parameter value is absent (as it will be until we wire up the
3485 // signaling of this message), use the second codec specified (i.e. the
3486 // one after "red") as the encoding parameter.
3487 int red_pt = -1;
3488 std::string red_params;
3489 CodecParameterMap::const_iterator it = red_codec.params.find("");
3490 if (it != red_codec.params.end()) {
3491 red_params = it->second;
3492 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003493 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003494 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003495 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003496 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3497 return false;
3498 }
3499 } else if (red_codec.params.empty()) {
3500 LOG(LS_WARNING) << "RED params not present, using defaults";
3501 if (all_codecs.size() > 1) {
3502 red_pt = all_codecs[1].id;
3503 }
3504 }
3505
3506 // Try to find red_pt in |codecs|.
3507 std::vector<AudioCodec>::const_iterator codec;
3508 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3509 if (codec->id == red_pt)
3510 break;
3511 }
3512
3513 // If we find the right codec, that will be the codec we pass to
3514 // SetSendCodec, with the desired payload type.
3515 if (codec != all_codecs.end() &&
3516 engine()->FindWebRtcCodec(*codec, send_codec)) {
3517 } else {
3518 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3519 return false;
3520 }
3521
3522 return true;
3523}
3524
3525bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3526 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003527 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003528 return false;
3529 }
3530 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3531 // what we want to do with them.
3532 // engine()->voe().EnableVQMon(voe_channel(), true);
3533 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3534 return true;
3535}
3536
3537bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3538 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3539 for (int i = 0; i < ncodecs; ++i) {
3540 webrtc::CodecInst voe_codec;
3541 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3542 voe_codec.pltype = -1;
3543 if (engine()->voe()->codec()->SetRecPayloadType(
3544 channel, voe_codec) == -1) {
3545 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3546 return false;
3547 }
3548 }
3549 }
3550 return true;
3551}
3552
3553bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3554 if (playout) {
3555 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3556 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3557 LOG_RTCERR1(StartPlayout, channel);
3558 return false;
3559 }
3560 } else {
3561 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3562 engine()->voe()->base()->StopPlayout(channel);
3563 }
3564 return true;
3565}
3566
3567uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3568 bool rtcp) {
3569 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3570 uint32 ssrc = 0;
3571 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003572 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003573 }
3574 return ssrc;
3575}
3576
3577// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3578VoiceMediaChannel::Error
3579 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3580 switch (err_code) {
3581 case 0:
3582 return ERROR_NONE;
3583 case VE_CANNOT_START_RECORDING:
3584 case VE_MIC_VOL_ERROR:
3585 case VE_GET_MIC_VOL_ERROR:
3586 case VE_CANNOT_ACCESS_MIC_VOL:
3587 return ERROR_REC_DEVICE_OPEN_FAILED;
3588 case VE_SATURATION_WARNING:
3589 return ERROR_REC_DEVICE_SATURATION;
3590 case VE_REC_DEVICE_REMOVED:
3591 return ERROR_REC_DEVICE_REMOVED;
3592 case VE_RUNTIME_REC_WARNING:
3593 case VE_RUNTIME_REC_ERROR:
3594 return ERROR_REC_RUNTIME_ERROR;
3595 case VE_CANNOT_START_PLAYOUT:
3596 case VE_SPEAKER_VOL_ERROR:
3597 case VE_GET_SPEAKER_VOL_ERROR:
3598 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3599 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3600 case VE_RUNTIME_PLAY_WARNING:
3601 case VE_RUNTIME_PLAY_ERROR:
3602 return ERROR_PLAY_RUNTIME_ERROR;
3603 case VE_TYPING_NOISE_WARNING:
3604 return ERROR_REC_TYPING_NOISE_DETECTED;
3605 default:
3606 return VoiceMediaChannel::ERROR_OTHER;
3607 }
3608}
3609
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003610bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3611 int channel_id, const RtpHeaderExtension* extension) {
3612 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003613 int id = 0;
3614 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003615 if (extension) {
3616 enable = true;
3617 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003618 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003619 }
3620 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003621 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003622 return false;
3623 }
3624 return true;
3625}
3626
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003627int WebRtcSoundclipStream::Read(void *buf, int len) {
3628 size_t res = 0;
3629 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003630 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003631}
3632
3633int WebRtcSoundclipStream::Rewind() {
3634 mem_.Rewind();
3635 // Return -1 to keep VoiceEngine from looping.
3636 return (loop_) ? 0 : -1;
3637}
3638
3639} // namespace cricket
3640
3641#endif // HAVE_WEBRTC_VOICE