blob: ff5f6d5c07b67329ed703dcf2cf0494f9dbdbc09 [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
Thiago Farinaef883092015-04-06 10:36:41 +000041#include "talk/media/base/audioframe.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000042#include "talk/media/base/audiorenderer.h"
43#include "talk/media/base/constants.h"
44#include "talk/media/base/streamparams.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000045#include "talk/media/webrtc/webrtcvoe.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000046#include "webrtc/base/base64.h"
47#include "webrtc/base/byteorder.h"
48#include "webrtc/base/common.h"
49#include "webrtc/base/helpers.h"
50#include "webrtc/base/logging.h"
51#include "webrtc/base/stringencode.h"
52#include "webrtc/base/stringutils.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000053#include "webrtc/common.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054#include "webrtc/modules/audio_processing/include/audio_processing.h"
55
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056namespace cricket {
57
Brave Yao5225dd82015-03-26 07:39:19 +080058static const int kMaxNumPacketSize = 6;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000059struct CodecPref {
60 const char* name;
61 int clockrate;
62 int channels;
63 int payload_type;
64 bool is_multi_rate;
Brave Yao5225dd82015-03-26 07:39:19 +080065 int packet_sizes_ms[kMaxNumPacketSize];
henrike@webrtc.org28e20752013-07-10 00:45:36 +000066};
Brave Yao5225dd82015-03-26 07:39:19 +080067// Note: keep the supported packet sizes in ascending order.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000068static const CodecPref kCodecPrefs[] = {
Brave Yao5225dd82015-03-26 07:39:19 +080069 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
70 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
71 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +000072 // G722 should be advertised as 8000 Hz because of the RFC "bug".
Brave Yao5225dd82015-03-26 07:39:19 +080073 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
74 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
75 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
76 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
Brave Yao5225dd82015-03-26 07:39:19 +080077 { kCnCodecName, 32000, 1, 106, false, { } },
78 { kCnCodecName, 16000, 1, 105, false, { } },
79 { kCnCodecName, 8000, 1, 13, false, { } },
80 { kRedCodecName, 8000, 1, 127, false, { } },
81 { kDtmfCodecName, 8000, 1, 126, false, { } },
henrike@webrtc.org28e20752013-07-10 00:45:36 +000082};
83
84// For Linux/Mac, using the default device is done by specifying index 0 for
85// VoE 4.0 and not -1 (which was the case for VoE 3.5).
86//
87// On Windows Vista and newer, Microsoft introduced the concept of "Default
88// Communications Device". This means that there are two types of default
89// devices (old Wave Audio style default and Default Communications Device).
90//
91// On Windows systems which only support Wave Audio style default, uses either
92// -1 or 0 to select the default device.
93//
94// On Windows systems which support both "Default Communication Device" and
95// old Wave Audio style default, use -1 for Default Communications Device and
96// -2 for Wave Audio style default, which is what we want to use for clips.
97// It's not clear yet whether the -2 index is handled properly on other OSes.
98
99#ifdef WIN32
100static const int kDefaultAudioDeviceId = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000101#else
102static const int kDefaultAudioDeviceId = 0;
103#endif
104
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105// Parameter used for NACK.
106// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
107static const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000108
109// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000110// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000111
112// Recommended bitrates:
113// 8-12 kb/s for NB speech,
114// 16-20 kb/s for WB speech,
115// 28-40 kb/s for FB speech,
116// 48-64 kb/s for FB mono music, and
117// 64-128 kb/s for FB stereo music.
118// The current implementation applies the following values to mono signals,
119// and multiplies them by 2 for stereo.
120static 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}
Minyue Li7100dcd2015-03-27 05:05:59 +0100157
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000158static std::string ToString(const webrtc::CodecInst& codec) {
159 std::stringstream ss;
160 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
161 << " (" << codec.pltype << ")";
162 return ss.str();
163}
164
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000165static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000166 const char* delim = "\r\n";
167 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
168 LOG_V(sev) << tok;
169 }
170}
171
172// Severity is an integer because it comes is assumed to be from command line.
173static int SeverityToFilter(int severity) {
174 int filter = webrtc::kTraceNone;
175 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000176 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000177 filter |= webrtc::kTraceAll;
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200178 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000179 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000180 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200181 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000182 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000183 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200184 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000185 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000186 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
187 }
188 return filter;
189}
190
Minyue Li7100dcd2015-03-27 05:05:59 +0100191static bool IsCodec(const AudioCodec& codec, const char* ref_name) {
192 return (_stricmp(codec.name.c_str(), ref_name) == 0);
193}
194
195static bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
196 return (_stricmp(codec.plname, ref_name) == 0);
197}
198
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000199static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
200 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100201 if (IsCodec(codec, kCodecPrefs[i].name) &&
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000202 kCodecPrefs[i].clockrate == codec.plfreq) {
203 return kCodecPrefs[i].is_multi_rate;
204 }
205 }
206 return false;
207}
208
209static bool FindCodec(const std::vector<AudioCodec>& codecs,
210 const AudioCodec& codec,
211 AudioCodec* found_codec) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200212 for (const AudioCodec& c : codecs) {
213 if (c.Matches(codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000214 if (found_codec != NULL) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200215 *found_codec = c;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000216 }
217 return true;
218 }
219 }
220 return false;
221}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000222
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000223static bool IsNackEnabled(const AudioCodec& codec) {
224 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
225 kParamValueEmpty));
226}
227
Brave Yao5225dd82015-03-26 07:39:19 +0800228static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
229 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
230 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
231 if (packet_size_ms && packet_size_ms <= ptime_ms) {
232 selected_packet_size_ms = packet_size_ms;
233 }
234 }
235 return selected_packet_size_ms;
236}
237
238// If the AudioCodec param kCodecParamPTime is set, then we will set it to codec
239// pacsize if it's valid, or we will pick the next smallest value we support.
240// TODO(Brave): Query supported packet sizes from ACM when the API is ready.
241static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
242 for (const CodecPref& codec_pref : kCodecPrefs) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100243 if ((IsCodec(*codec, codec_pref.name) &&
Brave Yao5225dd82015-03-26 07:39:19 +0800244 codec_pref.clockrate == codec->plfreq) ||
Minyue Li7100dcd2015-03-27 05:05:59 +0100245 IsCodec(*codec, kG722CodecName)) {
Brave Yao5225dd82015-03-26 07:39:19 +0800246 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
247 if (packet_size_ms) {
248 // Convert unit from milli-seconds to samples.
249 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
250 return true;
251 }
252 }
253 }
254 return false;
255}
256
Minyue Li7100dcd2015-03-27 05:05:59 +0100257// Return true if codec.params[feature] == "1", false otherwise.
258static bool IsCodecFeatureEnabled(const AudioCodec& codec,
259 const char* feature) {
260 int value;
261 return codec.GetParam(feature, &value) && value == 1;
262}
263
264// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
265// otherwise. If the value (either from params or codec.bitrate) <=0, use the
266// default configuration. If the value is beyond feasible bit rate of Opus,
267// clamp it. Returns the Opus bit rate for operation.
268static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
269 int bitrate = 0;
270 bool use_param = true;
271 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
272 bitrate = codec.bitrate;
273 use_param = false;
274 }
275 if (bitrate <= 0) {
276 if (max_playback_rate <= 8000) {
277 bitrate = kOpusBitrateNb;
278 } else if (max_playback_rate <= 16000) {
279 bitrate = kOpusBitrateWb;
280 } else {
281 bitrate = kOpusBitrateFb;
282 }
283
284 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
285 bitrate *= 2;
286 }
287 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
288 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
289 std::string rate_source =
290 use_param ? "Codec parameter \"maxaveragebitrate\"" :
291 "Supplied Opus bitrate";
292 LOG(LS_WARNING) << rate_source
293 << " is invalid and is replaced by: "
294 << bitrate;
295 }
296 return bitrate;
297}
298
299// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
300// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
301static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
302 int value;
303 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
304 return value;
305 }
306 return kOpusDefaultMaxPlaybackRate;
307}
308
309static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
310 bool* enable_codec_fec, int* max_playback_rate,
311 bool* enable_codec_dtx) {
312 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
313 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
314 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
315
316 // If OPUS, change what we send according to the "stereo" codec
317 // parameter, and not the "channels" parameter. We set
318 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
319 // the bitrate is not specified, i.e. is <= zero, we set it to the
320 // appropriate default value for mono or stereo Opus.
321
322 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
323 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
324}
325
326// Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
327// which says that G722 should be advertised as 8 kHz although it is a 16 kHz
328// codec.
329static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
330 if (IsCodec(*voe_codec, kG722CodecName)) {
331 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
332 // has changed, and this special case is no longer needed.
henrikg91d6ede2015-09-17 00:24:34 -0700333 RTC_DCHECK(voe_codec->plfreq != new_plfreq);
Minyue Li7100dcd2015-03-27 05:05:59 +0100334 voe_codec->plfreq = new_plfreq;
335 }
336}
337
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000338// Gets the default set of options applied to the engine. Historically, these
339// were supplied as a combination of flags from the channel manager (ec, agc,
340// ns, and highpass) and the rest hardcoded in InitInternal.
341static AudioOptions GetDefaultEngineOptions() {
342 AudioOptions options;
343 options.echo_cancellation.Set(true);
344 options.auto_gain_control.Set(true);
345 options.noise_suppression.Set(true);
346 options.highpass_filter.Set(true);
347 options.stereo_swapping.Set(false);
Henrik Lundin64dad832015-05-11 12:44:23 +0200348 options.audio_jitter_buffer_max_packets.Set(50);
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200349 options.audio_jitter_buffer_fast_accelerate.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000350 options.typing_detection.Set(true);
351 options.conference_mode.Set(false);
352 options.adjust_agc_delta.Set(0);
353 options.experimental_agc.Set(false);
Henrik Lundin441f6342015-06-09 16:03:13 +0200354 options.extended_filter_aec.Set(false);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100355 options.delay_agnostic_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000356 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000357 options.aec_dump.Set(false);
358 return options;
359}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000360
Minyue Li7100dcd2015-03-27 05:05:59 +0100361static std::string GetEnableString(bool enable) {
362 return enable ? "enable" : "disable";
Brave Yao5225dd82015-03-26 07:39:19 +0800363}
364
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000365WebRtcVoiceEngine::WebRtcVoiceEngine()
366 : voe_wrapper_(new VoEWrapper()),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000367 tracing_(new VoETraceWrapper()),
368 adm_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000369 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
Fredrik Solenberg7d173362015-09-23 12:23:21 +0200370 is_dumping_aec_(false) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000371 Construct();
372}
373
374WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000375 VoETraceWrapper* tracing)
376 : voe_wrapper_(voe_wrapper),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000377 tracing_(tracing),
378 adm_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000379 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
Fredrik Solenberg7d173362015-09-23 12:23:21 +0200380 is_dumping_aec_(false) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000381 Construct();
382}
383
384void WebRtcVoiceEngine::Construct() {
385 SetTraceFilter(log_filter_);
386 initialized_ = false;
387 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
388 SetTraceOptions("");
389 if (tracing_->SetTraceCallback(this) == -1) {
390 LOG_RTCERR0(SetTraceCallback);
391 }
392 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
393 LOG_RTCERR0(RegisterVoiceEngineObserver);
394 }
395 // Clear the default agc state.
396 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
397
398 // Load our audio codec list.
399 ConstructCodecs();
400
401 // Load our RTP Header extensions.
402 rtp_header_extensions_.push_back(
403 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
404 kRtpAudioLevelHeaderExtensionDefaultId));
405 rtp_header_extensions_.push_back(
406 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
407 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
408 options_ = GetDefaultEngineOptions();
409}
410
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000411void WebRtcVoiceEngine::ConstructCodecs() {
412 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
413 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
414 for (int i = 0; i < ncodecs; ++i) {
415 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000416 if (GetVoeCodec(i, &voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000417 // Skip uncompressed formats.
Minyue Li7100dcd2015-03-27 05:05:59 +0100418 if (IsCodec(voe_codec, kL16CodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000419 continue;
420 }
421
422 const CodecPref* pref = NULL;
423 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100424 if (IsCodec(voe_codec, kCodecPrefs[j].name) &&
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000425 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
426 kCodecPrefs[j].channels == voe_codec.channels) {
427 pref = &kCodecPrefs[j];
428 break;
429 }
430 }
431
432 if (pref) {
433 // Use the payload type that we've configured in our pref table;
434 // use the offset in our pref table to determine the sort order.
435 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
436 voe_codec.rate, voe_codec.channels,
437 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
438 LOG(LS_INFO) << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100439 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000440 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000441 codec.bitrate = 0;
442 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100443 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000444 // Only add fmtp parameters that differ from the spec.
445 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
446 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000447 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000448 }
449 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
450 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000451 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000452 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000453 codec.SetParam(kCodecParamUseInbandFec, 1);
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000454
455 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000456 // when they can be set to values other than the default.
457 }
458 codecs_.push_back(codec);
459 } else {
460 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
461 }
462 }
463 }
464 // Make sure they are in local preference order.
465 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
466}
467
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000468bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst* codec) {
469 if (voe_wrapper_->codec()->GetCodec(index, *codec) == -1) {
470 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000471 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000472 // Change the sample rate of G722 to 8000 to match SDP.
473 MaybeFixupG722(codec, 8000);
474 return true;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000475}
476
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000477WebRtcVoiceEngine::~WebRtcVoiceEngine() {
478 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
479 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
480 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
481 }
482 if (adm_) {
483 voe_wrapper_.reset();
484 adm_->Release();
485 adm_ = NULL;
486 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000487
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000488 tracing_->SetTraceCallback(NULL);
489}
490
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000491bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
henrikg91d6ede2015-09-17 00:24:34 -0700492 RTC_DCHECK(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000493 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
494 bool res = InitInternal();
495 if (res) {
496 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
497 } else {
498 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
499 Terminate();
500 }
501 return res;
502}
503
504bool WebRtcVoiceEngine::InitInternal() {
505 // Temporarily turn logging level up for the Init call
506 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000507 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000508 SetTraceFilter(extended_filter);
509 SetTraceOptions("");
510
511 // Init WebRtc VoiceEngine.
512 if (voe_wrapper_->base()->Init(adm_) == -1) {
513 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
514 SetTraceFilter(old_filter);
515 return false;
516 }
517
518 SetTraceFilter(old_filter);
519 SetTraceOptions(log_options_);
520
521 // Log the VoiceEngine version info
522 char buffer[1024] = "";
523 voe_wrapper_->base()->GetVersion(buffer);
524 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000525 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000526
527 // Save the default AGC configuration settings. This must happen before
528 // calling SetOptions or the default will be overwritten.
529 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
530 LOG_RTCERR0(GetAgcConfig);
531 return false;
532 }
533
534 // Set defaults for options, so that ApplyOptions applies them explicitly
535 // when we clear option (channel) overrides. External clients can still
536 // modify the defaults via SetOptions (on the media engine).
537 if (!SetOptions(GetDefaultEngineOptions())) {
538 return false;
539 }
540
541 // Print our codec list again for the call diagnostic log
542 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200543 for (const AudioCodec& codec : codecs_) {
544 LOG(LS_INFO) << ToString(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000545 }
546
547 // Disable the DTMF playout when a tone is sent.
548 // PlayDtmfTone will be used if local playout is needed.
549 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
550 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
551 }
552
553 initialized_ = true;
554 return true;
555}
556
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000557void WebRtcVoiceEngine::Terminate() {
558 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
559 initialized_ = false;
560
561 StopAecDump();
562
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000563 voe_wrapper_->base()->Terminate();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000564}
565
566int WebRtcVoiceEngine::GetCapabilities() {
567 return AUDIO_SEND | AUDIO_RECV;
568}
569
Fredrik Solenberg709ed672015-09-15 12:26:33 +0200570VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel(webrtc::Call* call,
Jelena Marusicc28a8962015-05-29 15:05:44 +0200571 const AudioOptions& options) {
Fredrik Solenbergb071a192015-09-17 16:42:56 +0200572 WebRtcVoiceMediaChannel* ch =
573 new WebRtcVoiceMediaChannel(this, options, call);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000574 if (!ch->valid()) {
575 delete ch;
Jelena Marusicc28a8962015-05-29 15:05:44 +0200576 return nullptr;
577 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000578 return ch;
579}
580
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000581bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
582 if (!ApplyOptions(options)) {
583 return false;
584 }
585 options_ = options;
586 return true;
587}
588
589bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
590 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
591 if (!ApplyOptions(overrides)) {
592 return false;
593 }
594 option_overrides_ = overrides;
595 return true;
596}
597
598bool WebRtcVoiceEngine::ClearOptionOverrides() {
599 LOG(LS_INFO) << "Clearing option overrides.";
600 AudioOptions options = options_;
601 // Only call ApplyOptions if |options_overrides_| contains overrided options.
602 // ApplyOptions affects NS, AGC other options that is shared between
603 // all WebRtcVoiceEngineChannels.
604 if (option_overrides_ == AudioOptions()) {
605 return true;
606 }
607
608 if (!ApplyOptions(options)) {
609 return false;
610 }
611 option_overrides_ = AudioOptions();
612 return true;
613}
614
615// AudioOptions defaults are set in InitInternal (for options with corresponding
616// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
617bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
618 AudioOptions options = options_in; // The options are modified below.
619 // kEcConference is AEC with high suppression.
620 webrtc::EcModes ec_mode = webrtc::kEcConference;
621 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
622 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
623 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
624 bool aecm_comfort_noise = false;
625 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
626 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
627 << aecm_comfort_noise << " (default is false).";
628 }
629
630#if defined(IOS)
631 // On iOS, VPIO provides built-in EC and AGC.
632 options.echo_cancellation.Set(false);
633 options.auto_gain_control.Set(false);
henrika86d907c2015-09-07 16:09:50 +0200634 LOG(LS_INFO) << "Always disable AEC and AGC on iOS. Use built-in instead.";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000635#elif defined(ANDROID)
636 ec_mode = webrtc::kEcAecm;
637#endif
638
639#if defined(IOS) || defined(ANDROID)
640 // Set the AGC mode for iOS as well despite disabling it above, to avoid
641 // unsupported configuration errors from webrtc.
642 agc_mode = webrtc::kAgcFixedDigital;
643 options.typing_detection.Set(false);
644 options.experimental_agc.Set(false);
Henrik Lundin441f6342015-06-09 16:03:13 +0200645 options.extended_filter_aec.Set(false);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000646 options.experimental_ns.Set(false);
647#endif
648
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100649 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
650 // where the feature is not supported.
651 bool use_delay_agnostic_aec = false;
652#if !defined(IOS)
653 if (options.delay_agnostic_aec.Get(&use_delay_agnostic_aec)) {
654 if (use_delay_agnostic_aec) {
655 options.echo_cancellation.Set(true);
Henrik Lundin441f6342015-06-09 16:03:13 +0200656 options.extended_filter_aec.Set(true);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100657 ec_mode = webrtc::kEcConference;
658 }
659 }
660#endif
661
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000662 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
663
664 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
665
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000666 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000667 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000668 // Check if platform supports built-in EC. Currently only supported on
669 // Android and in combination with Java based audio layer.
670 // TODO(henrika): investigate possibility to support built-in EC also
671 // in combination with Open SL ES audio.
672 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
Bjorn Volcker73f72102015-06-03 14:50:15 +0200673 if (built_in_aec) {
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200674 // Built-in EC exists on this device and use_delay_agnostic_aec is not
675 // overriding it. Enable/Disable it according to the echo_cancellation
676 // audio option.
Bjorn Volcker73f72102015-06-03 14:50:15 +0200677 const bool enable_built_in_aec =
678 echo_cancellation && !use_delay_agnostic_aec;
679 if (voe_wrapper_->hw()->EnableBuiltInAEC(enable_built_in_aec) == 0 &&
680 enable_built_in_aec) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100681 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000682 // i.e., replace the software EC with the built-in EC.
683 options.echo_cancellation.Set(false);
bjornv@webrtc.org3f118232015-03-16 14:22:03 +0000684 echo_cancellation = false;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000685 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
686 }
687 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000688 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
689 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
690 return false;
691 } else {
henrika86d907c2015-09-07 16:09:50 +0200692 LOG(LS_INFO) << "Echo control set to " << echo_cancellation
693 << " with mode " << ec_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000694 }
695#if !defined(ANDROID)
696 // TODO(ajm): Remove the error return on Android from webrtc.
697 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
698 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
699 return false;
700 }
701#endif
702 if (ec_mode == webrtc::kEcAecm) {
703 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
704 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
705 return false;
706 }
707 }
708 }
709
710 bool auto_gain_control;
711 if (options.auto_gain_control.Get(&auto_gain_control)) {
712 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
713 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
714 return false;
715 } else {
henrika86d907c2015-09-07 16:09:50 +0200716 LOG(LS_INFO) << "Auto gain set to " << auto_gain_control << " with mode "
717 << agc_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000718 }
719 }
720
721 if (options.tx_agc_target_dbov.IsSet() ||
722 options.tx_agc_digital_compression_gain.IsSet() ||
723 options.tx_agc_limiter.IsSet()) {
724 // Override default_agc_config_. Generally, an unset option means "leave
725 // the VoE bits alone" in this function, so we want whatever is set to be
726 // stored as the new "default". If we didn't, then setting e.g.
727 // tx_agc_target_dbov would reset digital compression gain and limiter
728 // settings.
729 // Also, if we don't update default_agc_config_, then adjust_agc_delta
730 // would be an offset from the original values, and not whatever was set
731 // explicitly.
732 default_agc_config_.targetLeveldBOv =
733 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
734 default_agc_config_.targetLeveldBOv);
735 default_agc_config_.digitalCompressionGaindB =
736 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
737 default_agc_config_.digitalCompressionGaindB);
738 default_agc_config_.limiterEnable =
739 options.tx_agc_limiter.GetWithDefaultIfUnset(
740 default_agc_config_.limiterEnable);
741 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
742 LOG_RTCERR3(SetAgcConfig,
743 default_agc_config_.targetLeveldBOv,
744 default_agc_config_.digitalCompressionGaindB,
745 default_agc_config_.limiterEnable);
746 return false;
747 }
748 }
749
750 bool noise_suppression;
751 if (options.noise_suppression.Get(&noise_suppression)) {
752 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
753 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
754 return false;
755 } else {
756 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
757 << " with mode " << ns_mode;
758 }
759 }
760
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000761 bool highpass_filter;
762 if (options.highpass_filter.Get(&highpass_filter)) {
763 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
764 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
765 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
766 return false;
767 }
768 }
769
770 bool stereo_swapping;
771 if (options.stereo_swapping.Get(&stereo_swapping)) {
772 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
773 voep->EnableStereoChannelSwapping(stereo_swapping);
774 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
775 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
776 return false;
777 }
778 }
779
Henrik Lundin64dad832015-05-11 12:44:23 +0200780 int audio_jitter_buffer_max_packets;
781 if (options.audio_jitter_buffer_max_packets.Get(
782 &audio_jitter_buffer_max_packets)) {
783 LOG(LS_INFO) << "NetEq capacity is " << audio_jitter_buffer_max_packets;
784 voe_config_.Set<webrtc::NetEqCapacityConfig>(
785 new webrtc::NetEqCapacityConfig(audio_jitter_buffer_max_packets));
786 }
787
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200788 bool audio_jitter_buffer_fast_accelerate;
789 if (options.audio_jitter_buffer_fast_accelerate.Get(
790 &audio_jitter_buffer_fast_accelerate)) {
791 LOG(LS_INFO) << "NetEq fast mode? " << audio_jitter_buffer_fast_accelerate;
792 voe_config_.Set<webrtc::NetEqFastAccelerate>(
793 new webrtc::NetEqFastAccelerate(audio_jitter_buffer_fast_accelerate));
794 }
795
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000796 bool typing_detection;
797 if (options.typing_detection.Get(&typing_detection)) {
798 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
799 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
800 // In case of error, log the info and continue
801 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
802 }
803 }
804
805 int adjust_agc_delta;
806 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
807 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
808 if (!AdjustAgcLevel(adjust_agc_delta)) {
809 return false;
810 }
811 }
812
813 bool aec_dump;
814 if (options.aec_dump.Get(&aec_dump)) {
815 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
816 if (aec_dump)
817 StartAecDump(kAecDumpByAudioOptionFilename);
818 else
819 StopAecDump();
820 }
821
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000822 webrtc::Config config;
823
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100824 delay_agnostic_aec_.SetFrom(options.delay_agnostic_aec);
825 bool delay_agnostic_aec;
826 if (delay_agnostic_aec_.Get(&delay_agnostic_aec)) {
827 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << delay_agnostic_aec;
henrik.lundin0f133b92015-07-02 00:17:55 -0700828 config.Set<webrtc::DelayAgnostic>(
829 new webrtc::DelayAgnostic(delay_agnostic_aec));
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100830 }
831
Henrik Lundin441f6342015-06-09 16:03:13 +0200832 extended_filter_aec_.SetFrom(options.extended_filter_aec);
833 bool extended_filter;
834 if (extended_filter_aec_.Get(&extended_filter)) {
835 LOG(LS_INFO) << "Extended filter aec is enabled? " << extended_filter;
836 config.Set<webrtc::ExtendedFilter>(
837 new webrtc::ExtendedFilter(extended_filter));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000838 }
839
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000840 experimental_ns_.SetFrom(options.experimental_ns);
841 bool experimental_ns;
842 if (experimental_ns_.Get(&experimental_ns)) {
843 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
844 config.Set<webrtc::ExperimentalNs>(
845 new webrtc::ExperimentalNs(experimental_ns));
846 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000847
848 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
849 // returns NULL on audio_processing().
850 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
851 if (audioproc) {
852 audioproc->SetExtraOptions(config);
853 }
854
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000855 uint32 recording_sample_rate;
856 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
857 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
858 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
859 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
860 }
861 }
862
863 uint32 playout_sample_rate;
864 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
865 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
866 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
867 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
868 }
869 }
870
871 return true;
872}
873
874bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
875 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
876 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
877 LOG_RTCERR1(SetDelayOffsetMs, offset);
878 return false;
879 }
880
881 return true;
882}
883
884struct ResumeEntry {
885 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
886 : channel(c),
887 playout(p),
888 send(s) {
889 }
890
891 WebRtcVoiceMediaChannel *channel;
892 bool playout;
893 SendFlags send;
894};
895
896// TODO(juberti): Refactor this so that the core logic can be used to set the
897// soundclip device. At that time, reinstate the soundclip pause/resume code.
898bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
899 const Device* out_device) {
900#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000901 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000902 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000903 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000904 kDefaultAudioDeviceId;
905 // The device manager uses -1 as the default device, which was the case for
906 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
907#ifndef WIN32
908 if (-1 == in_id) {
909 in_id = kDefaultAudioDeviceId;
910 }
911 if (-1 == out_id) {
912 out_id = kDefaultAudioDeviceId;
913 }
914#endif
915
916 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
917 in_device->name : "Default device";
918 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
919 out_device->name : "Default device";
920 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
921 << ") and speaker to (id=" << out_id << ", name=" << out_name
922 << ")";
923
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000924 // Must also pause all audio playback and capture.
solenbergc1a1b352015-09-22 13:31:20 -0700925 bool ret = true;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200926 for (WebRtcVoiceMediaChannel* channel : channels_) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000927 if (!channel->PausePlayout()) {
928 LOG(LS_WARNING) << "Failed to pause playout";
929 ret = false;
930 }
931 if (!channel->PauseSend()) {
932 LOG(LS_WARNING) << "Failed to pause send";
933 ret = false;
934 }
935 }
936
937 // Find the recording device id in VoiceEngine and set recording device.
938 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
939 ret = false;
940 }
941 if (ret) {
942 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
943 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
944 ret = false;
945 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +0000946 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
947 if (ap)
948 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000949 }
950
951 // Find the playout device id in VoiceEngine and set playout device.
952 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
953 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
954 ret = false;
955 }
956 if (ret) {
957 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000958 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000959 ret = false;
960 }
961 }
962
963 // Resume all audio playback and capture.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200964 for (WebRtcVoiceMediaChannel* channel : channels_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000965 if (!channel->ResumePlayout()) {
966 LOG(LS_WARNING) << "Failed to resume playout";
967 ret = false;
968 }
969 if (!channel->ResumeSend()) {
970 LOG(LS_WARNING) << "Failed to resume send";
971 ret = false;
972 }
973 }
974
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000975 if (ret) {
976 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
977 << ") and speaker to (id="<< out_id << " name=" << out_name
978 << ")";
979 }
980
981 return ret;
982#else
983 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000984#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000985}
986
987bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
988 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
989 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000990#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000991 *rtc_id = dev_id;
992 return true;
993#else
994 // In Windows and Mac, we need to find the VoiceEngine device id by name
995 // unless the input dev_id is the default device id.
996 if (kDefaultAudioDeviceId == dev_id) {
997 *rtc_id = dev_id;
998 return true;
999 }
1000
1001 // Get the number of VoiceEngine audio devices.
1002 int count = 0;
1003 if (is_input) {
1004 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1005 LOG_RTCERR0(GetNumOfRecordingDevices);
1006 return false;
1007 }
1008 } else {
1009 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1010 LOG_RTCERR0(GetNumOfPlayoutDevices);
1011 return false;
1012 }
1013 }
1014
1015 for (int i = 0; i < count; ++i) {
1016 char name[128];
1017 char guid[128];
1018 if (is_input) {
1019 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1020 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1021 } else {
1022 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1023 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1024 }
1025
1026 std::string webrtc_name(name);
1027 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1028 *rtc_id = i;
1029 return true;
1030 }
1031 }
1032 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1033 return false;
1034#endif
1035}
1036
1037bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1038 unsigned int ulevel;
1039 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1040 LOG_RTCERR1(GetSpeakerVolume, level);
1041 return false;
1042 }
1043 *level = ulevel;
1044 return true;
1045}
1046
1047bool WebRtcVoiceEngine::SetOutputVolume(int level) {
henrikg91d6ede2015-09-17 00:24:34 -07001048 RTC_DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001049 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1050 LOG_RTCERR1(SetSpeakerVolume, level);
1051 return false;
1052 }
1053 return true;
1054}
1055
1056int WebRtcVoiceEngine::GetInputLevel() {
1057 unsigned int ulevel;
1058 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1059 static_cast<int>(ulevel) : -1;
1060}
1061
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001062const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1063 return codecs_;
1064}
1065
1066bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1067 return FindWebRtcCodec(in, NULL);
1068}
1069
1070// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1071bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1072 webrtc::CodecInst* out) {
1073 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1074 for (int i = 0; i < ncodecs; ++i) {
1075 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001076 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001077 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1078 voe_codec.rate, voe_codec.channels, 0);
1079 bool multi_rate = IsCodecMultiRate(voe_codec);
1080 // Allow arbitrary rates for ISAC to be specified.
1081 if (multi_rate) {
1082 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1083 codec.bitrate = 0;
1084 }
1085 if (codec.Matches(in)) {
1086 if (out) {
1087 // Fixup the payload type.
1088 voe_codec.pltype = in.id;
1089
1090 // Set bitrate if specified.
1091 if (multi_rate && in.bitrate != 0) {
1092 voe_codec.rate = in.bitrate;
1093 }
1094
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001095 // Reset G722 sample rate to 16000 to match WebRTC.
1096 MaybeFixupG722(&voe_codec, 16000);
1097
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001098 // Apply codec-specific settings.
Minyue Li7100dcd2015-03-27 05:05:59 +01001099 if (IsCodec(codec, kIsacCodecName)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001100 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001101 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001102 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1103 }
1104 *out = voe_codec;
1105 }
1106 return true;
1107 }
1108 }
1109 }
1110 return false;
1111}
1112const std::vector<RtpHeaderExtension>&
1113WebRtcVoiceEngine::rtp_header_extensions() const {
1114 return rtp_header_extensions_;
1115}
1116
1117void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1118 // if min_sev == -1, we keep the current log level.
1119 if (min_sev >= 0) {
1120 SetTraceFilter(SeverityToFilter(min_sev));
1121 }
1122 log_options_ = filter;
1123 SetTraceOptions(initialized_ ? log_options_ : "");
1124}
1125
1126int WebRtcVoiceEngine::GetLastEngineError() {
1127 return voe_wrapper_->error();
1128}
1129
1130void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1131 log_filter_ = filter;
1132 tracing_->SetTraceFilter(filter);
1133}
1134
1135// We suppport three different logging settings for VoiceEngine:
1136// 1. Observer callback that goes into talk diagnostic logfile.
1137// Use --logfile and --loglevel
1138//
1139// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1140// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1141//
1142// 3. EC log and dump for debugging QualityEngine.
1143// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1144//
1145// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1146// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1147void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1148 // Set encrypted trace file.
1149 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001150 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001151 std::vector<std::string>::iterator tracefile =
1152 std::find(opts.begin(), opts.end(), "tracefile");
1153 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1154 // Write encrypted debug output (at same loglevel) to file
1155 // EncryptedTraceFile no longer supported.
1156 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1157 LOG_RTCERR1(SetTraceFile, *tracefile);
1158 }
1159 }
1160
wu@webrtc.org97077a32013-10-25 21:18:33 +00001161 // Allow trace options to override the trace filter. We default
1162 // it to log_filter_ (as a translation of libjingle log levels)
1163 // elsewhere, but this allows clients to explicitly set webrtc
1164 // log levels.
1165 std::vector<std::string>::iterator tracefilter =
1166 std::find(opts.begin(), opts.end(), "tracefilter");
1167 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001168 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001169 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1170 }
1171 }
1172
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001173 // Set AEC dump file
1174 std::vector<std::string>::iterator recordEC =
1175 std::find(opts.begin(), opts.end(), "recordEC");
1176 if (recordEC != opts.end()) {
1177 ++recordEC;
1178 if (recordEC != opts.end())
1179 StartAecDump(recordEC->c_str());
1180 else
1181 StopAecDump();
1182 }
1183}
1184
1185// Ignore spammy trace messages, mostly from the stats API when we haven't
1186// gotten RTCP info yet from the remote side.
1187bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1188 static const char* kTracesToIgnore[] = {
1189 "\tfailed to GetReportBlockInformation",
1190 "GetRecCodec() failed to get received codec",
1191 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1192 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1193 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1194 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1195 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1196 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1197 "SenderInfoReceived No received SR",
1198 "StatisticsRTP() no statistics available",
1199 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1200 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1201 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1202 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1203 NULL
1204 };
1205 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1206 if (trace.find(*p) != std::string::npos) {
1207 return true;
1208 }
1209 }
1210 return false;
1211}
1212
1213void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1214 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001215 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001216 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001217 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001218 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001219 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001220 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001221 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001222 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001223 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001224
1225 // Skip past boilerplate prefix text
1226 if (length < 72) {
1227 std::string msg(trace, length);
1228 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1229 LOG_V(sev) << msg;
1230 } else {
1231 std::string msg(trace + 71, length - 72);
1232 if (!ShouldIgnoreTrace(msg)) {
1233 LOG_V(sev) << "webrtc: " << msg;
1234 }
1235 }
1236}
1237
1238void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001239 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001240 WebRtcVoiceMediaChannel* channel = NULL;
1241 uint32 ssrc = 0;
1242 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1243 << channel_num << ".";
1244 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
henrikg91d6ede2015-09-17 00:24:34 -07001245 RTC_DCHECK(channel != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001246 channel->OnError(ssrc, err_code);
1247 } else {
1248 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1249 << " could not be found in channel list when error reported.";
1250 }
1251}
1252
1253bool WebRtcVoiceEngine::FindChannelAndSsrc(
1254 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
henrikg91d6ede2015-09-17 00:24:34 -07001255 RTC_DCHECK(channel != NULL && ssrc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001256
1257 *channel = NULL;
1258 *ssrc = 0;
1259 // Find corresponding channel and ssrc
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001260 for (WebRtcVoiceMediaChannel* ch : channels_) {
henrikg91d6ede2015-09-17 00:24:34 -07001261 RTC_DCHECK(ch != NULL);
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001262 if (ch->FindSsrc(channel_num, ssrc)) {
1263 *channel = ch;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001264 return true;
1265 }
1266 }
1267
1268 return false;
1269}
1270
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001271void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001272 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001273 channels_.push_back(channel);
1274}
1275
1276void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001277 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001278 ChannelList::iterator i = std::find(channels_.begin(),
1279 channels_.end(),
1280 channel);
1281 if (i != channels_.end()) {
1282 channels_.erase(i);
1283 }
1284}
1285
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001286// Adjusts the default AGC target level by the specified delta.
1287// NB: If we start messing with other config fields, we'll want
1288// to save the current webrtc::AgcConfig as well.
1289bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1290 webrtc::AgcConfig config = default_agc_config_;
1291 config.targetLeveldBOv -= delta;
1292
1293 LOG(LS_INFO) << "Adjusting AGC level from default -"
1294 << default_agc_config_.targetLeveldBOv << "dB to -"
1295 << config.targetLeveldBOv << "dB";
1296
1297 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1298 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1299 return false;
1300 }
1301 return true;
1302}
1303
Fredrik Solenbergccb49e72015-05-19 11:37:56 +02001304bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001305 if (initialized_) {
1306 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1307 return false;
1308 }
1309 if (adm_) {
1310 adm_->Release();
1311 adm_ = NULL;
1312 }
1313 if (adm) {
1314 adm_ = adm;
1315 adm_->AddRef();
1316 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001317 return true;
1318}
1319
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001320bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1321 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001322 if (!aec_dump_file_stream) {
1323 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001324 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001325 LOG(LS_WARNING) << "Could not close file.";
1326 return false;
1327 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001328 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001329 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001330 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001331 LOG_RTCERR0(StartDebugRecording);
1332 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001333 return false;
1334 }
1335 is_dumping_aec_ = true;
1336 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001337}
1338
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001339void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1340 if (!is_dumping_aec_) {
1341 // Start dumping AEC when we are not dumping.
1342 if (voe_wrapper_->processing()->StartDebugRecording(
1343 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001344 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001345 } else {
1346 is_dumping_aec_ = true;
1347 }
1348 }
1349}
1350
1351void WebRtcVoiceEngine::StopAecDump() {
1352 if (is_dumping_aec_) {
1353 // Stop dumping AEC when we are dumping.
1354 if (voe_wrapper_->processing()->StopDebugRecording() !=
1355 webrtc::AudioProcessing::kNoError) {
1356 LOG_RTCERR0(StopDebugRecording);
1357 }
1358 is_dumping_aec_ = false;
1359 }
1360}
1361
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001362int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001363 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001364}
1365
1366int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1367 return CreateVoiceChannel(voe_wrapper_.get());
1368}
1369
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001370class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1371 : public AudioRenderer::Sink {
1372 public:
1373 WebRtcVoiceChannelRenderer(int ch,
1374 webrtc::AudioTransport* voe_audio_transport)
1375 : channel_(ch),
1376 voe_audio_transport_(voe_audio_transport),
pbos8fc7fa72015-07-15 08:02:58 -07001377 renderer_(NULL) {}
Fredrik Solenbergaaf8ff22015-05-07 16:05:53 +02001378 ~WebRtcVoiceChannelRenderer() override { Stop(); }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001379
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001380 // Starts the rendering by setting a sink to the renderer to get data
1381 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001382 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001383 // TODO(xians): Make sure Start() is called only once.
1384 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001385 rtc::CritScope lock(&lock_);
henrikg91d6ede2015-09-17 00:24:34 -07001386 RTC_DCHECK(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001387 if (renderer_ != NULL) {
henrikg91d6ede2015-09-17 00:24:34 -07001388 RTC_DCHECK(renderer_ == renderer);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001389 return;
1390 }
1391
1392 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1393 // in getUserMedia by default.
1394 renderer->AddChannel(channel_);
1395 renderer->SetSink(this);
1396 renderer_ = renderer;
1397 }
1398
1399 // Stops rendering by setting the sink of the renderer to NULL. No data
1400 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001401 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001402 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001403 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001404 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001405 return;
1406
1407 renderer_->RemoveChannel(channel_);
1408 renderer_->SetSink(NULL);
1409 renderer_ = NULL;
1410 }
1411
1412 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001413 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001414 void OnData(const void* audio_data,
1415 int bits_per_sample,
1416 int sample_rate,
1417 int number_of_channels,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001418 size_t number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001419 voe_audio_transport_->OnData(channel_,
1420 audio_data,
1421 bits_per_sample,
1422 sample_rate,
1423 number_of_channels,
1424 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001425 }
1426
1427 // Callback from the |renderer_| when it is going away. In case Start() has
1428 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001429 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001430 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001431 // Set |renderer_| to NULL to make sure no more callback will get into
1432 // the renderer.
1433 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001434 }
1435
1436 // Accessor to the VoE channel ID.
1437 int channel() const { return channel_; }
1438
1439 private:
1440 const int channel_;
1441 webrtc::AudioTransport* const voe_audio_transport_;
1442
1443 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1444 // PeerConnection will make sure invalidating the pointer before the object
1445 // goes away.
1446 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001447
1448 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001449 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001450};
1451
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001452// WebRtcVoiceMediaChannel
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001453WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine,
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001454 const AudioOptions& options,
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001455 webrtc::Call* call)
Fredrik Solenberge444a3d2015-05-07 16:42:08 +02001456 : engine_(engine),
1457 voe_channel_(engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001458 send_bitrate_setting_(false),
1459 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001460 options_(),
1461 dtmf_allowed_(false),
1462 desired_playout_(false),
1463 nack_enabled_(false),
1464 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001465 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001466 desired_send_(SEND_NOTHING),
1467 send_(SEND_NOTHING),
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001468 call_(call),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001469 default_receive_ssrc_(0) {
1470 engine->RegisterChannel(this);
1471 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1472 << voe_channel();
henrikg91d6ede2015-09-17 00:24:34 -07001473 RTC_DCHECK(nullptr != call);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001474 ConfigureSendChannel(voe_channel());
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001475 SetOptions(options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001476}
1477
1478WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1479 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1480 << voe_channel();
1481
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001482 // Remove any remaining send streams, the default channel will be deleted
1483 // later.
1484 while (!send_channels_.empty())
1485 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001486
1487 // Unregister ourselves from the engine.
1488 engine()->UnregisterChannel(this);
1489 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001490 while (!receive_channels_.empty()) {
1491 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001492 }
henrikg91d6ede2015-09-17 00:24:34 -07001493 RTC_DCHECK(receive_streams_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001494
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001495 // Delete the default channel.
1496 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001497}
1498
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001499bool WebRtcVoiceMediaChannel::SetSendParameters(
1500 const AudioSendParameters& params) {
1501 // TODO(pthatcher): Refactor this to be more clean now that we have
1502 // all the information at once.
1503 return (SetSendCodecs(params.codecs) &&
1504 SetSendRtpHeaderExtensions(params.extensions) &&
1505 SetMaxSendBandwidth(params.max_bandwidth_bps) &&
1506 SetOptions(params.options));
1507}
1508
1509bool WebRtcVoiceMediaChannel::SetRecvParameters(
1510 const AudioRecvParameters& params) {
1511 // TODO(pthatcher): Refactor this to be more clean now that we have
1512 // all the information at once.
1513 return (SetRecvCodecs(params.codecs) &&
1514 SetRecvRtpHeaderExtensions(params.extensions));
1515}
1516
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001517bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1518 LOG(LS_INFO) << "Setting voice channel options: "
1519 << options.ToString();
1520
wu@webrtc.orgde305012013-10-31 15:40:38 +00001521 // Check if DSCP value is changed from previous.
1522 bool dscp_option_changed = (options_.dscp != options.dscp);
1523
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001524 // TODO(xians): Add support to set different options for different send
1525 // streams after we support multiple APMs.
1526
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001527 // We retain all of the existing options, and apply the given ones
1528 // on top. This means there is no way to "clear" options such that
1529 // they go back to the engine default.
1530 options_.SetAll(options);
1531
1532 if (send_ != SEND_NOTHING) {
1533 if (!engine()->SetOptionOverrides(options_)) {
1534 LOG(LS_WARNING) <<
1535 "Failed to engine SetOptionOverrides during channel SetOptions.";
1536 return false;
1537 }
1538 } else {
1539 // Will be interpreted when appropriate.
1540 }
1541
wu@webrtc.org97077a32013-10-25 21:18:33 +00001542 // Receiver-side auto gain control happens per channel, so set it here from
1543 // options. Note that, like conference mode, setting it on the engine won't
1544 // have the desired effect, since voice channels don't inherit options from
1545 // the media engine when those options are applied per-channel.
1546 bool rx_auto_gain_control;
1547 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1548 if (engine()->voe()->processing()->SetRxAgcStatus(
1549 voe_channel(), rx_auto_gain_control,
1550 webrtc::kAgcFixedDigital) == -1) {
1551 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1552 return false;
1553 } else {
1554 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1555 << " with mode " << webrtc::kAgcFixedDigital;
1556 }
1557 }
1558 if (options.rx_agc_target_dbov.IsSet() ||
1559 options.rx_agc_digital_compression_gain.IsSet() ||
1560 options.rx_agc_limiter.IsSet()) {
1561 webrtc::AgcConfig config;
1562 // If only some of the options are being overridden, get the current
1563 // settings for the channel and bail if they aren't available.
1564 if (!options.rx_agc_target_dbov.IsSet() ||
1565 !options.rx_agc_digital_compression_gain.IsSet() ||
1566 !options.rx_agc_limiter.IsSet()) {
1567 if (engine()->voe()->processing()->GetRxAgcConfig(
1568 voe_channel(), config) != 0) {
1569 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1570 << "channel " << voe_channel() << ". Since not all rx "
1571 << "agc options are specified, unable to safely set rx "
1572 << "agc options.";
1573 return false;
1574 }
1575 }
1576 config.targetLeveldBOv =
1577 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1578 config.targetLeveldBOv);
1579 config.digitalCompressionGaindB =
1580 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1581 config.digitalCompressionGaindB);
1582 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1583 config.limiterEnable);
1584 if (engine()->voe()->processing()->SetRxAgcConfig(
1585 voe_channel(), config) == -1) {
1586 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1587 config.digitalCompressionGaindB, config.limiterEnable);
1588 return false;
1589 }
1590 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001591 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001592 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001593 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001594 dscp = kAudioDscpValue;
1595 if (MediaChannel::SetDscp(dscp) != 0) {
1596 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1597 }
1598 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001599
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001600 RecreateAudioReceiveStreams();
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001601
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001602 LOG(LS_INFO) << "Set voice channel options. Current options: "
1603 << options_.ToString();
1604 return true;
1605}
1606
1607bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1608 const std::vector<AudioCodec>& codecs) {
1609 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001610 LOG(LS_INFO) << "Setting receive voice codecs:";
1611
1612 std::vector<AudioCodec> new_codecs;
1613 // Find all new codecs. We allow adding new codecs but don't allow changing
1614 // the payload type of codecs that is already configured since we might
1615 // already be receiving packets with that payload type.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001616 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001617 AudioCodec old_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001618 if (FindCodec(recv_codecs_, codec, &old_codec)) {
1619 if (old_codec.id != codec.id) {
1620 LOG(LS_ERROR) << codec.name << " payload type changed.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001621 return false;
1622 }
1623 } else {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001624 new_codecs.push_back(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001625 }
1626 }
1627 if (new_codecs.empty()) {
1628 // There are no new codecs to configure. Already configured codecs are
1629 // never removed.
1630 return true;
1631 }
1632
1633 if (playout_) {
1634 // Receive codecs can not be changed while playing. So we temporarily
1635 // pause playout.
1636 PausePlayout();
1637 }
1638
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001639 bool result = SetRecvCodecsInternal(new_codecs);
1640 if (result) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001641 recv_codecs_ = codecs;
1642 }
1643
1644 if (desired_playout_ && !playout_) {
1645 ResumePlayout();
1646 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001647 return result;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001648}
1649
1650bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001651 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001652 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001653 engine()->voe()->codec()->SetVADStatus(channel, false);
1654 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001655 engine()->voe()->rtp()->SetREDStatus(channel, false);
1656 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001657
1658 // Scan through the list to figure out the codec to use for sending, along
1659 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001660 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001661 webrtc::CodecInst send_codec;
1662 memset(&send_codec, 0, sizeof(send_codec));
1663
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001664 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001665 bool enable_codec_fec = false;
Minyue Li7100dcd2015-03-27 05:05:59 +01001666 bool enable_opus_dtx = false;
minyue@webrtc.org26236952014-10-29 02:27:08 +00001667 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001668
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001669 // Set send codec (the first non-telephone-event/CN codec)
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001670 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001671 // Ignore codecs we don't know about. The negotiation step should prevent
1672 // this, but double-check to be sure.
1673 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001674 if (!engine()->FindWebRtcCodec(codec, &voe_codec)) {
1675 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001676 continue;
1677 }
1678
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001679 if (IsCodec(codec, kDtmfCodecName) || IsCodec(codec, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001680 // Skip telephone-event/CN codec, which will be handled later.
1681 continue;
1682 }
1683
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001684 // We'll use the first codec in the list to actually send audio data.
1685 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001686 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001687 // used is specified in params.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001688 if (IsCodec(codec, kRedCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001689 // Parse out the RED parameters. If we fail, just ignore RED;
1690 // we don't support all possible params/usage scenarios.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001691 if (!GetRedSendCodec(codec, codecs, &send_codec)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001692 continue;
1693 }
1694
1695 // Enable redundant encoding of the specified codec. Treat any
1696 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001697 LOG(LS_INFO) << "Enabling RED on channel " << channel;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001698 if (engine()->voe()->rtp()->SetREDStatus(channel, true, codec.id) == -1) {
1699 LOG_RTCERR3(SetREDStatus, channel, true, codec.id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001700 return false;
1701 }
1702 } else {
1703 send_codec = voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001704 nack_enabled = IsNackEnabled(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +01001705 // For Opus as the send codec, we are to determine inband FEC, maximum
1706 // playback rate, and opus internal dtx.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001707 if (IsCodec(codec, kOpusCodecName)) {
1708 GetOpusConfig(codec, &send_codec, &enable_codec_fec,
Minyue Li7100dcd2015-03-27 05:05:59 +01001709 &opus_max_playback_rate, &enable_opus_dtx);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001710 }
Brave Yao5225dd82015-03-26 07:39:19 +08001711
1712 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1713 int ptime_ms = 0;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001714 if (codec.GetParam(kCodecParamPTime, &ptime_ms)) {
Brave Yao5225dd82015-03-26 07:39:19 +08001715 if (!SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
1716 LOG(LS_WARNING) << "Failed to set packet size for codec "
1717 << send_codec.plname;
1718 return false;
1719 }
1720 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001721 }
1722 found_send_codec = true;
1723 break;
1724 }
1725
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001726 if (nack_enabled_ != nack_enabled) {
1727 SetNack(channel, nack_enabled);
1728 nack_enabled_ = nack_enabled;
1729 }
1730
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001731 if (!found_send_codec) {
1732 LOG(LS_WARNING) << "Received empty list of codecs.";
1733 return false;
1734 }
1735
1736 // Set the codec immediately, since SetVADStatus() depends on whether
1737 // the current codec is mono or stereo.
1738 if (!SetSendCodec(channel, send_codec))
1739 return false;
1740
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001741 // FEC should be enabled after SetSendCodec.
1742 if (enable_codec_fec) {
1743 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
1744 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001745 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
1746 // Enable codec internal FEC. Treat any failure as fatal internal error.
1747 LOG_RTCERR2(SetFECStatus, channel, true);
1748 return false;
1749 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001750 }
1751
Minyue Li7100dcd2015-03-27 05:05:59 +01001752 if (IsCodec(send_codec, kOpusCodecName)) {
1753 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
1754 // send codec has to be Opus.
1755
1756 // Set Opus internal DTX.
1757 LOG(LS_INFO) << "Attempt to "
1758 << GetEnableString(enable_opus_dtx)
1759 << " Opus DTX on channel "
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001760 << channel;
Minyue Li7100dcd2015-03-27 05:05:59 +01001761 if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) {
1762 LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx);
1763 return false;
1764 }
1765
1766 // If opus_max_playback_rate <= 0, the default maximum playback rate
1767 // (48 kHz) will be used.
1768 if (opus_max_playback_rate > 0) {
1769 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
1770 << opus_max_playback_rate
1771 << " Hz on channel "
1772 << channel;
1773 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
1774 channel, opus_max_playback_rate) == -1) {
1775 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate);
1776 return false;
1777 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001778 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001779 }
1780
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001781 // Always update the |send_codec_| to the currently set send codec.
1782 send_codec_.reset(new webrtc::CodecInst(send_codec));
1783
minyue@webrtc.org26236952014-10-29 02:27:08 +00001784 if (send_bitrate_setting_) {
1785 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001786 }
1787
1788 // Loop through the codecs list again to config the telephone-event/CN codec.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001789 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001790 // Ignore codecs we don't know about. The negotiation step should prevent
1791 // this, but double-check to be sure.
1792 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001793 if (!engine()->FindWebRtcCodec(codec, &voe_codec)) {
1794 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001795 continue;
1796 }
1797
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001798 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
1799 // about it.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001800 if (IsCodec(codec, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001801 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001802 channel, codec.id) == -1) {
1803 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, codec.id);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001804 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001805 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001806 } else if (IsCodec(codec, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001807 // Turn voice activity detection/comfort noise on if supported.
1808 // Set the wideband CN payload type appropriately.
1809 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001810 webrtc::PayloadFrequencies cn_freq;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001811 switch (codec.clockrate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001812 case 8000:
1813 cn_freq = webrtc::kFreq8000Hz;
1814 break;
1815 case 16000:
1816 cn_freq = webrtc::kFreq16000Hz;
1817 break;
1818 case 32000:
1819 cn_freq = webrtc::kFreq32000Hz;
1820 break;
1821 default:
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001822 LOG(LS_WARNING) << "CN frequency " << codec.clockrate
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001823 << " not supported.";
1824 continue;
1825 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001826 // Set the CN payloadtype and the VAD status.
1827 // The CN payload type for 8000 Hz clockrate is fixed at 13.
1828 if (cn_freq != webrtc::kFreq8000Hz) {
1829 if (engine()->voe()->codec()->SetSendCNPayloadType(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001830 channel, codec.id, cn_freq) == -1) {
1831 LOG_RTCERR3(SetSendCNPayloadType, channel, codec.id, cn_freq);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001832 // TODO(ajm): This failure condition will be removed from VoE.
1833 // Restore the return here when we update to a new enough webrtc.
1834 //
1835 // Not returning false because the SetSendCNPayloadType will fail if
1836 // the channel is already sending.
1837 // This can happen if the remote description is applied twice, for
1838 // example in the case of ROAP on top of JSEP, where both side will
1839 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001840 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001841 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001842 // Only turn on VAD if we have a CN payload type that matches the
1843 // clockrate for the codec we are going to use.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001844 if (codec.clockrate == send_codec.plfreq && send_codec.channels != 2) {
Minyue Li7100dcd2015-03-27 05:05:59 +01001845 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
1846 // interaction between VAD and Opus FEC.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001847 LOG(LS_INFO) << "Enabling VAD";
1848 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
1849 LOG_RTCERR2(SetVADStatus, channel, true);
1850 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001851 }
1852 }
1853 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001854 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001855 return true;
1856}
1857
1858bool WebRtcVoiceMediaChannel::SetSendCodecs(
1859 const std::vector<AudioCodec>& codecs) {
1860 dtmf_allowed_ = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001861 for (const AudioCodec& codec : codecs) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001862 // Find the DTMF telephone event "codec".
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001863 if (IsCodec(codec, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001864 dtmf_allowed_ = true;
1865 }
1866 }
1867
1868 // Cache the codecs in order to configure the channel created later.
1869 send_codecs_ = codecs;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001870 for (const auto& ch : send_channels_) {
1871 if (!SetSendCodecs(ch.second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001872 return false;
1873 }
1874 }
1875
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001876 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001877 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001878 return true;
1879}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001880
1881void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
1882 bool nack_enabled) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001883 for (const auto& ch : channels) {
1884 SetNack(ch.second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001885 }
1886}
1887
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001888void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001889 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001890 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001891 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
1892 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001893 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001894 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1895 }
1896}
1897
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001898bool WebRtcVoiceMediaChannel::SetSendCodec(
1899 const webrtc::CodecInst& send_codec) {
1900 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
1901 << ", bitrate=" << send_codec.rate;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001902 for (const auto& ch : send_channels_) {
1903 if (!SetSendCodec(ch.second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001904 return false;
1905 }
1906
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001907 return true;
1908}
1909
1910bool WebRtcVoiceMediaChannel::SetSendCodec(
1911 int channel, const webrtc::CodecInst& send_codec) {
1912 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
1913 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
1914
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001915 webrtc::CodecInst current_codec;
1916 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
1917 (send_codec == current_codec)) {
1918 // Codec is already configured, we can return without setting it again.
1919 return true;
1920 }
1921
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001922 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
1923 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001924 return false;
1925 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001926 return true;
1927}
1928
1929bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
1930 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00001931 if (receive_extensions_ == extensions) {
1932 return true;
1933 }
1934
1935 // The default channel may or may not be in |receive_channels_|. Set the rtp
1936 // header extensions for default channel regardless.
1937 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
1938 return false;
1939 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00001940
1941 // Loop through all receive channels and enable/disable the extensions.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001942 for (const auto& ch : receive_channels_) {
1943 if (!SetChannelRecvRtpHeaderExtensions(ch.second->channel(), extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00001944 return false;
1945 }
1946 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00001947
1948 receive_extensions_ = extensions;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001949
1950 // Recreate AudioReceiveStream:s.
1951 {
1952 std::vector<webrtc::RtpExtension> exts;
1953
1954 const RtpHeaderExtension* audio_level_extension =
1955 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
1956 if (audio_level_extension) {
1957 exts.push_back({
1958 kRtpAudioLevelHeaderExtension, audio_level_extension->id});
1959 }
1960
1961 const RtpHeaderExtension* send_time_extension =
1962 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
1963 if (send_time_extension) {
1964 exts.push_back({
1965 kRtpAbsoluteSenderTimeHeaderExtension, send_time_extension->id});
1966 }
1967
1968 recv_rtp_extensions_.swap(exts);
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001969 RecreateAudioReceiveStreams();
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001970 }
1971
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00001972 return true;
1973}
1974
1975bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
1976 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00001977 const RtpHeaderExtension* audio_level_extension =
1978 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
1979 if (!SetHeaderExtension(
1980 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
1981 audio_level_extension)) {
1982 return false;
1983 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00001984
1985 const RtpHeaderExtension* send_time_extension =
1986 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
1987 if (!SetHeaderExtension(
1988 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
1989 send_time_extension)) {
1990 return false;
1991 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001992
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001993 return true;
1994}
1995
1996bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
1997 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00001998 if (send_extensions_ == extensions) {
1999 return true;
2000 }
2001
2002 // The default channel may or may not be in |send_channels_|. Set the rtp
2003 // header extensions for default channel regardless.
2004
2005 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2006 return false;
2007 }
2008
2009 // Loop through all send channels and enable/disable the extensions.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002010 for (const auto& ch : send_channels_) {
2011 if (!SetChannelSendRtpHeaderExtensions(ch.second->channel(), extensions)) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002012 return false;
2013 }
2014 }
2015
2016 send_extensions_ = extensions;
2017 return true;
2018}
2019
2020bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2021 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002022 const RtpHeaderExtension* audio_level_extension =
2023 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002024
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002025 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002026 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002027 audio_level_extension)) {
2028 return false;
2029 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002030
2031 const RtpHeaderExtension* send_time_extension =
2032 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002033 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002034 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002035 send_time_extension)) {
2036 return false;
2037 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002038
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002039 return true;
2040}
2041
2042bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2043 desired_playout_ = playout;
2044 return ChangePlayout(desired_playout_);
2045}
2046
2047bool WebRtcVoiceMediaChannel::PausePlayout() {
2048 return ChangePlayout(false);
2049}
2050
2051bool WebRtcVoiceMediaChannel::ResumePlayout() {
2052 return ChangePlayout(desired_playout_);
2053}
2054
2055bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2056 if (playout_ == playout) {
2057 return true;
2058 }
2059
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002060 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002061 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002062 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002063 // Only toggle the default channel if we don't have any other channels.
2064 result = SetPlayout(voe_channel(), playout);
2065 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002066 for (const auto& ch : receive_channels_) {
2067 if (!SetPlayout(ch.second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002068 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002069 << ch.second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002070 result = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002071 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002072 }
2073 }
2074
2075 if (result) {
2076 playout_ = playout;
2077 }
2078 return result;
2079}
2080
2081bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2082 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002083 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002084 return ChangeSend(desired_send_);
2085 return true;
2086}
2087
2088bool WebRtcVoiceMediaChannel::PauseSend() {
2089 return ChangeSend(SEND_NOTHING);
2090}
2091
2092bool WebRtcVoiceMediaChannel::ResumeSend() {
2093 return ChangeSend(desired_send_);
2094}
2095
2096bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2097 if (send_ == send) {
2098 return true;
2099 }
2100
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002101 // Change the settings on each send channel.
2102 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002103 engine()->SetOptionOverrides(options_);
2104
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002105 // Change the settings on each send channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002106 for (const auto& ch : send_channels_) {
2107 if (!ChangeSend(ch.second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002108 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002109 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002110
2111 // Clear up the options after stopping sending.
2112 if (send == SEND_NOTHING)
2113 engine()->ClearOptionOverrides();
2114
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002115 send_ = send;
2116 return true;
2117}
2118
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002119bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2120 if (send == SEND_MICROPHONE) {
2121 if (engine()->voe()->base()->StartSend(channel) == -1) {
2122 LOG_RTCERR1(StartSend, channel);
2123 return false;
2124 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002125 } else { // SEND_NOTHING
henrikg91d6ede2015-09-17 00:24:34 -07002126 RTC_DCHECK(send == SEND_NOTHING);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002127 if (engine()->voe()->base()->StopSend(channel) == -1) {
2128 LOG_RTCERR1(StopSend, channel);
2129 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002130 }
2131 }
2132
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002133 return true;
2134}
2135
solenberg1dd98f32015-09-10 01:57:14 -07002136bool WebRtcVoiceMediaChannel::SetAudioSend(uint32 ssrc, bool mute,
2137 const AudioOptions* options,
2138 AudioRenderer* renderer) {
2139 // TODO(solenberg): The state change should be fully rolled back if any one of
2140 // these calls fail.
2141 if (!SetLocalRenderer(ssrc, renderer)) {
2142 return false;
2143 }
2144 if (!MuteStream(ssrc, mute)) {
2145 return false;
2146 }
2147 if (!mute && options) {
2148 return SetOptions(*options);
2149 }
2150 return true;
2151}
2152
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002153// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002154void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2155 if (engine()->voe()->network()->RegisterExternalTransport(
2156 channel, *this) == -1) {
2157 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2158 }
2159
2160 // Enable RTCP (for quality stats and feedback messages)
2161 EnableRtcp(channel);
2162
2163 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2164 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002165
2166 // Set RTP header extension for the new channel.
2167 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002168}
2169
2170bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2171 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2172 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2173 }
2174
2175 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2176 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002177 return false;
2178 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002179
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002180 return true;
2181}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002182
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002183bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2184 // If the default channel is already used for sending create a new channel
2185 // otherwise use the default channel for sending.
2186 int channel = GetSendChannelNum(sp.first_ssrc());
2187 if (channel != -1) {
2188 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2189 return false;
2190 }
2191
2192 bool default_channel_is_available = true;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002193 for (const auto& ch : send_channels_) {
2194 if (IsDefaultChannel(ch.second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002195 default_channel_is_available = false;
2196 break;
2197 }
2198 }
2199 if (default_channel_is_available) {
2200 channel = voe_channel();
2201 } else {
2202 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002203 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002204 if (channel == -1) {
2205 LOG_RTCERR0(CreateChannel);
2206 return false;
2207 }
2208
2209 ConfigureSendChannel(channel);
2210 }
2211
2212 // Save the channel to send_channels_, so that RemoveSendStream() can still
2213 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002214 webrtc::AudioTransport* audio_transport =
2215 engine()->voe()->base()->audio_transport();
pbos8fc7fa72015-07-15 08:02:58 -07002216 send_channels_.insert(
2217 std::make_pair(sp.first_ssrc(),
2218 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002219
2220 // Set the send (local) SSRC.
2221 // If there are multiple send SSRCs, we can only set the first one here, and
2222 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2223 // (with a codec requires multiple SSRC(s)).
2224 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2225 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2226 return false;
2227 }
2228
2229 // At this point the channel's local SSRC has been updated. If the channel is
2230 // the default channel make sure that all the receive channels are updated as
2231 // well. Receive channels have to have the same SSRC as the default channel in
2232 // order to send receiver reports with this SSRC.
2233 if (IsDefaultChannel(channel)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002234 for (const auto& ch : receive_channels_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002235 // Only update the SSRC for non-default channels.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002236 if (!IsDefaultChannel(ch.second->channel())) {
2237 if (engine()->voe()->rtp()->SetLocalSSRC(ch.second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002238 sp.first_ssrc()) != 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002239 LOG_RTCERR2(SetLocalSSRC, ch.second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002240 return false;
2241 }
2242 }
2243 }
2244 }
2245
2246 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002247 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2248 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002249 }
2250
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002251 // Set the current codecs to be used for the new channel.
2252 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002253 return false;
2254
2255 return ChangeSend(channel, desired_send_);
2256}
2257
2258bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2259 ChannelMap::iterator it = send_channels_.find(ssrc);
2260 if (it == send_channels_.end()) {
2261 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2262 << " which doesn't exist.";
2263 return false;
2264 }
2265
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002266 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002267 ChangeSend(channel, SEND_NOTHING);
2268
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002269 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2270 // this will disconnect the audio renderer with the send channel.
2271 delete it->second;
2272 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002273
2274 if (IsDefaultChannel(channel)) {
2275 // Do not delete the default channel since the receive channels depend on
2276 // the default channel, recycle it instead.
2277 ChangeSend(channel, SEND_NOTHING);
2278 } else {
2279 // Clean up and delete the send channel.
2280 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2281 << " with VoiceEngine channel #" << channel << ".";
2282 if (!DeleteChannel(channel))
2283 return false;
2284 }
2285
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002286 if (send_channels_.empty())
2287 ChangeSend(SEND_NOTHING);
2288
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002289 return true;
2290}
2291
2292bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
henrikg91d6ede2015-09-17 00:24:34 -07002293 RTC_DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002294 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002295
2296 if (!VERIFY(sp.ssrcs.size() == 1))
2297 return false;
2298 uint32 ssrc = sp.first_ssrc();
2299
wu@webrtc.org78187522013-10-07 23:32:02 +00002300 if (ssrc == 0) {
2301 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2302 return false;
2303 }
2304
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002305 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2306 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002307 return false;
2308 }
2309
henrikg91d6ede2015-09-17 00:24:34 -07002310 RTC_DCHECK(receive_stream_params_.find(ssrc) == receive_stream_params_.end());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002311
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002312 // Reuse default channel for recv stream in non-conference mode call
2313 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002314 webrtc::AudioTransport* audio_transport =
2315 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002316 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002317 LOG(LS_INFO) << "Recv stream " << ssrc << " reuse default channel";
2318 default_receive_ssrc_ = ssrc;
pbos8fc7fa72015-07-15 08:02:58 -07002319 WebRtcVoiceChannelRenderer* channel_renderer =
2320 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport);
2321 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2322 receive_stream_params_[ssrc] = sp;
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002323 AddAudioReceiveStream(ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002324 return SetPlayout(voe_channel(), playout_);
2325 }
2326
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002327 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002328 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002329 if (channel == -1) {
2330 LOG_RTCERR0(CreateChannel);
2331 return false;
2332 }
2333
wu@webrtc.org78187522013-10-07 23:32:02 +00002334 if (!ConfigureRecvChannel(channel)) {
2335 DeleteChannel(channel);
2336 return false;
2337 }
2338
pbos8fc7fa72015-07-15 08:02:58 -07002339 WebRtcVoiceChannelRenderer* channel_renderer =
2340 new WebRtcVoiceChannelRenderer(channel, audio_transport);
2341 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2342 receive_stream_params_[ssrc] = sp;
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002343 AddAudioReceiveStream(ssrc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002344
2345 LOG(LS_INFO) << "New audio stream " << ssrc
2346 << " registered to VoiceEngine channel #"
2347 << channel << ".";
2348 return true;
2349}
2350
2351bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002352 // Configure to use external transport, like our default channel.
2353 if (engine()->voe()->network()->RegisterExternalTransport(
2354 channel, *this) == -1) {
2355 LOG_RTCERR2(SetExternalTransport, channel, this);
2356 return false;
2357 }
2358
2359 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002360 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002361 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2362 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002363 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002364 return false;
2365 }
2366 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002367 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002368 return false;
2369 }
2370
Minyue2013aec2015-05-13 14:14:42 +02002371 // Associate receive channel to default channel (so the receive channel can
2372 // obtain RTT from the send channel)
2373 engine()->voe()->base()->AssociateSendChannel(channel, voe_channel());
2374 LOG(LS_INFO) << "VoiceEngine channel #"
2375 << channel << " is associated with channel #"
2376 << voe_channel() << ".";
2377
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002378 // Use the same recv payload types as our default channel.
2379 ResetRecvCodecs(channel);
2380 if (!recv_codecs_.empty()) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002381 for (const auto& codec : recv_codecs_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002382 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002383 if (engine()->FindWebRtcCodec(codec, &voe_codec)) {
2384 voe_codec.pltype = codec.id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002385 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2386 if (engine()->voe()->codec()->GetRecPayloadType(
2387 voe_channel(), voe_codec) != -1) {
2388 if (engine()->voe()->codec()->SetRecPayloadType(
2389 channel, voe_codec) == -1) {
2390 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2391 return false;
2392 }
2393 }
2394 }
2395 }
2396 }
2397
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002398 if (InConferenceMode()) {
2399 // To be in par with the video, voe_channel() is not used for receiving in
2400 // a conference call.
2401 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2402 // This is the first stream in a multi user meeting. We can now
2403 // disable playback of the default stream. This since the default
2404 // stream will probably have received some initial packets before
2405 // the new stream was added. This will mean that the CN state from
2406 // the default channel will be mixed in with the other streams
2407 // throughout the whole meeting, which might be disturbing.
2408 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2409 SetPlayout(voe_channel(), false);
2410 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002411 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002412 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002413
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002414 // Set RTP header extension for the new channel.
2415 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2416 return false;
2417 }
2418
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002419 return SetPlayout(channel, playout_);
2420}
2421
2422bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
henrikg91d6ede2015-09-17 00:24:34 -07002423 RTC_DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002424 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002425 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002426 if (it == receive_channels_.end()) {
2427 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2428 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002429 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002430 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002431
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002432 RemoveAudioReceiveStream(ssrc);
pbos8fc7fa72015-07-15 08:02:58 -07002433 receive_stream_params_.erase(ssrc);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002434
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002435 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2436 // will disconnect the audio renderer with the receive channel.
2437 // Cache the channel before the deletion.
2438 const int channel = it->second->channel();
2439 delete it->second;
2440 receive_channels_.erase(it);
2441
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002442 if (ssrc == default_receive_ssrc_) {
henrikg91d6ede2015-09-17 00:24:34 -07002443 RTC_DCHECK(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002444 // Recycle the default channel is for recv stream.
2445 if (playout_)
2446 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002447
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002448 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002449 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002450 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002451
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002452 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002453 << " with VoiceEngine channel #" << channel << ".";
2454 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002455 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002456
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002457 bool enable_default_channel_playout = false;
2458 if (receive_channels_.empty()) {
2459 // The last stream was removed. We can now enable the default
2460 // channel for new channels to be played out immediately without
2461 // waiting for AddStream messages.
2462 // We do this for both conference mode and non-conference mode.
2463 // TODO(oja): Does the default channel still have it's CN state?
2464 enable_default_channel_playout = true;
2465 }
2466 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2467 default_receive_ssrc_ != 0) {
2468 // Only the default channel is active, enable the playout on default
2469 // channel.
2470 enable_default_channel_playout = true;
2471 }
2472 if (enable_default_channel_playout && playout_) {
2473 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2474 SetPlayout(voe_channel(), true);
2475 }
2476
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002477 return true;
2478}
2479
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002480bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2481 AudioRenderer* renderer) {
2482 ChannelMap::iterator it = receive_channels_.find(ssrc);
2483 if (it == receive_channels_.end()) {
2484 if (renderer) {
2485 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002486 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002487 return false;
2488 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002489
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002490 // The channel likely has gone away, do nothing.
2491 return true;
2492 }
2493
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002494 if (renderer)
2495 it->second->Start(renderer);
2496 else
2497 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002498
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002499 return true;
2500}
2501
2502bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2503 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002504 ChannelMap::iterator it = send_channels_.find(ssrc);
2505 if (it == send_channels_.end()) {
2506 if (renderer) {
2507 // Return an error if trying to set a valid renderer with an invalid ssrc.
2508 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2509 return false;
2510 }
2511
2512 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002513 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002514 }
2515
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002516 if (renderer)
2517 it->second->Start(renderer);
2518 else
2519 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002520
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002521 return true;
2522}
2523
2524bool WebRtcVoiceMediaChannel::GetActiveStreams(
2525 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002526 // In conference mode, the default channel should not be in
2527 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002528 actives->clear();
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002529 for (const auto& ch : receive_channels_) {
2530 int level = GetOutputLevel(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002531 if (level > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002532 actives->push_back(std::make_pair(ch.first, level));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002533 }
2534 }
2535 return true;
2536}
2537
2538int WebRtcVoiceMediaChannel::GetOutputLevel() {
2539 // return the highest output level of all streams
2540 int highest = GetOutputLevel(voe_channel());
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002541 for (const auto& ch : receive_channels_) {
2542 int level = GetOutputLevel(ch.second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002543 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002544 }
2545 return highest;
2546}
2547
2548int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2549 int ret;
2550 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2551 // In case of error, log the info and continue
2552 LOG_RTCERR0(TimeSinceLastTyping);
2553 ret = -1;
2554 } else {
2555 ret *= 1000; // We return ms, webrtc returns seconds.
2556 }
2557 return ret;
2558}
2559
2560void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2561 int cost_per_typing, int reporting_threshold, int penalty_decay,
2562 int type_event_delay) {
2563 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2564 time_window, cost_per_typing,
2565 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2566 // In case of error, log the info and continue
2567 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2568 cost_per_typing, reporting_threshold, penalty_decay,
2569 type_event_delay);
2570 }
2571}
2572
2573bool WebRtcVoiceMediaChannel::SetOutputScaling(
2574 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002575 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002576 // Collect the channels to scale the output volume.
2577 std::vector<int> channels;
2578 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002579 // Default channel is not in receive_channels_ if it is not being used for
2580 // playout.
2581 if (default_receive_ssrc_ == 0)
2582 channels.push_back(voe_channel());
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002583 for (const auto& ch : receive_channels_) {
2584 channels.push_back(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002585 }
2586 } else { // Collect only the channel of the specified ssrc.
2587 int channel = GetReceiveChannelNum(ssrc);
2588 if (-1 == channel) {
2589 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2590 return false;
2591 }
2592 channels.push_back(channel);
2593 }
2594
2595 // Scale the output volume for the collected channels. We first normalize to
2596 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002597 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002598 if (scale > 0.0001f) {
2599 left /= scale;
2600 right /= scale;
2601 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002602 for (int ch_id : channels) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002603 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002604 ch_id, scale)) {
2605 LOG_RTCERR2(SetChannelOutputVolumeScaling, ch_id, scale);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002606 return false;
2607 }
2608 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002609 ch_id, static_cast<float>(left), static_cast<float>(right))) {
2610 LOG_RTCERR3(SetOutputVolumePan, ch_id, left, right);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002611 // Do not return if fails. SetOutputVolumePan is not available for all
2612 // pltforms.
2613 }
2614 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2615 << " right=" << right * scale
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002616 << " for channel " << ch_id << " and ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002617 }
2618 return true;
2619}
2620
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002621bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2622 return dtmf_allowed_;
2623}
2624
2625bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2626 int duration, int flags) {
2627 if (!dtmf_allowed_) {
2628 return false;
2629 }
2630
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002631 // Send the event.
2632 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002633 int channel = -1;
2634 if (ssrc == 0) {
2635 bool default_channel_is_inuse = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002636 for (const auto& ch : send_channels_) {
2637 if (IsDefaultChannel(ch.second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002638 default_channel_is_inuse = true;
2639 break;
2640 }
2641 }
2642 if (default_channel_is_inuse) {
2643 channel = voe_channel();
2644 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002645 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002646 }
2647 } else {
2648 channel = GetSendChannelNum(ssrc);
2649 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002650 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002651 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2652 << ssrc << " is not in use.";
2653 return false;
2654 }
2655 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002656 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2657 channel, event, true, duration) == -1) {
2658 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002659 return false;
2660 }
2661 }
2662
2663 // Play the event.
2664 if (flags & cricket::DF_PLAY) {
2665 // Play DTMF tone locally.
2666 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
2667 LOG_RTCERR2(PlayDtmfTone, event, duration);
2668 return false;
2669 }
2670 }
2671
2672 return true;
2673}
2674
wu@webrtc.orga9890802013-12-13 00:21:03 +00002675void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002676 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrikg91d6ede2015-09-17 00:24:34 -07002677 RTC_DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002678
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002679 // Forward packet to Call as well.
2680 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2681 packet_time.not_before);
2682 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
2683 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
2684 webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002685
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002686 // Pick which channel to send this packet to. If this packet doesn't match
2687 // any multiplexed streams, just send it to the default channel. Otherwise,
2688 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002689 int which_channel =
2690 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002691 if (which_channel == -1) {
2692 which_channel = voe_channel();
2693 }
2694
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002695 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002696 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002697 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002698 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002699}
2700
wu@webrtc.orga9890802013-12-13 00:21:03 +00002701void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002702 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrikg91d6ede2015-09-17 00:24:34 -07002703 RTC_DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002704
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002705 // Forward packet to Call as well.
2706 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2707 packet_time.not_before);
2708 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
2709 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
2710 webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002711
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002712 // Sending channels need all RTCP packets with feedback information.
2713 // Even sender reports can contain attached report blocks.
2714 // Receiving channels need sender reports in order to create
2715 // correct receiver reports.
2716 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002717 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002718 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2719 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002720 }
2721
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002722 // If it is a sender report, find the channel that is listening.
2723 bool has_sent_to_default_channel = false;
2724 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002725 int which_channel =
2726 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002727 if (which_channel != -1) {
2728 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002729 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002730
2731 if (IsDefaultChannel(which_channel))
2732 has_sent_to_default_channel = true;
2733 }
2734 }
2735
2736 // SR may continue RR and any RR entry may correspond to any one of the send
2737 // channels. So all RTCP packets must be forwarded all send channels. VoE
2738 // will filter out RR internally.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002739 for (const auto& ch : send_channels_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002740 // Make sure not sending the same packet to default channel more than once.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002741 if (IsDefaultChannel(ch.second->channel()) &&
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002742 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002743 continue;
2744
2745 engine()->voe()->network()->ReceivedRTCPPacket(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002746 ch.second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002747 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002748}
2749
2750bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002751 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
2752 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002753 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2754 return false;
2755 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002756 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
2757 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002758 return false;
2759 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002760 // We set the AGC to mute state only when all the channels are muted.
2761 // This implementation is not ideal, instead we should signal the AGC when
2762 // the mic channel is muted/unmuted. We can't do it today because there
2763 // is no good way to know which stream is mapping to the mic channel.
2764 bool all_muted = muted;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002765 for (const auto& ch : send_channels_) {
2766 if (!all_muted) {
2767 break;
2768 }
2769 if (engine()->voe()->volume()->GetInputMute(ch.second->channel(),
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002770 all_muted)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002771 LOG_RTCERR1(GetInputMute, ch.second->channel());
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002772 return false;
2773 }
2774 }
2775
2776 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
2777 if (ap)
2778 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002779 return true;
2780}
2781
minyue@webrtc.org26236952014-10-29 02:27:08 +00002782// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
2783// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002784bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002785 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002786
minyue@webrtc.org26236952014-10-29 02:27:08 +00002787 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002788}
2789
minyue@webrtc.org26236952014-10-29 02:27:08 +00002790bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
2791 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002792
minyue@webrtc.org26236952014-10-29 02:27:08 +00002793 send_bitrate_setting_ = true;
2794 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002795
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002796 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002797 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002798 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002799 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002800 }
2801
minyue@webrtc.org26236952014-10-29 02:27:08 +00002802 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002803 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
2804 // SetMaxSendBandwith(0), the second call removes the previous limit.
2805 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002806 return true;
2807
2808 webrtc::CodecInst codec = *send_codec_;
2809 bool is_multi_rate = IsCodecMultiRate(codec);
2810
2811 if (is_multi_rate) {
2812 // If codec is multi-rate then just set the bitrate.
2813 codec.rate = bps;
2814 if (!SetSendCodec(codec)) {
2815 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2816 << " to bitrate " << bps << " bps.";
2817 return false;
2818 }
2819 return true;
2820 } else {
2821 // If codec is not multi-rate and |bps| is less than the fixed bitrate
2822 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
2823 // fixed bitrate then ignore.
2824 if (bps < codec.rate) {
2825 LOG(LS_INFO) << "Failed to set codec " << codec.plname
2826 << " to bitrate " << bps << " bps"
2827 << ", requires at least " << codec.rate << " bps.";
2828 return false;
2829 }
2830 return true;
2831 }
2832}
2833
2834bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002835 bool echo_metrics_on = false;
2836 // These can take on valid negative values, so use the lowest possible level
2837 // as default rather than -1.
2838 int echo_return_loss = -100;
2839 int echo_return_loss_enhancement = -100;
2840 // These can also be negative, but in practice -1 is only used to signal
2841 // insufficient data, since the resolution is limited to multiples of 4 ms.
2842 int echo_delay_median_ms = -1;
2843 int echo_delay_std_ms = -1;
2844 if (engine()->voe()->processing()->GetEcMetricsStatus(
2845 echo_metrics_on) != -1 && echo_metrics_on) {
2846 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
2847 // here, but it appears to be unsuitable currently. Revisit after this is
2848 // investigated: http://b/issue?id=5666755
2849 int erl, erle, rerl, anlp;
2850 if (engine()->voe()->processing()->GetEchoMetrics(
2851 erl, erle, rerl, anlp) != -1) {
2852 echo_return_loss = erl;
2853 echo_return_loss_enhancement = erle;
2854 }
2855
2856 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00002857 float dummy;
2858 if (engine()->voe()->processing()->GetEcDelayMetrics(
2859 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002860 echo_delay_median_ms = median;
2861 echo_delay_std_ms = std;
2862 }
2863 }
2864
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002865 webrtc::CallStatistics cs;
2866 unsigned int ssrc;
2867 webrtc::CodecInst codec;
2868 unsigned int level;
2869
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002870 for (const auto& ch : send_channels_) {
2871 const int channel = ch.second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002872
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002873 // Fill in the sender info, based on what we know, and what the
2874 // remote side told us it got from its RTCP report.
2875 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002876
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002877 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
2878 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
2879 continue;
2880 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002881
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002882 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002883 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
2884 sinfo.bytes_sent = cs.bytesSent;
2885 sinfo.packets_sent = cs.packetsSent;
2886 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
2887 // returns 0 to indicate an error value.
2888 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
2889
2890 // Get data from the last remote RTCP report. Use default values if no data
2891 // available.
2892 sinfo.fraction_lost = -1.0;
2893 sinfo.jitter_ms = -1;
2894 sinfo.packets_lost = -1;
2895 sinfo.ext_seqnum = -1;
2896 std::vector<webrtc::ReportBlock> receive_blocks;
2897 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
2898 channel, &receive_blocks) != -1 &&
2899 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002900 for (const webrtc::ReportBlock& block : receive_blocks) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002901 // Lookup report for send ssrc only.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002902 if (block.source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002903 // Convert Q8 to floating point.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002904 sinfo.fraction_lost = static_cast<float>(block.fraction_lost) / 256;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002905 // Convert samples to milliseconds.
2906 if (codec.plfreq / 1000 > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002907 sinfo.jitter_ms = block.interarrival_jitter / (codec.plfreq / 1000);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002908 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002909 sinfo.packets_lost = block.cumulative_num_packets_lost;
2910 sinfo.ext_seqnum = block.extended_highest_sequence_number;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002911 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002912 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002913 }
2914 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002915
2916 // Local speech level.
2917 sinfo.audio_level = (engine()->voe()->volume()->
2918 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
2919
2920 // TODO(xians): We are injecting the same APM logging to all the send
2921 // channels here because there is no good way to know which send channel
2922 // is using the APM. The correct fix is to allow the send channels to have
2923 // their own APM so that we can feed the correct APM logging to different
2924 // send channels. See issue crbug/264611 .
2925 sinfo.echo_return_loss = echo_return_loss;
2926 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
2927 sinfo.echo_delay_median_ms = echo_delay_median_ms;
2928 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00002929 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
2930 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00002931 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002932
2933 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002934 }
2935
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002936 // Build the list of receivers, one for each receiving channel, or 1 in
2937 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002938 std::vector<int> channels;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002939 for (const auto& ch : receive_channels_) {
2940 channels.push_back(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002941 }
2942 if (channels.empty()) {
2943 channels.push_back(voe_channel());
2944 }
2945
2946 // Get the SSRC and stats for each receiver, based on our own calculations.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002947 for (int ch_id : channels) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002948 memset(&cs, 0, sizeof(cs));
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002949 if (engine()->voe()->rtp()->GetRemoteSSRC(ch_id, ssrc) != -1 &&
2950 engine()->voe()->rtp()->GetRTCPStatistics(ch_id, cs) != -1 &&
2951 engine()->voe()->codec()->GetRecCodec(ch_id, codec) != -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002952 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002953 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002954 rinfo.bytes_rcvd = cs.bytesReceived;
2955 rinfo.packets_rcvd = cs.packetsReceived;
2956 // The next four fields are from the most recently sent RTCP report.
2957 // Convert Q8 to floating point.
2958 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
2959 rinfo.packets_lost = cs.cumulativeLost;
2960 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00002961 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00002962 if (codec.pltype != -1) {
2963 rinfo.codec_name = codec.plname;
2964 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002965 // Convert samples to milliseconds.
2966 if (codec.plfreq / 1000 > 0) {
2967 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
2968 }
2969
2970 // Get jitter buffer and total delay (alg + jitter + playout) stats.
2971 webrtc::NetworkStatistics ns;
2972 if (engine()->voe()->neteq() &&
2973 engine()->voe()->neteq()->GetNetworkStatistics(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002974 ch_id, ns) != -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002975 rinfo.jitter_buffer_ms = ns.currentBufferSize;
2976 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
2977 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002978 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00002979 rinfo.speech_expand_rate =
2980 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
2981 rinfo.secondary_decoded_rate =
2982 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
Henrik Lundin8e6fd462015-06-02 09:24:52 +02002983 rinfo.accelerate_rate =
2984 static_cast<float>(ns.currentAccelerateRate) / (1 << 14);
2985 rinfo.preemptive_expand_rate =
2986 static_cast<float>(ns.currentPreemptiveRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002987 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00002988
2989 webrtc::AudioDecodingCallStats ds;
2990 if (engine()->voe()->neteq() &&
2991 engine()->voe()->neteq()->GetDecodingCallStatistics(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002992 ch_id, &ds) != -1) {
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00002993 rinfo.decoding_calls_to_silence_generator =
2994 ds.calls_to_silence_generator;
2995 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
2996 rinfo.decoding_normal = ds.decoded_normal;
2997 rinfo.decoding_plc = ds.decoded_plc;
2998 rinfo.decoding_cng = ds.decoded_cng;
2999 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3000 }
3001
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003002 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003003 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003004 int playout_buffer_delay_ms = 0;
3005 engine()->voe()->sync()->GetDelayEstimate(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003006 ch_id, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003007 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3008 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003009 }
3010
3011 // Get speech level.
3012 rinfo.audio_level = (engine()->voe()->volume()->
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003013 GetSpeechOutputLevelFullRange(ch_id, level) != -1) ? level : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003014 info->receivers.push_back(rinfo);
3015 }
3016 }
3017
3018 return true;
3019}
3020
3021void WebRtcVoiceMediaChannel::GetLastMediaError(
3022 uint32* ssrc, VoiceMediaChannel::Error* error) {
henrikg91d6ede2015-09-17 00:24:34 -07003023 RTC_DCHECK(ssrc != NULL);
3024 RTC_DCHECK(error != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003025 FindSsrc(voe_channel(), ssrc);
3026 *error = WebRtcErrorToChannelError(GetLastEngineError());
3027}
3028
3029bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003030 rtc::CritScope lock(&receive_channels_cs_);
henrikg91d6ede2015-09-17 00:24:34 -07003031 RTC_DCHECK(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003032 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003033 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3034 // This means the error is not limited to a specific channel. Signal the
3035 // message using ssrc=0. If the current channel is sending, use this
3036 // channel for sending the message.
3037 *ssrc = 0;
3038 return true;
3039 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003040 // Check whether this is a sending channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003041 for (const auto& ch : send_channels_) {
3042 if (ch.second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003043 // This is a sending channel.
3044 uint32 local_ssrc = 0;
3045 if (engine()->voe()->rtp()->GetLocalSSRC(
3046 channel_num, local_ssrc) != -1) {
3047 *ssrc = local_ssrc;
3048 }
3049 return true;
3050 }
3051 }
3052
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003053 // Check whether this is a receiving channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003054 for (const auto& ch : receive_channels_) {
3055 if (ch.second->channel() == channel_num) {
3056 *ssrc = ch.first;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003057 return true;
3058 }
3059 }
3060 }
3061 return false;
3062}
3063
3064void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003065 if (error == VE_TYPING_NOISE_WARNING) {
3066 typing_noise_detected_ = true;
3067 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3068 typing_noise_detected_ = false;
3069 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003070 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3071}
3072
3073int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3074 unsigned int ulevel;
3075 int ret =
3076 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3077 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3078}
3079
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003080int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) const {
3081 ChannelMap::const_iterator it = receive_channels_.find(ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003082 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003083 return it->second->channel();
pbos8fc7fa72015-07-15 08:02:58 -07003084 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003085}
3086
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003087int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) const {
3088 ChannelMap::const_iterator it = send_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003089 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003090 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003091
3092 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003093}
3094
3095bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3096 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3097 // Get the RED encodings from the parameter with no name. This may
3098 // change based on what is discussed on the Jingle list.
3099 // The encoding parameter is of the form "a/b"; we only support where
3100 // a == b. Verify this and parse out the value into red_pt.
3101 // If the parameter value is absent (as it will be until we wire up the
3102 // signaling of this message), use the second codec specified (i.e. the
3103 // one after "red") as the encoding parameter.
3104 int red_pt = -1;
3105 std::string red_params;
3106 CodecParameterMap::const_iterator it = red_codec.params.find("");
3107 if (it != red_codec.params.end()) {
3108 red_params = it->second;
3109 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003110 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003111 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003112 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003113 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3114 return false;
3115 }
3116 } else if (red_codec.params.empty()) {
3117 LOG(LS_WARNING) << "RED params not present, using defaults";
3118 if (all_codecs.size() > 1) {
3119 red_pt = all_codecs[1].id;
3120 }
3121 }
3122
3123 // Try to find red_pt in |codecs|.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003124 for (const AudioCodec& codec : all_codecs) {
3125 if (codec.id == red_pt) {
3126 // If we find the right codec, that will be the codec we pass to
3127 // SetSendCodec, with the desired payload type.
3128 if (engine()->FindWebRtcCodec(codec, send_codec)) {
3129 return true;
3130 } else {
3131 break;
3132 }
3133 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003134 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003135 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3136 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003137}
3138
3139bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3140 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003141 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003142 return false;
3143 }
3144 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3145 // what we want to do with them.
3146 // engine()->voe().EnableVQMon(voe_channel(), true);
3147 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3148 return true;
3149}
3150
3151bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3152 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3153 for (int i = 0; i < ncodecs; ++i) {
3154 webrtc::CodecInst voe_codec;
3155 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3156 voe_codec.pltype = -1;
3157 if (engine()->voe()->codec()->SetRecPayloadType(
3158 channel, voe_codec) == -1) {
3159 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3160 return false;
3161 }
3162 }
3163 }
3164 return true;
3165}
3166
3167bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3168 if (playout) {
3169 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3170 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3171 LOG_RTCERR1(StartPlayout, channel);
3172 return false;
3173 }
3174 } else {
3175 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3176 engine()->voe()->base()->StopPlayout(channel);
3177 }
3178 return true;
3179}
3180
3181uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3182 bool rtcp) {
3183 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3184 uint32 ssrc = 0;
3185 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003186 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003187 }
3188 return ssrc;
3189}
3190
3191// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3192VoiceMediaChannel::Error
3193 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3194 switch (err_code) {
3195 case 0:
3196 return ERROR_NONE;
3197 case VE_CANNOT_START_RECORDING:
3198 case VE_MIC_VOL_ERROR:
3199 case VE_GET_MIC_VOL_ERROR:
3200 case VE_CANNOT_ACCESS_MIC_VOL:
3201 return ERROR_REC_DEVICE_OPEN_FAILED;
3202 case VE_SATURATION_WARNING:
3203 return ERROR_REC_DEVICE_SATURATION;
3204 case VE_REC_DEVICE_REMOVED:
3205 return ERROR_REC_DEVICE_REMOVED;
3206 case VE_RUNTIME_REC_WARNING:
3207 case VE_RUNTIME_REC_ERROR:
3208 return ERROR_REC_RUNTIME_ERROR;
3209 case VE_CANNOT_START_PLAYOUT:
3210 case VE_SPEAKER_VOL_ERROR:
3211 case VE_GET_SPEAKER_VOL_ERROR:
3212 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3213 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3214 case VE_RUNTIME_PLAY_WARNING:
3215 case VE_RUNTIME_PLAY_ERROR:
3216 return ERROR_PLAY_RUNTIME_ERROR;
3217 case VE_TYPING_NOISE_WARNING:
3218 return ERROR_REC_TYPING_NOISE_DETECTED;
3219 default:
3220 return VoiceMediaChannel::ERROR_OTHER;
3221 }
3222}
3223
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003224bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3225 int channel_id, const RtpHeaderExtension* extension) {
3226 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003227 int id = 0;
3228 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003229 if (extension) {
3230 enable = true;
3231 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003232 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003233 }
3234 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003235 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003236 return false;
3237 }
3238 return true;
3239}
3240
Fredrik Solenberg709ed672015-09-15 12:26:33 +02003241void WebRtcVoiceMediaChannel::RecreateAudioReceiveStreams() {
henrikg91d6ede2015-09-17 00:24:34 -07003242 RTC_DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg709ed672015-09-15 12:26:33 +02003243 for (const auto& it : receive_channels_) {
3244 RemoveAudioReceiveStream(it.first);
3245 }
3246 for (const auto& it : receive_channels_) {
3247 AddAudioReceiveStream(it.first);
3248 }
3249}
3250
3251void WebRtcVoiceMediaChannel::AddAudioReceiveStream(uint32 ssrc) {
henrikg91d6ede2015-09-17 00:24:34 -07003252 RTC_DCHECK(thread_checker_.CalledOnValidThread());
pbos8fc7fa72015-07-15 08:02:58 -07003253 WebRtcVoiceChannelRenderer* channel = receive_channels_[ssrc];
henrikg91d6ede2015-09-17 00:24:34 -07003254 RTC_DCHECK(channel != nullptr);
3255 RTC_DCHECK(receive_streams_.find(ssrc) == receive_streams_.end());
pbos8fc7fa72015-07-15 08:02:58 -07003256 webrtc::AudioReceiveStream::Config config;
3257 config.rtp.remote_ssrc = ssrc;
3258 // Only add RTP extensions if we support combined A/V BWE.
pbos6bb1b6e2015-07-24 07:10:18 -07003259 config.rtp.extensions = recv_rtp_extensions_;
3260 config.combined_audio_video_bwe =
3261 options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false);
pbos8fc7fa72015-07-15 08:02:58 -07003262 config.voe_channel_id = channel->channel();
3263 config.sync_group = receive_stream_params_[ssrc].sync_label;
3264 webrtc::AudioReceiveStream* s = call_->CreateAudioReceiveStream(config);
3265 receive_streams_.insert(std::make_pair(ssrc, s));
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003266}
3267
Fredrik Solenberg709ed672015-09-15 12:26:33 +02003268void WebRtcVoiceMediaChannel::RemoveAudioReceiveStream(uint32 ssrc) {
henrikg91d6ede2015-09-17 00:24:34 -07003269 RTC_DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg709ed672015-09-15 12:26:33 +02003270 auto stream_it = receive_streams_.find(ssrc);
3271 if (stream_it != receive_streams_.end()) {
3272 call_->DestroyAudioReceiveStream(stream_it->second);
3273 receive_streams_.erase(stream_it);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003274 }
3275}
3276
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003277bool WebRtcVoiceMediaChannel::SetRecvCodecsInternal(
3278 const std::vector<AudioCodec>& new_codecs) {
3279 for (const AudioCodec& codec : new_codecs) {
3280 webrtc::CodecInst voe_codec;
3281 if (engine()->FindWebRtcCodec(codec, &voe_codec)) {
3282 LOG(LS_INFO) << ToString(codec);
3283 voe_codec.pltype = codec.id;
3284 if (default_receive_ssrc_ == 0) {
3285 // Set the receive codecs on the default channel explicitly if the
3286 // default channel is not used by |receive_channels_|, this happens in
3287 // conference mode or in non-conference mode when there is no playout
3288 // channel.
3289 // TODO(xians): Figure out how we use the default channel in conference
3290 // mode.
3291 if (engine()->voe()->codec()->SetRecPayloadType(
3292 voe_channel(), voe_codec) == -1) {
3293 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
3294 return false;
3295 }
3296 }
3297
3298 // Set the receive codecs on all receiving channels.
3299 for (const auto& ch : receive_channels_) {
3300 if (engine()->voe()->codec()->SetRecPayloadType(
3301 ch.second->channel(), voe_codec) == -1) {
3302 LOG_RTCERR2(SetRecPayloadType, ch.second->channel(),
3303 ToString(voe_codec));
3304 return false;
3305 }
3306 }
3307 } else {
3308 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
3309 return false;
3310 }
3311 }
3312 return true;
3313}
3314
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003315} // namespace cricket
3316
3317#endif // HAVE_WEBRTC_VOICE