blob: cf3a56fa8c51b9da355d87be345a20deb5dac5cf [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#ifdef HAVE_CONFIG_H
29#include <config.h>
30#endif
31
32#ifdef HAVE_WEBRTC_VOICE
33
34#include "talk/media/webrtc/webrtcvoiceengine.h"
35
36#include <algorithm>
37#include <cstdio>
38#include <string>
39#include <vector>
40
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000041#include "talk/media/base/audiorenderer.h"
42#include "talk/media/base/constants.h"
43#include "talk/media/base/streamparams.h"
44#include "talk/media/base/voiceprocessor.h"
45#include "talk/media/webrtc/webrtcvoe.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000046#include "webrtc/base/base64.h"
47#include "webrtc/base/byteorder.h"
48#include "webrtc/base/common.h"
49#include "webrtc/base/helpers.h"
50#include "webrtc/base/logging.h"
51#include "webrtc/base/stringencode.h"
52#include "webrtc/base/stringutils.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000053#include "webrtc/common.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054#include "webrtc/modules/audio_processing/include/audio_processing.h"
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +000055#include "webrtc/video_engine/include/vie_network.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056
57#ifdef WIN32
58#include <objbase.h> // NOLINT
59#endif
60
61namespace cricket {
62
63struct CodecPref {
64 const char* name;
65 int clockrate;
66 int channels;
67 int payload_type;
68 bool is_multi_rate;
69};
70
71static const CodecPref kCodecPrefs[] = {
72 { "OPUS", 48000, 2, 111, true },
73 { "ISAC", 16000, 1, 103, true },
74 { "ISAC", 32000, 1, 104, true },
75 { "CELT", 32000, 1, 109, true },
76 { "CELT", 32000, 2, 110, true },
77 { "G722", 16000, 1, 9, false },
78 { "ILBC", 8000, 1, 102, false },
79 { "PCMU", 8000, 1, 0, false },
80 { "PCMA", 8000, 1, 8, false },
81 { "CN", 48000, 1, 107, false },
82 { "CN", 32000, 1, 106, false },
83 { "CN", 16000, 1, 105, false },
84 { "CN", 8000, 1, 13, false },
85 { "red", 8000, 1, 127, false },
86 { "telephone-event", 8000, 1, 126, false },
87};
88
89// For Linux/Mac, using the default device is done by specifying index 0 for
90// VoE 4.0 and not -1 (which was the case for VoE 3.5).
91//
92// On Windows Vista and newer, Microsoft introduced the concept of "Default
93// Communications Device". This means that there are two types of default
94// devices (old Wave Audio style default and Default Communications Device).
95//
96// On Windows systems which only support Wave Audio style default, uses either
97// -1 or 0 to select the default device.
98//
99// On Windows systems which support both "Default Communication Device" and
100// old Wave Audio style default, use -1 for Default Communications Device and
101// -2 for Wave Audio style default, which is what we want to use for clips.
102// It's not clear yet whether the -2 index is handled properly on other OSes.
103
104#ifdef WIN32
105static const int kDefaultAudioDeviceId = -1;
106static const int kDefaultSoundclipDeviceId = -2;
107#else
108static const int kDefaultAudioDeviceId = 0;
109#endif
110
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111static const char kIsacCodecName[] = "ISAC";
112static const char kL16CodecName[] = "L16";
minyue@webrtc.org0b626722014-10-30 07:19:49 +0000113
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000114// 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;
minyue@webrtc.org0b626722014-10-30 07:19:49 +0000117
118// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000119// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org0b626722014-10-30 07:19:49 +0000120static const int kOpusBitrateNb = 12000;
121static const int kOpusBitrateWb = 20000;
122static const int kOpusBitrateFb = 32000;
123
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000124// Opus bitrate should be in the range between 6000 and 510000.
125static const int kOpusMinBitrate = 6000;
126static const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000127
wu@webrtc.orgde305012013-10-31 15:40:38 +0000128// Default audio dscp value.
129// See http://tools.ietf.org/html/rfc2474 for details.
130// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000131static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000132
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000133// Ensure we open the file in a writeable path on ChromeOS and Android. This
134// workaround can be removed when it's possible to specify a filename for audio
135// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000136//
137// TODO(grunell): Use a string in the options instead of hardcoding it here
138// and let the embedder choose the filename (crbug.com/264223).
139//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000140// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
141// below.
142#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000143static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000144#elif defined(ANDROID)
145static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000146#else
147static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
148#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000149
150// Dumps an AudioCodec in RFC 2327-ish format.
151static std::string ToString(const AudioCodec& codec) {
152 std::stringstream ss;
153 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
154 << " (" << codec.id << ")";
155 return ss.str();
156}
157static std::string ToString(const webrtc::CodecInst& codec) {
158 std::stringstream ss;
159 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
160 << " (" << codec.pltype << ")";
161 return ss.str();
162}
163
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000164static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000165 const char* delim = "\r\n";
166 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
167 LOG_V(sev) << tok;
168 }
169}
170
171// Severity is an integer because it comes is assumed to be from command line.
172static int SeverityToFilter(int severity) {
173 int filter = webrtc::kTraceNone;
174 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000175 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000176 filter |= webrtc::kTraceAll;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000177 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000178 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000179 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000180 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000181 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000182 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
183 }
184 return filter;
185}
186
187static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
188 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
189 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
190 kCodecPrefs[i].clockrate == codec.plfreq) {
191 return kCodecPrefs[i].is_multi_rate;
192 }
193 }
194 return false;
195}
196
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000197static bool IsTelephoneEventCodec(const std::string& name) {
198 return _stricmp(name.c_str(), "telephone-event") == 0;
199}
200
201static bool IsCNCodec(const std::string& name) {
202 return _stricmp(name.c_str(), "CN") == 0;
203}
204
205static bool IsRedCodec(const std::string& name) {
206 return _stricmp(name.c_str(), "red") == 0;
207}
208
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000209static bool FindCodec(const std::vector<AudioCodec>& codecs,
210 const AudioCodec& codec,
211 AudioCodec* found_codec) {
212 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
213 it != codecs.end(); ++it) {
214 if (it->Matches(codec)) {
215 if (found_codec != NULL) {
216 *found_codec = *it;
217 }
218 return true;
219 }
220 }
221 return false;
222}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000223
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000224static bool IsNackEnabled(const AudioCodec& codec) {
225 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
226 kParamValueEmpty));
227}
228
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000229// Gets the default set of options applied to the engine. Historically, these
230// were supplied as a combination of flags from the channel manager (ec, agc,
231// ns, and highpass) and the rest hardcoded in InitInternal.
232static AudioOptions GetDefaultEngineOptions() {
233 AudioOptions options;
234 options.echo_cancellation.Set(true);
235 options.auto_gain_control.Set(true);
236 options.noise_suppression.Set(true);
237 options.highpass_filter.Set(true);
238 options.stereo_swapping.Set(false);
239 options.typing_detection.Set(true);
240 options.conference_mode.Set(false);
241 options.adjust_agc_delta.Set(0);
242 options.experimental_agc.Set(false);
243 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000244 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000245 options.aec_dump.Set(false);
246 return options;
247}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000248
249class WebRtcSoundclipMedia : public SoundclipMedia {
250 public:
251 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
252 : engine_(engine), webrtc_channel_(-1) {
253 engine_->RegisterSoundclip(this);
254 }
255
256 virtual ~WebRtcSoundclipMedia() {
257 engine_->UnregisterSoundclip(this);
258 if (webrtc_channel_ != -1) {
259 // We shouldn't have to call Disable() here. DeleteChannel() should call
260 // StopPlayout() while deleting the channel. We should fix the bug
261 // inside WebRTC and remove the Disable() call bellow. This work is
262 // tracked by bug http://b/issue?id=5382855.
263 PlaySound(NULL, 0, 0);
264 Disable();
265 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
266 == -1) {
267 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
268 }
269 }
270 }
271
272 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000273 if (!engine_->voe_sc()) {
274 return false;
275 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000276 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000277 if (webrtc_channel_ == -1) {
278 LOG_RTCERR0(CreateChannel);
279 return false;
280 }
281 return true;
282 }
283
284 bool Enable() {
285 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
286 LOG_RTCERR1(StartPlayout, webrtc_channel_);
287 return false;
288 }
289 return true;
290 }
291
292 bool Disable() {
293 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
294 LOG_RTCERR1(StopPlayout, webrtc_channel_);
295 return false;
296 }
297 return true;
298 }
299
300 virtual bool PlaySound(const char *buf, int len, int flags) {
301 // The voe file api is not available in chrome.
302 if (!engine_->voe_sc()->file()) {
303 return false;
304 }
305 // Must stop playing the current sound (if any), because we are about to
306 // modify the stream.
307 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
308 == -1) {
309 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
310 return false;
311 }
312
313 if (buf) {
314 stream_.reset(new WebRtcSoundclipStream(buf, len));
315 stream_->set_loop((flags & SF_LOOP) != 0);
316 stream_->Rewind();
317
318 // Play it.
319 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
320 webrtc_channel_, stream_.get()) == -1) {
321 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
322 LOG(LS_ERROR) << "Unable to start soundclip";
323 return false;
324 }
325 } else {
326 stream_.reset();
327 }
328 return true;
329 }
330
331 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
332
333 private:
334 WebRtcVoiceEngine *engine_;
335 int webrtc_channel_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000336 rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000337};
338
339WebRtcVoiceEngine::WebRtcVoiceEngine()
340 : voe_wrapper_(new VoEWrapper()),
341 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000342 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000343 tracing_(new VoETraceWrapper()),
344 adm_(NULL),
345 adm_sc_(NULL),
346 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
347 is_dumping_aec_(false),
348 desired_local_monitor_enable_(false),
349 tx_processor_ssrc_(0),
350 rx_processor_ssrc_(0) {
351 Construct();
352}
353
354WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
355 VoEWrapper* voe_wrapper_sc,
356 VoETraceWrapper* tracing)
357 : voe_wrapper_(voe_wrapper),
358 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000359 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000360 tracing_(tracing),
361 adm_(NULL),
362 adm_sc_(NULL),
363 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
364 is_dumping_aec_(false),
365 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000366 tx_processor_ssrc_(0),
367 rx_processor_ssrc_(0) {
368 Construct();
369}
370
371void WebRtcVoiceEngine::Construct() {
372 SetTraceFilter(log_filter_);
373 initialized_ = false;
374 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
375 SetTraceOptions("");
376 if (tracing_->SetTraceCallback(this) == -1) {
377 LOG_RTCERR0(SetTraceCallback);
378 }
379 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
380 LOG_RTCERR0(RegisterVoiceEngineObserver);
381 }
382 // Clear the default agc state.
383 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
384
385 // Load our audio codec list.
386 ConstructCodecs();
387
388 // Load our RTP Header extensions.
389 rtp_header_extensions_.push_back(
390 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
391 kRtpAudioLevelHeaderExtensionDefaultId));
392 rtp_header_extensions_.push_back(
393 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
394 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
395 options_ = GetDefaultEngineOptions();
396}
397
398static bool IsOpus(const AudioCodec& codec) {
399 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
400}
401
402static bool IsIsac(const AudioCodec& codec) {
403 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
404}
405
406// True if params["stereo"] == "1"
407static bool IsOpusStereoEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000408 int value;
409 return codec.GetParam(kCodecParamStereo, &value) && value == 1;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000410}
411
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000412// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
413// otherwise. If the value (either from params or codec.bitrate) <=0, use the
414// default configuration. If the value is beyond feasible bit rate of Opus,
415// clamp it. Returns the Opus bit rate for operation.
minyue@webrtc.org5f73a372014-10-30 07:49:58 +0000416static int GetOpusBitrate(const AudioCodec& codec) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000417 int bitrate = 0;
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000418 bool use_param = true;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000419 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000420 bitrate = codec.bitrate;
421 use_param = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000422 }
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000423 if (bitrate <= 0) {
minyue@webrtc.org5f73a372014-10-30 07:49:58 +0000424 bitrate = IsOpusStereoEnabled(codec) ? kOpusStereoBitrate :
425 kOpusMonoBitrate;
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000426 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
427 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
428 std::string rate_source =
429 use_param ? "Codec parameter \"maxaveragebitrate\"" :
430 "Supplied Opus bitrate";
431 LOG(LS_WARNING) << rate_source
432 << " is invalid and is replaced by: "
433 << bitrate;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000434 }
435 return bitrate;
436}
437
buildbot@webrtc.orgfbd13282014-06-19 19:50:55 +0000438// Return true if params[kCodecParamUseInbandFec] == "1", false
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000439// otherwise.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000440static bool IsOpusFecEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000441 int value;
442 return codec.GetParam(kCodecParamUseInbandFec, &value) && value == 1;
443}
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000444
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000445// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
446// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
447static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
448 int value;
449 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
450 return value;
451 }
452 return kOpusDefaultMaxPlaybackRate;
453}
454
455static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
456 bool* enable_codec_fec, int* max_playback_rate) {
457 *enable_codec_fec = IsOpusFecEnabled(codec);
458 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
459
460 // If OPUS, change what we send according to the "stereo" codec
461 // parameter, and not the "channels" parameter. We set
462 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000463 // the bitrate is not specified, i.e. is <= zero, we set it to the
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000464 // appropriate default value for mono or stereo Opus.
465
minyue@webrtc.org5f73a372014-10-30 07:49:58 +0000466 // TODO(minyue): The determination of bit rate might take the maximum playback
467 // rate into account.
468
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000469 voe_codec->channels = IsOpusStereoEnabled(codec) ? 2 : 1;
minyue@webrtc.org5f73a372014-10-30 07:49:58 +0000470 voe_codec->rate = GetOpusBitrate(codec);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000471}
472
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000473void WebRtcVoiceEngine::ConstructCodecs() {
474 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
475 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
476 for (int i = 0; i < ncodecs; ++i) {
477 webrtc::CodecInst voe_codec;
478 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
479 // Skip uncompressed formats.
480 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
481 continue;
482 }
483
484 const CodecPref* pref = NULL;
485 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
486 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
487 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
488 kCodecPrefs[j].channels == voe_codec.channels) {
489 pref = &kCodecPrefs[j];
490 break;
491 }
492 }
493
494 if (pref) {
495 // Use the payload type that we've configured in our pref table;
496 // use the offset in our pref table to determine the sort order.
497 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
498 voe_codec.rate, voe_codec.channels,
499 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
500 LOG(LS_INFO) << ToString(codec);
501 if (IsIsac(codec)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000502 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000503 codec.bitrate = 0;
504 }
505 if (IsOpus(codec)) {
506 // Only add fmtp parameters that differ from the spec.
507 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
508 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000509 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000510 }
511 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
512 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000513 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000514 }
515 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
516 // when they can be set to values other than the default.
517 }
518 codecs_.push_back(codec);
519 } else {
520 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
521 }
522 }
523 }
524 // Make sure they are in local preference order.
525 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
526}
527
528WebRtcVoiceEngine::~WebRtcVoiceEngine() {
529 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
530 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
531 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
532 }
533 if (adm_) {
534 voe_wrapper_.reset();
535 adm_->Release();
536 adm_ = NULL;
537 }
538 if (adm_sc_) {
539 voe_wrapper_sc_.reset();
540 adm_sc_->Release();
541 adm_sc_ = NULL;
542 }
543
544 // Test to see if the media processor was deregistered properly
545 ASSERT(SignalRxMediaFrame.is_empty());
546 ASSERT(SignalTxMediaFrame.is_empty());
547
548 tracing_->SetTraceCallback(NULL);
549}
550
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000551bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000552 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
553 bool res = InitInternal();
554 if (res) {
555 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
556 } else {
557 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
558 Terminate();
559 }
560 return res;
561}
562
563bool WebRtcVoiceEngine::InitInternal() {
564 // Temporarily turn logging level up for the Init call
565 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000566 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000567 SetTraceFilter(extended_filter);
568 SetTraceOptions("");
569
570 // Init WebRtc VoiceEngine.
571 if (voe_wrapper_->base()->Init(adm_) == -1) {
572 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
573 SetTraceFilter(old_filter);
574 return false;
575 }
576
577 SetTraceFilter(old_filter);
578 SetTraceOptions(log_options_);
579
580 // Log the VoiceEngine version info
581 char buffer[1024] = "";
582 voe_wrapper_->base()->GetVersion(buffer);
583 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000584 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000585
586 // Save the default AGC configuration settings. This must happen before
587 // calling SetOptions or the default will be overwritten.
588 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
589 LOG_RTCERR0(GetAgcConfig);
590 return false;
591 }
592
593 // Set defaults for options, so that ApplyOptions applies them explicitly
594 // when we clear option (channel) overrides. External clients can still
595 // modify the defaults via SetOptions (on the media engine).
596 if (!SetOptions(GetDefaultEngineOptions())) {
597 return false;
598 }
599
600 // Print our codec list again for the call diagnostic log
601 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
602 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
603 it != codecs_.end(); ++it) {
604 LOG(LS_INFO) << ToString(*it);
605 }
606
607 // Disable the DTMF playout when a tone is sent.
608 // PlayDtmfTone will be used if local playout is needed.
609 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
610 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
611 }
612
613 initialized_ = true;
614 return true;
615}
616
617bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
618 if (voe_wrapper_sc_initialized_) {
619 return true;
620 }
621 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
622 // be false, so subsequent calls to EnsureSoundclipEngineInit will
623 // probably just fail again. That's acceptable behavior.
624#if defined(LINUX) && !defined(HAVE_LIBPULSE)
625 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
626#endif
627
628 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
629 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
630 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
631 return false;
632 }
633
634 // On Windows, tell it to use the default sound (not communication) devices.
635 // First check whether there is a valid sound device for playback.
636 // TODO(juberti): Clean this up when we support setting the soundclip device.
637#ifdef WIN32
638 // The SetPlayoutDevice may not be implemented in the case of external ADM.
639 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
640 // PeerConnection interface never set the adm_sc_, so need to check both
641 // in order to determine if the external adm is used.
642 if (!adm_ && !adm_sc_) {
643 int num_of_devices = 0;
644 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
645 num_of_devices > 0) {
646 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
647 == -1) {
648 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
649 voe_wrapper_sc_->error());
650 return false;
651 }
652 } else {
653 LOG(LS_WARNING) << "No valid sound playout device found.";
654 }
655 }
656#endif
657 voe_wrapper_sc_initialized_ = true;
658 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
659 return true;
660}
661
662void WebRtcVoiceEngine::Terminate() {
663 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
664 initialized_ = false;
665
666 StopAecDump();
667
668 if (voe_wrapper_sc_) {
669 voe_wrapper_sc_initialized_ = false;
670 voe_wrapper_sc_->base()->Terminate();
671 }
672 voe_wrapper_->base()->Terminate();
673 desired_local_monitor_enable_ = false;
674}
675
676int WebRtcVoiceEngine::GetCapabilities() {
677 return AUDIO_SEND | AUDIO_RECV;
678}
679
680VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
681 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
682 if (!ch->valid()) {
683 delete ch;
684 ch = NULL;
685 }
686 return ch;
687}
688
689SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
690 if (!EnsureSoundclipEngineInit()) {
691 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
692 << "initialize.";
693 return NULL;
694 }
695 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
696 if (!soundclip->Init() || !soundclip->Enable()) {
697 delete soundclip;
698 return NULL;
699 }
700 return soundclip;
701}
702
703bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
704 if (!ApplyOptions(options)) {
705 return false;
706 }
707 options_ = options;
708 return true;
709}
710
711bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
712 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
713 if (!ApplyOptions(overrides)) {
714 return false;
715 }
716 option_overrides_ = overrides;
717 return true;
718}
719
720bool WebRtcVoiceEngine::ClearOptionOverrides() {
721 LOG(LS_INFO) << "Clearing option overrides.";
722 AudioOptions options = options_;
723 // Only call ApplyOptions if |options_overrides_| contains overrided options.
724 // ApplyOptions affects NS, AGC other options that is shared between
725 // all WebRtcVoiceEngineChannels.
726 if (option_overrides_ == AudioOptions()) {
727 return true;
728 }
729
730 if (!ApplyOptions(options)) {
731 return false;
732 }
733 option_overrides_ = AudioOptions();
734 return true;
735}
736
737// AudioOptions defaults are set in InitInternal (for options with corresponding
738// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
739bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
740 AudioOptions options = options_in; // The options are modified below.
741 // kEcConference is AEC with high suppression.
742 webrtc::EcModes ec_mode = webrtc::kEcConference;
743 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
744 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
745 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
746 bool aecm_comfort_noise = false;
747 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
748 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
749 << aecm_comfort_noise << " (default is false).";
750 }
751
752#if defined(IOS)
753 // On iOS, VPIO provides built-in EC and AGC.
754 options.echo_cancellation.Set(false);
755 options.auto_gain_control.Set(false);
756#elif defined(ANDROID)
757 ec_mode = webrtc::kEcAecm;
758#endif
759
760#if defined(IOS) || defined(ANDROID)
761 // Set the AGC mode for iOS as well despite disabling it above, to avoid
762 // unsupported configuration errors from webrtc.
763 agc_mode = webrtc::kAgcFixedDigital;
764 options.typing_detection.Set(false);
765 options.experimental_agc.Set(false);
766 options.experimental_aec.Set(false);
767 options.experimental_ns.Set(false);
768#endif
769
770 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
771
772 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
773
774 bool echo_cancellation;
775 if (options.echo_cancellation.Get(&echo_cancellation)) {
776 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
777 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
778 return false;
779 } else {
780 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
781 << " with mode " << ec_mode;
782 }
783#if !defined(ANDROID)
784 // TODO(ajm): Remove the error return on Android from webrtc.
785 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
786 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
787 return false;
788 }
789#endif
790 if (ec_mode == webrtc::kEcAecm) {
791 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
792 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
793 return false;
794 }
795 }
796 }
797
798 bool auto_gain_control;
799 if (options.auto_gain_control.Get(&auto_gain_control)) {
800 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
801 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
802 return false;
803 } else {
804 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
805 << " with mode " << agc_mode;
806 }
807 }
808
809 if (options.tx_agc_target_dbov.IsSet() ||
810 options.tx_agc_digital_compression_gain.IsSet() ||
811 options.tx_agc_limiter.IsSet()) {
812 // Override default_agc_config_. Generally, an unset option means "leave
813 // the VoE bits alone" in this function, so we want whatever is set to be
814 // stored as the new "default". If we didn't, then setting e.g.
815 // tx_agc_target_dbov would reset digital compression gain and limiter
816 // settings.
817 // Also, if we don't update default_agc_config_, then adjust_agc_delta
818 // would be an offset from the original values, and not whatever was set
819 // explicitly.
820 default_agc_config_.targetLeveldBOv =
821 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
822 default_agc_config_.targetLeveldBOv);
823 default_agc_config_.digitalCompressionGaindB =
824 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
825 default_agc_config_.digitalCompressionGaindB);
826 default_agc_config_.limiterEnable =
827 options.tx_agc_limiter.GetWithDefaultIfUnset(
828 default_agc_config_.limiterEnable);
829 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
830 LOG_RTCERR3(SetAgcConfig,
831 default_agc_config_.targetLeveldBOv,
832 default_agc_config_.digitalCompressionGaindB,
833 default_agc_config_.limiterEnable);
834 return false;
835 }
836 }
837
838 bool noise_suppression;
839 if (options.noise_suppression.Get(&noise_suppression)) {
840 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
841 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
842 return false;
843 } else {
844 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
845 << " with mode " << ns_mode;
846 }
847 }
848
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000849 bool highpass_filter;
850 if (options.highpass_filter.Get(&highpass_filter)) {
851 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
852 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
853 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
854 return false;
855 }
856 }
857
858 bool stereo_swapping;
859 if (options.stereo_swapping.Get(&stereo_swapping)) {
860 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
861 voep->EnableStereoChannelSwapping(stereo_swapping);
862 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
863 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
864 return false;
865 }
866 }
867
868 bool typing_detection;
869 if (options.typing_detection.Get(&typing_detection)) {
870 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
871 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
872 // In case of error, log the info and continue
873 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
874 }
875 }
876
877 int adjust_agc_delta;
878 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
879 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
880 if (!AdjustAgcLevel(adjust_agc_delta)) {
881 return false;
882 }
883 }
884
885 bool aec_dump;
886 if (options.aec_dump.Get(&aec_dump)) {
887 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
888 if (aec_dump)
889 StartAecDump(kAecDumpByAudioOptionFilename);
890 else
891 StopAecDump();
892 }
893
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000894 webrtc::Config config;
895
896 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000897 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000898 if (experimental_aec_.Get(&experimental_aec)) {
899 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
900 config.Set<webrtc::DelayCorrection>(
901 new webrtc::DelayCorrection(experimental_aec));
902 }
903
904#ifdef USE_WEBRTC_DEV_BRANCH
905 experimental_ns_.SetFrom(options.experimental_ns);
906 bool experimental_ns;
907 if (experimental_ns_.Get(&experimental_ns)) {
908 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
909 config.Set<webrtc::ExperimentalNs>(
910 new webrtc::ExperimentalNs(experimental_ns));
911 }
912#endif
913
914 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
915 // returns NULL on audio_processing().
916 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
917 if (audioproc) {
918 audioproc->SetExtraOptions(config);
919 }
920
921#ifndef USE_WEBRTC_DEV_BRANCH
922 bool experimental_ns;
923 if (options.experimental_ns.Get(&experimental_ns)) {
924 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000925 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
926 // returns NULL on audio_processing().
927 if (audioproc) {
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000928 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
929 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
930 return false;
931 }
932 } else {
933 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
934 << experimental_ns;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000935 }
936 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000937#endif
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000938
939 uint32 recording_sample_rate;
940 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
941 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
942 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
943 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
944 }
945 }
946
947 uint32 playout_sample_rate;
948 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
949 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
950 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
951 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
952 }
953 }
954
955 return true;
956}
957
958bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
959 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
960 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
961 LOG_RTCERR1(SetDelayOffsetMs, offset);
962 return false;
963 }
964
965 return true;
966}
967
968struct ResumeEntry {
969 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
970 : channel(c),
971 playout(p),
972 send(s) {
973 }
974
975 WebRtcVoiceMediaChannel *channel;
976 bool playout;
977 SendFlags send;
978};
979
980// TODO(juberti): Refactor this so that the core logic can be used to set the
981// soundclip device. At that time, reinstate the soundclip pause/resume code.
982bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
983 const Device* out_device) {
984#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000985 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000986 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000987 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000988 kDefaultAudioDeviceId;
989 // The device manager uses -1 as the default device, which was the case for
990 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
991#ifndef WIN32
992 if (-1 == in_id) {
993 in_id = kDefaultAudioDeviceId;
994 }
995 if (-1 == out_id) {
996 out_id = kDefaultAudioDeviceId;
997 }
998#endif
999
1000 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
1001 in_device->name : "Default device";
1002 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
1003 out_device->name : "Default device";
1004 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
1005 << ") and speaker to (id=" << out_id << ", name=" << out_name
1006 << ")";
1007
1008 // If we're running the local monitor, we need to stop it first.
1009 bool ret = true;
1010 if (!PauseLocalMonitor()) {
1011 LOG(LS_WARNING) << "Failed to pause local monitor";
1012 ret = false;
1013 }
1014
1015 // Must also pause all audio playback and capture.
1016 for (ChannelList::const_iterator i = channels_.begin();
1017 i != channels_.end(); ++i) {
1018 WebRtcVoiceMediaChannel *channel = *i;
1019 if (!channel->PausePlayout()) {
1020 LOG(LS_WARNING) << "Failed to pause playout";
1021 ret = false;
1022 }
1023 if (!channel->PauseSend()) {
1024 LOG(LS_WARNING) << "Failed to pause send";
1025 ret = false;
1026 }
1027 }
1028
1029 // Find the recording device id in VoiceEngine and set recording device.
1030 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1031 ret = false;
1032 }
1033 if (ret) {
1034 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
1035 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
1036 ret = false;
1037 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00001038 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
1039 if (ap)
1040 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001041 }
1042
1043 // Find the playout device id in VoiceEngine and set playout device.
1044 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1045 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1046 ret = false;
1047 }
1048 if (ret) {
1049 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001050 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001051 ret = false;
1052 }
1053 }
1054
1055 // Resume all audio playback and capture.
1056 for (ChannelList::const_iterator i = channels_.begin();
1057 i != channels_.end(); ++i) {
1058 WebRtcVoiceMediaChannel *channel = *i;
1059 if (!channel->ResumePlayout()) {
1060 LOG(LS_WARNING) << "Failed to resume playout";
1061 ret = false;
1062 }
1063 if (!channel->ResumeSend()) {
1064 LOG(LS_WARNING) << "Failed to resume send";
1065 ret = false;
1066 }
1067 }
1068
1069 // Resume local monitor.
1070 if (!ResumeLocalMonitor()) {
1071 LOG(LS_WARNING) << "Failed to resume local monitor";
1072 ret = false;
1073 }
1074
1075 if (ret) {
1076 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1077 << ") and speaker to (id="<< out_id << " name=" << out_name
1078 << ")";
1079 }
1080
1081 return ret;
1082#else
1083 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001084#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001085}
1086
1087bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1088 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1089 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001090#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091 *rtc_id = dev_id;
1092 return true;
1093#else
1094 // In Windows and Mac, we need to find the VoiceEngine device id by name
1095 // unless the input dev_id is the default device id.
1096 if (kDefaultAudioDeviceId == dev_id) {
1097 *rtc_id = dev_id;
1098 return true;
1099 }
1100
1101 // Get the number of VoiceEngine audio devices.
1102 int count = 0;
1103 if (is_input) {
1104 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1105 LOG_RTCERR0(GetNumOfRecordingDevices);
1106 return false;
1107 }
1108 } else {
1109 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1110 LOG_RTCERR0(GetNumOfPlayoutDevices);
1111 return false;
1112 }
1113 }
1114
1115 for (int i = 0; i < count; ++i) {
1116 char name[128];
1117 char guid[128];
1118 if (is_input) {
1119 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1120 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1121 } else {
1122 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1123 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1124 }
1125
1126 std::string webrtc_name(name);
1127 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1128 *rtc_id = i;
1129 return true;
1130 }
1131 }
1132 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1133 return false;
1134#endif
1135}
1136
1137bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1138 unsigned int ulevel;
1139 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1140 LOG_RTCERR1(GetSpeakerVolume, level);
1141 return false;
1142 }
1143 *level = ulevel;
1144 return true;
1145}
1146
1147bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1148 ASSERT(level >= 0 && level <= 255);
1149 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1150 LOG_RTCERR1(SetSpeakerVolume, level);
1151 return false;
1152 }
1153 return true;
1154}
1155
1156int WebRtcVoiceEngine::GetInputLevel() {
1157 unsigned int ulevel;
1158 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1159 static_cast<int>(ulevel) : -1;
1160}
1161
1162bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1163 desired_local_monitor_enable_ = enable;
1164 return ChangeLocalMonitor(desired_local_monitor_enable_);
1165}
1166
1167bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1168 // The voe file api is not available in chrome.
1169 if (!voe_wrapper_->file()) {
1170 return false;
1171 }
1172 if (enable && !monitor_) {
1173 monitor_.reset(new WebRtcMonitorStream);
1174 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1175 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1176 // Must call Stop() because there are some cases where Start will report
1177 // failure but still change the state, and if we leave VE in the on state
1178 // then it could crash later when trying to invoke methods on our monitor.
1179 voe_wrapper_->file()->StopRecordingMicrophone();
1180 monitor_.reset();
1181 return false;
1182 }
1183 } else if (!enable && monitor_) {
1184 voe_wrapper_->file()->StopRecordingMicrophone();
1185 monitor_.reset();
1186 }
1187 return true;
1188}
1189
1190bool WebRtcVoiceEngine::PauseLocalMonitor() {
1191 return ChangeLocalMonitor(false);
1192}
1193
1194bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1195 return ChangeLocalMonitor(desired_local_monitor_enable_);
1196}
1197
1198const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1199 return codecs_;
1200}
1201
1202bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1203 return FindWebRtcCodec(in, NULL);
1204}
1205
1206// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1207bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1208 webrtc::CodecInst* out) {
1209 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1210 for (int i = 0; i < ncodecs; ++i) {
1211 webrtc::CodecInst voe_codec;
1212 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1213 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1214 voe_codec.rate, voe_codec.channels, 0);
1215 bool multi_rate = IsCodecMultiRate(voe_codec);
1216 // Allow arbitrary rates for ISAC to be specified.
1217 if (multi_rate) {
1218 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1219 codec.bitrate = 0;
1220 }
1221 if (codec.Matches(in)) {
1222 if (out) {
1223 // Fixup the payload type.
1224 voe_codec.pltype = in.id;
1225
1226 // Set bitrate if specified.
1227 if (multi_rate && in.bitrate != 0) {
1228 voe_codec.rate = in.bitrate;
1229 }
1230
1231 // Apply codec-specific settings.
1232 if (IsIsac(codec)) {
1233 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001234 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001235 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1236 }
1237 *out = voe_codec;
1238 }
1239 return true;
1240 }
1241 }
1242 }
1243 return false;
1244}
1245const std::vector<RtpHeaderExtension>&
1246WebRtcVoiceEngine::rtp_header_extensions() const {
1247 return rtp_header_extensions_;
1248}
1249
1250void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1251 // if min_sev == -1, we keep the current log level.
1252 if (min_sev >= 0) {
1253 SetTraceFilter(SeverityToFilter(min_sev));
1254 }
1255 log_options_ = filter;
1256 SetTraceOptions(initialized_ ? log_options_ : "");
1257}
1258
1259int WebRtcVoiceEngine::GetLastEngineError() {
1260 return voe_wrapper_->error();
1261}
1262
1263void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1264 log_filter_ = filter;
1265 tracing_->SetTraceFilter(filter);
1266}
1267
1268// We suppport three different logging settings for VoiceEngine:
1269// 1. Observer callback that goes into talk diagnostic logfile.
1270// Use --logfile and --loglevel
1271//
1272// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1273// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1274//
1275// 3. EC log and dump for debugging QualityEngine.
1276// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1277//
1278// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1279// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1280void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1281 // Set encrypted trace file.
1282 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001283 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001284 std::vector<std::string>::iterator tracefile =
1285 std::find(opts.begin(), opts.end(), "tracefile");
1286 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1287 // Write encrypted debug output (at same loglevel) to file
1288 // EncryptedTraceFile no longer supported.
1289 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1290 LOG_RTCERR1(SetTraceFile, *tracefile);
1291 }
1292 }
1293
wu@webrtc.org97077a32013-10-25 21:18:33 +00001294 // Allow trace options to override the trace filter. We default
1295 // it to log_filter_ (as a translation of libjingle log levels)
1296 // elsewhere, but this allows clients to explicitly set webrtc
1297 // log levels.
1298 std::vector<std::string>::iterator tracefilter =
1299 std::find(opts.begin(), opts.end(), "tracefilter");
1300 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001301 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001302 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1303 }
1304 }
1305
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001306 // Set AEC dump file
1307 std::vector<std::string>::iterator recordEC =
1308 std::find(opts.begin(), opts.end(), "recordEC");
1309 if (recordEC != opts.end()) {
1310 ++recordEC;
1311 if (recordEC != opts.end())
1312 StartAecDump(recordEC->c_str());
1313 else
1314 StopAecDump();
1315 }
1316}
1317
1318// Ignore spammy trace messages, mostly from the stats API when we haven't
1319// gotten RTCP info yet from the remote side.
1320bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1321 static const char* kTracesToIgnore[] = {
1322 "\tfailed to GetReportBlockInformation",
1323 "GetRecCodec() failed to get received codec",
1324 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1325 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1326 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1327 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1328 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1329 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1330 "SenderInfoReceived No received SR",
1331 "StatisticsRTP() no statistics available",
1332 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1333 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1334 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1335 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1336 NULL
1337 };
1338 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1339 if (trace.find(*p) != std::string::npos) {
1340 return true;
1341 }
1342 }
1343 return false;
1344}
1345
1346void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1347 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001348 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001350 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001352 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001353 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001354 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001355 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001356 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001357
1358 // Skip past boilerplate prefix text
1359 if (length < 72) {
1360 std::string msg(trace, length);
1361 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1362 LOG_V(sev) << msg;
1363 } else {
1364 std::string msg(trace + 71, length - 72);
1365 if (!ShouldIgnoreTrace(msg)) {
1366 LOG_V(sev) << "webrtc: " << msg;
1367 }
1368 }
1369}
1370
1371void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001372 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001373 WebRtcVoiceMediaChannel* channel = NULL;
1374 uint32 ssrc = 0;
1375 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1376 << channel_num << ".";
1377 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1378 ASSERT(channel != NULL);
1379 channel->OnError(ssrc, err_code);
1380 } else {
1381 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1382 << " could not be found in channel list when error reported.";
1383 }
1384}
1385
1386bool WebRtcVoiceEngine::FindChannelAndSsrc(
1387 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1388 ASSERT(channel != NULL && ssrc != NULL);
1389
1390 *channel = NULL;
1391 *ssrc = 0;
1392 // Find corresponding channel and ssrc
1393 for (ChannelList::const_iterator it = channels_.begin();
1394 it != channels_.end(); ++it) {
1395 ASSERT(*it != NULL);
1396 if ((*it)->FindSsrc(channel_num, ssrc)) {
1397 *channel = *it;
1398 return true;
1399 }
1400 }
1401
1402 return false;
1403}
1404
1405// This method will search through the WebRtcVoiceMediaChannels and
1406// obtain the voice engine's channel number.
1407bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1408 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1409 ASSERT(channel_num != NULL);
1410 ASSERT(direction == MPD_RX || direction == MPD_TX);
1411
1412 *channel_num = -1;
1413 // Find corresponding channel for ssrc.
1414 for (ChannelList::const_iterator it = channels_.begin();
1415 it != channels_.end(); ++it) {
1416 ASSERT(*it != NULL);
1417 if (direction & MPD_RX) {
1418 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1419 }
1420 if (*channel_num == -1 && (direction & MPD_TX)) {
1421 *channel_num = (*it)->GetSendChannelNum(ssrc);
1422 }
1423 if (*channel_num != -1) {
1424 return true;
1425 }
1426 }
1427 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1428 return false;
1429}
1430
1431void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001432 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001433 channels_.push_back(channel);
1434}
1435
1436void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001437 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001438 ChannelList::iterator i = std::find(channels_.begin(),
1439 channels_.end(),
1440 channel);
1441 if (i != channels_.end()) {
1442 channels_.erase(i);
1443 }
1444}
1445
1446void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1447 soundclips_.push_back(soundclip);
1448}
1449
1450void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1451 SoundclipList::iterator i = std::find(soundclips_.begin(),
1452 soundclips_.end(),
1453 soundclip);
1454 if (i != soundclips_.end()) {
1455 soundclips_.erase(i);
1456 }
1457}
1458
1459// Adjusts the default AGC target level by the specified delta.
1460// NB: If we start messing with other config fields, we'll want
1461// to save the current webrtc::AgcConfig as well.
1462bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1463 webrtc::AgcConfig config = default_agc_config_;
1464 config.targetLeveldBOv -= delta;
1465
1466 LOG(LS_INFO) << "Adjusting AGC level from default -"
1467 << default_agc_config_.targetLeveldBOv << "dB to -"
1468 << config.targetLeveldBOv << "dB";
1469
1470 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1471 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1472 return false;
1473 }
1474 return true;
1475}
1476
1477bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1478 webrtc::AudioDeviceModule* adm_sc) {
1479 if (initialized_) {
1480 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1481 return false;
1482 }
1483 if (adm_) {
1484 adm_->Release();
1485 adm_ = NULL;
1486 }
1487 if (adm) {
1488 adm_ = adm;
1489 adm_->AddRef();
1490 }
1491
1492 if (adm_sc_) {
1493 adm_sc_->Release();
1494 adm_sc_ = NULL;
1495 }
1496 if (adm_sc) {
1497 adm_sc_ = adm_sc;
1498 adm_sc_->AddRef();
1499 }
1500 return true;
1501}
1502
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001503bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1504 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001505 if (!aec_dump_file_stream) {
1506 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001507 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001508 LOG(LS_WARNING) << "Could not close file.";
1509 return false;
1510 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001511 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001512 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001513 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001514 LOG_RTCERR0(StartDebugRecording);
1515 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001516 return false;
1517 }
1518 is_dumping_aec_ = true;
1519 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001520}
1521
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001522bool WebRtcVoiceEngine::RegisterProcessor(
1523 uint32 ssrc,
1524 VoiceProcessor* voice_processor,
1525 MediaProcessorDirection direction) {
1526 bool register_with_webrtc = false;
1527 int channel_id = -1;
1528 bool success = false;
1529 uint32* processor_ssrc = NULL;
1530 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1531 if (voice_processor == NULL || !found_channel) {
1532 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1533 << " foundChannel: " << found_channel;
1534 return false;
1535 }
1536
1537 webrtc::ProcessingTypes processing_type;
1538 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001539 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001540 if (direction == MPD_RX) {
1541 processing_type = webrtc::kPlaybackAllChannelsMixed;
1542 if (SignalRxMediaFrame.is_empty()) {
1543 register_with_webrtc = true;
1544 processor_ssrc = &rx_processor_ssrc_;
1545 }
1546 SignalRxMediaFrame.connect(voice_processor,
1547 &VoiceProcessor::OnFrame);
1548 } else {
1549 processing_type = webrtc::kRecordingPerChannel;
1550 if (SignalTxMediaFrame.is_empty()) {
1551 register_with_webrtc = true;
1552 processor_ssrc = &tx_processor_ssrc_;
1553 }
1554 SignalTxMediaFrame.connect(voice_processor,
1555 &VoiceProcessor::OnFrame);
1556 }
1557 }
1558 if (register_with_webrtc) {
1559 // TODO(janahan): when registering consider instantiating a
1560 // a VoeMediaProcess object and not make the engine extend the interface.
1561 if (voe()->media() && voe()->media()->
1562 RegisterExternalMediaProcessing(channel_id,
1563 processing_type,
1564 *this) != -1) {
1565 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1566 << channel_id;
1567 *processor_ssrc = ssrc;
1568 success = true;
1569 } else {
1570 LOG_RTCERR2(RegisterExternalMediaProcessing,
1571 channel_id,
1572 processing_type);
1573 success = false;
1574 }
1575 } else {
1576 // If we don't have to register with the engine, we just needed to
1577 // connect a new processor, set success to true;
1578 success = true;
1579 }
1580 return success;
1581}
1582
1583bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1584 MediaProcessorDirection channel_direction,
1585 uint32 ssrc,
1586 VoiceProcessor* voice_processor,
1587 MediaProcessorDirection processor_direction) {
1588 bool success = true;
1589 FrameSignal* signal;
1590 webrtc::ProcessingTypes processing_type;
1591 uint32* processor_ssrc = NULL;
1592 if (channel_direction == MPD_RX) {
1593 signal = &SignalRxMediaFrame;
1594 processing_type = webrtc::kPlaybackAllChannelsMixed;
1595 processor_ssrc = &rx_processor_ssrc_;
1596 } else {
1597 signal = &SignalTxMediaFrame;
1598 processing_type = webrtc::kRecordingPerChannel;
1599 processor_ssrc = &tx_processor_ssrc_;
1600 }
1601
1602 int deregister_id = -1;
1603 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001604 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001605 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1606 signal->disconnect(voice_processor);
1607 int channel_id = -1;
1608 bool found_channel = FindChannelNumFromSsrc(ssrc,
1609 channel_direction,
1610 &channel_id);
1611 if (signal->is_empty() && found_channel) {
1612 deregister_id = channel_id;
1613 }
1614 }
1615 }
1616 if (deregister_id != -1) {
1617 if (voe()->media() &&
1618 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1619 processing_type) != -1) {
1620 *processor_ssrc = 0;
1621 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1622 << deregister_id;
1623 } else {
1624 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1625 deregister_id,
1626 processing_type);
1627 success = false;
1628 }
1629 }
1630 return success;
1631}
1632
1633bool WebRtcVoiceEngine::UnregisterProcessor(
1634 uint32 ssrc,
1635 VoiceProcessor* voice_processor,
1636 MediaProcessorDirection direction) {
1637 bool success = true;
1638 if (voice_processor == NULL) {
1639 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1640 << ssrc;
1641 return false;
1642 }
1643 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1644 success = false;
1645 }
1646 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1647 success = false;
1648 }
1649 return success;
1650}
1651
1652// Implementing method from WebRtc VoEMediaProcess interface
1653// Do not lock mux_channel_cs_ in this callback.
1654void WebRtcVoiceEngine::Process(int channel,
1655 webrtc::ProcessingTypes type,
1656 int16_t audio10ms[],
1657 int length,
1658 int sampling_freq,
1659 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001660 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001661 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1662 if (type == webrtc::kPlaybackAllChannelsMixed) {
1663 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1664 } else if (type == webrtc::kRecordingPerChannel) {
1665 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1666 } else {
1667 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1668 << " channel: " << channel << " type: " << type
1669 << " tx_ssrc: " << tx_processor_ssrc_
1670 << " rx_ssrc: " << rx_processor_ssrc_;
1671 }
1672}
1673
1674void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1675 if (!is_dumping_aec_) {
1676 // Start dumping AEC when we are not dumping.
1677 if (voe_wrapper_->processing()->StartDebugRecording(
1678 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001679 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001680 } else {
1681 is_dumping_aec_ = true;
1682 }
1683 }
1684}
1685
1686void WebRtcVoiceEngine::StopAecDump() {
1687 if (is_dumping_aec_) {
1688 // Stop dumping AEC when we are dumping.
1689 if (voe_wrapper_->processing()->StopDebugRecording() !=
1690 webrtc::AudioProcessing::kNoError) {
1691 LOG_RTCERR0(StopDebugRecording);
1692 }
1693 is_dumping_aec_ = false;
1694 }
1695}
1696
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001697int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001698 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001699}
1700
1701int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1702 return CreateVoiceChannel(voe_wrapper_.get());
1703}
1704
1705int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1706 return CreateVoiceChannel(voe_wrapper_sc_.get());
1707}
1708
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001709class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1710 : public AudioRenderer::Sink {
1711 public:
1712 WebRtcVoiceChannelRenderer(int ch,
1713 webrtc::AudioTransport* voe_audio_transport)
1714 : channel_(ch),
1715 voe_audio_transport_(voe_audio_transport),
1716 renderer_(NULL) {
1717 }
1718 virtual ~WebRtcVoiceChannelRenderer() {
1719 Stop();
1720 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001721
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001722 // Starts the rendering by setting a sink to the renderer to get data
1723 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001724 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001725 // TODO(xians): Make sure Start() is called only once.
1726 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001727 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001728 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001729 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001730 ASSERT(renderer_ == renderer);
1731 return;
1732 }
1733
1734 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1735 // in getUserMedia by default.
1736 renderer->AddChannel(channel_);
1737 renderer->SetSink(this);
1738 renderer_ = renderer;
1739 }
1740
1741 // Stops rendering by setting the sink of the renderer to NULL. No data
1742 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001743 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001744 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001745 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001746 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001747 return;
1748
1749 renderer_->RemoveChannel(channel_);
1750 renderer_->SetSink(NULL);
1751 renderer_ = NULL;
1752 }
1753
1754 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001755 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001756 virtual void OnData(const void* audio_data,
1757 int bits_per_sample,
1758 int sample_rate,
1759 int number_of_channels,
1760 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001761 voe_audio_transport_->OnData(channel_,
1762 audio_data,
1763 bits_per_sample,
1764 sample_rate,
1765 number_of_channels,
1766 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001767 }
1768
1769 // Callback from the |renderer_| when it is going away. In case Start() has
1770 // never been called, this callback won't be triggered.
1771 virtual void OnClose() OVERRIDE {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001772 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001773 // Set |renderer_| to NULL to make sure no more callback will get into
1774 // the renderer.
1775 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001776 }
1777
1778 // Accessor to the VoE channel ID.
1779 int channel() const { return channel_; }
1780
1781 private:
1782 const int channel_;
1783 webrtc::AudioTransport* const voe_audio_transport_;
1784
1785 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1786 // PeerConnection will make sure invalidating the pointer before the object
1787 // goes away.
1788 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001789
1790 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001791 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001792};
1793
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001794// WebRtcVoiceMediaChannel
1795WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1796 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1797 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001798 engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001799 send_bitrate_setting_(false),
1800 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001801 options_(),
1802 dtmf_allowed_(false),
1803 desired_playout_(false),
1804 nack_enabled_(false),
1805 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001806 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001807 desired_send_(SEND_NOTHING),
1808 send_(SEND_NOTHING),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001809 shared_bwe_vie_(NULL),
1810 shared_bwe_vie_channel_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001811 default_receive_ssrc_(0) {
1812 engine->RegisterChannel(this);
1813 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1814 << voe_channel();
1815
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001816 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001817}
1818
1819WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1820 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1821 << voe_channel();
buildbot@webrtc.org6e5c7842014-09-19 06:46:37 +00001822 SetupSharedBandwidthEstimation(NULL, -1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001823
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001824 // Remove any remaining send streams, the default channel will be deleted
1825 // later.
1826 while (!send_channels_.empty())
1827 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001828
1829 // Unregister ourselves from the engine.
1830 engine()->UnregisterChannel(this);
1831 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001832 while (!receive_channels_.empty()) {
1833 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001834 }
1835
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001836 // Delete the default channel.
1837 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001838}
1839
1840bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1841 LOG(LS_INFO) << "Setting voice channel options: "
1842 << options.ToString();
1843
wu@webrtc.orgde305012013-10-31 15:40:38 +00001844 // Check if DSCP value is changed from previous.
1845 bool dscp_option_changed = (options_.dscp != options.dscp);
1846
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001847 // TODO(xians): Add support to set different options for different send
1848 // streams after we support multiple APMs.
1849
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001850 // We retain all of the existing options, and apply the given ones
1851 // on top. This means there is no way to "clear" options such that
1852 // they go back to the engine default.
1853 options_.SetAll(options);
1854
1855 if (send_ != SEND_NOTHING) {
1856 if (!engine()->SetOptionOverrides(options_)) {
1857 LOG(LS_WARNING) <<
1858 "Failed to engine SetOptionOverrides during channel SetOptions.";
1859 return false;
1860 }
1861 } else {
1862 // Will be interpreted when appropriate.
1863 }
1864
wu@webrtc.org97077a32013-10-25 21:18:33 +00001865 // Receiver-side auto gain control happens per channel, so set it here from
1866 // options. Note that, like conference mode, setting it on the engine won't
1867 // have the desired effect, since voice channels don't inherit options from
1868 // the media engine when those options are applied per-channel.
1869 bool rx_auto_gain_control;
1870 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1871 if (engine()->voe()->processing()->SetRxAgcStatus(
1872 voe_channel(), rx_auto_gain_control,
1873 webrtc::kAgcFixedDigital) == -1) {
1874 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1875 return false;
1876 } else {
1877 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1878 << " with mode " << webrtc::kAgcFixedDigital;
1879 }
1880 }
1881 if (options.rx_agc_target_dbov.IsSet() ||
1882 options.rx_agc_digital_compression_gain.IsSet() ||
1883 options.rx_agc_limiter.IsSet()) {
1884 webrtc::AgcConfig config;
1885 // If only some of the options are being overridden, get the current
1886 // settings for the channel and bail if they aren't available.
1887 if (!options.rx_agc_target_dbov.IsSet() ||
1888 !options.rx_agc_digital_compression_gain.IsSet() ||
1889 !options.rx_agc_limiter.IsSet()) {
1890 if (engine()->voe()->processing()->GetRxAgcConfig(
1891 voe_channel(), config) != 0) {
1892 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1893 << "channel " << voe_channel() << ". Since not all rx "
1894 << "agc options are specified, unable to safely set rx "
1895 << "agc options.";
1896 return false;
1897 }
1898 }
1899 config.targetLeveldBOv =
1900 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1901 config.targetLeveldBOv);
1902 config.digitalCompressionGaindB =
1903 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1904 config.digitalCompressionGaindB);
1905 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1906 config.limiterEnable);
1907 if (engine()->voe()->processing()->SetRxAgcConfig(
1908 voe_channel(), config) == -1) {
1909 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1910 config.digitalCompressionGaindB, config.limiterEnable);
1911 return false;
1912 }
1913 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001914 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001915 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001916 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001917 dscp = kAudioDscpValue;
1918 if (MediaChannel::SetDscp(dscp) != 0) {
1919 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1920 }
1921 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001922
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001923 // Force update of Video Engine BWE forwarding to reflect experiment setting.
1924 if (!SetupSharedBandwidthEstimation(shared_bwe_vie_,
1925 shared_bwe_vie_channel_)) {
1926 return false;
1927 }
1928
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001929 LOG(LS_INFO) << "Set voice channel options. Current options: "
1930 << options_.ToString();
1931 return true;
1932}
1933
1934bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1935 const std::vector<AudioCodec>& codecs) {
1936 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001937 LOG(LS_INFO) << "Setting receive voice codecs:";
1938
1939 std::vector<AudioCodec> new_codecs;
1940 // Find all new codecs. We allow adding new codecs but don't allow changing
1941 // the payload type of codecs that is already configured since we might
1942 // already be receiving packets with that payload type.
1943 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001944 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001945 AudioCodec old_codec;
1946 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1947 if (old_codec.id != it->id) {
1948 LOG(LS_ERROR) << it->name << " payload type changed.";
1949 return false;
1950 }
1951 } else {
1952 new_codecs.push_back(*it);
1953 }
1954 }
1955 if (new_codecs.empty()) {
1956 // There are no new codecs to configure. Already configured codecs are
1957 // never removed.
1958 return true;
1959 }
1960
1961 if (playout_) {
1962 // Receive codecs can not be changed while playing. So we temporarily
1963 // pause playout.
1964 PausePlayout();
1965 }
1966
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001967 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001968 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1969 it != new_codecs.end() && ret; ++it) {
1970 webrtc::CodecInst voe_codec;
1971 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1972 LOG(LS_INFO) << ToString(*it);
1973 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001974 if (default_receive_ssrc_ == 0) {
1975 // Set the receive codecs on the default channel explicitly if the
1976 // default channel is not used by |receive_channels_|, this happens in
1977 // conference mode or in non-conference mode when there is no playout
1978 // channel.
1979 // TODO(xians): Figure out how we use the default channel in conference
1980 // mode.
1981 if (engine()->voe()->codec()->SetRecPayloadType(
1982 voe_channel(), voe_codec) == -1) {
1983 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1984 ret = false;
1985 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001986 }
1987
1988 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001989 for (ChannelMap::iterator it = receive_channels_.begin();
1990 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001991 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001992 it->second->channel(), voe_codec) == -1) {
1993 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001994 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001995 ret = false;
1996 }
1997 }
1998 } else {
1999 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2000 ret = false;
2001 }
2002 }
2003 if (ret) {
2004 recv_codecs_ = codecs;
2005 }
2006
2007 if (desired_playout_ && !playout_) {
2008 ResumePlayout();
2009 }
2010 return ret;
2011}
2012
2013bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002014 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002015 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002016 engine()->voe()->codec()->SetVADStatus(channel, false);
2017 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002018#ifdef USE_WEBRTC_DEV_BRANCH
2019 engine()->voe()->rtp()->SetREDStatus(channel, false);
2020 engine()->voe()->codec()->SetFECStatus(channel, false);
2021#else
2022 // TODO(minyue): Remove code under #else case after new WebRTC roll.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002023 engine()->voe()->rtp()->SetFECStatus(channel, false);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002024#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002025
2026 // Scan through the list to figure out the codec to use for sending, along
2027 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002028 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002029 webrtc::CodecInst send_codec;
2030 memset(&send_codec, 0, sizeof(send_codec));
2031
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002032 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002033 bool enable_codec_fec = false;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002034
minyue@webrtc.org26236952014-10-29 02:27:08 +00002035 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002036
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002037 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002038 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2039 it != codecs.end(); ++it) {
2040 // Ignore codecs we don't know about. The negotiation step should prevent
2041 // this, but double-check to be sure.
2042 webrtc::CodecInst voe_codec;
2043 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002044 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002045 continue;
2046 }
2047
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002048 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2049 // Skip telephone-event/CN codec, which will be handled later.
2050 continue;
2051 }
2052
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002053 // We'll use the first codec in the list to actually send audio data.
2054 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002055 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002056 // used is specified in params.
2057 if (IsRedCodec(it->name)) {
2058 // Parse out the RED parameters. If we fail, just ignore RED;
2059 // we don't support all possible params/usage scenarios.
2060 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2061 continue;
2062 }
2063
2064 // Enable redundant encoding of the specified codec. Treat any
2065 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002066#ifdef USE_WEBRTC_DEV_BRANCH
2067 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2068 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2069 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
2070#else
2071 // TODO(minyue): Remove code under #else case after new WebRTC roll.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002072 LOG(LS_INFO) << "Enabling FEC";
2073 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2074 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002075#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002076 return false;
2077 }
2078 } else {
2079 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002080 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002081 // For Opus as the send codec, we are to enable inband FEC if requested
2082 // and set maximum playback rate.
2083 if (IsOpus(*it)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002084 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
2085 &opus_max_playback_rate);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002086 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002087 }
2088 found_send_codec = true;
2089 break;
2090 }
2091
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002092 if (nack_enabled_ != nack_enabled) {
2093 SetNack(channel, nack_enabled);
2094 nack_enabled_ = nack_enabled;
2095 }
2096
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002097 if (!found_send_codec) {
2098 LOG(LS_WARNING) << "Received empty list of codecs.";
2099 return false;
2100 }
2101
2102 // Set the codec immediately, since SetVADStatus() depends on whether
2103 // the current codec is mono or stereo.
2104 if (!SetSendCodec(channel, send_codec))
2105 return false;
2106
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002107 // FEC should be enabled after SetSendCodec.
2108 if (enable_codec_fec) {
2109 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2110 << channel;
2111#ifdef USE_WEBRTC_DEV_BRANCH
2112 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2113 // Enable codec internal FEC. Treat any failure as fatal internal error.
2114 LOG_RTCERR2(SetFECStatus, channel, true);
2115 return false;
2116 }
2117#endif // USE_WEBRTC_DEV_BRANCH
2118 }
2119
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002120 // maxplaybackrate should be set after SetSendCodec.
minyue@webrtc.org26236952014-10-29 02:27:08 +00002121 // If opus_max_playback_rate <= 0, the default maximum playback rate of 48 kHz
2122 // will be used.
2123 if (opus_max_playback_rate > 0) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002124 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002125 << opus_max_playback_rate
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002126 << " Hz on channel "
2127 << channel;
2128#ifdef USE_WEBRTC_DEV_BRANCH
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002129 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
minyue@webrtc.org26236952014-10-29 02:27:08 +00002130 channel, opus_max_playback_rate) == -1) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002131 LOG(LS_WARNING) << "Could not set maximum playback rate.";
2132 }
2133#endif
2134 }
2135
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002136 // Always update the |send_codec_| to the currently set send codec.
2137 send_codec_.reset(new webrtc::CodecInst(send_codec));
2138
minyue@webrtc.org26236952014-10-29 02:27:08 +00002139 if (send_bitrate_setting_) {
2140 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002141 }
2142
2143 // Loop through the codecs list again to config the telephone-event/CN codec.
2144 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2145 it != codecs.end(); ++it) {
2146 // Ignore codecs we don't know about. The negotiation step should prevent
2147 // this, but double-check to be sure.
2148 webrtc::CodecInst voe_codec;
2149 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2150 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2151 continue;
2152 }
2153
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002154 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2155 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002156 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002157 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2158 channel, it->id) == -1) {
2159 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2160 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002161 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002162 } else if (IsCNCodec(it->name)) {
2163 // Turn voice activity detection/comfort noise on if supported.
2164 // Set the wideband CN payload type appropriately.
2165 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002166 webrtc::PayloadFrequencies cn_freq;
2167 switch (it->clockrate) {
2168 case 8000:
2169 cn_freq = webrtc::kFreq8000Hz;
2170 break;
2171 case 16000:
2172 cn_freq = webrtc::kFreq16000Hz;
2173 break;
2174 case 32000:
2175 cn_freq = webrtc::kFreq32000Hz;
2176 break;
2177 default:
2178 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2179 << " not supported.";
2180 continue;
2181 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002182 // Set the CN payloadtype and the VAD status.
2183 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2184 if (cn_freq != webrtc::kFreq8000Hz) {
2185 if (engine()->voe()->codec()->SetSendCNPayloadType(
2186 channel, it->id, cn_freq) == -1) {
2187 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2188 // TODO(ajm): This failure condition will be removed from VoE.
2189 // Restore the return here when we update to a new enough webrtc.
2190 //
2191 // Not returning false because the SetSendCNPayloadType will fail if
2192 // the channel is already sending.
2193 // This can happen if the remote description is applied twice, for
2194 // example in the case of ROAP on top of JSEP, where both side will
2195 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002196 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002197 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002198 // Only turn on VAD if we have a CN payload type that matches the
2199 // clockrate for the codec we are going to use.
2200 if (it->clockrate == send_codec.plfreq) {
2201 LOG(LS_INFO) << "Enabling VAD";
2202 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2203 LOG_RTCERR2(SetVADStatus, channel, true);
2204 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002205 }
2206 }
2207 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002208 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002209 return true;
2210}
2211
2212bool WebRtcVoiceMediaChannel::SetSendCodecs(
2213 const std::vector<AudioCodec>& codecs) {
2214 dtmf_allowed_ = false;
2215 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2216 it != codecs.end(); ++it) {
2217 // Find the DTMF telephone event "codec".
2218 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2219 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2220 dtmf_allowed_ = true;
2221 }
2222 }
2223
2224 // Cache the codecs in order to configure the channel created later.
2225 send_codecs_ = codecs;
2226 for (ChannelMap::iterator iter = send_channels_.begin();
2227 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002228 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002229 return false;
2230 }
2231 }
2232
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002233 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002234 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002235 return true;
2236}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002237
2238void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2239 bool nack_enabled) {
2240 for (ChannelMap::const_iterator it = channels.begin();
2241 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002242 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002243 }
2244}
2245
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002246void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002247 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002248 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002249 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2250 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002251 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002252 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2253 }
2254}
2255
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002256bool WebRtcVoiceMediaChannel::SetSendCodec(
2257 const webrtc::CodecInst& send_codec) {
2258 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2259 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002260 for (ChannelMap::iterator iter = send_channels_.begin();
2261 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002262 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002263 return false;
2264 }
2265
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002266 return true;
2267}
2268
2269bool WebRtcVoiceMediaChannel::SetSendCodec(
2270 int channel, const webrtc::CodecInst& send_codec) {
2271 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2272 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2273
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002274 webrtc::CodecInst current_codec;
2275 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2276 (send_codec == current_codec)) {
2277 // Codec is already configured, we can return without setting it again.
2278 return true;
2279 }
2280
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002281 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2282 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002283 return false;
2284 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002285 return true;
2286}
2287
2288bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2289 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002290 if (receive_extensions_ == extensions) {
2291 return true;
2292 }
2293
2294 // The default channel may or may not be in |receive_channels_|. Set the rtp
2295 // header extensions for default channel regardless.
2296 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2297 return false;
2298 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002299
2300 // Loop through all receive channels and enable/disable the extensions.
2301 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2302 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002303 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2304 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002305 return false;
2306 }
2307 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002308
2309 receive_extensions_ = extensions;
2310 return true;
2311}
2312
2313bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2314 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002315 const RtpHeaderExtension* audio_level_extension =
2316 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2317 if (!SetHeaderExtension(
2318 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2319 audio_level_extension)) {
2320 return false;
2321 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002322
2323 const RtpHeaderExtension* send_time_extension =
2324 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2325 if (!SetHeaderExtension(
2326 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2327 send_time_extension)) {
2328 return false;
2329 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002330 return true;
2331}
2332
2333bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2334 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002335 if (send_extensions_ == extensions) {
2336 return true;
2337 }
2338
2339 // The default channel may or may not be in |send_channels_|. Set the rtp
2340 // header extensions for default channel regardless.
2341
2342 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2343 return false;
2344 }
2345
2346 // Loop through all send channels and enable/disable the extensions.
2347 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2348 channel_it != send_channels_.end(); ++channel_it) {
2349 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2350 extensions)) {
2351 return false;
2352 }
2353 }
2354
2355 send_extensions_ = extensions;
2356 return true;
2357}
2358
2359bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2360 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002361 const RtpHeaderExtension* audio_level_extension =
2362 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002363
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002364 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002365 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002366 audio_level_extension)) {
2367 return false;
2368 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002369
2370 const RtpHeaderExtension* send_time_extension =
2371 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002372 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002373 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002374 send_time_extension)) {
2375 return false;
2376 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002377
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002378 return true;
2379}
2380
2381bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2382 desired_playout_ = playout;
2383 return ChangePlayout(desired_playout_);
2384}
2385
2386bool WebRtcVoiceMediaChannel::PausePlayout() {
2387 return ChangePlayout(false);
2388}
2389
2390bool WebRtcVoiceMediaChannel::ResumePlayout() {
2391 return ChangePlayout(desired_playout_);
2392}
2393
2394bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2395 if (playout_ == playout) {
2396 return true;
2397 }
2398
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002399 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002400 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002401 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002402 // Only toggle the default channel if we don't have any other channels.
2403 result = SetPlayout(voe_channel(), playout);
2404 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002405 for (ChannelMap::iterator it = receive_channels_.begin();
2406 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002407 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002408 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002409 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002410 result = false;
2411 }
2412 }
2413
2414 if (result) {
2415 playout_ = playout;
2416 }
2417 return result;
2418}
2419
2420bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2421 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002422 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002423 return ChangeSend(desired_send_);
2424 return true;
2425}
2426
2427bool WebRtcVoiceMediaChannel::PauseSend() {
2428 return ChangeSend(SEND_NOTHING);
2429}
2430
2431bool WebRtcVoiceMediaChannel::ResumeSend() {
2432 return ChangeSend(desired_send_);
2433}
2434
2435bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2436 if (send_ == send) {
2437 return true;
2438 }
2439
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002440 // Change the settings on each send channel.
2441 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002442 engine()->SetOptionOverrides(options_);
2443
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002444 // Change the settings on each send channel.
2445 for (ChannelMap::iterator iter = send_channels_.begin();
2446 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002447 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002448 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002449 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002450
2451 // Clear up the options after stopping sending.
2452 if (send == SEND_NOTHING)
2453 engine()->ClearOptionOverrides();
2454
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002455 send_ = send;
2456 return true;
2457}
2458
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002459bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2460 if (send == SEND_MICROPHONE) {
2461 if (engine()->voe()->base()->StartSend(channel) == -1) {
2462 LOG_RTCERR1(StartSend, channel);
2463 return false;
2464 }
2465 if (engine()->voe()->file() &&
2466 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2467 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2468 return false;
2469 }
2470 } else { // SEND_NOTHING
2471 ASSERT(send == SEND_NOTHING);
2472 if (engine()->voe()->base()->StopSend(channel) == -1) {
2473 LOG_RTCERR1(StopSend, channel);
2474 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002475 }
2476 }
2477
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002478 return true;
2479}
2480
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002481// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002482void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2483 if (engine()->voe()->network()->RegisterExternalTransport(
2484 channel, *this) == -1) {
2485 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2486 }
2487
2488 // Enable RTCP (for quality stats and feedback messages)
2489 EnableRtcp(channel);
2490
2491 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2492 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002493
2494 // Set RTP header extension for the new channel.
2495 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002496}
2497
2498bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2499 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2500 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2501 }
2502
2503 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2504 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002505 return false;
2506 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002507
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002508 return true;
2509}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002510
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002511bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2512 // If the default channel is already used for sending create a new channel
2513 // otherwise use the default channel for sending.
2514 int channel = GetSendChannelNum(sp.first_ssrc());
2515 if (channel != -1) {
2516 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2517 return false;
2518 }
2519
2520 bool default_channel_is_available = true;
2521 for (ChannelMap::const_iterator iter = send_channels_.begin();
2522 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002523 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002524 default_channel_is_available = false;
2525 break;
2526 }
2527 }
2528 if (default_channel_is_available) {
2529 channel = voe_channel();
2530 } else {
2531 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002532 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002533 if (channel == -1) {
2534 LOG_RTCERR0(CreateChannel);
2535 return false;
2536 }
2537
2538 ConfigureSendChannel(channel);
2539 }
2540
2541 // Save the channel to send_channels_, so that RemoveSendStream() can still
2542 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002543 webrtc::AudioTransport* audio_transport =
2544 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002545 send_channels_.insert(std::make_pair(
2546 sp.first_ssrc(),
2547 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002548
2549 // Set the send (local) SSRC.
2550 // If there are multiple send SSRCs, we can only set the first one here, and
2551 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2552 // (with a codec requires multiple SSRC(s)).
2553 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2554 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2555 return false;
2556 }
2557
2558 // At this point the channel's local SSRC has been updated. If the channel is
2559 // the default channel make sure that all the receive channels are updated as
2560 // well. Receive channels have to have the same SSRC as the default channel in
2561 // order to send receiver reports with this SSRC.
2562 if (IsDefaultChannel(channel)) {
2563 for (ChannelMap::const_iterator it = receive_channels_.begin();
2564 it != receive_channels_.end(); ++it) {
2565 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002566 if (!IsDefaultChannel(it->second->channel())) {
2567 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002568 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002569 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002570 return false;
2571 }
2572 }
2573 }
2574 }
2575
2576 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002577 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2578 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002579 }
2580
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002581 // Set the current codecs to be used for the new channel.
2582 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002583 return false;
2584
2585 return ChangeSend(channel, desired_send_);
2586}
2587
2588bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2589 ChannelMap::iterator it = send_channels_.find(ssrc);
2590 if (it == send_channels_.end()) {
2591 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2592 << " which doesn't exist.";
2593 return false;
2594 }
2595
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002596 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002597 ChangeSend(channel, SEND_NOTHING);
2598
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002599 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2600 // this will disconnect the audio renderer with the send channel.
2601 delete it->second;
2602 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002603
2604 if (IsDefaultChannel(channel)) {
2605 // Do not delete the default channel since the receive channels depend on
2606 // the default channel, recycle it instead.
2607 ChangeSend(channel, SEND_NOTHING);
2608 } else {
2609 // Clean up and delete the send channel.
2610 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2611 << " with VoiceEngine channel #" << channel << ".";
2612 if (!DeleteChannel(channel))
2613 return false;
2614 }
2615
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002616 if (send_channels_.empty())
2617 ChangeSend(SEND_NOTHING);
2618
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002619 return true;
2620}
2621
2622bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002623 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002624
2625 if (!VERIFY(sp.ssrcs.size() == 1))
2626 return false;
2627 uint32 ssrc = sp.first_ssrc();
2628
wu@webrtc.org78187522013-10-07 23:32:02 +00002629 if (ssrc == 0) {
2630 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2631 return false;
2632 }
2633
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002634 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2635 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002636 return false;
2637 }
2638
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002639 // Reuse default channel for recv stream in non-conference mode call
2640 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002641 webrtc::AudioTransport* audio_transport =
2642 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002643 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2644 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2645 << " reuse default channel";
2646 default_receive_ssrc_ = sp.first_ssrc();
2647 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002648 default_receive_ssrc_,
2649 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002650 if (!SetupSharedBweOnChannel(voe_channel())) {
2651 return false;
2652 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002653 return SetPlayout(voe_channel(), playout_);
2654 }
2655
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002656 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002657 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002658 if (channel == -1) {
2659 LOG_RTCERR0(CreateChannel);
2660 return false;
2661 }
2662
wu@webrtc.org78187522013-10-07 23:32:02 +00002663 if (!ConfigureRecvChannel(channel)) {
2664 DeleteChannel(channel);
2665 return false;
2666 }
2667
2668 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002669 std::make_pair(
2670 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002671
2672 LOG(LS_INFO) << "New audio stream " << ssrc
2673 << " registered to VoiceEngine channel #"
2674 << channel << ".";
2675 return true;
2676}
2677
2678bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002679 // Configure to use external transport, like our default channel.
2680 if (engine()->voe()->network()->RegisterExternalTransport(
2681 channel, *this) == -1) {
2682 LOG_RTCERR2(SetExternalTransport, channel, this);
2683 return false;
2684 }
2685
2686 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002687 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002688 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2689 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002690 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002691 return false;
2692 }
2693 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002694 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002695 return false;
2696 }
2697
2698 // Use the same recv payload types as our default channel.
2699 ResetRecvCodecs(channel);
2700 if (!recv_codecs_.empty()) {
2701 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2702 it != recv_codecs_.end(); ++it) {
2703 webrtc::CodecInst voe_codec;
2704 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2705 voe_codec.pltype = it->id;
2706 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2707 if (engine()->voe()->codec()->GetRecPayloadType(
2708 voe_channel(), voe_codec) != -1) {
2709 if (engine()->voe()->codec()->SetRecPayloadType(
2710 channel, voe_codec) == -1) {
2711 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2712 return false;
2713 }
2714 }
2715 }
2716 }
2717 }
2718
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002719 if (InConferenceMode()) {
2720 // To be in par with the video, voe_channel() is not used for receiving in
2721 // a conference call.
2722 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2723 // This is the first stream in a multi user meeting. We can now
2724 // disable playback of the default stream. This since the default
2725 // stream will probably have received some initial packets before
2726 // the new stream was added. This will mean that the CN state from
2727 // the default channel will be mixed in with the other streams
2728 // throughout the whole meeting, which might be disturbing.
2729 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2730 SetPlayout(voe_channel(), false);
2731 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002732 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002733 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002734
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002735 // Set RTP header extension for the new channel.
2736 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2737 return false;
2738 }
2739
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002740 // Set up channel to be able to forward incoming packets to video engine BWE.
2741 if (!SetupSharedBweOnChannel(channel)) {
2742 return false;
2743 }
2744
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002745 return SetPlayout(channel, playout_);
2746}
2747
2748bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002749 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002750 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002751 if (it == receive_channels_.end()) {
2752 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2753 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002754 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002755 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002756
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002757 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2758 // will disconnect the audio renderer with the receive channel.
2759 // Cache the channel before the deletion.
2760 const int channel = it->second->channel();
2761 delete it->second;
2762 receive_channels_.erase(it);
2763
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002764 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002765 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002766 // Recycle the default channel is for recv stream.
2767 if (playout_)
2768 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002769
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002770 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002771 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002772 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002773
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002774 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002775 << " with VoiceEngine channel #" << channel << ".";
2776 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002777 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002778
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002779 bool enable_default_channel_playout = false;
2780 if (receive_channels_.empty()) {
2781 // The last stream was removed. We can now enable the default
2782 // channel for new channels to be played out immediately without
2783 // waiting for AddStream messages.
2784 // We do this for both conference mode and non-conference mode.
2785 // TODO(oja): Does the default channel still have it's CN state?
2786 enable_default_channel_playout = true;
2787 }
2788 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2789 default_receive_ssrc_ != 0) {
2790 // Only the default channel is active, enable the playout on default
2791 // channel.
2792 enable_default_channel_playout = true;
2793 }
2794 if (enable_default_channel_playout && playout_) {
2795 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2796 SetPlayout(voe_channel(), true);
2797 }
2798
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002799 return true;
2800}
2801
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002802bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2803 AudioRenderer* renderer) {
2804 ChannelMap::iterator it = receive_channels_.find(ssrc);
2805 if (it == receive_channels_.end()) {
2806 if (renderer) {
2807 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002808 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002809 return false;
2810 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002811
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002812 // The channel likely has gone away, do nothing.
2813 return true;
2814 }
2815
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002816 if (renderer)
2817 it->second->Start(renderer);
2818 else
2819 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002820
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002821 return true;
2822}
2823
2824bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2825 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002826 ChannelMap::iterator it = send_channels_.find(ssrc);
2827 if (it == send_channels_.end()) {
2828 if (renderer) {
2829 // Return an error if trying to set a valid renderer with an invalid ssrc.
2830 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2831 return false;
2832 }
2833
2834 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002835 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002836 }
2837
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002838 if (renderer)
2839 it->second->Start(renderer);
2840 else
2841 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002842
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002843 return true;
2844}
2845
2846bool WebRtcVoiceMediaChannel::GetActiveStreams(
2847 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002848 // In conference mode, the default channel should not be in
2849 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002850 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002851 for (ChannelMap::iterator it = receive_channels_.begin();
2852 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002853 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002854 if (level > 0) {
2855 actives->push_back(std::make_pair(it->first, level));
2856 }
2857 }
2858 return true;
2859}
2860
2861int WebRtcVoiceMediaChannel::GetOutputLevel() {
2862 // return the highest output level of all streams
2863 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002864 for (ChannelMap::iterator it = receive_channels_.begin();
2865 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002866 int level = GetOutputLevel(it->second->channel());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002867 highest = rtc::_max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002868 }
2869 return highest;
2870}
2871
2872int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2873 int ret;
2874 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2875 // In case of error, log the info and continue
2876 LOG_RTCERR0(TimeSinceLastTyping);
2877 ret = -1;
2878 } else {
2879 ret *= 1000; // We return ms, webrtc returns seconds.
2880 }
2881 return ret;
2882}
2883
2884void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2885 int cost_per_typing, int reporting_threshold, int penalty_decay,
2886 int type_event_delay) {
2887 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2888 time_window, cost_per_typing,
2889 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2890 // In case of error, log the info and continue
2891 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2892 cost_per_typing, reporting_threshold, penalty_decay,
2893 type_event_delay);
2894 }
2895}
2896
2897bool WebRtcVoiceMediaChannel::SetOutputScaling(
2898 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002899 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002900 // Collect the channels to scale the output volume.
2901 std::vector<int> channels;
2902 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002903 // Default channel is not in receive_channels_ if it is not being used for
2904 // playout.
2905 if (default_receive_ssrc_ == 0)
2906 channels.push_back(voe_channel());
2907 for (ChannelMap::const_iterator it = receive_channels_.begin();
2908 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002909 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002910 }
2911 } else { // Collect only the channel of the specified ssrc.
2912 int channel = GetReceiveChannelNum(ssrc);
2913 if (-1 == channel) {
2914 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2915 return false;
2916 }
2917 channels.push_back(channel);
2918 }
2919
2920 // Scale the output volume for the collected channels. We first normalize to
2921 // scale the volume and then set the left and right pan.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002922 float scale = static_cast<float>(rtc::_max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002923 if (scale > 0.0001f) {
2924 left /= scale;
2925 right /= scale;
2926 }
2927 for (std::vector<int>::const_iterator it = channels.begin();
2928 it != channels.end(); ++it) {
2929 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2930 *it, scale)) {
2931 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2932 return false;
2933 }
2934 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2935 *it, static_cast<float>(left), static_cast<float>(right))) {
2936 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2937 // Do not return if fails. SetOutputVolumePan is not available for all
2938 // pltforms.
2939 }
2940 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2941 << " right=" << right * scale
2942 << " for channel " << *it << " and ssrc " << ssrc;
2943 }
2944 return true;
2945}
2946
2947bool WebRtcVoiceMediaChannel::GetOutputScaling(
2948 uint32 ssrc, double* left, double* right) {
2949 if (!left || !right) return false;
2950
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002951 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002952 // Determine which channel based on ssrc.
2953 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2954 if (channel == -1) {
2955 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2956 return false;
2957 }
2958
2959 float scaling;
2960 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2961 channel, scaling)) {
2962 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2963 return false;
2964 }
2965
2966 float left_pan;
2967 float right_pan;
2968 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2969 channel, left_pan, right_pan)) {
2970 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2971 // If GetOutputVolumePan fails, we use the default left and right pan.
2972 left_pan = 1.0f;
2973 right_pan = 1.0f;
2974 }
2975
2976 *left = scaling * left_pan;
2977 *right = scaling * right_pan;
2978 return true;
2979}
2980
2981bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2982 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2983 return true;
2984}
2985
2986bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2987 bool play, bool loop) {
2988 if (!ringback_tone_) {
2989 return false;
2990 }
2991
2992 // The voe file api is not available in chrome.
2993 if (!engine()->voe()->file()) {
2994 return false;
2995 }
2996
2997 // Determine which VoiceEngine channel to play on.
2998 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2999 if (channel == -1) {
3000 return false;
3001 }
3002
3003 // Make sure the ringtone is cued properly, and play it out.
3004 if (play) {
3005 ringback_tone_->set_loop(loop);
3006 ringback_tone_->Rewind();
3007 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
3008 ringback_tone_.get()) == -1) {
3009 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
3010 LOG(LS_ERROR) << "Unable to start ringback tone";
3011 return false;
3012 }
3013 ringback_channels_.insert(channel);
3014 LOG(LS_INFO) << "Started ringback on channel " << channel;
3015 } else {
3016 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
3017 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
3018 LOG_RTCERR1(StopPlayingFileLocally, channel);
3019 return false;
3020 }
3021 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
3022 ringback_channels_.erase(channel);
3023 }
3024
3025 return true;
3026}
3027
3028bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3029 return dtmf_allowed_;
3030}
3031
3032bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3033 int duration, int flags) {
3034 if (!dtmf_allowed_) {
3035 return false;
3036 }
3037
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003038 // Send the event.
3039 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003040 int channel = -1;
3041 if (ssrc == 0) {
3042 bool default_channel_is_inuse = false;
3043 for (ChannelMap::const_iterator iter = send_channels_.begin();
3044 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003045 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003046 default_channel_is_inuse = true;
3047 break;
3048 }
3049 }
3050 if (default_channel_is_inuse) {
3051 channel = voe_channel();
3052 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003053 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003054 }
3055 } else {
3056 channel = GetSendChannelNum(ssrc);
3057 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003058 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003059 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3060 << ssrc << " is not in use.";
3061 return false;
3062 }
3063 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003064 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3065 channel, event, true, duration) == -1) {
3066 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003067 return false;
3068 }
3069 }
3070
3071 // Play the event.
3072 if (flags & cricket::DF_PLAY) {
3073 // Play DTMF tone locally.
3074 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3075 LOG_RTCERR2(PlayDtmfTone, event, duration);
3076 return false;
3077 }
3078 }
3079
3080 return true;
3081}
3082
wu@webrtc.orga9890802013-12-13 00:21:03 +00003083void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003084 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003085 // Pick which channel to send this packet to. If this packet doesn't match
3086 // any multiplexed streams, just send it to the default channel. Otherwise,
3087 // send it to the specific decoder instance for that stream.
3088 int which_channel = GetReceiveChannelNum(
3089 ParseSsrc(packet->data(), packet->length(), false));
3090 if (which_channel == -1) {
3091 which_channel = voe_channel();
3092 }
3093
3094 // Stop any ringback that might be playing on the channel.
3095 // It's possible the ringback has already stopped, ih which case we'll just
3096 // use the opportunity to remove the channel from ringback_channels_.
3097 if (engine()->voe()->file()) {
3098 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3099 if (it != ringback_channels_.end()) {
3100 if (engine()->voe()->file()->IsPlayingFileLocally(
3101 which_channel) == 1) {
3102 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3103 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3104 << " due to incoming media";
3105 }
3106 ringback_channels_.erase(which_channel);
3107 }
3108 }
3109
3110 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003111 engine()->voe()->network()->ReceivedRTPPacket(
3112 which_channel,
3113 packet->data(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003114 static_cast<unsigned int>(packet->length()),
3115 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003116}
3117
wu@webrtc.orga9890802013-12-13 00:21:03 +00003118void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003119 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003120 // Sending channels need all RTCP packets with feedback information.
3121 // Even sender reports can contain attached report blocks.
3122 // Receiving channels need sender reports in order to create
3123 // correct receiver reports.
3124 int type = 0;
3125 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3126 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3127 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003128 }
3129
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003130 // If it is a sender report, find the channel that is listening.
3131 bool has_sent_to_default_channel = false;
3132 if (type == kRtcpTypeSR) {
3133 int which_channel = GetReceiveChannelNum(
3134 ParseSsrc(packet->data(), packet->length(), true));
3135 if (which_channel != -1) {
3136 engine()->voe()->network()->ReceivedRTCPPacket(
3137 which_channel,
3138 packet->data(),
3139 static_cast<unsigned int>(packet->length()));
3140
3141 if (IsDefaultChannel(which_channel))
3142 has_sent_to_default_channel = true;
3143 }
3144 }
3145
3146 // SR may continue RR and any RR entry may correspond to any one of the send
3147 // channels. So all RTCP packets must be forwarded all send channels. VoE
3148 // will filter out RR internally.
3149 for (ChannelMap::iterator iter = send_channels_.begin();
3150 iter != send_channels_.end(); ++iter) {
3151 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003152 if (IsDefaultChannel(iter->second->channel()) &&
3153 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003154 continue;
3155
3156 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003157 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003158 packet->data(),
3159 static_cast<unsigned int>(packet->length()));
3160 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003161}
3162
3163bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003164 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3165 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003166 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3167 return false;
3168 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003169 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3170 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003171 return false;
3172 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003173 // We set the AGC to mute state only when all the channels are muted.
3174 // This implementation is not ideal, instead we should signal the AGC when
3175 // the mic channel is muted/unmuted. We can't do it today because there
3176 // is no good way to know which stream is mapping to the mic channel.
3177 bool all_muted = muted;
3178 for (ChannelMap::const_iterator iter = send_channels_.begin();
3179 iter != send_channels_.end() && all_muted; ++iter) {
3180 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3181 all_muted)) {
3182 LOG_RTCERR1(GetInputMute, iter->second->channel());
3183 return false;
3184 }
3185 }
3186
3187 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3188 if (ap)
3189 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003190 return true;
3191}
3192
minyue@webrtc.org26236952014-10-29 02:27:08 +00003193// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3194// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003195bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003196 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003197
minyue@webrtc.org26236952014-10-29 02:27:08 +00003198 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003199}
3200
minyue@webrtc.org26236952014-10-29 02:27:08 +00003201bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3202 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003203
minyue@webrtc.org26236952014-10-29 02:27:08 +00003204 send_bitrate_setting_ = true;
3205 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003206
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003207 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003208 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003209 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003210 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003211 }
3212
minyue@webrtc.org26236952014-10-29 02:27:08 +00003213 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003214 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3215 // SetMaxSendBandwith(0), the second call removes the previous limit.
3216 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003217 return true;
3218
3219 webrtc::CodecInst codec = *send_codec_;
3220 bool is_multi_rate = IsCodecMultiRate(codec);
3221
3222 if (is_multi_rate) {
3223 // If codec is multi-rate then just set the bitrate.
3224 codec.rate = bps;
3225 if (!SetSendCodec(codec)) {
3226 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3227 << " to bitrate " << bps << " bps.";
3228 return false;
3229 }
3230 return true;
3231 } else {
3232 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3233 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3234 // fixed bitrate then ignore.
3235 if (bps < codec.rate) {
3236 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3237 << " to bitrate " << bps << " bps"
3238 << ", requires at least " << codec.rate << " bps.";
3239 return false;
3240 }
3241 return true;
3242 }
3243}
3244
3245bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003246 bool echo_metrics_on = false;
3247 // These can take on valid negative values, so use the lowest possible level
3248 // as default rather than -1.
3249 int echo_return_loss = -100;
3250 int echo_return_loss_enhancement = -100;
3251 // These can also be negative, but in practice -1 is only used to signal
3252 // insufficient data, since the resolution is limited to multiples of 4 ms.
3253 int echo_delay_median_ms = -1;
3254 int echo_delay_std_ms = -1;
3255 if (engine()->voe()->processing()->GetEcMetricsStatus(
3256 echo_metrics_on) != -1 && echo_metrics_on) {
3257 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3258 // here, but it appears to be unsuitable currently. Revisit after this is
3259 // investigated: http://b/issue?id=5666755
3260 int erl, erle, rerl, anlp;
3261 if (engine()->voe()->processing()->GetEchoMetrics(
3262 erl, erle, rerl, anlp) != -1) {
3263 echo_return_loss = erl;
3264 echo_return_loss_enhancement = erle;
3265 }
3266
3267 int median, std;
3268 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3269 echo_delay_median_ms = median;
3270 echo_delay_std_ms = std;
3271 }
3272 }
3273
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003274 webrtc::CallStatistics cs;
3275 unsigned int ssrc;
3276 webrtc::CodecInst codec;
3277 unsigned int level;
3278
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003279 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3280 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003281 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003282
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003283 // Fill in the sender info, based on what we know, and what the
3284 // remote side told us it got from its RTCP report.
3285 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003286
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003287 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3288 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3289 continue;
3290 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003291
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003292 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003293 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3294 sinfo.bytes_sent = cs.bytesSent;
3295 sinfo.packets_sent = cs.packetsSent;
3296 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3297 // returns 0 to indicate an error value.
3298 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3299
3300 // Get data from the last remote RTCP report. Use default values if no data
3301 // available.
3302 sinfo.fraction_lost = -1.0;
3303 sinfo.jitter_ms = -1;
3304 sinfo.packets_lost = -1;
3305 sinfo.ext_seqnum = -1;
3306 std::vector<webrtc::ReportBlock> receive_blocks;
3307 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3308 channel, &receive_blocks) != -1 &&
3309 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3310 std::vector<webrtc::ReportBlock>::iterator iter;
3311 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3312 ++iter) {
3313 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003314 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003315 // Convert Q8 to floating point.
3316 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3317 // Convert samples to milliseconds.
3318 if (codec.plfreq / 1000 > 0) {
3319 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3320 }
3321 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3322 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3323 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003324 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003325 }
3326 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003327
3328 // Local speech level.
3329 sinfo.audio_level = (engine()->voe()->volume()->
3330 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3331
3332 // TODO(xians): We are injecting the same APM logging to all the send
3333 // channels here because there is no good way to know which send channel
3334 // is using the APM. The correct fix is to allow the send channels to have
3335 // their own APM so that we can feed the correct APM logging to different
3336 // send channels. See issue crbug/264611 .
3337 sinfo.echo_return_loss = echo_return_loss;
3338 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3339 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3340 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003341 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3342 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003343 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003344
3345 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003346 }
3347
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003348 // Build the list of receivers, one for each receiving channel, or 1 in
3349 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003350 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003351 for (ChannelMap::const_iterator it = receive_channels_.begin();
3352 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003353 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003354 }
3355 if (channels.empty()) {
3356 channels.push_back(voe_channel());
3357 }
3358
3359 // Get the SSRC and stats for each receiver, based on our own calculations.
3360 for (std::vector<int>::const_iterator it = channels.begin();
3361 it != channels.end(); ++it) {
3362 memset(&cs, 0, sizeof(cs));
3363 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3364 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3365 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3366 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003367 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003368 rinfo.bytes_rcvd = cs.bytesReceived;
3369 rinfo.packets_rcvd = cs.packetsReceived;
3370 // The next four fields are from the most recently sent RTCP report.
3371 // Convert Q8 to floating point.
3372 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3373 rinfo.packets_lost = cs.cumulativeLost;
3374 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003375#ifdef USE_WEBRTC_DEV_BRANCH
3376 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
3377#endif
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003378 if (codec.pltype != -1) {
3379 rinfo.codec_name = codec.plname;
3380 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003381 // Convert samples to milliseconds.
3382 if (codec.plfreq / 1000 > 0) {
3383 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3384 }
3385
3386 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3387 webrtc::NetworkStatistics ns;
3388 if (engine()->voe()->neteq() &&
3389 engine()->voe()->neteq()->GetNetworkStatistics(
3390 *it, ns) != -1) {
3391 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3392 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3393 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003394 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003395 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003396
3397 webrtc::AudioDecodingCallStats ds;
3398 if (engine()->voe()->neteq() &&
3399 engine()->voe()->neteq()->GetDecodingCallStatistics(
3400 *it, &ds) != -1) {
3401 rinfo.decoding_calls_to_silence_generator =
3402 ds.calls_to_silence_generator;
3403 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3404 rinfo.decoding_normal = ds.decoded_normal;
3405 rinfo.decoding_plc = ds.decoded_plc;
3406 rinfo.decoding_cng = ds.decoded_cng;
3407 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3408 }
3409
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003410 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003411 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003412 int playout_buffer_delay_ms = 0;
3413 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003414 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3415 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3416 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003417 }
3418
3419 // Get speech level.
3420 rinfo.audio_level = (engine()->voe()->volume()->
3421 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3422 info->receivers.push_back(rinfo);
3423 }
3424 }
3425
3426 return true;
3427}
3428
3429void WebRtcVoiceMediaChannel::GetLastMediaError(
3430 uint32* ssrc, VoiceMediaChannel::Error* error) {
3431 ASSERT(ssrc != NULL);
3432 ASSERT(error != NULL);
3433 FindSsrc(voe_channel(), ssrc);
3434 *error = WebRtcErrorToChannelError(GetLastEngineError());
3435}
3436
3437bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003438 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003439 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003440 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003441 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3442 // This means the error is not limited to a specific channel. Signal the
3443 // message using ssrc=0. If the current channel is sending, use this
3444 // channel for sending the message.
3445 *ssrc = 0;
3446 return true;
3447 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003448 // Check whether this is a sending channel.
3449 for (ChannelMap::const_iterator it = send_channels_.begin();
3450 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003451 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003452 // This is a sending channel.
3453 uint32 local_ssrc = 0;
3454 if (engine()->voe()->rtp()->GetLocalSSRC(
3455 channel_num, local_ssrc) != -1) {
3456 *ssrc = local_ssrc;
3457 }
3458 return true;
3459 }
3460 }
3461
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003462 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003463 for (ChannelMap::const_iterator it = receive_channels_.begin();
3464 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003465 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003466 *ssrc = it->first;
3467 return true;
3468 }
3469 }
3470 }
3471 return false;
3472}
3473
3474void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003475 if (error == VE_TYPING_NOISE_WARNING) {
3476 typing_noise_detected_ = true;
3477 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3478 typing_noise_detected_ = false;
3479 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003480 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3481}
3482
3483int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3484 unsigned int ulevel;
3485 int ret =
3486 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3487 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3488}
3489
3490int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003491 ChannelMap::iterator it = receive_channels_.find(ssrc);
3492 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003493 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003494 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3495}
3496
3497int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003498 ChannelMap::iterator it = send_channels_.find(ssrc);
3499 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003500 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003501
3502 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003503}
3504
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003505bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
3506 webrtc::VideoEngine* vie, int vie_channel) {
3507 shared_bwe_vie_ = vie;
3508 shared_bwe_vie_channel_ = vie_channel;
3509
3510 if (!SetupSharedBweOnChannel(voe_channel())) {
3511 return false;
3512 }
3513 for (ChannelMap::iterator it = receive_channels_.begin();
3514 it != receive_channels_.end(); ++it) {
3515 if (!SetupSharedBweOnChannel(it->second->channel())) {
3516 return false;
3517 }
3518 }
3519 return true;
3520}
3521
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003522bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3523 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3524 // Get the RED encodings from the parameter with no name. This may
3525 // change based on what is discussed on the Jingle list.
3526 // The encoding parameter is of the form "a/b"; we only support where
3527 // a == b. Verify this and parse out the value into red_pt.
3528 // If the parameter value is absent (as it will be until we wire up the
3529 // signaling of this message), use the second codec specified (i.e. the
3530 // one after "red") as the encoding parameter.
3531 int red_pt = -1;
3532 std::string red_params;
3533 CodecParameterMap::const_iterator it = red_codec.params.find("");
3534 if (it != red_codec.params.end()) {
3535 red_params = it->second;
3536 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003537 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003538 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003539 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003540 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3541 return false;
3542 }
3543 } else if (red_codec.params.empty()) {
3544 LOG(LS_WARNING) << "RED params not present, using defaults";
3545 if (all_codecs.size() > 1) {
3546 red_pt = all_codecs[1].id;
3547 }
3548 }
3549
3550 // Try to find red_pt in |codecs|.
3551 std::vector<AudioCodec>::const_iterator codec;
3552 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3553 if (codec->id == red_pt)
3554 break;
3555 }
3556
3557 // If we find the right codec, that will be the codec we pass to
3558 // SetSendCodec, with the desired payload type.
3559 if (codec != all_codecs.end() &&
3560 engine()->FindWebRtcCodec(*codec, send_codec)) {
3561 } else {
3562 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3563 return false;
3564 }
3565
3566 return true;
3567}
3568
3569bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3570 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003571 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003572 return false;
3573 }
3574 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3575 // what we want to do with them.
3576 // engine()->voe().EnableVQMon(voe_channel(), true);
3577 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3578 return true;
3579}
3580
3581bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3582 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3583 for (int i = 0; i < ncodecs; ++i) {
3584 webrtc::CodecInst voe_codec;
3585 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3586 voe_codec.pltype = -1;
3587 if (engine()->voe()->codec()->SetRecPayloadType(
3588 channel, voe_codec) == -1) {
3589 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3590 return false;
3591 }
3592 }
3593 }
3594 return true;
3595}
3596
3597bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3598 if (playout) {
3599 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3600 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3601 LOG_RTCERR1(StartPlayout, channel);
3602 return false;
3603 }
3604 } else {
3605 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3606 engine()->voe()->base()->StopPlayout(channel);
3607 }
3608 return true;
3609}
3610
3611uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3612 bool rtcp) {
3613 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3614 uint32 ssrc = 0;
3615 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003616 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003617 }
3618 return ssrc;
3619}
3620
3621// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3622VoiceMediaChannel::Error
3623 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3624 switch (err_code) {
3625 case 0:
3626 return ERROR_NONE;
3627 case VE_CANNOT_START_RECORDING:
3628 case VE_MIC_VOL_ERROR:
3629 case VE_GET_MIC_VOL_ERROR:
3630 case VE_CANNOT_ACCESS_MIC_VOL:
3631 return ERROR_REC_DEVICE_OPEN_FAILED;
3632 case VE_SATURATION_WARNING:
3633 return ERROR_REC_DEVICE_SATURATION;
3634 case VE_REC_DEVICE_REMOVED:
3635 return ERROR_REC_DEVICE_REMOVED;
3636 case VE_RUNTIME_REC_WARNING:
3637 case VE_RUNTIME_REC_ERROR:
3638 return ERROR_REC_RUNTIME_ERROR;
3639 case VE_CANNOT_START_PLAYOUT:
3640 case VE_SPEAKER_VOL_ERROR:
3641 case VE_GET_SPEAKER_VOL_ERROR:
3642 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3643 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3644 case VE_RUNTIME_PLAY_WARNING:
3645 case VE_RUNTIME_PLAY_ERROR:
3646 return ERROR_PLAY_RUNTIME_ERROR;
3647 case VE_TYPING_NOISE_WARNING:
3648 return ERROR_REC_TYPING_NOISE_DETECTED;
3649 default:
3650 return VoiceMediaChannel::ERROR_OTHER;
3651 }
3652}
3653
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003654bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3655 int channel_id, const RtpHeaderExtension* extension) {
3656 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003657 int id = 0;
3658 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003659 if (extension) {
3660 enable = true;
3661 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003662 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003663 }
3664 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003665 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003666 return false;
3667 }
3668 return true;
3669}
3670
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003671bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
3672 webrtc::ViENetwork* vie_network = NULL;
3673 int vie_channel = -1;
3674 if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
3675 shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
3676 vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
3677 vie_channel = shared_bwe_vie_channel_;
3678 }
3679 if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
3680 vie_channel) == -1) {
3681 LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
3682 if (vie_network != NULL) {
3683 // Don't fail if we're tearing down.
3684 return false;
3685 }
3686 }
3687 return true;
3688}
3689
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003690int WebRtcSoundclipStream::Read(void *buf, int len) {
3691 size_t res = 0;
3692 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003693 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003694}
3695
3696int WebRtcSoundclipStream::Rewind() {
3697 mem_.Rewind();
3698 // Return -1 to keep VoiceEngine from looping.
3699 return (loop_) ? 0 : -1;
3700}
3701
3702} // namespace cricket
3703
3704#endif // HAVE_WEBRTC_VOICE