blob: 5cf53e4f06dc2bd0329a972a4f573e5cef5cfe3b [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#ifdef HAVE_CONFIG_H
29#include <config.h>
30#endif
31
32#ifdef HAVE_WEBRTC_VOICE
33
34#include "talk/media/webrtc/webrtcvoiceengine.h"
35
36#include <algorithm>
37#include <cstdio>
38#include <string>
39#include <vector>
40
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000041#include "talk/media/base/audiorenderer.h"
42#include "talk/media/base/constants.h"
43#include "talk/media/base/streamparams.h"
44#include "talk/media/base/voiceprocessor.h"
45#include "talk/media/webrtc/webrtcvoe.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000046#include "webrtc/base/base64.h"
47#include "webrtc/base/byteorder.h"
48#include "webrtc/base/common.h"
49#include "webrtc/base/helpers.h"
50#include "webrtc/base/logging.h"
51#include "webrtc/base/stringencode.h"
52#include "webrtc/base/stringutils.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000053#include "webrtc/common.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054#include "webrtc/modules/audio_processing/include/audio_processing.h"
55
56#ifdef WIN32
57#include <objbase.h> // NOLINT
58#endif
59
60namespace cricket {
61
62struct CodecPref {
63 const char* name;
64 int clockrate;
65 int channels;
66 int payload_type;
67 bool is_multi_rate;
68};
69
70static const CodecPref kCodecPrefs[] = {
71 { "OPUS", 48000, 2, 111, true },
72 { "ISAC", 16000, 1, 103, true },
73 { "ISAC", 32000, 1, 104, true },
74 { "CELT", 32000, 1, 109, true },
75 { "CELT", 32000, 2, 110, true },
76 { "G722", 16000, 1, 9, false },
77 { "ILBC", 8000, 1, 102, false },
78 { "PCMU", 8000, 1, 0, false },
79 { "PCMA", 8000, 1, 8, false },
80 { "CN", 48000, 1, 107, false },
81 { "CN", 32000, 1, 106, false },
82 { "CN", 16000, 1, 105, false },
83 { "CN", 8000, 1, 13, false },
84 { "red", 8000, 1, 127, false },
85 { "telephone-event", 8000, 1, 126, false },
86};
87
88// For Linux/Mac, using the default device is done by specifying index 0 for
89// VoE 4.0 and not -1 (which was the case for VoE 3.5).
90//
91// On Windows Vista and newer, Microsoft introduced the concept of "Default
92// Communications Device". This means that there are two types of default
93// devices (old Wave Audio style default and Default Communications Device).
94//
95// On Windows systems which only support Wave Audio style default, uses either
96// -1 or 0 to select the default device.
97//
98// On Windows systems which support both "Default Communication Device" and
99// old Wave Audio style default, use -1 for Default Communications Device and
100// -2 for Wave Audio style default, which is what we want to use for clips.
101// It's not clear yet whether the -2 index is handled properly on other OSes.
102
103#ifdef WIN32
104static const int kDefaultAudioDeviceId = -1;
105static const int kDefaultSoundclipDeviceId = -2;
106#else
107static const int kDefaultAudioDeviceId = 0;
108#endif
109
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110static const char kIsacCodecName[] = "ISAC";
111static const char kL16CodecName[] = "L16";
112// Codec parameters for Opus.
113static const int kOpusMonoBitrate = 32000;
114// Parameter used for NACK.
115// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
116static const int kNackMaxPackets = 250;
117static const int kOpusStereoBitrate = 64000;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000118// draft-spittka-payload-rtp-opus-03
119// Opus bitrate should be in the range between 6000 and 510000.
120static const int kOpusMinBitrate = 6000;
121static const int kOpusMaxBitrate = 510000;
wu@webrtc.orgde305012013-10-31 15:40:38 +0000122// Default audio dscp value.
123// See http://tools.ietf.org/html/rfc2474 for details.
124// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000125static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000126
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000127// Ensure we open the file in a writeable path on ChromeOS and Android. This
128// workaround can be removed when it's possible to specify a filename for audio
129// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000130//
131// TODO(grunell): Use a string in the options instead of hardcoding it here
132// and let the embedder choose the filename (crbug.com/264223).
133//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000134// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
135// below.
136#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000137static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000138#elif defined(ANDROID)
139static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000140#else
141static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
142#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000143
144// Dumps an AudioCodec in RFC 2327-ish format.
145static std::string ToString(const AudioCodec& codec) {
146 std::stringstream ss;
147 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
148 << " (" << codec.id << ")";
149 return ss.str();
150}
151static std::string ToString(const webrtc::CodecInst& codec) {
152 std::stringstream ss;
153 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
154 << " (" << codec.pltype << ")";
155 return ss.str();
156}
157
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000158static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000159 const char* delim = "\r\n";
160 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
161 LOG_V(sev) << tok;
162 }
163}
164
165// Severity is an integer because it comes is assumed to be from command line.
166static int SeverityToFilter(int severity) {
167 int filter = webrtc::kTraceNone;
168 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000169 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000170 filter |= webrtc::kTraceAll;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000171 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000172 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000173 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000174 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000175 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000176 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
177 }
178 return filter;
179}
180
181static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
182 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
183 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
184 kCodecPrefs[i].clockrate == codec.plfreq) {
185 return kCodecPrefs[i].is_multi_rate;
186 }
187 }
188 return false;
189}
190
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000191static bool IsTelephoneEventCodec(const std::string& name) {
192 return _stricmp(name.c_str(), "telephone-event") == 0;
193}
194
195static bool IsCNCodec(const std::string& name) {
196 return _stricmp(name.c_str(), "CN") == 0;
197}
198
199static bool IsRedCodec(const std::string& name) {
200 return _stricmp(name.c_str(), "red") == 0;
201}
202
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000203static bool FindCodec(const std::vector<AudioCodec>& codecs,
204 const AudioCodec& codec,
205 AudioCodec* found_codec) {
206 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
207 it != codecs.end(); ++it) {
208 if (it->Matches(codec)) {
209 if (found_codec != NULL) {
210 *found_codec = *it;
211 }
212 return true;
213 }
214 }
215 return false;
216}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000217
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000218static bool IsNackEnabled(const AudioCodec& codec) {
219 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
220 kParamValueEmpty));
221}
222
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000223// Gets the default set of options applied to the engine. Historically, these
224// were supplied as a combination of flags from the channel manager (ec, agc,
225// ns, and highpass) and the rest hardcoded in InitInternal.
226static AudioOptions GetDefaultEngineOptions() {
227 AudioOptions options;
228 options.echo_cancellation.Set(true);
229 options.auto_gain_control.Set(true);
230 options.noise_suppression.Set(true);
231 options.highpass_filter.Set(true);
232 options.stereo_swapping.Set(false);
233 options.typing_detection.Set(true);
234 options.conference_mode.Set(false);
235 options.adjust_agc_delta.Set(0);
236 options.experimental_agc.Set(false);
237 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000238 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000239 options.aec_dump.Set(false);
240 return options;
241}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000242
243class WebRtcSoundclipMedia : public SoundclipMedia {
244 public:
245 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
246 : engine_(engine), webrtc_channel_(-1) {
247 engine_->RegisterSoundclip(this);
248 }
249
250 virtual ~WebRtcSoundclipMedia() {
251 engine_->UnregisterSoundclip(this);
252 if (webrtc_channel_ != -1) {
253 // We shouldn't have to call Disable() here. DeleteChannel() should call
254 // StopPlayout() while deleting the channel. We should fix the bug
255 // inside WebRTC and remove the Disable() call bellow. This work is
256 // tracked by bug http://b/issue?id=5382855.
257 PlaySound(NULL, 0, 0);
258 Disable();
259 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
260 == -1) {
261 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
262 }
263 }
264 }
265
266 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000267 if (!engine_->voe_sc()) {
268 return false;
269 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000270 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000271 if (webrtc_channel_ == -1) {
272 LOG_RTCERR0(CreateChannel);
273 return false;
274 }
275 return true;
276 }
277
278 bool Enable() {
279 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
280 LOG_RTCERR1(StartPlayout, webrtc_channel_);
281 return false;
282 }
283 return true;
284 }
285
286 bool Disable() {
287 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
288 LOG_RTCERR1(StopPlayout, webrtc_channel_);
289 return false;
290 }
291 return true;
292 }
293
294 virtual bool PlaySound(const char *buf, int len, int flags) {
295 // The voe file api is not available in chrome.
296 if (!engine_->voe_sc()->file()) {
297 return false;
298 }
299 // Must stop playing the current sound (if any), because we are about to
300 // modify the stream.
301 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
302 == -1) {
303 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
304 return false;
305 }
306
307 if (buf) {
308 stream_.reset(new WebRtcSoundclipStream(buf, len));
309 stream_->set_loop((flags & SF_LOOP) != 0);
310 stream_->Rewind();
311
312 // Play it.
313 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
314 webrtc_channel_, stream_.get()) == -1) {
315 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
316 LOG(LS_ERROR) << "Unable to start soundclip";
317 return false;
318 }
319 } else {
320 stream_.reset();
321 }
322 return true;
323 }
324
325 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
326
327 private:
328 WebRtcVoiceEngine *engine_;
329 int webrtc_channel_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000330 rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000331};
332
333WebRtcVoiceEngine::WebRtcVoiceEngine()
334 : voe_wrapper_(new VoEWrapper()),
335 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000336 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000337 tracing_(new VoETraceWrapper()),
338 adm_(NULL),
339 adm_sc_(NULL),
340 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
341 is_dumping_aec_(false),
342 desired_local_monitor_enable_(false),
343 tx_processor_ssrc_(0),
344 rx_processor_ssrc_(0) {
345 Construct();
346}
347
348WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
349 VoEWrapper* voe_wrapper_sc,
350 VoETraceWrapper* tracing)
351 : voe_wrapper_(voe_wrapper),
352 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000353 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000354 tracing_(tracing),
355 adm_(NULL),
356 adm_sc_(NULL),
357 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
358 is_dumping_aec_(false),
359 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000360 tx_processor_ssrc_(0),
361 rx_processor_ssrc_(0) {
362 Construct();
363}
364
365void WebRtcVoiceEngine::Construct() {
366 SetTraceFilter(log_filter_);
367 initialized_ = false;
368 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
369 SetTraceOptions("");
370 if (tracing_->SetTraceCallback(this) == -1) {
371 LOG_RTCERR0(SetTraceCallback);
372 }
373 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
374 LOG_RTCERR0(RegisterVoiceEngineObserver);
375 }
376 // Clear the default agc state.
377 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
378
379 // Load our audio codec list.
380 ConstructCodecs();
381
382 // Load our RTP Header extensions.
383 rtp_header_extensions_.push_back(
384 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
385 kRtpAudioLevelHeaderExtensionDefaultId));
386 rtp_header_extensions_.push_back(
387 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
388 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
389 options_ = GetDefaultEngineOptions();
390}
391
392static bool IsOpus(const AudioCodec& codec) {
393 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
394}
395
396static bool IsIsac(const AudioCodec& codec) {
397 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
398}
399
400// True if params["stereo"] == "1"
401static bool IsOpusStereoEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000402 int value;
403 return codec.GetParam(kCodecParamStereo, &value) && value == 1;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000404}
405
406static bool IsValidOpusBitrate(int bitrate) {
407 return (bitrate >= kOpusMinBitrate && bitrate <= kOpusMaxBitrate);
408}
409
410// Returns 0 if params[kCodecParamMaxAverageBitrate] is not defined or invalid.
411// Returns the value of params[kCodecParamMaxAverageBitrate] otherwise.
412static int GetOpusBitrateFromParams(const AudioCodec& codec) {
413 int bitrate = 0;
414 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
415 return 0;
416 }
417 if (!IsValidOpusBitrate(bitrate)) {
418 LOG(LS_WARNING) << "Codec parameter \"maxaveragebitrate\" has an "
419 << "invalid value: " << bitrate;
420 return 0;
421 }
422 return bitrate;
423}
424
buildbot@webrtc.orgfbd13282014-06-19 19:50:55 +0000425// Return true if params[kCodecParamUseInbandFec] == "1", false
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000426// otherwise.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000427static bool IsOpusFecEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000428 int value;
429 return codec.GetParam(kCodecParamUseInbandFec, &value) && value == 1;
430}
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000431
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000432void WebRtcVoiceEngine::ConstructCodecs() {
433 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
434 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
435 for (int i = 0; i < ncodecs; ++i) {
436 webrtc::CodecInst voe_codec;
437 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
438 // Skip uncompressed formats.
439 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
440 continue;
441 }
442
443 const CodecPref* pref = NULL;
444 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
445 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
446 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
447 kCodecPrefs[j].channels == voe_codec.channels) {
448 pref = &kCodecPrefs[j];
449 break;
450 }
451 }
452
453 if (pref) {
454 // Use the payload type that we've configured in our pref table;
455 // use the offset in our pref table to determine the sort order.
456 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
457 voe_codec.rate, voe_codec.channels,
458 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
459 LOG(LS_INFO) << ToString(codec);
460 if (IsIsac(codec)) {
461 // Indicate auto-bandwidth in signaling.
462 codec.bitrate = 0;
463 }
464 if (IsOpus(codec)) {
465 // Only add fmtp parameters that differ from the spec.
466 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
467 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000468 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000469 }
470 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
471 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000472 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000473 }
474 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
475 // when they can be set to values other than the default.
476 }
477 codecs_.push_back(codec);
478 } else {
479 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
480 }
481 }
482 }
483 // Make sure they are in local preference order.
484 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
485}
486
487WebRtcVoiceEngine::~WebRtcVoiceEngine() {
488 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
489 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
490 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
491 }
492 if (adm_) {
493 voe_wrapper_.reset();
494 adm_->Release();
495 adm_ = NULL;
496 }
497 if (adm_sc_) {
498 voe_wrapper_sc_.reset();
499 adm_sc_->Release();
500 adm_sc_ = NULL;
501 }
502
503 // Test to see if the media processor was deregistered properly
504 ASSERT(SignalRxMediaFrame.is_empty());
505 ASSERT(SignalTxMediaFrame.is_empty());
506
507 tracing_->SetTraceCallback(NULL);
508}
509
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000510bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000511 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
512 bool res = InitInternal();
513 if (res) {
514 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
515 } else {
516 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
517 Terminate();
518 }
519 return res;
520}
521
522bool WebRtcVoiceEngine::InitInternal() {
523 // Temporarily turn logging level up for the Init call
524 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000525 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000526 SetTraceFilter(extended_filter);
527 SetTraceOptions("");
528
529 // Init WebRtc VoiceEngine.
530 if (voe_wrapper_->base()->Init(adm_) == -1) {
531 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
532 SetTraceFilter(old_filter);
533 return false;
534 }
535
536 SetTraceFilter(old_filter);
537 SetTraceOptions(log_options_);
538
539 // Log the VoiceEngine version info
540 char buffer[1024] = "";
541 voe_wrapper_->base()->GetVersion(buffer);
542 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000543 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000544
545 // Save the default AGC configuration settings. This must happen before
546 // calling SetOptions or the default will be overwritten.
547 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
548 LOG_RTCERR0(GetAgcConfig);
549 return false;
550 }
551
552 // Set defaults for options, so that ApplyOptions applies them explicitly
553 // when we clear option (channel) overrides. External clients can still
554 // modify the defaults via SetOptions (on the media engine).
555 if (!SetOptions(GetDefaultEngineOptions())) {
556 return false;
557 }
558
559 // Print our codec list again for the call diagnostic log
560 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
561 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
562 it != codecs_.end(); ++it) {
563 LOG(LS_INFO) << ToString(*it);
564 }
565
566 // Disable the DTMF playout when a tone is sent.
567 // PlayDtmfTone will be used if local playout is needed.
568 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
569 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
570 }
571
572 initialized_ = true;
573 return true;
574}
575
576bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
577 if (voe_wrapper_sc_initialized_) {
578 return true;
579 }
580 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
581 // be false, so subsequent calls to EnsureSoundclipEngineInit will
582 // probably just fail again. That's acceptable behavior.
583#if defined(LINUX) && !defined(HAVE_LIBPULSE)
584 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
585#endif
586
587 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
588 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
589 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
590 return false;
591 }
592
593 // On Windows, tell it to use the default sound (not communication) devices.
594 // First check whether there is a valid sound device for playback.
595 // TODO(juberti): Clean this up when we support setting the soundclip device.
596#ifdef WIN32
597 // The SetPlayoutDevice may not be implemented in the case of external ADM.
598 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
599 // PeerConnection interface never set the adm_sc_, so need to check both
600 // in order to determine if the external adm is used.
601 if (!adm_ && !adm_sc_) {
602 int num_of_devices = 0;
603 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
604 num_of_devices > 0) {
605 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
606 == -1) {
607 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
608 voe_wrapper_sc_->error());
609 return false;
610 }
611 } else {
612 LOG(LS_WARNING) << "No valid sound playout device found.";
613 }
614 }
615#endif
616 voe_wrapper_sc_initialized_ = true;
617 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
618 return true;
619}
620
621void WebRtcVoiceEngine::Terminate() {
622 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
623 initialized_ = false;
624
625 StopAecDump();
626
627 if (voe_wrapper_sc_) {
628 voe_wrapper_sc_initialized_ = false;
629 voe_wrapper_sc_->base()->Terminate();
630 }
631 voe_wrapper_->base()->Terminate();
632 desired_local_monitor_enable_ = false;
633}
634
635int WebRtcVoiceEngine::GetCapabilities() {
636 return AUDIO_SEND | AUDIO_RECV;
637}
638
639VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
640 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
641 if (!ch->valid()) {
642 delete ch;
643 ch = NULL;
644 }
645 return ch;
646}
647
648SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
649 if (!EnsureSoundclipEngineInit()) {
650 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
651 << "initialize.";
652 return NULL;
653 }
654 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
655 if (!soundclip->Init() || !soundclip->Enable()) {
656 delete soundclip;
657 return NULL;
658 }
659 return soundclip;
660}
661
662bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
663 if (!ApplyOptions(options)) {
664 return false;
665 }
666 options_ = options;
667 return true;
668}
669
670bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
671 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
672 if (!ApplyOptions(overrides)) {
673 return false;
674 }
675 option_overrides_ = overrides;
676 return true;
677}
678
679bool WebRtcVoiceEngine::ClearOptionOverrides() {
680 LOG(LS_INFO) << "Clearing option overrides.";
681 AudioOptions options = options_;
682 // Only call ApplyOptions if |options_overrides_| contains overrided options.
683 // ApplyOptions affects NS, AGC other options that is shared between
684 // all WebRtcVoiceEngineChannels.
685 if (option_overrides_ == AudioOptions()) {
686 return true;
687 }
688
689 if (!ApplyOptions(options)) {
690 return false;
691 }
692 option_overrides_ = AudioOptions();
693 return true;
694}
695
696// AudioOptions defaults are set in InitInternal (for options with corresponding
697// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
698bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
699 AudioOptions options = options_in; // The options are modified below.
700 // kEcConference is AEC with high suppression.
701 webrtc::EcModes ec_mode = webrtc::kEcConference;
702 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
703 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
704 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
705 bool aecm_comfort_noise = false;
706 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
707 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
708 << aecm_comfort_noise << " (default is false).";
709 }
710
711#if defined(IOS)
712 // On iOS, VPIO provides built-in EC and AGC.
713 options.echo_cancellation.Set(false);
714 options.auto_gain_control.Set(false);
715#elif defined(ANDROID)
716 ec_mode = webrtc::kEcAecm;
717#endif
718
719#if defined(IOS) || defined(ANDROID)
720 // Set the AGC mode for iOS as well despite disabling it above, to avoid
721 // unsupported configuration errors from webrtc.
722 agc_mode = webrtc::kAgcFixedDigital;
723 options.typing_detection.Set(false);
724 options.experimental_agc.Set(false);
725 options.experimental_aec.Set(false);
726 options.experimental_ns.Set(false);
727#endif
728
729 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
730
731 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
732
733 bool echo_cancellation;
734 if (options.echo_cancellation.Get(&echo_cancellation)) {
735 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
736 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
737 return false;
738 } else {
739 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
740 << " with mode " << ec_mode;
741 }
742#if !defined(ANDROID)
743 // TODO(ajm): Remove the error return on Android from webrtc.
744 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
745 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
746 return false;
747 }
748#endif
749 if (ec_mode == webrtc::kEcAecm) {
750 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
751 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
752 return false;
753 }
754 }
755 }
756
757 bool auto_gain_control;
758 if (options.auto_gain_control.Get(&auto_gain_control)) {
759 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
760 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
761 return false;
762 } else {
763 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
764 << " with mode " << agc_mode;
765 }
766 }
767
768 if (options.tx_agc_target_dbov.IsSet() ||
769 options.tx_agc_digital_compression_gain.IsSet() ||
770 options.tx_agc_limiter.IsSet()) {
771 // Override default_agc_config_. Generally, an unset option means "leave
772 // the VoE bits alone" in this function, so we want whatever is set to be
773 // stored as the new "default". If we didn't, then setting e.g.
774 // tx_agc_target_dbov would reset digital compression gain and limiter
775 // settings.
776 // Also, if we don't update default_agc_config_, then adjust_agc_delta
777 // would be an offset from the original values, and not whatever was set
778 // explicitly.
779 default_agc_config_.targetLeveldBOv =
780 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
781 default_agc_config_.targetLeveldBOv);
782 default_agc_config_.digitalCompressionGaindB =
783 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
784 default_agc_config_.digitalCompressionGaindB);
785 default_agc_config_.limiterEnable =
786 options.tx_agc_limiter.GetWithDefaultIfUnset(
787 default_agc_config_.limiterEnable);
788 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
789 LOG_RTCERR3(SetAgcConfig,
790 default_agc_config_.targetLeveldBOv,
791 default_agc_config_.digitalCompressionGaindB,
792 default_agc_config_.limiterEnable);
793 return false;
794 }
795 }
796
797 bool noise_suppression;
798 if (options.noise_suppression.Get(&noise_suppression)) {
799 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
800 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
801 return false;
802 } else {
803 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
804 << " with mode " << ns_mode;
805 }
806 }
807
808 bool experimental_ns;
809 if (options.experimental_ns.Get(&experimental_ns)) {
810 webrtc::AudioProcessing* audioproc =
811 voe_wrapper_->base()->audio_processing();
buildbot@webrtc.orga8d8ad22014-07-16 14:23:08 +0000812#ifdef USE_WEBRTC_DEV_BRANCH
813 webrtc::Config config;
814 config.Set<webrtc::ExperimentalNs>(new webrtc::ExperimentalNs(
815 experimental_ns));
816 audioproc->SetExtraOptions(config);
817#else
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000818 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
819 // returns NULL on audio_processing().
820 if (audioproc) {
821 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
822 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
823 return false;
824 }
825 } else {
826 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
827 << experimental_ns;
828 }
buildbot@webrtc.orga8d8ad22014-07-16 14:23:08 +0000829#endif
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000830 }
831
832 bool highpass_filter;
833 if (options.highpass_filter.Get(&highpass_filter)) {
834 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
835 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
836 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
837 return false;
838 }
839 }
840
841 bool stereo_swapping;
842 if (options.stereo_swapping.Get(&stereo_swapping)) {
843 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
844 voep->EnableStereoChannelSwapping(stereo_swapping);
845 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
846 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
847 return false;
848 }
849 }
850
851 bool typing_detection;
852 if (options.typing_detection.Get(&typing_detection)) {
853 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
854 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
855 // In case of error, log the info and continue
856 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
857 }
858 }
859
860 int adjust_agc_delta;
861 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
862 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
863 if (!AdjustAgcLevel(adjust_agc_delta)) {
864 return false;
865 }
866 }
867
868 bool aec_dump;
869 if (options.aec_dump.Get(&aec_dump)) {
870 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
871 if (aec_dump)
872 StartAecDump(kAecDumpByAudioOptionFilename);
873 else
874 StopAecDump();
875 }
876
877 bool experimental_aec;
878 if (options.experimental_aec.Get(&experimental_aec)) {
879 LOG(LS_INFO) << "Experimental aec is " << experimental_aec;
880 webrtc::AudioProcessing* audioproc =
881 voe_wrapper_->base()->audio_processing();
882 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
883 // returns NULL on audio_processing().
884 if (audioproc) {
885 webrtc::Config config;
886 config.Set<webrtc::DelayCorrection>(
887 new webrtc::DelayCorrection(experimental_aec));
888 audioproc->SetExtraOptions(config);
889 }
890 }
891
892 uint32 recording_sample_rate;
893 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
894 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
895 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
896 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
897 }
898 }
899
900 uint32 playout_sample_rate;
901 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
902 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
903 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
904 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
905 }
906 }
907
908 return true;
909}
910
911bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
912 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
913 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
914 LOG_RTCERR1(SetDelayOffsetMs, offset);
915 return false;
916 }
917
918 return true;
919}
920
921struct ResumeEntry {
922 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
923 : channel(c),
924 playout(p),
925 send(s) {
926 }
927
928 WebRtcVoiceMediaChannel *channel;
929 bool playout;
930 SendFlags send;
931};
932
933// TODO(juberti): Refactor this so that the core logic can be used to set the
934// soundclip device. At that time, reinstate the soundclip pause/resume code.
935bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
936 const Device* out_device) {
937#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000938 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000939 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000940 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000941 kDefaultAudioDeviceId;
942 // The device manager uses -1 as the default device, which was the case for
943 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
944#ifndef WIN32
945 if (-1 == in_id) {
946 in_id = kDefaultAudioDeviceId;
947 }
948 if (-1 == out_id) {
949 out_id = kDefaultAudioDeviceId;
950 }
951#endif
952
953 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
954 in_device->name : "Default device";
955 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
956 out_device->name : "Default device";
957 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
958 << ") and speaker to (id=" << out_id << ", name=" << out_name
959 << ")";
960
961 // If we're running the local monitor, we need to stop it first.
962 bool ret = true;
963 if (!PauseLocalMonitor()) {
964 LOG(LS_WARNING) << "Failed to pause local monitor";
965 ret = false;
966 }
967
968 // Must also pause all audio playback and capture.
969 for (ChannelList::const_iterator i = channels_.begin();
970 i != channels_.end(); ++i) {
971 WebRtcVoiceMediaChannel *channel = *i;
972 if (!channel->PausePlayout()) {
973 LOG(LS_WARNING) << "Failed to pause playout";
974 ret = false;
975 }
976 if (!channel->PauseSend()) {
977 LOG(LS_WARNING) << "Failed to pause send";
978 ret = false;
979 }
980 }
981
982 // Find the recording device id in VoiceEngine and set recording device.
983 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
984 ret = false;
985 }
986 if (ret) {
987 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
988 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
989 ret = false;
990 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +0000991 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
992 if (ap)
993 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000994 }
995
996 // Find the playout device id in VoiceEngine and set playout device.
997 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
998 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
999 ret = false;
1000 }
1001 if (ret) {
1002 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001003 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001004 ret = false;
1005 }
1006 }
1007
1008 // Resume all audio playback and capture.
1009 for (ChannelList::const_iterator i = channels_.begin();
1010 i != channels_.end(); ++i) {
1011 WebRtcVoiceMediaChannel *channel = *i;
1012 if (!channel->ResumePlayout()) {
1013 LOG(LS_WARNING) << "Failed to resume playout";
1014 ret = false;
1015 }
1016 if (!channel->ResumeSend()) {
1017 LOG(LS_WARNING) << "Failed to resume send";
1018 ret = false;
1019 }
1020 }
1021
1022 // Resume local monitor.
1023 if (!ResumeLocalMonitor()) {
1024 LOG(LS_WARNING) << "Failed to resume local monitor";
1025 ret = false;
1026 }
1027
1028 if (ret) {
1029 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1030 << ") and speaker to (id="<< out_id << " name=" << out_name
1031 << ")";
1032 }
1033
1034 return ret;
1035#else
1036 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001037#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001038}
1039
1040bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1041 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1042 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001043#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001044 *rtc_id = dev_id;
1045 return true;
1046#else
1047 // In Windows and Mac, we need to find the VoiceEngine device id by name
1048 // unless the input dev_id is the default device id.
1049 if (kDefaultAudioDeviceId == dev_id) {
1050 *rtc_id = dev_id;
1051 return true;
1052 }
1053
1054 // Get the number of VoiceEngine audio devices.
1055 int count = 0;
1056 if (is_input) {
1057 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1058 LOG_RTCERR0(GetNumOfRecordingDevices);
1059 return false;
1060 }
1061 } else {
1062 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1063 LOG_RTCERR0(GetNumOfPlayoutDevices);
1064 return false;
1065 }
1066 }
1067
1068 for (int i = 0; i < count; ++i) {
1069 char name[128];
1070 char guid[128];
1071 if (is_input) {
1072 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1073 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1074 } else {
1075 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1076 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1077 }
1078
1079 std::string webrtc_name(name);
1080 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1081 *rtc_id = i;
1082 return true;
1083 }
1084 }
1085 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1086 return false;
1087#endif
1088}
1089
1090bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1091 unsigned int ulevel;
1092 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1093 LOG_RTCERR1(GetSpeakerVolume, level);
1094 return false;
1095 }
1096 *level = ulevel;
1097 return true;
1098}
1099
1100bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1101 ASSERT(level >= 0 && level <= 255);
1102 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1103 LOG_RTCERR1(SetSpeakerVolume, level);
1104 return false;
1105 }
1106 return true;
1107}
1108
1109int WebRtcVoiceEngine::GetInputLevel() {
1110 unsigned int ulevel;
1111 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1112 static_cast<int>(ulevel) : -1;
1113}
1114
1115bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1116 desired_local_monitor_enable_ = enable;
1117 return ChangeLocalMonitor(desired_local_monitor_enable_);
1118}
1119
1120bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1121 // The voe file api is not available in chrome.
1122 if (!voe_wrapper_->file()) {
1123 return false;
1124 }
1125 if (enable && !monitor_) {
1126 monitor_.reset(new WebRtcMonitorStream);
1127 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1128 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1129 // Must call Stop() because there are some cases where Start will report
1130 // failure but still change the state, and if we leave VE in the on state
1131 // then it could crash later when trying to invoke methods on our monitor.
1132 voe_wrapper_->file()->StopRecordingMicrophone();
1133 monitor_.reset();
1134 return false;
1135 }
1136 } else if (!enable && monitor_) {
1137 voe_wrapper_->file()->StopRecordingMicrophone();
1138 monitor_.reset();
1139 }
1140 return true;
1141}
1142
1143bool WebRtcVoiceEngine::PauseLocalMonitor() {
1144 return ChangeLocalMonitor(false);
1145}
1146
1147bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1148 return ChangeLocalMonitor(desired_local_monitor_enable_);
1149}
1150
1151const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1152 return codecs_;
1153}
1154
1155bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1156 return FindWebRtcCodec(in, NULL);
1157}
1158
1159// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1160bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1161 webrtc::CodecInst* out) {
1162 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1163 for (int i = 0; i < ncodecs; ++i) {
1164 webrtc::CodecInst voe_codec;
1165 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1166 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1167 voe_codec.rate, voe_codec.channels, 0);
1168 bool multi_rate = IsCodecMultiRate(voe_codec);
1169 // Allow arbitrary rates for ISAC to be specified.
1170 if (multi_rate) {
1171 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1172 codec.bitrate = 0;
1173 }
1174 if (codec.Matches(in)) {
1175 if (out) {
1176 // Fixup the payload type.
1177 voe_codec.pltype = in.id;
1178
1179 // Set bitrate if specified.
1180 if (multi_rate && in.bitrate != 0) {
1181 voe_codec.rate = in.bitrate;
1182 }
1183
1184 // Apply codec-specific settings.
1185 if (IsIsac(codec)) {
1186 // If ISAC and an explicit bitrate is not specified,
1187 // enable auto bandwidth adjustment.
1188 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1189 }
1190 *out = voe_codec;
1191 }
1192 return true;
1193 }
1194 }
1195 }
1196 return false;
1197}
1198const std::vector<RtpHeaderExtension>&
1199WebRtcVoiceEngine::rtp_header_extensions() const {
1200 return rtp_header_extensions_;
1201}
1202
1203void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1204 // if min_sev == -1, we keep the current log level.
1205 if (min_sev >= 0) {
1206 SetTraceFilter(SeverityToFilter(min_sev));
1207 }
1208 log_options_ = filter;
1209 SetTraceOptions(initialized_ ? log_options_ : "");
1210}
1211
1212int WebRtcVoiceEngine::GetLastEngineError() {
1213 return voe_wrapper_->error();
1214}
1215
1216void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1217 log_filter_ = filter;
1218 tracing_->SetTraceFilter(filter);
1219}
1220
1221// We suppport three different logging settings for VoiceEngine:
1222// 1. Observer callback that goes into talk diagnostic logfile.
1223// Use --logfile and --loglevel
1224//
1225// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1226// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1227//
1228// 3. EC log and dump for debugging QualityEngine.
1229// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1230//
1231// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1232// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1233void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1234 // Set encrypted trace file.
1235 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001236 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001237 std::vector<std::string>::iterator tracefile =
1238 std::find(opts.begin(), opts.end(), "tracefile");
1239 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1240 // Write encrypted debug output (at same loglevel) to file
1241 // EncryptedTraceFile no longer supported.
1242 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1243 LOG_RTCERR1(SetTraceFile, *tracefile);
1244 }
1245 }
1246
wu@webrtc.org97077a32013-10-25 21:18:33 +00001247 // Allow trace options to override the trace filter. We default
1248 // it to log_filter_ (as a translation of libjingle log levels)
1249 // elsewhere, but this allows clients to explicitly set webrtc
1250 // log levels.
1251 std::vector<std::string>::iterator tracefilter =
1252 std::find(opts.begin(), opts.end(), "tracefilter");
1253 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001254 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001255 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1256 }
1257 }
1258
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001259 // Set AEC dump file
1260 std::vector<std::string>::iterator recordEC =
1261 std::find(opts.begin(), opts.end(), "recordEC");
1262 if (recordEC != opts.end()) {
1263 ++recordEC;
1264 if (recordEC != opts.end())
1265 StartAecDump(recordEC->c_str());
1266 else
1267 StopAecDump();
1268 }
1269}
1270
1271// Ignore spammy trace messages, mostly from the stats API when we haven't
1272// gotten RTCP info yet from the remote side.
1273bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1274 static const char* kTracesToIgnore[] = {
1275 "\tfailed to GetReportBlockInformation",
1276 "GetRecCodec() failed to get received codec",
1277 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1278 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1279 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1280 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1281 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1282 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1283 "SenderInfoReceived No received SR",
1284 "StatisticsRTP() no statistics available",
1285 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1286 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1287 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1288 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1289 NULL
1290 };
1291 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1292 if (trace.find(*p) != std::string::npos) {
1293 return true;
1294 }
1295 }
1296 return false;
1297}
1298
1299void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1300 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001301 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001302 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001303 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001304 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001305 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001306 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001307 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001308 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001309 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001310
1311 // Skip past boilerplate prefix text
1312 if (length < 72) {
1313 std::string msg(trace, length);
1314 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1315 LOG_V(sev) << msg;
1316 } else {
1317 std::string msg(trace + 71, length - 72);
1318 if (!ShouldIgnoreTrace(msg)) {
1319 LOG_V(sev) << "webrtc: " << msg;
1320 }
1321 }
1322}
1323
1324void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001325 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001326 WebRtcVoiceMediaChannel* channel = NULL;
1327 uint32 ssrc = 0;
1328 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1329 << channel_num << ".";
1330 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1331 ASSERT(channel != NULL);
1332 channel->OnError(ssrc, err_code);
1333 } else {
1334 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1335 << " could not be found in channel list when error reported.";
1336 }
1337}
1338
1339bool WebRtcVoiceEngine::FindChannelAndSsrc(
1340 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1341 ASSERT(channel != NULL && ssrc != NULL);
1342
1343 *channel = NULL;
1344 *ssrc = 0;
1345 // Find corresponding channel and ssrc
1346 for (ChannelList::const_iterator it = channels_.begin();
1347 it != channels_.end(); ++it) {
1348 ASSERT(*it != NULL);
1349 if ((*it)->FindSsrc(channel_num, ssrc)) {
1350 *channel = *it;
1351 return true;
1352 }
1353 }
1354
1355 return false;
1356}
1357
1358// This method will search through the WebRtcVoiceMediaChannels and
1359// obtain the voice engine's channel number.
1360bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1361 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1362 ASSERT(channel_num != NULL);
1363 ASSERT(direction == MPD_RX || direction == MPD_TX);
1364
1365 *channel_num = -1;
1366 // Find corresponding channel for ssrc.
1367 for (ChannelList::const_iterator it = channels_.begin();
1368 it != channels_.end(); ++it) {
1369 ASSERT(*it != NULL);
1370 if (direction & MPD_RX) {
1371 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1372 }
1373 if (*channel_num == -1 && (direction & MPD_TX)) {
1374 *channel_num = (*it)->GetSendChannelNum(ssrc);
1375 }
1376 if (*channel_num != -1) {
1377 return true;
1378 }
1379 }
1380 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1381 return false;
1382}
1383
1384void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001385 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001386 channels_.push_back(channel);
1387}
1388
1389void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001390 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001391 ChannelList::iterator i = std::find(channels_.begin(),
1392 channels_.end(),
1393 channel);
1394 if (i != channels_.end()) {
1395 channels_.erase(i);
1396 }
1397}
1398
1399void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1400 soundclips_.push_back(soundclip);
1401}
1402
1403void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1404 SoundclipList::iterator i = std::find(soundclips_.begin(),
1405 soundclips_.end(),
1406 soundclip);
1407 if (i != soundclips_.end()) {
1408 soundclips_.erase(i);
1409 }
1410}
1411
1412// Adjusts the default AGC target level by the specified delta.
1413// NB: If we start messing with other config fields, we'll want
1414// to save the current webrtc::AgcConfig as well.
1415bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1416 webrtc::AgcConfig config = default_agc_config_;
1417 config.targetLeveldBOv -= delta;
1418
1419 LOG(LS_INFO) << "Adjusting AGC level from default -"
1420 << default_agc_config_.targetLeveldBOv << "dB to -"
1421 << config.targetLeveldBOv << "dB";
1422
1423 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1424 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1425 return false;
1426 }
1427 return true;
1428}
1429
1430bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1431 webrtc::AudioDeviceModule* adm_sc) {
1432 if (initialized_) {
1433 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1434 return false;
1435 }
1436 if (adm_) {
1437 adm_->Release();
1438 adm_ = NULL;
1439 }
1440 if (adm) {
1441 adm_ = adm;
1442 adm_->AddRef();
1443 }
1444
1445 if (adm_sc_) {
1446 adm_sc_->Release();
1447 adm_sc_ = NULL;
1448 }
1449 if (adm_sc) {
1450 adm_sc_ = adm_sc;
1451 adm_sc_->AddRef();
1452 }
1453 return true;
1454}
1455
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001456bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1457 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001458 if (!aec_dump_file_stream) {
1459 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001460 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001461 LOG(LS_WARNING) << "Could not close file.";
1462 return false;
1463 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001464 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001465 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001466 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001467 LOG_RTCERR0(StartDebugRecording);
1468 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001469 return false;
1470 }
1471 is_dumping_aec_ = true;
1472 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001473}
1474
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001475bool WebRtcVoiceEngine::RegisterProcessor(
1476 uint32 ssrc,
1477 VoiceProcessor* voice_processor,
1478 MediaProcessorDirection direction) {
1479 bool register_with_webrtc = false;
1480 int channel_id = -1;
1481 bool success = false;
1482 uint32* processor_ssrc = NULL;
1483 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1484 if (voice_processor == NULL || !found_channel) {
1485 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1486 << " foundChannel: " << found_channel;
1487 return false;
1488 }
1489
1490 webrtc::ProcessingTypes processing_type;
1491 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001492 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001493 if (direction == MPD_RX) {
1494 processing_type = webrtc::kPlaybackAllChannelsMixed;
1495 if (SignalRxMediaFrame.is_empty()) {
1496 register_with_webrtc = true;
1497 processor_ssrc = &rx_processor_ssrc_;
1498 }
1499 SignalRxMediaFrame.connect(voice_processor,
1500 &VoiceProcessor::OnFrame);
1501 } else {
1502 processing_type = webrtc::kRecordingPerChannel;
1503 if (SignalTxMediaFrame.is_empty()) {
1504 register_with_webrtc = true;
1505 processor_ssrc = &tx_processor_ssrc_;
1506 }
1507 SignalTxMediaFrame.connect(voice_processor,
1508 &VoiceProcessor::OnFrame);
1509 }
1510 }
1511 if (register_with_webrtc) {
1512 // TODO(janahan): when registering consider instantiating a
1513 // a VoeMediaProcess object and not make the engine extend the interface.
1514 if (voe()->media() && voe()->media()->
1515 RegisterExternalMediaProcessing(channel_id,
1516 processing_type,
1517 *this) != -1) {
1518 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1519 << channel_id;
1520 *processor_ssrc = ssrc;
1521 success = true;
1522 } else {
1523 LOG_RTCERR2(RegisterExternalMediaProcessing,
1524 channel_id,
1525 processing_type);
1526 success = false;
1527 }
1528 } else {
1529 // If we don't have to register with the engine, we just needed to
1530 // connect a new processor, set success to true;
1531 success = true;
1532 }
1533 return success;
1534}
1535
1536bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1537 MediaProcessorDirection channel_direction,
1538 uint32 ssrc,
1539 VoiceProcessor* voice_processor,
1540 MediaProcessorDirection processor_direction) {
1541 bool success = true;
1542 FrameSignal* signal;
1543 webrtc::ProcessingTypes processing_type;
1544 uint32* processor_ssrc = NULL;
1545 if (channel_direction == MPD_RX) {
1546 signal = &SignalRxMediaFrame;
1547 processing_type = webrtc::kPlaybackAllChannelsMixed;
1548 processor_ssrc = &rx_processor_ssrc_;
1549 } else {
1550 signal = &SignalTxMediaFrame;
1551 processing_type = webrtc::kRecordingPerChannel;
1552 processor_ssrc = &tx_processor_ssrc_;
1553 }
1554
1555 int deregister_id = -1;
1556 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001557 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001558 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1559 signal->disconnect(voice_processor);
1560 int channel_id = -1;
1561 bool found_channel = FindChannelNumFromSsrc(ssrc,
1562 channel_direction,
1563 &channel_id);
1564 if (signal->is_empty() && found_channel) {
1565 deregister_id = channel_id;
1566 }
1567 }
1568 }
1569 if (deregister_id != -1) {
1570 if (voe()->media() &&
1571 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1572 processing_type) != -1) {
1573 *processor_ssrc = 0;
1574 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1575 << deregister_id;
1576 } else {
1577 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1578 deregister_id,
1579 processing_type);
1580 success = false;
1581 }
1582 }
1583 return success;
1584}
1585
1586bool WebRtcVoiceEngine::UnregisterProcessor(
1587 uint32 ssrc,
1588 VoiceProcessor* voice_processor,
1589 MediaProcessorDirection direction) {
1590 bool success = true;
1591 if (voice_processor == NULL) {
1592 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1593 << ssrc;
1594 return false;
1595 }
1596 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1597 success = false;
1598 }
1599 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1600 success = false;
1601 }
1602 return success;
1603}
1604
1605// Implementing method from WebRtc VoEMediaProcess interface
1606// Do not lock mux_channel_cs_ in this callback.
1607void WebRtcVoiceEngine::Process(int channel,
1608 webrtc::ProcessingTypes type,
1609 int16_t audio10ms[],
1610 int length,
1611 int sampling_freq,
1612 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001613 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001614 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1615 if (type == webrtc::kPlaybackAllChannelsMixed) {
1616 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1617 } else if (type == webrtc::kRecordingPerChannel) {
1618 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1619 } else {
1620 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1621 << " channel: " << channel << " type: " << type
1622 << " tx_ssrc: " << tx_processor_ssrc_
1623 << " rx_ssrc: " << rx_processor_ssrc_;
1624 }
1625}
1626
1627void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1628 if (!is_dumping_aec_) {
1629 // Start dumping AEC when we are not dumping.
1630 if (voe_wrapper_->processing()->StartDebugRecording(
1631 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001632 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001633 } else {
1634 is_dumping_aec_ = true;
1635 }
1636 }
1637}
1638
1639void WebRtcVoiceEngine::StopAecDump() {
1640 if (is_dumping_aec_) {
1641 // Stop dumping AEC when we are dumping.
1642 if (voe_wrapper_->processing()->StopDebugRecording() !=
1643 webrtc::AudioProcessing::kNoError) {
1644 LOG_RTCERR0(StopDebugRecording);
1645 }
1646 is_dumping_aec_ = false;
1647 }
1648}
1649
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001650int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001651 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001652}
1653
1654int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1655 return CreateVoiceChannel(voe_wrapper_.get());
1656}
1657
1658int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1659 return CreateVoiceChannel(voe_wrapper_sc_.get());
1660}
1661
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001662class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1663 : public AudioRenderer::Sink {
1664 public:
1665 WebRtcVoiceChannelRenderer(int ch,
1666 webrtc::AudioTransport* voe_audio_transport)
1667 : channel_(ch),
1668 voe_audio_transport_(voe_audio_transport),
1669 renderer_(NULL) {
1670 }
1671 virtual ~WebRtcVoiceChannelRenderer() {
1672 Stop();
1673 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001674
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001675 // Starts the rendering by setting a sink to the renderer to get data
1676 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001677 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001678 // TODO(xians): Make sure Start() is called only once.
1679 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001680 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001681 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001682 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001683 ASSERT(renderer_ == renderer);
1684 return;
1685 }
1686
1687 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1688 // in getUserMedia by default.
1689 renderer->AddChannel(channel_);
1690 renderer->SetSink(this);
1691 renderer_ = renderer;
1692 }
1693
1694 // Stops rendering by setting the sink of the renderer to NULL. No data
1695 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001696 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001697 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001698 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001699 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001700 return;
1701
1702 renderer_->RemoveChannel(channel_);
1703 renderer_->SetSink(NULL);
1704 renderer_ = NULL;
1705 }
1706
1707 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001708 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001709 virtual void OnData(const void* audio_data,
1710 int bits_per_sample,
1711 int sample_rate,
1712 int number_of_channels,
1713 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001714 voe_audio_transport_->OnData(channel_,
1715 audio_data,
1716 bits_per_sample,
1717 sample_rate,
1718 number_of_channels,
1719 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001720 }
1721
1722 // Callback from the |renderer_| when it is going away. In case Start() has
1723 // never been called, this callback won't be triggered.
1724 virtual void OnClose() OVERRIDE {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001725 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001726 // Set |renderer_| to NULL to make sure no more callback will get into
1727 // the renderer.
1728 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001729 }
1730
1731 // Accessor to the VoE channel ID.
1732 int channel() const { return channel_; }
1733
1734 private:
1735 const int channel_;
1736 webrtc::AudioTransport* const voe_audio_transport_;
1737
1738 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1739 // PeerConnection will make sure invalidating the pointer before the object
1740 // goes away.
1741 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001742
1743 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001744 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001745};
1746
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001747// WebRtcVoiceMediaChannel
1748WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1749 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1750 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001751 engine->CreateMediaVoiceChannel()),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001752 send_bw_setting_(false),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001753 send_bw_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001754 options_(),
1755 dtmf_allowed_(false),
1756 desired_playout_(false),
1757 nack_enabled_(false),
1758 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001759 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001760 desired_send_(SEND_NOTHING),
1761 send_(SEND_NOTHING),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001762 default_receive_ssrc_(0) {
1763 engine->RegisterChannel(this);
1764 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1765 << voe_channel();
1766
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001767 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001768}
1769
1770WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1771 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1772 << voe_channel();
1773
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001774 // Remove any remaining send streams, the default channel will be deleted
1775 // later.
1776 while (!send_channels_.empty())
1777 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001778
1779 // Unregister ourselves from the engine.
1780 engine()->UnregisterChannel(this);
1781 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001782 while (!receive_channels_.empty()) {
1783 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001784 }
1785
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001786 // Delete the default channel.
1787 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001788}
1789
1790bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1791 LOG(LS_INFO) << "Setting voice channel options: "
1792 << options.ToString();
1793
wu@webrtc.orgde305012013-10-31 15:40:38 +00001794 // Check if DSCP value is changed from previous.
1795 bool dscp_option_changed = (options_.dscp != options.dscp);
1796
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001797 // TODO(xians): Add support to set different options for different send
1798 // streams after we support multiple APMs.
1799
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001800 // We retain all of the existing options, and apply the given ones
1801 // on top. This means there is no way to "clear" options such that
1802 // they go back to the engine default.
1803 options_.SetAll(options);
1804
1805 if (send_ != SEND_NOTHING) {
1806 if (!engine()->SetOptionOverrides(options_)) {
1807 LOG(LS_WARNING) <<
1808 "Failed to engine SetOptionOverrides during channel SetOptions.";
1809 return false;
1810 }
1811 } else {
1812 // Will be interpreted when appropriate.
1813 }
1814
wu@webrtc.org97077a32013-10-25 21:18:33 +00001815 // Receiver-side auto gain control happens per channel, so set it here from
1816 // options. Note that, like conference mode, setting it on the engine won't
1817 // have the desired effect, since voice channels don't inherit options from
1818 // the media engine when those options are applied per-channel.
1819 bool rx_auto_gain_control;
1820 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1821 if (engine()->voe()->processing()->SetRxAgcStatus(
1822 voe_channel(), rx_auto_gain_control,
1823 webrtc::kAgcFixedDigital) == -1) {
1824 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1825 return false;
1826 } else {
1827 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1828 << " with mode " << webrtc::kAgcFixedDigital;
1829 }
1830 }
1831 if (options.rx_agc_target_dbov.IsSet() ||
1832 options.rx_agc_digital_compression_gain.IsSet() ||
1833 options.rx_agc_limiter.IsSet()) {
1834 webrtc::AgcConfig config;
1835 // If only some of the options are being overridden, get the current
1836 // settings for the channel and bail if they aren't available.
1837 if (!options.rx_agc_target_dbov.IsSet() ||
1838 !options.rx_agc_digital_compression_gain.IsSet() ||
1839 !options.rx_agc_limiter.IsSet()) {
1840 if (engine()->voe()->processing()->GetRxAgcConfig(
1841 voe_channel(), config) != 0) {
1842 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1843 << "channel " << voe_channel() << ". Since not all rx "
1844 << "agc options are specified, unable to safely set rx "
1845 << "agc options.";
1846 return false;
1847 }
1848 }
1849 config.targetLeveldBOv =
1850 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1851 config.targetLeveldBOv);
1852 config.digitalCompressionGaindB =
1853 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1854 config.digitalCompressionGaindB);
1855 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1856 config.limiterEnable);
1857 if (engine()->voe()->processing()->SetRxAgcConfig(
1858 voe_channel(), config) == -1) {
1859 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1860 config.digitalCompressionGaindB, config.limiterEnable);
1861 return false;
1862 }
1863 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001864 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001865 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001866 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001867 dscp = kAudioDscpValue;
1868 if (MediaChannel::SetDscp(dscp) != 0) {
1869 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1870 }
1871 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001872
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001873 LOG(LS_INFO) << "Set voice channel options. Current options: "
1874 << options_.ToString();
1875 return true;
1876}
1877
1878bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1879 const std::vector<AudioCodec>& codecs) {
1880 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001881 LOG(LS_INFO) << "Setting receive voice codecs:";
1882
1883 std::vector<AudioCodec> new_codecs;
1884 // Find all new codecs. We allow adding new codecs but don't allow changing
1885 // the payload type of codecs that is already configured since we might
1886 // already be receiving packets with that payload type.
1887 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001888 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001889 AudioCodec old_codec;
1890 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1891 if (old_codec.id != it->id) {
1892 LOG(LS_ERROR) << it->name << " payload type changed.";
1893 return false;
1894 }
1895 } else {
1896 new_codecs.push_back(*it);
1897 }
1898 }
1899 if (new_codecs.empty()) {
1900 // There are no new codecs to configure. Already configured codecs are
1901 // never removed.
1902 return true;
1903 }
1904
1905 if (playout_) {
1906 // Receive codecs can not be changed while playing. So we temporarily
1907 // pause playout.
1908 PausePlayout();
1909 }
1910
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001911 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001912 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1913 it != new_codecs.end() && ret; ++it) {
1914 webrtc::CodecInst voe_codec;
1915 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1916 LOG(LS_INFO) << ToString(*it);
1917 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001918 if (default_receive_ssrc_ == 0) {
1919 // Set the receive codecs on the default channel explicitly if the
1920 // default channel is not used by |receive_channels_|, this happens in
1921 // conference mode or in non-conference mode when there is no playout
1922 // channel.
1923 // TODO(xians): Figure out how we use the default channel in conference
1924 // mode.
1925 if (engine()->voe()->codec()->SetRecPayloadType(
1926 voe_channel(), voe_codec) == -1) {
1927 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1928 ret = false;
1929 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001930 }
1931
1932 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001933 for (ChannelMap::iterator it = receive_channels_.begin();
1934 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001935 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001936 it->second->channel(), voe_codec) == -1) {
1937 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001938 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001939 ret = false;
1940 }
1941 }
1942 } else {
1943 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1944 ret = false;
1945 }
1946 }
1947 if (ret) {
1948 recv_codecs_ = codecs;
1949 }
1950
1951 if (desired_playout_ && !playout_) {
1952 ResumePlayout();
1953 }
1954 return ret;
1955}
1956
1957bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001958 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001959 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001960 engine()->voe()->codec()->SetVADStatus(channel, false);
1961 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001962#ifdef USE_WEBRTC_DEV_BRANCH
1963 engine()->voe()->rtp()->SetREDStatus(channel, false);
1964 engine()->voe()->codec()->SetFECStatus(channel, false);
1965#else
1966 // TODO(minyue): Remove code under #else case after new WebRTC roll.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001967 engine()->voe()->rtp()->SetFECStatus(channel, false);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001968#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001969
1970 // Scan through the list to figure out the codec to use for sending, along
1971 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001972 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001973 webrtc::CodecInst send_codec;
1974 memset(&send_codec, 0, sizeof(send_codec));
1975
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001976 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001977 bool enable_codec_fec = false;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001978
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001979 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001980 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1981 it != codecs.end(); ++it) {
1982 // Ignore codecs we don't know about. The negotiation step should prevent
1983 // this, but double-check to be sure.
1984 webrtc::CodecInst voe_codec;
1985 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001986 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001987 continue;
1988 }
1989
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001990 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
1991 // Skip telephone-event/CN codec, which will be handled later.
1992 continue;
1993 }
1994
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001995 // If OPUS, change what we send according to the "stereo" codec
1996 // parameter, and not the "channels" parameter. We set
1997 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
1998 // the bitrate is not specified, i.e. is zero, we set it to the
1999 // appropriate default value for mono or stereo Opus.
2000 if (IsOpus(*it)) {
2001 if (IsOpusStereoEnabled(*it)) {
2002 voe_codec.channels = 2;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002003 if (!IsValidOpusBitrate(it->bitrate)) {
2004 if (it->bitrate != 0) {
2005 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2006 << it->bitrate
2007 << ") with default opus stereo bitrate: "
2008 << kOpusStereoBitrate;
2009 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002010 voe_codec.rate = kOpusStereoBitrate;
2011 }
2012 } else {
2013 voe_codec.channels = 1;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002014 if (!IsValidOpusBitrate(it->bitrate)) {
2015 if (it->bitrate != 0) {
2016 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2017 << it->bitrate
2018 << ") with default opus mono bitrate: "
2019 << kOpusMonoBitrate;
2020 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002021 voe_codec.rate = kOpusMonoBitrate;
2022 }
2023 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002024 int bitrate_from_params = GetOpusBitrateFromParams(*it);
2025 if (bitrate_from_params != 0) {
2026 voe_codec.rate = bitrate_from_params;
2027 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002028 }
2029
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002030 // We'll use the first codec in the list to actually send audio data.
2031 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002032 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002033 // used is specified in params.
2034 if (IsRedCodec(it->name)) {
2035 // Parse out the RED parameters. If we fail, just ignore RED;
2036 // we don't support all possible params/usage scenarios.
2037 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2038 continue;
2039 }
2040
2041 // Enable redundant encoding of the specified codec. Treat any
2042 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002043#ifdef USE_WEBRTC_DEV_BRANCH
2044 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2045 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2046 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
2047#else
2048 // TODO(minyue): Remove code under #else case after new WebRTC roll.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002049 LOG(LS_INFO) << "Enabling FEC";
2050 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2051 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002052#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002053 return false;
2054 }
2055 } else {
2056 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002057 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002058 // For Opus as the send codec, we enable inband FEC if requested.
2059 enable_codec_fec = IsOpus(*it) && IsOpusFecEnabled(*it);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002060 }
2061 found_send_codec = true;
2062 break;
2063 }
2064
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002065 if (nack_enabled_ != nack_enabled) {
2066 SetNack(channel, nack_enabled);
2067 nack_enabled_ = nack_enabled;
2068 }
2069
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002070 if (!found_send_codec) {
2071 LOG(LS_WARNING) << "Received empty list of codecs.";
2072 return false;
2073 }
2074
2075 // Set the codec immediately, since SetVADStatus() depends on whether
2076 // the current codec is mono or stereo.
2077 if (!SetSendCodec(channel, send_codec))
2078 return false;
2079
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002080 // FEC should be enabled after SetSendCodec.
2081 if (enable_codec_fec) {
2082 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2083 << channel;
2084#ifdef USE_WEBRTC_DEV_BRANCH
2085 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2086 // Enable codec internal FEC. Treat any failure as fatal internal error.
2087 LOG_RTCERR2(SetFECStatus, channel, true);
2088 return false;
2089 }
2090#endif // USE_WEBRTC_DEV_BRANCH
2091 }
2092
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002093 // Always update the |send_codec_| to the currently set send codec.
2094 send_codec_.reset(new webrtc::CodecInst(send_codec));
2095
2096 if (send_bw_setting_) {
2097 SetSendBandwidthInternal(send_bw_bps_);
2098 }
2099
2100 // Loop through the codecs list again to config the telephone-event/CN codec.
2101 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2102 it != codecs.end(); ++it) {
2103 // Ignore codecs we don't know about. The negotiation step should prevent
2104 // this, but double-check to be sure.
2105 webrtc::CodecInst voe_codec;
2106 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2107 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2108 continue;
2109 }
2110
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002111 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2112 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002113 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002114 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2115 channel, it->id) == -1) {
2116 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2117 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002118 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002119 } else if (IsCNCodec(it->name)) {
2120 // Turn voice activity detection/comfort noise on if supported.
2121 // Set the wideband CN payload type appropriately.
2122 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002123 webrtc::PayloadFrequencies cn_freq;
2124 switch (it->clockrate) {
2125 case 8000:
2126 cn_freq = webrtc::kFreq8000Hz;
2127 break;
2128 case 16000:
2129 cn_freq = webrtc::kFreq16000Hz;
2130 break;
2131 case 32000:
2132 cn_freq = webrtc::kFreq32000Hz;
2133 break;
2134 default:
2135 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2136 << " not supported.";
2137 continue;
2138 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002139 // Set the CN payloadtype and the VAD status.
2140 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2141 if (cn_freq != webrtc::kFreq8000Hz) {
2142 if (engine()->voe()->codec()->SetSendCNPayloadType(
2143 channel, it->id, cn_freq) == -1) {
2144 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2145 // TODO(ajm): This failure condition will be removed from VoE.
2146 // Restore the return here when we update to a new enough webrtc.
2147 //
2148 // Not returning false because the SetSendCNPayloadType will fail if
2149 // the channel is already sending.
2150 // This can happen if the remote description is applied twice, for
2151 // example in the case of ROAP on top of JSEP, where both side will
2152 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002153 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002154 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002155 // Only turn on VAD if we have a CN payload type that matches the
2156 // clockrate for the codec we are going to use.
2157 if (it->clockrate == send_codec.plfreq) {
2158 LOG(LS_INFO) << "Enabling VAD";
2159 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2160 LOG_RTCERR2(SetVADStatus, channel, true);
2161 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002162 }
2163 }
2164 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002165 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002166 return true;
2167}
2168
2169bool WebRtcVoiceMediaChannel::SetSendCodecs(
2170 const std::vector<AudioCodec>& codecs) {
2171 dtmf_allowed_ = false;
2172 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2173 it != codecs.end(); ++it) {
2174 // Find the DTMF telephone event "codec".
2175 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2176 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2177 dtmf_allowed_ = true;
2178 }
2179 }
2180
2181 // Cache the codecs in order to configure the channel created later.
2182 send_codecs_ = codecs;
2183 for (ChannelMap::iterator iter = send_channels_.begin();
2184 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002185 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002186 return false;
2187 }
2188 }
2189
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002190 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002191 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002192 return true;
2193}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002194
2195void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2196 bool nack_enabled) {
2197 for (ChannelMap::const_iterator it = channels.begin();
2198 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002199 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002200 }
2201}
2202
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002203void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002204 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002205 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002206 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2207 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002208 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002209 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2210 }
2211}
2212
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002213bool WebRtcVoiceMediaChannel::SetSendCodec(
2214 const webrtc::CodecInst& send_codec) {
2215 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2216 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002217 for (ChannelMap::iterator iter = send_channels_.begin();
2218 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002219 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002220 return false;
2221 }
2222
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002223 return true;
2224}
2225
2226bool WebRtcVoiceMediaChannel::SetSendCodec(
2227 int channel, const webrtc::CodecInst& send_codec) {
2228 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2229 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2230
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002231 webrtc::CodecInst current_codec;
2232 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2233 (send_codec == current_codec)) {
2234 // Codec is already configured, we can return without setting it again.
2235 return true;
2236 }
2237
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002238 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2239 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002240 return false;
2241 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002242 return true;
2243}
2244
2245bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2246 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002247 if (receive_extensions_ == extensions) {
2248 return true;
2249 }
2250
2251 // The default channel may or may not be in |receive_channels_|. Set the rtp
2252 // header extensions for default channel regardless.
2253 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2254 return false;
2255 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002256
2257 // Loop through all receive channels and enable/disable the extensions.
2258 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2259 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002260 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2261 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002262 return false;
2263 }
2264 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002265
2266 receive_extensions_ = extensions;
2267 return true;
2268}
2269
2270bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2271 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002272 const RtpHeaderExtension* audio_level_extension =
2273 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2274 if (!SetHeaderExtension(
2275 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2276 audio_level_extension)) {
2277 return false;
2278 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002279
2280 const RtpHeaderExtension* send_time_extension =
2281 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2282 if (!SetHeaderExtension(
2283 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2284 send_time_extension)) {
2285 return false;
2286 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002287 return true;
2288}
2289
2290bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2291 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002292 if (send_extensions_ == extensions) {
2293 return true;
2294 }
2295
2296 // The default channel may or may not be in |send_channels_|. Set the rtp
2297 // header extensions for default channel regardless.
2298
2299 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2300 return false;
2301 }
2302
2303 // Loop through all send channels and enable/disable the extensions.
2304 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2305 channel_it != send_channels_.end(); ++channel_it) {
2306 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2307 extensions)) {
2308 return false;
2309 }
2310 }
2311
2312 send_extensions_ = extensions;
2313 return true;
2314}
2315
2316bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2317 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002318 const RtpHeaderExtension* audio_level_extension =
2319 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002320
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002321 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002322 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002323 audio_level_extension)) {
2324 return false;
2325 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002326
2327 const RtpHeaderExtension* send_time_extension =
2328 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002329 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002330 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002331 send_time_extension)) {
2332 return false;
2333 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002334
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002335 return true;
2336}
2337
2338bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2339 desired_playout_ = playout;
2340 return ChangePlayout(desired_playout_);
2341}
2342
2343bool WebRtcVoiceMediaChannel::PausePlayout() {
2344 return ChangePlayout(false);
2345}
2346
2347bool WebRtcVoiceMediaChannel::ResumePlayout() {
2348 return ChangePlayout(desired_playout_);
2349}
2350
2351bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2352 if (playout_ == playout) {
2353 return true;
2354 }
2355
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002356 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002357 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002358 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002359 // Only toggle the default channel if we don't have any other channels.
2360 result = SetPlayout(voe_channel(), playout);
2361 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002362 for (ChannelMap::iterator it = receive_channels_.begin();
2363 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002364 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002365 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002366 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002367 result = false;
2368 }
2369 }
2370
2371 if (result) {
2372 playout_ = playout;
2373 }
2374 return result;
2375}
2376
2377bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2378 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002379 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002380 return ChangeSend(desired_send_);
2381 return true;
2382}
2383
2384bool WebRtcVoiceMediaChannel::PauseSend() {
2385 return ChangeSend(SEND_NOTHING);
2386}
2387
2388bool WebRtcVoiceMediaChannel::ResumeSend() {
2389 return ChangeSend(desired_send_);
2390}
2391
2392bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2393 if (send_ == send) {
2394 return true;
2395 }
2396
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002397 // Change the settings on each send channel.
2398 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002399 engine()->SetOptionOverrides(options_);
2400
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002401 // Change the settings on each send channel.
2402 for (ChannelMap::iterator iter = send_channels_.begin();
2403 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002404 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002405 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002406 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002407
2408 // Clear up the options after stopping sending.
2409 if (send == SEND_NOTHING)
2410 engine()->ClearOptionOverrides();
2411
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002412 send_ = send;
2413 return true;
2414}
2415
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002416bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2417 if (send == SEND_MICROPHONE) {
2418 if (engine()->voe()->base()->StartSend(channel) == -1) {
2419 LOG_RTCERR1(StartSend, channel);
2420 return false;
2421 }
2422 if (engine()->voe()->file() &&
2423 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2424 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2425 return false;
2426 }
2427 } else { // SEND_NOTHING
2428 ASSERT(send == SEND_NOTHING);
2429 if (engine()->voe()->base()->StopSend(channel) == -1) {
2430 LOG_RTCERR1(StopSend, channel);
2431 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002432 }
2433 }
2434
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002435 return true;
2436}
2437
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002438// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002439void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2440 if (engine()->voe()->network()->RegisterExternalTransport(
2441 channel, *this) == -1) {
2442 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2443 }
2444
2445 // Enable RTCP (for quality stats and feedback messages)
2446 EnableRtcp(channel);
2447
2448 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2449 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002450
2451 // Set RTP header extension for the new channel.
2452 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002453}
2454
2455bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2456 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2457 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2458 }
2459
2460 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2461 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002462 return false;
2463 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002464
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002465 return true;
2466}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002467
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002468bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2469 // If the default channel is already used for sending create a new channel
2470 // otherwise use the default channel for sending.
2471 int channel = GetSendChannelNum(sp.first_ssrc());
2472 if (channel != -1) {
2473 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2474 return false;
2475 }
2476
2477 bool default_channel_is_available = true;
2478 for (ChannelMap::const_iterator iter = send_channels_.begin();
2479 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002480 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002481 default_channel_is_available = false;
2482 break;
2483 }
2484 }
2485 if (default_channel_is_available) {
2486 channel = voe_channel();
2487 } else {
2488 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002489 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002490 if (channel == -1) {
2491 LOG_RTCERR0(CreateChannel);
2492 return false;
2493 }
2494
2495 ConfigureSendChannel(channel);
2496 }
2497
2498 // Save the channel to send_channels_, so that RemoveSendStream() can still
2499 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002500 webrtc::AudioTransport* audio_transport =
2501 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002502 send_channels_.insert(std::make_pair(
2503 sp.first_ssrc(),
2504 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002505
2506 // Set the send (local) SSRC.
2507 // If there are multiple send SSRCs, we can only set the first one here, and
2508 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2509 // (with a codec requires multiple SSRC(s)).
2510 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2511 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2512 return false;
2513 }
2514
2515 // At this point the channel's local SSRC has been updated. If the channel is
2516 // the default channel make sure that all the receive channels are updated as
2517 // well. Receive channels have to have the same SSRC as the default channel in
2518 // order to send receiver reports with this SSRC.
2519 if (IsDefaultChannel(channel)) {
2520 for (ChannelMap::const_iterator it = receive_channels_.begin();
2521 it != receive_channels_.end(); ++it) {
2522 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002523 if (!IsDefaultChannel(it->second->channel())) {
2524 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002525 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002526 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002527 return false;
2528 }
2529 }
2530 }
2531 }
2532
2533 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
2534 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2535 return false;
2536 }
2537
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002538 // Set the current codecs to be used for the new channel.
2539 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002540 return false;
2541
2542 return ChangeSend(channel, desired_send_);
2543}
2544
2545bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2546 ChannelMap::iterator it = send_channels_.find(ssrc);
2547 if (it == send_channels_.end()) {
2548 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2549 << " which doesn't exist.";
2550 return false;
2551 }
2552
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002553 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002554 ChangeSend(channel, SEND_NOTHING);
2555
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002556 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2557 // this will disconnect the audio renderer with the send channel.
2558 delete it->second;
2559 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002560
2561 if (IsDefaultChannel(channel)) {
2562 // Do not delete the default channel since the receive channels depend on
2563 // the default channel, recycle it instead.
2564 ChangeSend(channel, SEND_NOTHING);
2565 } else {
2566 // Clean up and delete the send channel.
2567 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2568 << " with VoiceEngine channel #" << channel << ".";
2569 if (!DeleteChannel(channel))
2570 return false;
2571 }
2572
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002573 if (send_channels_.empty())
2574 ChangeSend(SEND_NOTHING);
2575
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002576 return true;
2577}
2578
2579bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002580 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002581
2582 if (!VERIFY(sp.ssrcs.size() == 1))
2583 return false;
2584 uint32 ssrc = sp.first_ssrc();
2585
wu@webrtc.org78187522013-10-07 23:32:02 +00002586 if (ssrc == 0) {
2587 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2588 return false;
2589 }
2590
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002591 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2592 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002593 return false;
2594 }
2595
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002596 // Reuse default channel for recv stream in non-conference mode call
2597 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002598 webrtc::AudioTransport* audio_transport =
2599 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002600 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2601 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2602 << " reuse default channel";
2603 default_receive_ssrc_ = sp.first_ssrc();
2604 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002605 default_receive_ssrc_,
2606 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002607 return SetPlayout(voe_channel(), playout_);
2608 }
2609
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002610 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002611 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002612 if (channel == -1) {
2613 LOG_RTCERR0(CreateChannel);
2614 return false;
2615 }
2616
wu@webrtc.org78187522013-10-07 23:32:02 +00002617 if (!ConfigureRecvChannel(channel)) {
2618 DeleteChannel(channel);
2619 return false;
2620 }
2621
2622 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002623 std::make_pair(
2624 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002625
2626 LOG(LS_INFO) << "New audio stream " << ssrc
2627 << " registered to VoiceEngine channel #"
2628 << channel << ".";
2629 return true;
2630}
2631
2632bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002633 // Configure to use external transport, like our default channel.
2634 if (engine()->voe()->network()->RegisterExternalTransport(
2635 channel, *this) == -1) {
2636 LOG_RTCERR2(SetExternalTransport, channel, this);
2637 return false;
2638 }
2639
2640 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002641 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002642 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2643 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002644 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002645 return false;
2646 }
2647 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002648 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002649 return false;
2650 }
2651
2652 // Use the same recv payload types as our default channel.
2653 ResetRecvCodecs(channel);
2654 if (!recv_codecs_.empty()) {
2655 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2656 it != recv_codecs_.end(); ++it) {
2657 webrtc::CodecInst voe_codec;
2658 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2659 voe_codec.pltype = it->id;
2660 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2661 if (engine()->voe()->codec()->GetRecPayloadType(
2662 voe_channel(), voe_codec) != -1) {
2663 if (engine()->voe()->codec()->SetRecPayloadType(
2664 channel, voe_codec) == -1) {
2665 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2666 return false;
2667 }
2668 }
2669 }
2670 }
2671 }
2672
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002673 if (InConferenceMode()) {
2674 // To be in par with the video, voe_channel() is not used for receiving in
2675 // a conference call.
2676 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2677 // This is the first stream in a multi user meeting. We can now
2678 // disable playback of the default stream. This since the default
2679 // stream will probably have received some initial packets before
2680 // the new stream was added. This will mean that the CN state from
2681 // the default channel will be mixed in with the other streams
2682 // throughout the whole meeting, which might be disturbing.
2683 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2684 SetPlayout(voe_channel(), false);
2685 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002686 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002687 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002688
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002689 // Set RTP header extension for the new channel.
2690 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2691 return false;
2692 }
2693
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002694 return SetPlayout(channel, playout_);
2695}
2696
2697bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002698 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002699 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002700 if (it == receive_channels_.end()) {
2701 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2702 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002703 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002704 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002705
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002706 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2707 // will disconnect the audio renderer with the receive channel.
2708 // Cache the channel before the deletion.
2709 const int channel = it->second->channel();
2710 delete it->second;
2711 receive_channels_.erase(it);
2712
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002713 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002714 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002715 // Recycle the default channel is for recv stream.
2716 if (playout_)
2717 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002718
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002719 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002720 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002721 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002722
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002723 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002724 << " with VoiceEngine channel #" << channel << ".";
2725 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002726 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002727
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002728 bool enable_default_channel_playout = false;
2729 if (receive_channels_.empty()) {
2730 // The last stream was removed. We can now enable the default
2731 // channel for new channels to be played out immediately without
2732 // waiting for AddStream messages.
2733 // We do this for both conference mode and non-conference mode.
2734 // TODO(oja): Does the default channel still have it's CN state?
2735 enable_default_channel_playout = true;
2736 }
2737 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2738 default_receive_ssrc_ != 0) {
2739 // Only the default channel is active, enable the playout on default
2740 // channel.
2741 enable_default_channel_playout = true;
2742 }
2743 if (enable_default_channel_playout && playout_) {
2744 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2745 SetPlayout(voe_channel(), true);
2746 }
2747
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002748 return true;
2749}
2750
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002751bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2752 AudioRenderer* renderer) {
2753 ChannelMap::iterator it = receive_channels_.find(ssrc);
2754 if (it == receive_channels_.end()) {
2755 if (renderer) {
2756 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002757 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002758 return false;
2759 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002760
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002761 // The channel likely has gone away, do nothing.
2762 return true;
2763 }
2764
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002765 if (renderer)
2766 it->second->Start(renderer);
2767 else
2768 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002769
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002770 return true;
2771}
2772
2773bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2774 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002775 ChannelMap::iterator it = send_channels_.find(ssrc);
2776 if (it == send_channels_.end()) {
2777 if (renderer) {
2778 // Return an error if trying to set a valid renderer with an invalid ssrc.
2779 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2780 return false;
2781 }
2782
2783 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002784 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002785 }
2786
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002787 if (renderer)
2788 it->second->Start(renderer);
2789 else
2790 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002791
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002792 return true;
2793}
2794
2795bool WebRtcVoiceMediaChannel::GetActiveStreams(
2796 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002797 // In conference mode, the default channel should not be in
2798 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002799 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002800 for (ChannelMap::iterator it = receive_channels_.begin();
2801 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002802 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002803 if (level > 0) {
2804 actives->push_back(std::make_pair(it->first, level));
2805 }
2806 }
2807 return true;
2808}
2809
2810int WebRtcVoiceMediaChannel::GetOutputLevel() {
2811 // return the highest output level of all streams
2812 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002813 for (ChannelMap::iterator it = receive_channels_.begin();
2814 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002815 int level = GetOutputLevel(it->second->channel());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002816 highest = rtc::_max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002817 }
2818 return highest;
2819}
2820
2821int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2822 int ret;
2823 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2824 // In case of error, log the info and continue
2825 LOG_RTCERR0(TimeSinceLastTyping);
2826 ret = -1;
2827 } else {
2828 ret *= 1000; // We return ms, webrtc returns seconds.
2829 }
2830 return ret;
2831}
2832
2833void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2834 int cost_per_typing, int reporting_threshold, int penalty_decay,
2835 int type_event_delay) {
2836 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2837 time_window, cost_per_typing,
2838 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2839 // In case of error, log the info and continue
2840 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2841 cost_per_typing, reporting_threshold, penalty_decay,
2842 type_event_delay);
2843 }
2844}
2845
2846bool WebRtcVoiceMediaChannel::SetOutputScaling(
2847 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002848 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002849 // Collect the channels to scale the output volume.
2850 std::vector<int> channels;
2851 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002852 // Default channel is not in receive_channels_ if it is not being used for
2853 // playout.
2854 if (default_receive_ssrc_ == 0)
2855 channels.push_back(voe_channel());
2856 for (ChannelMap::const_iterator it = receive_channels_.begin();
2857 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002858 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002859 }
2860 } else { // Collect only the channel of the specified ssrc.
2861 int channel = GetReceiveChannelNum(ssrc);
2862 if (-1 == channel) {
2863 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2864 return false;
2865 }
2866 channels.push_back(channel);
2867 }
2868
2869 // Scale the output volume for the collected channels. We first normalize to
2870 // scale the volume and then set the left and right pan.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002871 float scale = static_cast<float>(rtc::_max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002872 if (scale > 0.0001f) {
2873 left /= scale;
2874 right /= scale;
2875 }
2876 for (std::vector<int>::const_iterator it = channels.begin();
2877 it != channels.end(); ++it) {
2878 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2879 *it, scale)) {
2880 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2881 return false;
2882 }
2883 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2884 *it, static_cast<float>(left), static_cast<float>(right))) {
2885 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2886 // Do not return if fails. SetOutputVolumePan is not available for all
2887 // pltforms.
2888 }
2889 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2890 << " right=" << right * scale
2891 << " for channel " << *it << " and ssrc " << ssrc;
2892 }
2893 return true;
2894}
2895
2896bool WebRtcVoiceMediaChannel::GetOutputScaling(
2897 uint32 ssrc, double* left, double* right) {
2898 if (!left || !right) return false;
2899
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002900 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002901 // Determine which channel based on ssrc.
2902 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2903 if (channel == -1) {
2904 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2905 return false;
2906 }
2907
2908 float scaling;
2909 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2910 channel, scaling)) {
2911 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2912 return false;
2913 }
2914
2915 float left_pan;
2916 float right_pan;
2917 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2918 channel, left_pan, right_pan)) {
2919 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2920 // If GetOutputVolumePan fails, we use the default left and right pan.
2921 left_pan = 1.0f;
2922 right_pan = 1.0f;
2923 }
2924
2925 *left = scaling * left_pan;
2926 *right = scaling * right_pan;
2927 return true;
2928}
2929
2930bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2931 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2932 return true;
2933}
2934
2935bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2936 bool play, bool loop) {
2937 if (!ringback_tone_) {
2938 return false;
2939 }
2940
2941 // The voe file api is not available in chrome.
2942 if (!engine()->voe()->file()) {
2943 return false;
2944 }
2945
2946 // Determine which VoiceEngine channel to play on.
2947 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2948 if (channel == -1) {
2949 return false;
2950 }
2951
2952 // Make sure the ringtone is cued properly, and play it out.
2953 if (play) {
2954 ringback_tone_->set_loop(loop);
2955 ringback_tone_->Rewind();
2956 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2957 ringback_tone_.get()) == -1) {
2958 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2959 LOG(LS_ERROR) << "Unable to start ringback tone";
2960 return false;
2961 }
2962 ringback_channels_.insert(channel);
2963 LOG(LS_INFO) << "Started ringback on channel " << channel;
2964 } else {
2965 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2966 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2967 LOG_RTCERR1(StopPlayingFileLocally, channel);
2968 return false;
2969 }
2970 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2971 ringback_channels_.erase(channel);
2972 }
2973
2974 return true;
2975}
2976
2977bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2978 return dtmf_allowed_;
2979}
2980
2981bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2982 int duration, int flags) {
2983 if (!dtmf_allowed_) {
2984 return false;
2985 }
2986
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002987 // Send the event.
2988 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002989 int channel = -1;
2990 if (ssrc == 0) {
2991 bool default_channel_is_inuse = false;
2992 for (ChannelMap::const_iterator iter = send_channels_.begin();
2993 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002994 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002995 default_channel_is_inuse = true;
2996 break;
2997 }
2998 }
2999 if (default_channel_is_inuse) {
3000 channel = voe_channel();
3001 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003002 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003003 }
3004 } else {
3005 channel = GetSendChannelNum(ssrc);
3006 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003007 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003008 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3009 << ssrc << " is not in use.";
3010 return false;
3011 }
3012 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003013 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3014 channel, event, true, duration) == -1) {
3015 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003016 return false;
3017 }
3018 }
3019
3020 // Play the event.
3021 if (flags & cricket::DF_PLAY) {
3022 // Play DTMF tone locally.
3023 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3024 LOG_RTCERR2(PlayDtmfTone, event, duration);
3025 return false;
3026 }
3027 }
3028
3029 return true;
3030}
3031
wu@webrtc.orga9890802013-12-13 00:21:03 +00003032void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003033 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003034 // Pick which channel to send this packet to. If this packet doesn't match
3035 // any multiplexed streams, just send it to the default channel. Otherwise,
3036 // send it to the specific decoder instance for that stream.
3037 int which_channel = GetReceiveChannelNum(
3038 ParseSsrc(packet->data(), packet->length(), false));
3039 if (which_channel == -1) {
3040 which_channel = voe_channel();
3041 }
3042
3043 // Stop any ringback that might be playing on the channel.
3044 // It's possible the ringback has already stopped, ih which case we'll just
3045 // use the opportunity to remove the channel from ringback_channels_.
3046 if (engine()->voe()->file()) {
3047 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3048 if (it != ringback_channels_.end()) {
3049 if (engine()->voe()->file()->IsPlayingFileLocally(
3050 which_channel) == 1) {
3051 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3052 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3053 << " due to incoming media";
3054 }
3055 ringback_channels_.erase(which_channel);
3056 }
3057 }
3058
3059 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003060 engine()->voe()->network()->ReceivedRTPPacket(
3061 which_channel,
3062 packet->data(),
3063 static_cast<unsigned int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003064}
3065
wu@webrtc.orga9890802013-12-13 00:21:03 +00003066void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003067 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003068 // Sending channels need all RTCP packets with feedback information.
3069 // Even sender reports can contain attached report blocks.
3070 // Receiving channels need sender reports in order to create
3071 // correct receiver reports.
3072 int type = 0;
3073 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3074 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3075 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003076 }
3077
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003078 // If it is a sender report, find the channel that is listening.
3079 bool has_sent_to_default_channel = false;
3080 if (type == kRtcpTypeSR) {
3081 int which_channel = GetReceiveChannelNum(
3082 ParseSsrc(packet->data(), packet->length(), true));
3083 if (which_channel != -1) {
3084 engine()->voe()->network()->ReceivedRTCPPacket(
3085 which_channel,
3086 packet->data(),
3087 static_cast<unsigned int>(packet->length()));
3088
3089 if (IsDefaultChannel(which_channel))
3090 has_sent_to_default_channel = true;
3091 }
3092 }
3093
3094 // SR may continue RR and any RR entry may correspond to any one of the send
3095 // channels. So all RTCP packets must be forwarded all send channels. VoE
3096 // will filter out RR internally.
3097 for (ChannelMap::iterator iter = send_channels_.begin();
3098 iter != send_channels_.end(); ++iter) {
3099 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003100 if (IsDefaultChannel(iter->second->channel()) &&
3101 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003102 continue;
3103
3104 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003105 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003106 packet->data(),
3107 static_cast<unsigned int>(packet->length()));
3108 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003109}
3110
3111bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003112 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3113 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003114 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3115 return false;
3116 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003117 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3118 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003119 return false;
3120 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003121 // We set the AGC to mute state only when all the channels are muted.
3122 // This implementation is not ideal, instead we should signal the AGC when
3123 // the mic channel is muted/unmuted. We can't do it today because there
3124 // is no good way to know which stream is mapping to the mic channel.
3125 bool all_muted = muted;
3126 for (ChannelMap::const_iterator iter = send_channels_.begin();
3127 iter != send_channels_.end() && all_muted; ++iter) {
3128 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3129 all_muted)) {
3130 LOG_RTCERR1(GetInputMute, iter->second->channel());
3131 return false;
3132 }
3133 }
3134
3135 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3136 if (ap)
3137 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003138 return true;
3139}
3140
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003141bool WebRtcVoiceMediaChannel::SetStartSendBandwidth(int bps) {
3142 // TODO(andresp): Add support for setting an independent start bandwidth when
3143 // bandwidth estimation is enabled for voice engine.
3144 return false;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003145}
3146
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003147bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
3148 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
3149
3150 return SetSendBandwidthInternal(bps);
3151}
3152
3153bool WebRtcVoiceMediaChannel::SetSendBandwidthInternal(int bps) {
3154 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBandwidthInternal.";
3155
3156 send_bw_setting_ = true;
3157 send_bw_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003158
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003159 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003160 LOG(LS_INFO) << "The send codec has not been set up yet. "
3161 << "The send bandwidth setting will be applied later.";
3162 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003163 }
3164
3165 // Bandwidth is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003166 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3167 // SetMaxSendBandwith(0), the second call removes the previous limit.
3168 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003169 return true;
3170
3171 webrtc::CodecInst codec = *send_codec_;
3172 bool is_multi_rate = IsCodecMultiRate(codec);
3173
3174 if (is_multi_rate) {
3175 // If codec is multi-rate then just set the bitrate.
3176 codec.rate = bps;
3177 if (!SetSendCodec(codec)) {
3178 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3179 << " to bitrate " << bps << " bps.";
3180 return false;
3181 }
3182 return true;
3183 } else {
3184 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3185 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3186 // fixed bitrate then ignore.
3187 if (bps < codec.rate) {
3188 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3189 << " to bitrate " << bps << " bps"
3190 << ", requires at least " << codec.rate << " bps.";
3191 return false;
3192 }
3193 return true;
3194 }
3195}
3196
3197bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003198 bool echo_metrics_on = false;
3199 // These can take on valid negative values, so use the lowest possible level
3200 // as default rather than -1.
3201 int echo_return_loss = -100;
3202 int echo_return_loss_enhancement = -100;
3203 // These can also be negative, but in practice -1 is only used to signal
3204 // insufficient data, since the resolution is limited to multiples of 4 ms.
3205 int echo_delay_median_ms = -1;
3206 int echo_delay_std_ms = -1;
3207 if (engine()->voe()->processing()->GetEcMetricsStatus(
3208 echo_metrics_on) != -1 && echo_metrics_on) {
3209 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3210 // here, but it appears to be unsuitable currently. Revisit after this is
3211 // investigated: http://b/issue?id=5666755
3212 int erl, erle, rerl, anlp;
3213 if (engine()->voe()->processing()->GetEchoMetrics(
3214 erl, erle, rerl, anlp) != -1) {
3215 echo_return_loss = erl;
3216 echo_return_loss_enhancement = erle;
3217 }
3218
3219 int median, std;
3220 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3221 echo_delay_median_ms = median;
3222 echo_delay_std_ms = std;
3223 }
3224 }
3225
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003226 webrtc::CallStatistics cs;
3227 unsigned int ssrc;
3228 webrtc::CodecInst codec;
3229 unsigned int level;
3230
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003231 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3232 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003233 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003234
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003235 // Fill in the sender info, based on what we know, and what the
3236 // remote side told us it got from its RTCP report.
3237 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003238
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003239 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3240 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3241 continue;
3242 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003243
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003244 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003245 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3246 sinfo.bytes_sent = cs.bytesSent;
3247 sinfo.packets_sent = cs.packetsSent;
3248 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3249 // returns 0 to indicate an error value.
3250 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3251
3252 // Get data from the last remote RTCP report. Use default values if no data
3253 // available.
3254 sinfo.fraction_lost = -1.0;
3255 sinfo.jitter_ms = -1;
3256 sinfo.packets_lost = -1;
3257 sinfo.ext_seqnum = -1;
3258 std::vector<webrtc::ReportBlock> receive_blocks;
3259 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3260 channel, &receive_blocks) != -1 &&
3261 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3262 std::vector<webrtc::ReportBlock>::iterator iter;
3263 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3264 ++iter) {
3265 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003266 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003267 // Convert Q8 to floating point.
3268 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3269 // Convert samples to milliseconds.
3270 if (codec.plfreq / 1000 > 0) {
3271 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3272 }
3273 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3274 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3275 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003276 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003277 }
3278 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003279
3280 // Local speech level.
3281 sinfo.audio_level = (engine()->voe()->volume()->
3282 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3283
3284 // TODO(xians): We are injecting the same APM logging to all the send
3285 // channels here because there is no good way to know which send channel
3286 // is using the APM. The correct fix is to allow the send channels to have
3287 // their own APM so that we can feed the correct APM logging to different
3288 // send channels. See issue crbug/264611 .
3289 sinfo.echo_return_loss = echo_return_loss;
3290 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3291 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3292 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003293 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3294 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003295 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003296
3297 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003298 }
3299
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003300 // Build the list of receivers, one for each receiving channel, or 1 in
3301 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003302 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003303 for (ChannelMap::const_iterator it = receive_channels_.begin();
3304 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003305 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003306 }
3307 if (channels.empty()) {
3308 channels.push_back(voe_channel());
3309 }
3310
3311 // Get the SSRC and stats for each receiver, based on our own calculations.
3312 for (std::vector<int>::const_iterator it = channels.begin();
3313 it != channels.end(); ++it) {
3314 memset(&cs, 0, sizeof(cs));
3315 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3316 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3317 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3318 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003319 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003320 rinfo.bytes_rcvd = cs.bytesReceived;
3321 rinfo.packets_rcvd = cs.packetsReceived;
3322 // The next four fields are from the most recently sent RTCP report.
3323 // Convert Q8 to floating point.
3324 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3325 rinfo.packets_lost = cs.cumulativeLost;
3326 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003327#ifdef USE_WEBRTC_DEV_BRANCH
3328 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
3329#endif
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003330 if (codec.pltype != -1) {
3331 rinfo.codec_name = codec.plname;
3332 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003333 // Convert samples to milliseconds.
3334 if (codec.plfreq / 1000 > 0) {
3335 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3336 }
3337
3338 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3339 webrtc::NetworkStatistics ns;
3340 if (engine()->voe()->neteq() &&
3341 engine()->voe()->neteq()->GetNetworkStatistics(
3342 *it, ns) != -1) {
3343 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3344 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3345 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003346 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003347 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003348
3349 webrtc::AudioDecodingCallStats ds;
3350 if (engine()->voe()->neteq() &&
3351 engine()->voe()->neteq()->GetDecodingCallStatistics(
3352 *it, &ds) != -1) {
3353 rinfo.decoding_calls_to_silence_generator =
3354 ds.calls_to_silence_generator;
3355 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3356 rinfo.decoding_normal = ds.decoded_normal;
3357 rinfo.decoding_plc = ds.decoded_plc;
3358 rinfo.decoding_cng = ds.decoded_cng;
3359 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3360 }
3361
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003362 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003363 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003364 int playout_buffer_delay_ms = 0;
3365 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003366 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3367 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3368 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003369 }
3370
3371 // Get speech level.
3372 rinfo.audio_level = (engine()->voe()->volume()->
3373 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3374 info->receivers.push_back(rinfo);
3375 }
3376 }
3377
3378 return true;
3379}
3380
3381void WebRtcVoiceMediaChannel::GetLastMediaError(
3382 uint32* ssrc, VoiceMediaChannel::Error* error) {
3383 ASSERT(ssrc != NULL);
3384 ASSERT(error != NULL);
3385 FindSsrc(voe_channel(), ssrc);
3386 *error = WebRtcErrorToChannelError(GetLastEngineError());
3387}
3388
3389bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003390 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003391 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003392 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003393 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3394 // This means the error is not limited to a specific channel. Signal the
3395 // message using ssrc=0. If the current channel is sending, use this
3396 // channel for sending the message.
3397 *ssrc = 0;
3398 return true;
3399 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003400 // Check whether this is a sending channel.
3401 for (ChannelMap::const_iterator it = send_channels_.begin();
3402 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003403 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003404 // This is a sending channel.
3405 uint32 local_ssrc = 0;
3406 if (engine()->voe()->rtp()->GetLocalSSRC(
3407 channel_num, local_ssrc) != -1) {
3408 *ssrc = local_ssrc;
3409 }
3410 return true;
3411 }
3412 }
3413
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003414 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003415 for (ChannelMap::const_iterator it = receive_channels_.begin();
3416 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003417 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003418 *ssrc = it->first;
3419 return true;
3420 }
3421 }
3422 }
3423 return false;
3424}
3425
3426void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003427 if (error == VE_TYPING_NOISE_WARNING) {
3428 typing_noise_detected_ = true;
3429 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3430 typing_noise_detected_ = false;
3431 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003432 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3433}
3434
3435int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3436 unsigned int ulevel;
3437 int ret =
3438 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3439 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3440}
3441
3442int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003443 ChannelMap::iterator it = receive_channels_.find(ssrc);
3444 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003445 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003446 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3447}
3448
3449int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003450 ChannelMap::iterator it = send_channels_.find(ssrc);
3451 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003452 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003453
3454 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003455}
3456
3457bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3458 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3459 // Get the RED encodings from the parameter with no name. This may
3460 // change based on what is discussed on the Jingle list.
3461 // The encoding parameter is of the form "a/b"; we only support where
3462 // a == b. Verify this and parse out the value into red_pt.
3463 // If the parameter value is absent (as it will be until we wire up the
3464 // signaling of this message), use the second codec specified (i.e. the
3465 // one after "red") as the encoding parameter.
3466 int red_pt = -1;
3467 std::string red_params;
3468 CodecParameterMap::const_iterator it = red_codec.params.find("");
3469 if (it != red_codec.params.end()) {
3470 red_params = it->second;
3471 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003472 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003473 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003474 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003475 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3476 return false;
3477 }
3478 } else if (red_codec.params.empty()) {
3479 LOG(LS_WARNING) << "RED params not present, using defaults";
3480 if (all_codecs.size() > 1) {
3481 red_pt = all_codecs[1].id;
3482 }
3483 }
3484
3485 // Try to find red_pt in |codecs|.
3486 std::vector<AudioCodec>::const_iterator codec;
3487 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3488 if (codec->id == red_pt)
3489 break;
3490 }
3491
3492 // If we find the right codec, that will be the codec we pass to
3493 // SetSendCodec, with the desired payload type.
3494 if (codec != all_codecs.end() &&
3495 engine()->FindWebRtcCodec(*codec, send_codec)) {
3496 } else {
3497 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3498 return false;
3499 }
3500
3501 return true;
3502}
3503
3504bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3505 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003506 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003507 return false;
3508 }
3509 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3510 // what we want to do with them.
3511 // engine()->voe().EnableVQMon(voe_channel(), true);
3512 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3513 return true;
3514}
3515
3516bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3517 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3518 for (int i = 0; i < ncodecs; ++i) {
3519 webrtc::CodecInst voe_codec;
3520 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3521 voe_codec.pltype = -1;
3522 if (engine()->voe()->codec()->SetRecPayloadType(
3523 channel, voe_codec) == -1) {
3524 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3525 return false;
3526 }
3527 }
3528 }
3529 return true;
3530}
3531
3532bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3533 if (playout) {
3534 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3535 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3536 LOG_RTCERR1(StartPlayout, channel);
3537 return false;
3538 }
3539 } else {
3540 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3541 engine()->voe()->base()->StopPlayout(channel);
3542 }
3543 return true;
3544}
3545
3546uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3547 bool rtcp) {
3548 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3549 uint32 ssrc = 0;
3550 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003551 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003552 }
3553 return ssrc;
3554}
3555
3556// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3557VoiceMediaChannel::Error
3558 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3559 switch (err_code) {
3560 case 0:
3561 return ERROR_NONE;
3562 case VE_CANNOT_START_RECORDING:
3563 case VE_MIC_VOL_ERROR:
3564 case VE_GET_MIC_VOL_ERROR:
3565 case VE_CANNOT_ACCESS_MIC_VOL:
3566 return ERROR_REC_DEVICE_OPEN_FAILED;
3567 case VE_SATURATION_WARNING:
3568 return ERROR_REC_DEVICE_SATURATION;
3569 case VE_REC_DEVICE_REMOVED:
3570 return ERROR_REC_DEVICE_REMOVED;
3571 case VE_RUNTIME_REC_WARNING:
3572 case VE_RUNTIME_REC_ERROR:
3573 return ERROR_REC_RUNTIME_ERROR;
3574 case VE_CANNOT_START_PLAYOUT:
3575 case VE_SPEAKER_VOL_ERROR:
3576 case VE_GET_SPEAKER_VOL_ERROR:
3577 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3578 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3579 case VE_RUNTIME_PLAY_WARNING:
3580 case VE_RUNTIME_PLAY_ERROR:
3581 return ERROR_PLAY_RUNTIME_ERROR;
3582 case VE_TYPING_NOISE_WARNING:
3583 return ERROR_REC_TYPING_NOISE_DETECTED;
3584 default:
3585 return VoiceMediaChannel::ERROR_OTHER;
3586 }
3587}
3588
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003589bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3590 int channel_id, const RtpHeaderExtension* extension) {
3591 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003592 int id = 0;
3593 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003594 if (extension) {
3595 enable = true;
3596 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003597 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003598 }
3599 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003600 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003601 return false;
3602 }
3603 return true;
3604}
3605
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003606int WebRtcSoundclipStream::Read(void *buf, int len) {
3607 size_t res = 0;
3608 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003609 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003610}
3611
3612int WebRtcSoundclipStream::Rewind() {
3613 mem_.Rewind();
3614 // Return -1 to keep VoiceEngine from looping.
3615 return (loop_) ? 0 : -1;
3616}
3617
3618} // namespace cricket
3619
3620#endif // HAVE_WEBRTC_VOICE