blob: 8faa46bb26822dd85b7707f09db6eb8d8106b12f [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.orgd4e598d2014-07-29 17:36:52 +000041#include "webrtc/base/base64.h"
42#include "webrtc/base/byteorder.h"
43#include "webrtc/base/common.h"
44#include "webrtc/base/helpers.h"
45#include "webrtc/base/logging.h"
46#include "webrtc/base/stringencode.h"
47#include "webrtc/base/stringutils.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000048#include "talk/media/base/audiorenderer.h"
49#include "talk/media/base/constants.h"
50#include "talk/media/base/streamparams.h"
51#include "talk/media/base/voiceprocessor.h"
52#include "talk/media/webrtc/webrtcvoe.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 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001012 }
1013
1014 // Find the playout device id in VoiceEngine and set playout device.
1015 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1016 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1017 ret = false;
1018 }
1019 if (ret) {
1020 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001021 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001022 ret = false;
1023 }
1024 }
1025
1026 // Resume all audio playback and capture.
1027 for (ChannelList::const_iterator i = channels_.begin();
1028 i != channels_.end(); ++i) {
1029 WebRtcVoiceMediaChannel *channel = *i;
1030 if (!channel->ResumePlayout()) {
1031 LOG(LS_WARNING) << "Failed to resume playout";
1032 ret = false;
1033 }
1034 if (!channel->ResumeSend()) {
1035 LOG(LS_WARNING) << "Failed to resume send";
1036 ret = false;
1037 }
1038 }
1039
1040 // Resume local monitor.
1041 if (!ResumeLocalMonitor()) {
1042 LOG(LS_WARNING) << "Failed to resume local monitor";
1043 ret = false;
1044 }
1045
1046 if (ret) {
1047 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1048 << ") and speaker to (id="<< out_id << " name=" << out_name
1049 << ")";
1050 }
1051
1052 return ret;
1053#else
1054 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001055#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001056}
1057
1058bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1059 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1060 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001061#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001062 *rtc_id = dev_id;
1063 return true;
1064#else
1065 // In Windows and Mac, we need to find the VoiceEngine device id by name
1066 // unless the input dev_id is the default device id.
1067 if (kDefaultAudioDeviceId == dev_id) {
1068 *rtc_id = dev_id;
1069 return true;
1070 }
1071
1072 // Get the number of VoiceEngine audio devices.
1073 int count = 0;
1074 if (is_input) {
1075 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1076 LOG_RTCERR0(GetNumOfRecordingDevices);
1077 return false;
1078 }
1079 } else {
1080 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1081 LOG_RTCERR0(GetNumOfPlayoutDevices);
1082 return false;
1083 }
1084 }
1085
1086 for (int i = 0; i < count; ++i) {
1087 char name[128];
1088 char guid[128];
1089 if (is_input) {
1090 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1091 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1092 } else {
1093 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1094 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1095 }
1096
1097 std::string webrtc_name(name);
1098 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1099 *rtc_id = i;
1100 return true;
1101 }
1102 }
1103 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1104 return false;
1105#endif
1106}
1107
1108bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1109 unsigned int ulevel;
1110 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1111 LOG_RTCERR1(GetSpeakerVolume, level);
1112 return false;
1113 }
1114 *level = ulevel;
1115 return true;
1116}
1117
1118bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1119 ASSERT(level >= 0 && level <= 255);
1120 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1121 LOG_RTCERR1(SetSpeakerVolume, level);
1122 return false;
1123 }
1124 return true;
1125}
1126
1127int WebRtcVoiceEngine::GetInputLevel() {
1128 unsigned int ulevel;
1129 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1130 static_cast<int>(ulevel) : -1;
1131}
1132
1133bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1134 desired_local_monitor_enable_ = enable;
1135 return ChangeLocalMonitor(desired_local_monitor_enable_);
1136}
1137
1138bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1139 // The voe file api is not available in chrome.
1140 if (!voe_wrapper_->file()) {
1141 return false;
1142 }
1143 if (enable && !monitor_) {
1144 monitor_.reset(new WebRtcMonitorStream);
1145 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1146 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1147 // Must call Stop() because there are some cases where Start will report
1148 // failure but still change the state, and if we leave VE in the on state
1149 // then it could crash later when trying to invoke methods on our monitor.
1150 voe_wrapper_->file()->StopRecordingMicrophone();
1151 monitor_.reset();
1152 return false;
1153 }
1154 } else if (!enable && monitor_) {
1155 voe_wrapper_->file()->StopRecordingMicrophone();
1156 monitor_.reset();
1157 }
1158 return true;
1159}
1160
1161bool WebRtcVoiceEngine::PauseLocalMonitor() {
1162 return ChangeLocalMonitor(false);
1163}
1164
1165bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1166 return ChangeLocalMonitor(desired_local_monitor_enable_);
1167}
1168
1169const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1170 return codecs_;
1171}
1172
1173bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1174 return FindWebRtcCodec(in, NULL);
1175}
1176
1177// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1178bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1179 webrtc::CodecInst* out) {
1180 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1181 for (int i = 0; i < ncodecs; ++i) {
1182 webrtc::CodecInst voe_codec;
1183 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1184 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1185 voe_codec.rate, voe_codec.channels, 0);
1186 bool multi_rate = IsCodecMultiRate(voe_codec);
1187 // Allow arbitrary rates for ISAC to be specified.
1188 if (multi_rate) {
1189 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1190 codec.bitrate = 0;
1191 }
1192 if (codec.Matches(in)) {
1193 if (out) {
1194 // Fixup the payload type.
1195 voe_codec.pltype = in.id;
1196
1197 // Set bitrate if specified.
1198 if (multi_rate && in.bitrate != 0) {
1199 voe_codec.rate = in.bitrate;
1200 }
1201
1202 // Apply codec-specific settings.
1203 if (IsIsac(codec)) {
1204 // If ISAC and an explicit bitrate is not specified,
1205 // enable auto bandwidth adjustment.
1206 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1207 }
1208 *out = voe_codec;
1209 }
1210 return true;
1211 }
1212 }
1213 }
1214 return false;
1215}
1216const std::vector<RtpHeaderExtension>&
1217WebRtcVoiceEngine::rtp_header_extensions() const {
1218 return rtp_header_extensions_;
1219}
1220
1221void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1222 // if min_sev == -1, we keep the current log level.
1223 if (min_sev >= 0) {
1224 SetTraceFilter(SeverityToFilter(min_sev));
1225 }
1226 log_options_ = filter;
1227 SetTraceOptions(initialized_ ? log_options_ : "");
1228}
1229
1230int WebRtcVoiceEngine::GetLastEngineError() {
1231 return voe_wrapper_->error();
1232}
1233
1234void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1235 log_filter_ = filter;
1236 tracing_->SetTraceFilter(filter);
1237}
1238
1239// We suppport three different logging settings for VoiceEngine:
1240// 1. Observer callback that goes into talk diagnostic logfile.
1241// Use --logfile and --loglevel
1242//
1243// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1244// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1245//
1246// 3. EC log and dump for debugging QualityEngine.
1247// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1248//
1249// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1250// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1251void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1252 // Set encrypted trace file.
1253 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001254 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001255 std::vector<std::string>::iterator tracefile =
1256 std::find(opts.begin(), opts.end(), "tracefile");
1257 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1258 // Write encrypted debug output (at same loglevel) to file
1259 // EncryptedTraceFile no longer supported.
1260 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1261 LOG_RTCERR1(SetTraceFile, *tracefile);
1262 }
1263 }
1264
wu@webrtc.org97077a32013-10-25 21:18:33 +00001265 // Allow trace options to override the trace filter. We default
1266 // it to log_filter_ (as a translation of libjingle log levels)
1267 // elsewhere, but this allows clients to explicitly set webrtc
1268 // log levels.
1269 std::vector<std::string>::iterator tracefilter =
1270 std::find(opts.begin(), opts.end(), "tracefilter");
1271 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001272 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001273 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1274 }
1275 }
1276
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001277 // Set AEC dump file
1278 std::vector<std::string>::iterator recordEC =
1279 std::find(opts.begin(), opts.end(), "recordEC");
1280 if (recordEC != opts.end()) {
1281 ++recordEC;
1282 if (recordEC != opts.end())
1283 StartAecDump(recordEC->c_str());
1284 else
1285 StopAecDump();
1286 }
1287}
1288
1289// Ignore spammy trace messages, mostly from the stats API when we haven't
1290// gotten RTCP info yet from the remote side.
1291bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1292 static const char* kTracesToIgnore[] = {
1293 "\tfailed to GetReportBlockInformation",
1294 "GetRecCodec() failed to get received codec",
1295 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1296 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1297 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1298 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1299 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1300 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1301 "SenderInfoReceived No received SR",
1302 "StatisticsRTP() no statistics available",
1303 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1304 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1305 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1306 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1307 NULL
1308 };
1309 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1310 if (trace.find(*p) != std::string::npos) {
1311 return true;
1312 }
1313 }
1314 return false;
1315}
1316
1317void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1318 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001319 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001320 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001321 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001322 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001323 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001324 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001325 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001326 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001327 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001328
1329 // Skip past boilerplate prefix text
1330 if (length < 72) {
1331 std::string msg(trace, length);
1332 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1333 LOG_V(sev) << msg;
1334 } else {
1335 std::string msg(trace + 71, length - 72);
1336 if (!ShouldIgnoreTrace(msg)) {
1337 LOG_V(sev) << "webrtc: " << msg;
1338 }
1339 }
1340}
1341
1342void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001343 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001344 WebRtcVoiceMediaChannel* channel = NULL;
1345 uint32 ssrc = 0;
1346 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1347 << channel_num << ".";
1348 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1349 ASSERT(channel != NULL);
1350 channel->OnError(ssrc, err_code);
1351 } else {
1352 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1353 << " could not be found in channel list when error reported.";
1354 }
1355}
1356
1357bool WebRtcVoiceEngine::FindChannelAndSsrc(
1358 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1359 ASSERT(channel != NULL && ssrc != NULL);
1360
1361 *channel = NULL;
1362 *ssrc = 0;
1363 // Find corresponding channel and ssrc
1364 for (ChannelList::const_iterator it = channels_.begin();
1365 it != channels_.end(); ++it) {
1366 ASSERT(*it != NULL);
1367 if ((*it)->FindSsrc(channel_num, ssrc)) {
1368 *channel = *it;
1369 return true;
1370 }
1371 }
1372
1373 return false;
1374}
1375
1376// This method will search through the WebRtcVoiceMediaChannels and
1377// obtain the voice engine's channel number.
1378bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1379 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1380 ASSERT(channel_num != NULL);
1381 ASSERT(direction == MPD_RX || direction == MPD_TX);
1382
1383 *channel_num = -1;
1384 // Find corresponding channel for ssrc.
1385 for (ChannelList::const_iterator it = channels_.begin();
1386 it != channels_.end(); ++it) {
1387 ASSERT(*it != NULL);
1388 if (direction & MPD_RX) {
1389 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1390 }
1391 if (*channel_num == -1 && (direction & MPD_TX)) {
1392 *channel_num = (*it)->GetSendChannelNum(ssrc);
1393 }
1394 if (*channel_num != -1) {
1395 return true;
1396 }
1397 }
1398 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1399 return false;
1400}
1401
1402void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001403 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001404 channels_.push_back(channel);
1405}
1406
1407void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001408 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001409 ChannelList::iterator i = std::find(channels_.begin(),
1410 channels_.end(),
1411 channel);
1412 if (i != channels_.end()) {
1413 channels_.erase(i);
1414 }
1415}
1416
1417void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1418 soundclips_.push_back(soundclip);
1419}
1420
1421void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1422 SoundclipList::iterator i = std::find(soundclips_.begin(),
1423 soundclips_.end(),
1424 soundclip);
1425 if (i != soundclips_.end()) {
1426 soundclips_.erase(i);
1427 }
1428}
1429
1430// Adjusts the default AGC target level by the specified delta.
1431// NB: If we start messing with other config fields, we'll want
1432// to save the current webrtc::AgcConfig as well.
1433bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1434 webrtc::AgcConfig config = default_agc_config_;
1435 config.targetLeveldBOv -= delta;
1436
1437 LOG(LS_INFO) << "Adjusting AGC level from default -"
1438 << default_agc_config_.targetLeveldBOv << "dB to -"
1439 << config.targetLeveldBOv << "dB";
1440
1441 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1442 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1443 return false;
1444 }
1445 return true;
1446}
1447
1448bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1449 webrtc::AudioDeviceModule* adm_sc) {
1450 if (initialized_) {
1451 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1452 return false;
1453 }
1454 if (adm_) {
1455 adm_->Release();
1456 adm_ = NULL;
1457 }
1458 if (adm) {
1459 adm_ = adm;
1460 adm_->AddRef();
1461 }
1462
1463 if (adm_sc_) {
1464 adm_sc_->Release();
1465 adm_sc_ = NULL;
1466 }
1467 if (adm_sc) {
1468 adm_sc_ = adm_sc;
1469 adm_sc_->AddRef();
1470 }
1471 return true;
1472}
1473
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001474bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1475 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001476 if (!aec_dump_file_stream) {
1477 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001478 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001479 LOG(LS_WARNING) << "Could not close file.";
1480 return false;
1481 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001482 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001483 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001484 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001485 LOG_RTCERR0(StartDebugRecording);
1486 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001487 return false;
1488 }
1489 is_dumping_aec_ = true;
1490 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001491}
1492
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001493bool WebRtcVoiceEngine::RegisterProcessor(
1494 uint32 ssrc,
1495 VoiceProcessor* voice_processor,
1496 MediaProcessorDirection direction) {
1497 bool register_with_webrtc = false;
1498 int channel_id = -1;
1499 bool success = false;
1500 uint32* processor_ssrc = NULL;
1501 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1502 if (voice_processor == NULL || !found_channel) {
1503 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1504 << " foundChannel: " << found_channel;
1505 return false;
1506 }
1507
1508 webrtc::ProcessingTypes processing_type;
1509 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001510 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001511 if (direction == MPD_RX) {
1512 processing_type = webrtc::kPlaybackAllChannelsMixed;
1513 if (SignalRxMediaFrame.is_empty()) {
1514 register_with_webrtc = true;
1515 processor_ssrc = &rx_processor_ssrc_;
1516 }
1517 SignalRxMediaFrame.connect(voice_processor,
1518 &VoiceProcessor::OnFrame);
1519 } else {
1520 processing_type = webrtc::kRecordingPerChannel;
1521 if (SignalTxMediaFrame.is_empty()) {
1522 register_with_webrtc = true;
1523 processor_ssrc = &tx_processor_ssrc_;
1524 }
1525 SignalTxMediaFrame.connect(voice_processor,
1526 &VoiceProcessor::OnFrame);
1527 }
1528 }
1529 if (register_with_webrtc) {
1530 // TODO(janahan): when registering consider instantiating a
1531 // a VoeMediaProcess object and not make the engine extend the interface.
1532 if (voe()->media() && voe()->media()->
1533 RegisterExternalMediaProcessing(channel_id,
1534 processing_type,
1535 *this) != -1) {
1536 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1537 << channel_id;
1538 *processor_ssrc = ssrc;
1539 success = true;
1540 } else {
1541 LOG_RTCERR2(RegisterExternalMediaProcessing,
1542 channel_id,
1543 processing_type);
1544 success = false;
1545 }
1546 } else {
1547 // If we don't have to register with the engine, we just needed to
1548 // connect a new processor, set success to true;
1549 success = true;
1550 }
1551 return success;
1552}
1553
1554bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1555 MediaProcessorDirection channel_direction,
1556 uint32 ssrc,
1557 VoiceProcessor* voice_processor,
1558 MediaProcessorDirection processor_direction) {
1559 bool success = true;
1560 FrameSignal* signal;
1561 webrtc::ProcessingTypes processing_type;
1562 uint32* processor_ssrc = NULL;
1563 if (channel_direction == MPD_RX) {
1564 signal = &SignalRxMediaFrame;
1565 processing_type = webrtc::kPlaybackAllChannelsMixed;
1566 processor_ssrc = &rx_processor_ssrc_;
1567 } else {
1568 signal = &SignalTxMediaFrame;
1569 processing_type = webrtc::kRecordingPerChannel;
1570 processor_ssrc = &tx_processor_ssrc_;
1571 }
1572
1573 int deregister_id = -1;
1574 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001575 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001576 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1577 signal->disconnect(voice_processor);
1578 int channel_id = -1;
1579 bool found_channel = FindChannelNumFromSsrc(ssrc,
1580 channel_direction,
1581 &channel_id);
1582 if (signal->is_empty() && found_channel) {
1583 deregister_id = channel_id;
1584 }
1585 }
1586 }
1587 if (deregister_id != -1) {
1588 if (voe()->media() &&
1589 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1590 processing_type) != -1) {
1591 *processor_ssrc = 0;
1592 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1593 << deregister_id;
1594 } else {
1595 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1596 deregister_id,
1597 processing_type);
1598 success = false;
1599 }
1600 }
1601 return success;
1602}
1603
1604bool WebRtcVoiceEngine::UnregisterProcessor(
1605 uint32 ssrc,
1606 VoiceProcessor* voice_processor,
1607 MediaProcessorDirection direction) {
1608 bool success = true;
1609 if (voice_processor == NULL) {
1610 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1611 << ssrc;
1612 return false;
1613 }
1614 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1615 success = false;
1616 }
1617 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1618 success = false;
1619 }
1620 return success;
1621}
1622
1623// Implementing method from WebRtc VoEMediaProcess interface
1624// Do not lock mux_channel_cs_ in this callback.
1625void WebRtcVoiceEngine::Process(int channel,
1626 webrtc::ProcessingTypes type,
1627 int16_t audio10ms[],
1628 int length,
1629 int sampling_freq,
1630 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001631 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001632 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1633 if (type == webrtc::kPlaybackAllChannelsMixed) {
1634 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1635 } else if (type == webrtc::kRecordingPerChannel) {
1636 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1637 } else {
1638 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1639 << " channel: " << channel << " type: " << type
1640 << " tx_ssrc: " << tx_processor_ssrc_
1641 << " rx_ssrc: " << rx_processor_ssrc_;
1642 }
1643}
1644
1645void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1646 if (!is_dumping_aec_) {
1647 // Start dumping AEC when we are not dumping.
1648 if (voe_wrapper_->processing()->StartDebugRecording(
1649 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001650 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001651 } else {
1652 is_dumping_aec_ = true;
1653 }
1654 }
1655}
1656
1657void WebRtcVoiceEngine::StopAecDump() {
1658 if (is_dumping_aec_) {
1659 // Stop dumping AEC when we are dumping.
1660 if (voe_wrapper_->processing()->StopDebugRecording() !=
1661 webrtc::AudioProcessing::kNoError) {
1662 LOG_RTCERR0(StopDebugRecording);
1663 }
1664 is_dumping_aec_ = false;
1665 }
1666}
1667
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001668int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001669 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001670}
1671
1672int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1673 return CreateVoiceChannel(voe_wrapper_.get());
1674}
1675
1676int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1677 return CreateVoiceChannel(voe_wrapper_sc_.get());
1678}
1679
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001680class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1681 : public AudioRenderer::Sink {
1682 public:
1683 WebRtcVoiceChannelRenderer(int ch,
1684 webrtc::AudioTransport* voe_audio_transport)
1685 : channel_(ch),
1686 voe_audio_transport_(voe_audio_transport),
1687 renderer_(NULL) {
1688 }
1689 virtual ~WebRtcVoiceChannelRenderer() {
1690 Stop();
1691 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001692
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001693 // Starts the rendering by setting a sink to the renderer to get data
1694 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001695 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001696 // TODO(xians): Make sure Start() is called only once.
1697 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001698 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001699 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001700 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001701 ASSERT(renderer_ == renderer);
1702 return;
1703 }
1704
1705 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1706 // in getUserMedia by default.
1707 renderer->AddChannel(channel_);
1708 renderer->SetSink(this);
1709 renderer_ = renderer;
1710 }
1711
1712 // Stops rendering by setting the sink of the renderer to NULL. No data
1713 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001714 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001715 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001716 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001717 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001718 return;
1719
1720 renderer_->RemoveChannel(channel_);
1721 renderer_->SetSink(NULL);
1722 renderer_ = NULL;
1723 }
1724
1725 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001726 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001727 virtual void OnData(const void* audio_data,
1728 int bits_per_sample,
1729 int sample_rate,
1730 int number_of_channels,
1731 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001732 voe_audio_transport_->OnData(channel_,
1733 audio_data,
1734 bits_per_sample,
1735 sample_rate,
1736 number_of_channels,
1737 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001738 }
1739
1740 // Callback from the |renderer_| when it is going away. In case Start() has
1741 // never been called, this callback won't be triggered.
1742 virtual void OnClose() OVERRIDE {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001743 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001744 // Set |renderer_| to NULL to make sure no more callback will get into
1745 // the renderer.
1746 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001747 }
1748
1749 // Accessor to the VoE channel ID.
1750 int channel() const { return channel_; }
1751
1752 private:
1753 const int channel_;
1754 webrtc::AudioTransport* const voe_audio_transport_;
1755
1756 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1757 // PeerConnection will make sure invalidating the pointer before the object
1758 // goes away.
1759 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001760
1761 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001762 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001763};
1764
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001765// WebRtcVoiceMediaChannel
1766WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1767 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1768 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001769 engine->CreateMediaVoiceChannel()),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001770 send_bw_setting_(false),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001771 send_bw_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001772 options_(),
1773 dtmf_allowed_(false),
1774 desired_playout_(false),
1775 nack_enabled_(false),
1776 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001777 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001778 desired_send_(SEND_NOTHING),
1779 send_(SEND_NOTHING),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001780 default_receive_ssrc_(0) {
1781 engine->RegisterChannel(this);
1782 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1783 << voe_channel();
1784
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001785 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001786}
1787
1788WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1789 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1790 << voe_channel();
1791
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001792 // Remove any remaining send streams, the default channel will be deleted
1793 // later.
1794 while (!send_channels_.empty())
1795 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001796
1797 // Unregister ourselves from the engine.
1798 engine()->UnregisterChannel(this);
1799 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001800 while (!receive_channels_.empty()) {
1801 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001802 }
1803
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001804 // Delete the default channel.
1805 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001806}
1807
1808bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1809 LOG(LS_INFO) << "Setting voice channel options: "
1810 << options.ToString();
1811
wu@webrtc.orgde305012013-10-31 15:40:38 +00001812 // Check if DSCP value is changed from previous.
1813 bool dscp_option_changed = (options_.dscp != options.dscp);
1814
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001815 // TODO(xians): Add support to set different options for different send
1816 // streams after we support multiple APMs.
1817
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001818 // We retain all of the existing options, and apply the given ones
1819 // on top. This means there is no way to "clear" options such that
1820 // they go back to the engine default.
1821 options_.SetAll(options);
1822
1823 if (send_ != SEND_NOTHING) {
1824 if (!engine()->SetOptionOverrides(options_)) {
1825 LOG(LS_WARNING) <<
1826 "Failed to engine SetOptionOverrides during channel SetOptions.";
1827 return false;
1828 }
1829 } else {
1830 // Will be interpreted when appropriate.
1831 }
1832
wu@webrtc.org97077a32013-10-25 21:18:33 +00001833 // Receiver-side auto gain control happens per channel, so set it here from
1834 // options. Note that, like conference mode, setting it on the engine won't
1835 // have the desired effect, since voice channels don't inherit options from
1836 // the media engine when those options are applied per-channel.
1837 bool rx_auto_gain_control;
1838 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1839 if (engine()->voe()->processing()->SetRxAgcStatus(
1840 voe_channel(), rx_auto_gain_control,
1841 webrtc::kAgcFixedDigital) == -1) {
1842 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1843 return false;
1844 } else {
1845 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1846 << " with mode " << webrtc::kAgcFixedDigital;
1847 }
1848 }
1849 if (options.rx_agc_target_dbov.IsSet() ||
1850 options.rx_agc_digital_compression_gain.IsSet() ||
1851 options.rx_agc_limiter.IsSet()) {
1852 webrtc::AgcConfig config;
1853 // If only some of the options are being overridden, get the current
1854 // settings for the channel and bail if they aren't available.
1855 if (!options.rx_agc_target_dbov.IsSet() ||
1856 !options.rx_agc_digital_compression_gain.IsSet() ||
1857 !options.rx_agc_limiter.IsSet()) {
1858 if (engine()->voe()->processing()->GetRxAgcConfig(
1859 voe_channel(), config) != 0) {
1860 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1861 << "channel " << voe_channel() << ". Since not all rx "
1862 << "agc options are specified, unable to safely set rx "
1863 << "agc options.";
1864 return false;
1865 }
1866 }
1867 config.targetLeveldBOv =
1868 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1869 config.targetLeveldBOv);
1870 config.digitalCompressionGaindB =
1871 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1872 config.digitalCompressionGaindB);
1873 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1874 config.limiterEnable);
1875 if (engine()->voe()->processing()->SetRxAgcConfig(
1876 voe_channel(), config) == -1) {
1877 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1878 config.digitalCompressionGaindB, config.limiterEnable);
1879 return false;
1880 }
1881 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001882 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001883 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001884 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001885 dscp = kAudioDscpValue;
1886 if (MediaChannel::SetDscp(dscp) != 0) {
1887 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1888 }
1889 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001890
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001891 LOG(LS_INFO) << "Set voice channel options. Current options: "
1892 << options_.ToString();
1893 return true;
1894}
1895
1896bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1897 const std::vector<AudioCodec>& codecs) {
1898 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001899 LOG(LS_INFO) << "Setting receive voice codecs:";
1900
1901 std::vector<AudioCodec> new_codecs;
1902 // Find all new codecs. We allow adding new codecs but don't allow changing
1903 // the payload type of codecs that is already configured since we might
1904 // already be receiving packets with that payload type.
1905 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001906 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001907 AudioCodec old_codec;
1908 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1909 if (old_codec.id != it->id) {
1910 LOG(LS_ERROR) << it->name << " payload type changed.";
1911 return false;
1912 }
1913 } else {
1914 new_codecs.push_back(*it);
1915 }
1916 }
1917 if (new_codecs.empty()) {
1918 // There are no new codecs to configure. Already configured codecs are
1919 // never removed.
1920 return true;
1921 }
1922
1923 if (playout_) {
1924 // Receive codecs can not be changed while playing. So we temporarily
1925 // pause playout.
1926 PausePlayout();
1927 }
1928
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001929 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001930 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1931 it != new_codecs.end() && ret; ++it) {
1932 webrtc::CodecInst voe_codec;
1933 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1934 LOG(LS_INFO) << ToString(*it);
1935 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001936 if (default_receive_ssrc_ == 0) {
1937 // Set the receive codecs on the default channel explicitly if the
1938 // default channel is not used by |receive_channels_|, this happens in
1939 // conference mode or in non-conference mode when there is no playout
1940 // channel.
1941 // TODO(xians): Figure out how we use the default channel in conference
1942 // mode.
1943 if (engine()->voe()->codec()->SetRecPayloadType(
1944 voe_channel(), voe_codec) == -1) {
1945 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1946 ret = false;
1947 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001948 }
1949
1950 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001951 for (ChannelMap::iterator it = receive_channels_.begin();
1952 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001953 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001954 it->second->channel(), voe_codec) == -1) {
1955 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001956 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001957 ret = false;
1958 }
1959 }
1960 } else {
1961 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1962 ret = false;
1963 }
1964 }
1965 if (ret) {
1966 recv_codecs_ = codecs;
1967 }
1968
1969 if (desired_playout_ && !playout_) {
1970 ResumePlayout();
1971 }
1972 return ret;
1973}
1974
1975bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001976 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001977 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001978 engine()->voe()->codec()->SetVADStatus(channel, false);
1979 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001980#ifdef USE_WEBRTC_DEV_BRANCH
1981 engine()->voe()->rtp()->SetREDStatus(channel, false);
1982 engine()->voe()->codec()->SetFECStatus(channel, false);
1983#else
1984 // TODO(minyue): Remove code under #else case after new WebRTC roll.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001985 engine()->voe()->rtp()->SetFECStatus(channel, false);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001986#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001987
1988 // Scan through the list to figure out the codec to use for sending, along
1989 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001990 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001991 webrtc::CodecInst send_codec;
1992 memset(&send_codec, 0, sizeof(send_codec));
1993
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001994 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001995 bool enable_codec_fec = false;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001996
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001997 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001998 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1999 it != codecs.end(); ++it) {
2000 // Ignore codecs we don't know about. The negotiation step should prevent
2001 // this, but double-check to be sure.
2002 webrtc::CodecInst voe_codec;
2003 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002004 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002005 continue;
2006 }
2007
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002008 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2009 // Skip telephone-event/CN codec, which will be handled later.
2010 continue;
2011 }
2012
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002013 // If OPUS, change what we send according to the "stereo" codec
2014 // parameter, and not the "channels" parameter. We set
2015 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
2016 // the bitrate is not specified, i.e. is zero, we set it to the
2017 // appropriate default value for mono or stereo Opus.
2018 if (IsOpus(*it)) {
2019 if (IsOpusStereoEnabled(*it)) {
2020 voe_codec.channels = 2;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002021 if (!IsValidOpusBitrate(it->bitrate)) {
2022 if (it->bitrate != 0) {
2023 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2024 << it->bitrate
2025 << ") with default opus stereo bitrate: "
2026 << kOpusStereoBitrate;
2027 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002028 voe_codec.rate = kOpusStereoBitrate;
2029 }
2030 } else {
2031 voe_codec.channels = 1;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002032 if (!IsValidOpusBitrate(it->bitrate)) {
2033 if (it->bitrate != 0) {
2034 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2035 << it->bitrate
2036 << ") with default opus mono bitrate: "
2037 << kOpusMonoBitrate;
2038 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002039 voe_codec.rate = kOpusMonoBitrate;
2040 }
2041 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002042 int bitrate_from_params = GetOpusBitrateFromParams(*it);
2043 if (bitrate_from_params != 0) {
2044 voe_codec.rate = bitrate_from_params;
2045 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002046 }
2047
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002048 // We'll use the first codec in the list to actually send audio data.
2049 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002050 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002051 // used is specified in params.
2052 if (IsRedCodec(it->name)) {
2053 // Parse out the RED parameters. If we fail, just ignore RED;
2054 // we don't support all possible params/usage scenarios.
2055 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2056 continue;
2057 }
2058
2059 // Enable redundant encoding of the specified codec. Treat any
2060 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002061#ifdef USE_WEBRTC_DEV_BRANCH
2062 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2063 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2064 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
2065#else
2066 // TODO(minyue): Remove code under #else case after new WebRTC roll.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002067 LOG(LS_INFO) << "Enabling FEC";
2068 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2069 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002070#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002071 return false;
2072 }
2073 } else {
2074 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002075 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002076 // For Opus as the send codec, we enable inband FEC if requested.
2077 enable_codec_fec = IsOpus(*it) && IsOpusFecEnabled(*it);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002078 }
2079 found_send_codec = true;
2080 break;
2081 }
2082
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002083 if (nack_enabled_ != nack_enabled) {
2084 SetNack(channel, nack_enabled);
2085 nack_enabled_ = nack_enabled;
2086 }
2087
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002088 if (!found_send_codec) {
2089 LOG(LS_WARNING) << "Received empty list of codecs.";
2090 return false;
2091 }
2092
2093 // Set the codec immediately, since SetVADStatus() depends on whether
2094 // the current codec is mono or stereo.
2095 if (!SetSendCodec(channel, send_codec))
2096 return false;
2097
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002098 // FEC should be enabled after SetSendCodec.
2099 if (enable_codec_fec) {
2100 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2101 << channel;
2102#ifdef USE_WEBRTC_DEV_BRANCH
2103 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2104 // Enable codec internal FEC. Treat any failure as fatal internal error.
2105 LOG_RTCERR2(SetFECStatus, channel, true);
2106 return false;
2107 }
2108#endif // USE_WEBRTC_DEV_BRANCH
2109 }
2110
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002111 // Always update the |send_codec_| to the currently set send codec.
2112 send_codec_.reset(new webrtc::CodecInst(send_codec));
2113
2114 if (send_bw_setting_) {
2115 SetSendBandwidthInternal(send_bw_bps_);
2116 }
2117
2118 // Loop through the codecs list again to config the telephone-event/CN codec.
2119 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2120 it != codecs.end(); ++it) {
2121 // Ignore codecs we don't know about. The negotiation step should prevent
2122 // this, but double-check to be sure.
2123 webrtc::CodecInst voe_codec;
2124 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2125 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2126 continue;
2127 }
2128
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002129 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2130 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002131 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002132 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2133 channel, it->id) == -1) {
2134 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2135 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002136 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002137 } else if (IsCNCodec(it->name)) {
2138 // Turn voice activity detection/comfort noise on if supported.
2139 // Set the wideband CN payload type appropriately.
2140 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002141 webrtc::PayloadFrequencies cn_freq;
2142 switch (it->clockrate) {
2143 case 8000:
2144 cn_freq = webrtc::kFreq8000Hz;
2145 break;
2146 case 16000:
2147 cn_freq = webrtc::kFreq16000Hz;
2148 break;
2149 case 32000:
2150 cn_freq = webrtc::kFreq32000Hz;
2151 break;
2152 default:
2153 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2154 << " not supported.";
2155 continue;
2156 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002157 // Set the CN payloadtype and the VAD status.
2158 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2159 if (cn_freq != webrtc::kFreq8000Hz) {
2160 if (engine()->voe()->codec()->SetSendCNPayloadType(
2161 channel, it->id, cn_freq) == -1) {
2162 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2163 // TODO(ajm): This failure condition will be removed from VoE.
2164 // Restore the return here when we update to a new enough webrtc.
2165 //
2166 // Not returning false because the SetSendCNPayloadType will fail if
2167 // the channel is already sending.
2168 // This can happen if the remote description is applied twice, for
2169 // example in the case of ROAP on top of JSEP, where both side will
2170 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002171 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002172 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002173 // Only turn on VAD if we have a CN payload type that matches the
2174 // clockrate for the codec we are going to use.
2175 if (it->clockrate == send_codec.plfreq) {
2176 LOG(LS_INFO) << "Enabling VAD";
2177 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2178 LOG_RTCERR2(SetVADStatus, channel, true);
2179 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002180 }
2181 }
2182 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002183 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002184 return true;
2185}
2186
2187bool WebRtcVoiceMediaChannel::SetSendCodecs(
2188 const std::vector<AudioCodec>& codecs) {
2189 dtmf_allowed_ = false;
2190 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2191 it != codecs.end(); ++it) {
2192 // Find the DTMF telephone event "codec".
2193 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2194 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2195 dtmf_allowed_ = true;
2196 }
2197 }
2198
2199 // Cache the codecs in order to configure the channel created later.
2200 send_codecs_ = codecs;
2201 for (ChannelMap::iterator iter = send_channels_.begin();
2202 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002203 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002204 return false;
2205 }
2206 }
2207
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002208 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002209 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002210 return true;
2211}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002212
2213void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2214 bool nack_enabled) {
2215 for (ChannelMap::const_iterator it = channels.begin();
2216 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002217 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002218 }
2219}
2220
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002221void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002222 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002223 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002224 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2225 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002226 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002227 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2228 }
2229}
2230
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002231bool WebRtcVoiceMediaChannel::SetSendCodec(
2232 const webrtc::CodecInst& send_codec) {
2233 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2234 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002235 for (ChannelMap::iterator iter = send_channels_.begin();
2236 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002237 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002238 return false;
2239 }
2240
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002241 return true;
2242}
2243
2244bool WebRtcVoiceMediaChannel::SetSendCodec(
2245 int channel, const webrtc::CodecInst& send_codec) {
2246 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2247 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2248
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002249 webrtc::CodecInst current_codec;
2250 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2251 (send_codec == current_codec)) {
2252 // Codec is already configured, we can return without setting it again.
2253 return true;
2254 }
2255
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002256 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2257 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002258 return false;
2259 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002260 return true;
2261}
2262
2263bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2264 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002265 if (receive_extensions_ == extensions) {
2266 return true;
2267 }
2268
2269 // The default channel may or may not be in |receive_channels_|. Set the rtp
2270 // header extensions for default channel regardless.
2271 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2272 return false;
2273 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002274
2275 // Loop through all receive channels and enable/disable the extensions.
2276 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2277 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002278 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2279 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002280 return false;
2281 }
2282 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002283
2284 receive_extensions_ = extensions;
2285 return true;
2286}
2287
2288bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2289 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002290 const RtpHeaderExtension* audio_level_extension =
2291 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2292 if (!SetHeaderExtension(
2293 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2294 audio_level_extension)) {
2295 return false;
2296 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002297
2298 const RtpHeaderExtension* send_time_extension =
2299 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2300 if (!SetHeaderExtension(
2301 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2302 send_time_extension)) {
2303 return false;
2304 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002305 return true;
2306}
2307
2308bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2309 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002310 if (send_extensions_ == extensions) {
2311 return true;
2312 }
2313
2314 // The default channel may or may not be in |send_channels_|. Set the rtp
2315 // header extensions for default channel regardless.
2316
2317 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2318 return false;
2319 }
2320
2321 // Loop through all send channels and enable/disable the extensions.
2322 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2323 channel_it != send_channels_.end(); ++channel_it) {
2324 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2325 extensions)) {
2326 return false;
2327 }
2328 }
2329
2330 send_extensions_ = extensions;
2331 return true;
2332}
2333
2334bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2335 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002336 const RtpHeaderExtension* audio_level_extension =
2337 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002338
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002339 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002340 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002341 audio_level_extension)) {
2342 return false;
2343 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002344
2345 const RtpHeaderExtension* send_time_extension =
2346 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002347 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002348 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002349 send_time_extension)) {
2350 return false;
2351 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002352
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002353 return true;
2354}
2355
2356bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2357 desired_playout_ = playout;
2358 return ChangePlayout(desired_playout_);
2359}
2360
2361bool WebRtcVoiceMediaChannel::PausePlayout() {
2362 return ChangePlayout(false);
2363}
2364
2365bool WebRtcVoiceMediaChannel::ResumePlayout() {
2366 return ChangePlayout(desired_playout_);
2367}
2368
2369bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2370 if (playout_ == playout) {
2371 return true;
2372 }
2373
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002374 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002375 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002376 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002377 // Only toggle the default channel if we don't have any other channels.
2378 result = SetPlayout(voe_channel(), playout);
2379 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002380 for (ChannelMap::iterator it = receive_channels_.begin();
2381 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002382 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002383 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002384 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002385 result = false;
2386 }
2387 }
2388
2389 if (result) {
2390 playout_ = playout;
2391 }
2392 return result;
2393}
2394
2395bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2396 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002397 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002398 return ChangeSend(desired_send_);
2399 return true;
2400}
2401
2402bool WebRtcVoiceMediaChannel::PauseSend() {
2403 return ChangeSend(SEND_NOTHING);
2404}
2405
2406bool WebRtcVoiceMediaChannel::ResumeSend() {
2407 return ChangeSend(desired_send_);
2408}
2409
2410bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2411 if (send_ == send) {
2412 return true;
2413 }
2414
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002415 // Change the settings on each send channel.
2416 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002417 engine()->SetOptionOverrides(options_);
2418
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002419 // Change the settings on each send channel.
2420 for (ChannelMap::iterator iter = send_channels_.begin();
2421 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002422 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002423 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002424 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002425
2426 // Clear up the options after stopping sending.
2427 if (send == SEND_NOTHING)
2428 engine()->ClearOptionOverrides();
2429
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002430 send_ = send;
2431 return true;
2432}
2433
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002434bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2435 if (send == SEND_MICROPHONE) {
2436 if (engine()->voe()->base()->StartSend(channel) == -1) {
2437 LOG_RTCERR1(StartSend, channel);
2438 return false;
2439 }
2440 if (engine()->voe()->file() &&
2441 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2442 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2443 return false;
2444 }
2445 } else { // SEND_NOTHING
2446 ASSERT(send == SEND_NOTHING);
2447 if (engine()->voe()->base()->StopSend(channel) == -1) {
2448 LOG_RTCERR1(StopSend, channel);
2449 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002450 }
2451 }
2452
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002453 return true;
2454}
2455
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002456// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002457void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2458 if (engine()->voe()->network()->RegisterExternalTransport(
2459 channel, *this) == -1) {
2460 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2461 }
2462
2463 // Enable RTCP (for quality stats and feedback messages)
2464 EnableRtcp(channel);
2465
2466 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2467 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002468
2469 // Set RTP header extension for the new channel.
2470 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002471}
2472
2473bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2474 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2475 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2476 }
2477
2478 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2479 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002480 return false;
2481 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002482
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002483 return true;
2484}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002485
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002486bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2487 // If the default channel is already used for sending create a new channel
2488 // otherwise use the default channel for sending.
2489 int channel = GetSendChannelNum(sp.first_ssrc());
2490 if (channel != -1) {
2491 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2492 return false;
2493 }
2494
2495 bool default_channel_is_available = true;
2496 for (ChannelMap::const_iterator iter = send_channels_.begin();
2497 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002498 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002499 default_channel_is_available = false;
2500 break;
2501 }
2502 }
2503 if (default_channel_is_available) {
2504 channel = voe_channel();
2505 } else {
2506 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002507 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002508 if (channel == -1) {
2509 LOG_RTCERR0(CreateChannel);
2510 return false;
2511 }
2512
2513 ConfigureSendChannel(channel);
2514 }
2515
2516 // Save the channel to send_channels_, so that RemoveSendStream() can still
2517 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002518 webrtc::AudioTransport* audio_transport =
2519 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002520 send_channels_.insert(std::make_pair(
2521 sp.first_ssrc(),
2522 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002523
2524 // Set the send (local) SSRC.
2525 // If there are multiple send SSRCs, we can only set the first one here, and
2526 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2527 // (with a codec requires multiple SSRC(s)).
2528 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2529 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2530 return false;
2531 }
2532
2533 // At this point the channel's local SSRC has been updated. If the channel is
2534 // the default channel make sure that all the receive channels are updated as
2535 // well. Receive channels have to have the same SSRC as the default channel in
2536 // order to send receiver reports with this SSRC.
2537 if (IsDefaultChannel(channel)) {
2538 for (ChannelMap::const_iterator it = receive_channels_.begin();
2539 it != receive_channels_.end(); ++it) {
2540 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002541 if (!IsDefaultChannel(it->second->channel())) {
2542 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002543 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002544 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002545 return false;
2546 }
2547 }
2548 }
2549 }
2550
2551 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
2552 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2553 return false;
2554 }
2555
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002556 // Set the current codecs to be used for the new channel.
2557 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002558 return false;
2559
2560 return ChangeSend(channel, desired_send_);
2561}
2562
2563bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2564 ChannelMap::iterator it = send_channels_.find(ssrc);
2565 if (it == send_channels_.end()) {
2566 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2567 << " which doesn't exist.";
2568 return false;
2569 }
2570
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002571 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002572 ChangeSend(channel, SEND_NOTHING);
2573
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002574 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2575 // this will disconnect the audio renderer with the send channel.
2576 delete it->second;
2577 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002578
2579 if (IsDefaultChannel(channel)) {
2580 // Do not delete the default channel since the receive channels depend on
2581 // the default channel, recycle it instead.
2582 ChangeSend(channel, SEND_NOTHING);
2583 } else {
2584 // Clean up and delete the send channel.
2585 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2586 << " with VoiceEngine channel #" << channel << ".";
2587 if (!DeleteChannel(channel))
2588 return false;
2589 }
2590
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002591 if (send_channels_.empty())
2592 ChangeSend(SEND_NOTHING);
2593
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002594 return true;
2595}
2596
2597bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002598 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002599
2600 if (!VERIFY(sp.ssrcs.size() == 1))
2601 return false;
2602 uint32 ssrc = sp.first_ssrc();
2603
wu@webrtc.org78187522013-10-07 23:32:02 +00002604 if (ssrc == 0) {
2605 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2606 return false;
2607 }
2608
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002609 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2610 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002611 return false;
2612 }
2613
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002614 // Reuse default channel for recv stream in non-conference mode call
2615 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002616 webrtc::AudioTransport* audio_transport =
2617 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002618 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2619 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2620 << " reuse default channel";
2621 default_receive_ssrc_ = sp.first_ssrc();
2622 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002623 default_receive_ssrc_,
2624 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002625 return SetPlayout(voe_channel(), playout_);
2626 }
2627
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002628 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002629 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002630 if (channel == -1) {
2631 LOG_RTCERR0(CreateChannel);
2632 return false;
2633 }
2634
wu@webrtc.org78187522013-10-07 23:32:02 +00002635 if (!ConfigureRecvChannel(channel)) {
2636 DeleteChannel(channel);
2637 return false;
2638 }
2639
2640 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002641 std::make_pair(
2642 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002643
2644 LOG(LS_INFO) << "New audio stream " << ssrc
2645 << " registered to VoiceEngine channel #"
2646 << channel << ".";
2647 return true;
2648}
2649
2650bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002651 // Configure to use external transport, like our default channel.
2652 if (engine()->voe()->network()->RegisterExternalTransport(
2653 channel, *this) == -1) {
2654 LOG_RTCERR2(SetExternalTransport, channel, this);
2655 return false;
2656 }
2657
2658 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002659 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002660 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2661 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002662 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002663 return false;
2664 }
2665 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002666 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002667 return false;
2668 }
2669
2670 // Use the same recv payload types as our default channel.
2671 ResetRecvCodecs(channel);
2672 if (!recv_codecs_.empty()) {
2673 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2674 it != recv_codecs_.end(); ++it) {
2675 webrtc::CodecInst voe_codec;
2676 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2677 voe_codec.pltype = it->id;
2678 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2679 if (engine()->voe()->codec()->GetRecPayloadType(
2680 voe_channel(), voe_codec) != -1) {
2681 if (engine()->voe()->codec()->SetRecPayloadType(
2682 channel, voe_codec) == -1) {
2683 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2684 return false;
2685 }
2686 }
2687 }
2688 }
2689 }
2690
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002691 if (InConferenceMode()) {
2692 // To be in par with the video, voe_channel() is not used for receiving in
2693 // a conference call.
2694 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2695 // This is the first stream in a multi user meeting. We can now
2696 // disable playback of the default stream. This since the default
2697 // stream will probably have received some initial packets before
2698 // the new stream was added. This will mean that the CN state from
2699 // the default channel will be mixed in with the other streams
2700 // throughout the whole meeting, which might be disturbing.
2701 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2702 SetPlayout(voe_channel(), false);
2703 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002704 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002705 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002706
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002707 // Set RTP header extension for the new channel.
2708 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2709 return false;
2710 }
2711
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002712 return SetPlayout(channel, playout_);
2713}
2714
2715bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002716 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002717 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002718 if (it == receive_channels_.end()) {
2719 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2720 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002721 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002722 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002723
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002724 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2725 // will disconnect the audio renderer with the receive channel.
2726 // Cache the channel before the deletion.
2727 const int channel = it->second->channel();
2728 delete it->second;
2729 receive_channels_.erase(it);
2730
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002731 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002732 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002733 // Recycle the default channel is for recv stream.
2734 if (playout_)
2735 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002736
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002737 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002738 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002739 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002740
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002741 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002742 << " with VoiceEngine channel #" << channel << ".";
2743 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002744 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002745
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002746 bool enable_default_channel_playout = false;
2747 if (receive_channels_.empty()) {
2748 // The last stream was removed. We can now enable the default
2749 // channel for new channels to be played out immediately without
2750 // waiting for AddStream messages.
2751 // We do this for both conference mode and non-conference mode.
2752 // TODO(oja): Does the default channel still have it's CN state?
2753 enable_default_channel_playout = true;
2754 }
2755 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2756 default_receive_ssrc_ != 0) {
2757 // Only the default channel is active, enable the playout on default
2758 // channel.
2759 enable_default_channel_playout = true;
2760 }
2761 if (enable_default_channel_playout && playout_) {
2762 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2763 SetPlayout(voe_channel(), true);
2764 }
2765
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002766 return true;
2767}
2768
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002769bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2770 AudioRenderer* renderer) {
2771 ChannelMap::iterator it = receive_channels_.find(ssrc);
2772 if (it == receive_channels_.end()) {
2773 if (renderer) {
2774 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002775 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002776 return false;
2777 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002778
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002779 // The channel likely has gone away, do nothing.
2780 return true;
2781 }
2782
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002783 if (renderer)
2784 it->second->Start(renderer);
2785 else
2786 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002787
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002788 return true;
2789}
2790
2791bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2792 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002793 ChannelMap::iterator it = send_channels_.find(ssrc);
2794 if (it == send_channels_.end()) {
2795 if (renderer) {
2796 // Return an error if trying to set a valid renderer with an invalid ssrc.
2797 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2798 return false;
2799 }
2800
2801 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002802 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002803 }
2804
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002805 if (renderer)
2806 it->second->Start(renderer);
2807 else
2808 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002809
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002810 return true;
2811}
2812
2813bool WebRtcVoiceMediaChannel::GetActiveStreams(
2814 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002815 // In conference mode, the default channel should not be in
2816 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002817 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002818 for (ChannelMap::iterator it = receive_channels_.begin();
2819 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002820 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002821 if (level > 0) {
2822 actives->push_back(std::make_pair(it->first, level));
2823 }
2824 }
2825 return true;
2826}
2827
2828int WebRtcVoiceMediaChannel::GetOutputLevel() {
2829 // return the highest output level of all streams
2830 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002831 for (ChannelMap::iterator it = receive_channels_.begin();
2832 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002833 int level = GetOutputLevel(it->second->channel());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002834 highest = rtc::_max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002835 }
2836 return highest;
2837}
2838
2839int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2840 int ret;
2841 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2842 // In case of error, log the info and continue
2843 LOG_RTCERR0(TimeSinceLastTyping);
2844 ret = -1;
2845 } else {
2846 ret *= 1000; // We return ms, webrtc returns seconds.
2847 }
2848 return ret;
2849}
2850
2851void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2852 int cost_per_typing, int reporting_threshold, int penalty_decay,
2853 int type_event_delay) {
2854 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2855 time_window, cost_per_typing,
2856 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2857 // In case of error, log the info and continue
2858 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2859 cost_per_typing, reporting_threshold, penalty_decay,
2860 type_event_delay);
2861 }
2862}
2863
2864bool WebRtcVoiceMediaChannel::SetOutputScaling(
2865 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002866 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002867 // Collect the channels to scale the output volume.
2868 std::vector<int> channels;
2869 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002870 // Default channel is not in receive_channels_ if it is not being used for
2871 // playout.
2872 if (default_receive_ssrc_ == 0)
2873 channels.push_back(voe_channel());
2874 for (ChannelMap::const_iterator it = receive_channels_.begin();
2875 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002876 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002877 }
2878 } else { // Collect only the channel of the specified ssrc.
2879 int channel = GetReceiveChannelNum(ssrc);
2880 if (-1 == channel) {
2881 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2882 return false;
2883 }
2884 channels.push_back(channel);
2885 }
2886
2887 // Scale the output volume for the collected channels. We first normalize to
2888 // scale the volume and then set the left and right pan.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002889 float scale = static_cast<float>(rtc::_max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002890 if (scale > 0.0001f) {
2891 left /= scale;
2892 right /= scale;
2893 }
2894 for (std::vector<int>::const_iterator it = channels.begin();
2895 it != channels.end(); ++it) {
2896 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2897 *it, scale)) {
2898 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2899 return false;
2900 }
2901 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2902 *it, static_cast<float>(left), static_cast<float>(right))) {
2903 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2904 // Do not return if fails. SetOutputVolumePan is not available for all
2905 // pltforms.
2906 }
2907 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2908 << " right=" << right * scale
2909 << " for channel " << *it << " and ssrc " << ssrc;
2910 }
2911 return true;
2912}
2913
2914bool WebRtcVoiceMediaChannel::GetOutputScaling(
2915 uint32 ssrc, double* left, double* right) {
2916 if (!left || !right) return false;
2917
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002918 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002919 // Determine which channel based on ssrc.
2920 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2921 if (channel == -1) {
2922 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2923 return false;
2924 }
2925
2926 float scaling;
2927 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2928 channel, scaling)) {
2929 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2930 return false;
2931 }
2932
2933 float left_pan;
2934 float right_pan;
2935 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2936 channel, left_pan, right_pan)) {
2937 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2938 // If GetOutputVolumePan fails, we use the default left and right pan.
2939 left_pan = 1.0f;
2940 right_pan = 1.0f;
2941 }
2942
2943 *left = scaling * left_pan;
2944 *right = scaling * right_pan;
2945 return true;
2946}
2947
2948bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2949 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2950 return true;
2951}
2952
2953bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2954 bool play, bool loop) {
2955 if (!ringback_tone_) {
2956 return false;
2957 }
2958
2959 // The voe file api is not available in chrome.
2960 if (!engine()->voe()->file()) {
2961 return false;
2962 }
2963
2964 // Determine which VoiceEngine channel to play on.
2965 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2966 if (channel == -1) {
2967 return false;
2968 }
2969
2970 // Make sure the ringtone is cued properly, and play it out.
2971 if (play) {
2972 ringback_tone_->set_loop(loop);
2973 ringback_tone_->Rewind();
2974 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2975 ringback_tone_.get()) == -1) {
2976 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2977 LOG(LS_ERROR) << "Unable to start ringback tone";
2978 return false;
2979 }
2980 ringback_channels_.insert(channel);
2981 LOG(LS_INFO) << "Started ringback on channel " << channel;
2982 } else {
2983 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2984 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2985 LOG_RTCERR1(StopPlayingFileLocally, channel);
2986 return false;
2987 }
2988 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2989 ringback_channels_.erase(channel);
2990 }
2991
2992 return true;
2993}
2994
2995bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2996 return dtmf_allowed_;
2997}
2998
2999bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3000 int duration, int flags) {
3001 if (!dtmf_allowed_) {
3002 return false;
3003 }
3004
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003005 // Send the event.
3006 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003007 int channel = -1;
3008 if (ssrc == 0) {
3009 bool default_channel_is_inuse = false;
3010 for (ChannelMap::const_iterator iter = send_channels_.begin();
3011 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003012 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003013 default_channel_is_inuse = true;
3014 break;
3015 }
3016 }
3017 if (default_channel_is_inuse) {
3018 channel = voe_channel();
3019 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003020 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003021 }
3022 } else {
3023 channel = GetSendChannelNum(ssrc);
3024 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003025 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003026 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3027 << ssrc << " is not in use.";
3028 return false;
3029 }
3030 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003031 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3032 channel, event, true, duration) == -1) {
3033 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003034 return false;
3035 }
3036 }
3037
3038 // Play the event.
3039 if (flags & cricket::DF_PLAY) {
3040 // Play DTMF tone locally.
3041 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3042 LOG_RTCERR2(PlayDtmfTone, event, duration);
3043 return false;
3044 }
3045 }
3046
3047 return true;
3048}
3049
wu@webrtc.orga9890802013-12-13 00:21:03 +00003050void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003051 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003052 // Pick which channel to send this packet to. If this packet doesn't match
3053 // any multiplexed streams, just send it to the default channel. Otherwise,
3054 // send it to the specific decoder instance for that stream.
3055 int which_channel = GetReceiveChannelNum(
3056 ParseSsrc(packet->data(), packet->length(), false));
3057 if (which_channel == -1) {
3058 which_channel = voe_channel();
3059 }
3060
3061 // Stop any ringback that might be playing on the channel.
3062 // It's possible the ringback has already stopped, ih which case we'll just
3063 // use the opportunity to remove the channel from ringback_channels_.
3064 if (engine()->voe()->file()) {
3065 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3066 if (it != ringback_channels_.end()) {
3067 if (engine()->voe()->file()->IsPlayingFileLocally(
3068 which_channel) == 1) {
3069 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3070 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3071 << " due to incoming media";
3072 }
3073 ringback_channels_.erase(which_channel);
3074 }
3075 }
3076
3077 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003078 engine()->voe()->network()->ReceivedRTPPacket(
3079 which_channel,
3080 packet->data(),
3081 static_cast<unsigned int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003082}
3083
wu@webrtc.orga9890802013-12-13 00:21:03 +00003084void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003085 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003086 // Sending channels need all RTCP packets with feedback information.
3087 // Even sender reports can contain attached report blocks.
3088 // Receiving channels need sender reports in order to create
3089 // correct receiver reports.
3090 int type = 0;
3091 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3092 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3093 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003094 }
3095
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003096 // If it is a sender report, find the channel that is listening.
3097 bool has_sent_to_default_channel = false;
3098 if (type == kRtcpTypeSR) {
3099 int which_channel = GetReceiveChannelNum(
3100 ParseSsrc(packet->data(), packet->length(), true));
3101 if (which_channel != -1) {
3102 engine()->voe()->network()->ReceivedRTCPPacket(
3103 which_channel,
3104 packet->data(),
3105 static_cast<unsigned int>(packet->length()));
3106
3107 if (IsDefaultChannel(which_channel))
3108 has_sent_to_default_channel = true;
3109 }
3110 }
3111
3112 // SR may continue RR and any RR entry may correspond to any one of the send
3113 // channels. So all RTCP packets must be forwarded all send channels. VoE
3114 // will filter out RR internally.
3115 for (ChannelMap::iterator iter = send_channels_.begin();
3116 iter != send_channels_.end(); ++iter) {
3117 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003118 if (IsDefaultChannel(iter->second->channel()) &&
3119 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003120 continue;
3121
3122 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003123 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003124 packet->data(),
3125 static_cast<unsigned int>(packet->length()));
3126 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003127}
3128
3129bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003130 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3131 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003132 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3133 return false;
3134 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003135 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3136 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003137 return false;
3138 }
3139 return true;
3140}
3141
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003142bool WebRtcVoiceMediaChannel::SetStartSendBandwidth(int bps) {
3143 // TODO(andresp): Add support for setting an independent start bandwidth when
3144 // bandwidth estimation is enabled for voice engine.
3145 return false;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003146}
3147
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003148bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
3149 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
3150
3151 return SetSendBandwidthInternal(bps);
3152}
3153
3154bool WebRtcVoiceMediaChannel::SetSendBandwidthInternal(int bps) {
3155 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBandwidthInternal.";
3156
3157 send_bw_setting_ = true;
3158 send_bw_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003159
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003160 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003161 LOG(LS_INFO) << "The send codec has not been set up yet. "
3162 << "The send bandwidth setting will be applied later.";
3163 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003164 }
3165
3166 // Bandwidth is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003167 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3168 // SetMaxSendBandwith(0), the second call removes the previous limit.
3169 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003170 return true;
3171
3172 webrtc::CodecInst codec = *send_codec_;
3173 bool is_multi_rate = IsCodecMultiRate(codec);
3174
3175 if (is_multi_rate) {
3176 // If codec is multi-rate then just set the bitrate.
3177 codec.rate = bps;
3178 if (!SetSendCodec(codec)) {
3179 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3180 << " to bitrate " << bps << " bps.";
3181 return false;
3182 }
3183 return true;
3184 } else {
3185 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3186 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3187 // fixed bitrate then ignore.
3188 if (bps < codec.rate) {
3189 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3190 << " to bitrate " << bps << " bps"
3191 << ", requires at least " << codec.rate << " bps.";
3192 return false;
3193 }
3194 return true;
3195 }
3196}
3197
3198bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003199 bool echo_metrics_on = false;
3200 // These can take on valid negative values, so use the lowest possible level
3201 // as default rather than -1.
3202 int echo_return_loss = -100;
3203 int echo_return_loss_enhancement = -100;
3204 // These can also be negative, but in practice -1 is only used to signal
3205 // insufficient data, since the resolution is limited to multiples of 4 ms.
3206 int echo_delay_median_ms = -1;
3207 int echo_delay_std_ms = -1;
3208 if (engine()->voe()->processing()->GetEcMetricsStatus(
3209 echo_metrics_on) != -1 && echo_metrics_on) {
3210 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3211 // here, but it appears to be unsuitable currently. Revisit after this is
3212 // investigated: http://b/issue?id=5666755
3213 int erl, erle, rerl, anlp;
3214 if (engine()->voe()->processing()->GetEchoMetrics(
3215 erl, erle, rerl, anlp) != -1) {
3216 echo_return_loss = erl;
3217 echo_return_loss_enhancement = erle;
3218 }
3219
3220 int median, std;
3221 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3222 echo_delay_median_ms = median;
3223 echo_delay_std_ms = std;
3224 }
3225 }
3226
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003227 webrtc::CallStatistics cs;
3228 unsigned int ssrc;
3229 webrtc::CodecInst codec;
3230 unsigned int level;
3231
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003232 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3233 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003234 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003235
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003236 // Fill in the sender info, based on what we know, and what the
3237 // remote side told us it got from its RTCP report.
3238 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003239
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003240 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3241 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3242 continue;
3243 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003244
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003245 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003246 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3247 sinfo.bytes_sent = cs.bytesSent;
3248 sinfo.packets_sent = cs.packetsSent;
3249 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3250 // returns 0 to indicate an error value.
3251 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3252
3253 // Get data from the last remote RTCP report. Use default values if no data
3254 // available.
3255 sinfo.fraction_lost = -1.0;
3256 sinfo.jitter_ms = -1;
3257 sinfo.packets_lost = -1;
3258 sinfo.ext_seqnum = -1;
3259 std::vector<webrtc::ReportBlock> receive_blocks;
3260 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3261 channel, &receive_blocks) != -1 &&
3262 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3263 std::vector<webrtc::ReportBlock>::iterator iter;
3264 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3265 ++iter) {
3266 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003267 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003268 // Convert Q8 to floating point.
3269 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3270 // Convert samples to milliseconds.
3271 if (codec.plfreq / 1000 > 0) {
3272 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3273 }
3274 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3275 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3276 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003277 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003278 }
3279 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003280
3281 // Local speech level.
3282 sinfo.audio_level = (engine()->voe()->volume()->
3283 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3284
3285 // TODO(xians): We are injecting the same APM logging to all the send
3286 // channels here because there is no good way to know which send channel
3287 // is using the APM. The correct fix is to allow the send channels to have
3288 // their own APM so that we can feed the correct APM logging to different
3289 // send channels. See issue crbug/264611 .
3290 sinfo.echo_return_loss = echo_return_loss;
3291 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3292 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3293 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003294 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3295 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003296 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003297
3298 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003299 }
3300
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003301 // Build the list of receivers, one for each receiving channel, or 1 in
3302 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003303 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003304 for (ChannelMap::const_iterator it = receive_channels_.begin();
3305 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003306 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003307 }
3308 if (channels.empty()) {
3309 channels.push_back(voe_channel());
3310 }
3311
3312 // Get the SSRC and stats for each receiver, based on our own calculations.
3313 for (std::vector<int>::const_iterator it = channels.begin();
3314 it != channels.end(); ++it) {
3315 memset(&cs, 0, sizeof(cs));
3316 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3317 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3318 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3319 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003320 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003321 rinfo.bytes_rcvd = cs.bytesReceived;
3322 rinfo.packets_rcvd = cs.packetsReceived;
3323 // The next four fields are from the most recently sent RTCP report.
3324 // Convert Q8 to floating point.
3325 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3326 rinfo.packets_lost = cs.cumulativeLost;
3327 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003328#ifdef USE_WEBRTC_DEV_BRANCH
3329 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
3330#endif
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003331 if (codec.pltype != -1) {
3332 rinfo.codec_name = codec.plname;
3333 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003334 // Convert samples to milliseconds.
3335 if (codec.plfreq / 1000 > 0) {
3336 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3337 }
3338
3339 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3340 webrtc::NetworkStatistics ns;
3341 if (engine()->voe()->neteq() &&
3342 engine()->voe()->neteq()->GetNetworkStatistics(
3343 *it, ns) != -1) {
3344 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3345 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3346 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003347 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003348 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003349
3350 webrtc::AudioDecodingCallStats ds;
3351 if (engine()->voe()->neteq() &&
3352 engine()->voe()->neteq()->GetDecodingCallStatistics(
3353 *it, &ds) != -1) {
3354 rinfo.decoding_calls_to_silence_generator =
3355 ds.calls_to_silence_generator;
3356 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3357 rinfo.decoding_normal = ds.decoded_normal;
3358 rinfo.decoding_plc = ds.decoded_plc;
3359 rinfo.decoding_cng = ds.decoded_cng;
3360 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3361 }
3362
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003363 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003364 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003365 int playout_buffer_delay_ms = 0;
3366 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003367 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3368 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3369 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003370 }
3371
3372 // Get speech level.
3373 rinfo.audio_level = (engine()->voe()->volume()->
3374 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3375 info->receivers.push_back(rinfo);
3376 }
3377 }
3378
3379 return true;
3380}
3381
3382void WebRtcVoiceMediaChannel::GetLastMediaError(
3383 uint32* ssrc, VoiceMediaChannel::Error* error) {
3384 ASSERT(ssrc != NULL);
3385 ASSERT(error != NULL);
3386 FindSsrc(voe_channel(), ssrc);
3387 *error = WebRtcErrorToChannelError(GetLastEngineError());
3388}
3389
3390bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003391 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003392 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003393 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003394 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3395 // This means the error is not limited to a specific channel. Signal the
3396 // message using ssrc=0. If the current channel is sending, use this
3397 // channel for sending the message.
3398 *ssrc = 0;
3399 return true;
3400 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003401 // Check whether this is a sending channel.
3402 for (ChannelMap::const_iterator it = send_channels_.begin();
3403 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003404 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003405 // This is a sending channel.
3406 uint32 local_ssrc = 0;
3407 if (engine()->voe()->rtp()->GetLocalSSRC(
3408 channel_num, local_ssrc) != -1) {
3409 *ssrc = local_ssrc;
3410 }
3411 return true;
3412 }
3413 }
3414
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003415 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003416 for (ChannelMap::const_iterator it = receive_channels_.begin();
3417 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003418 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003419 *ssrc = it->first;
3420 return true;
3421 }
3422 }
3423 }
3424 return false;
3425}
3426
3427void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003428 if (error == VE_TYPING_NOISE_WARNING) {
3429 typing_noise_detected_ = true;
3430 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3431 typing_noise_detected_ = false;
3432 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003433 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3434}
3435
3436int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3437 unsigned int ulevel;
3438 int ret =
3439 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3440 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3441}
3442
3443int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003444 ChannelMap::iterator it = receive_channels_.find(ssrc);
3445 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003446 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003447 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3448}
3449
3450int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003451 ChannelMap::iterator it = send_channels_.find(ssrc);
3452 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003453 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003454
3455 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003456}
3457
3458bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3459 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3460 // Get the RED encodings from the parameter with no name. This may
3461 // change based on what is discussed on the Jingle list.
3462 // The encoding parameter is of the form "a/b"; we only support where
3463 // a == b. Verify this and parse out the value into red_pt.
3464 // If the parameter value is absent (as it will be until we wire up the
3465 // signaling of this message), use the second codec specified (i.e. the
3466 // one after "red") as the encoding parameter.
3467 int red_pt = -1;
3468 std::string red_params;
3469 CodecParameterMap::const_iterator it = red_codec.params.find("");
3470 if (it != red_codec.params.end()) {
3471 red_params = it->second;
3472 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003473 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003474 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003475 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003476 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3477 return false;
3478 }
3479 } else if (red_codec.params.empty()) {
3480 LOG(LS_WARNING) << "RED params not present, using defaults";
3481 if (all_codecs.size() > 1) {
3482 red_pt = all_codecs[1].id;
3483 }
3484 }
3485
3486 // Try to find red_pt in |codecs|.
3487 std::vector<AudioCodec>::const_iterator codec;
3488 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3489 if (codec->id == red_pt)
3490 break;
3491 }
3492
3493 // If we find the right codec, that will be the codec we pass to
3494 // SetSendCodec, with the desired payload type.
3495 if (codec != all_codecs.end() &&
3496 engine()->FindWebRtcCodec(*codec, send_codec)) {
3497 } else {
3498 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3499 return false;
3500 }
3501
3502 return true;
3503}
3504
3505bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3506 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003507 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003508 return false;
3509 }
3510 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3511 // what we want to do with them.
3512 // engine()->voe().EnableVQMon(voe_channel(), true);
3513 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3514 return true;
3515}
3516
3517bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3518 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3519 for (int i = 0; i < ncodecs; ++i) {
3520 webrtc::CodecInst voe_codec;
3521 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3522 voe_codec.pltype = -1;
3523 if (engine()->voe()->codec()->SetRecPayloadType(
3524 channel, voe_codec) == -1) {
3525 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3526 return false;
3527 }
3528 }
3529 }
3530 return true;
3531}
3532
3533bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3534 if (playout) {
3535 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3536 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3537 LOG_RTCERR1(StartPlayout, channel);
3538 return false;
3539 }
3540 } else {
3541 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3542 engine()->voe()->base()->StopPlayout(channel);
3543 }
3544 return true;
3545}
3546
3547uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3548 bool rtcp) {
3549 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3550 uint32 ssrc = 0;
3551 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003552 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003553 }
3554 return ssrc;
3555}
3556
3557// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3558VoiceMediaChannel::Error
3559 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3560 switch (err_code) {
3561 case 0:
3562 return ERROR_NONE;
3563 case VE_CANNOT_START_RECORDING:
3564 case VE_MIC_VOL_ERROR:
3565 case VE_GET_MIC_VOL_ERROR:
3566 case VE_CANNOT_ACCESS_MIC_VOL:
3567 return ERROR_REC_DEVICE_OPEN_FAILED;
3568 case VE_SATURATION_WARNING:
3569 return ERROR_REC_DEVICE_SATURATION;
3570 case VE_REC_DEVICE_REMOVED:
3571 return ERROR_REC_DEVICE_REMOVED;
3572 case VE_RUNTIME_REC_WARNING:
3573 case VE_RUNTIME_REC_ERROR:
3574 return ERROR_REC_RUNTIME_ERROR;
3575 case VE_CANNOT_START_PLAYOUT:
3576 case VE_SPEAKER_VOL_ERROR:
3577 case VE_GET_SPEAKER_VOL_ERROR:
3578 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3579 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3580 case VE_RUNTIME_PLAY_WARNING:
3581 case VE_RUNTIME_PLAY_ERROR:
3582 return ERROR_PLAY_RUNTIME_ERROR;
3583 case VE_TYPING_NOISE_WARNING:
3584 return ERROR_REC_TYPING_NOISE_DETECTED;
3585 default:
3586 return VoiceMediaChannel::ERROR_OTHER;
3587 }
3588}
3589
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003590bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3591 int channel_id, const RtpHeaderExtension* extension) {
3592 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003593 int id = 0;
3594 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003595 if (extension) {
3596 enable = true;
3597 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003598 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003599 }
3600 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003601 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003602 return false;
3603 }
3604 return true;
3605}
3606
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003607int WebRtcSoundclipStream::Read(void *buf, int len) {
3608 size_t res = 0;
3609 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003610 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003611}
3612
3613int WebRtcSoundclipStream::Rewind() {
3614 mem_.Rewind();
3615 // Return -1 to keep VoiceEngine from looping.
3616 return (loop_) ? 0 : -1;
3617}
3618
3619} // namespace cricket
3620
3621#endif // HAVE_WEBRTC_VOICE