blob: 642fd3d233e649ecbcb989a85391176b1761e0dc [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"
45#include "talk/media/base/voiceprocessor.h"
46#include "talk/media/webrtc/webrtcvoe.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000047#include "webrtc/base/base64.h"
48#include "webrtc/base/byteorder.h"
49#include "webrtc/base/common.h"
50#include "webrtc/base/helpers.h"
51#include "webrtc/base/logging.h"
52#include "webrtc/base/stringencode.h"
53#include "webrtc/base/stringutils.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000054#include "webrtc/common.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055#include "webrtc/modules/audio_processing/include/audio_processing.h"
56
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057namespace cricket {
58
Brave Yao5225dd82015-03-26 07:39:19 +080059static const int kMaxNumPacketSize = 6;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000060struct CodecPref {
61 const char* name;
62 int clockrate;
63 int channels;
64 int payload_type;
65 bool is_multi_rate;
Brave Yao5225dd82015-03-26 07:39:19 +080066 int packet_sizes_ms[kMaxNumPacketSize];
henrike@webrtc.org28e20752013-07-10 00:45:36 +000067};
Brave Yao5225dd82015-03-26 07:39:19 +080068// Note: keep the supported packet sizes in ascending order.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000069static const CodecPref kCodecPrefs[] = {
Brave Yao5225dd82015-03-26 07:39:19 +080070 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
71 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
72 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +000073 // G722 should be advertised as 8000 Hz because of the RFC "bug".
Brave Yao5225dd82015-03-26 07:39:19 +080074 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
75 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
76 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
77 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
Brave Yao5225dd82015-03-26 07:39:19 +080078 { kCnCodecName, 32000, 1, 106, false, { } },
79 { kCnCodecName, 16000, 1, 105, false, { } },
80 { kCnCodecName, 8000, 1, 13, false, { } },
81 { kRedCodecName, 8000, 1, 127, false, { } },
82 { kDtmfCodecName, 8000, 1, 126, false, { } },
henrike@webrtc.org28e20752013-07-10 00:45:36 +000083};
84
85// For Linux/Mac, using the default device is done by specifying index 0 for
86// VoE 4.0 and not -1 (which was the case for VoE 3.5).
87//
88// On Windows Vista and newer, Microsoft introduced the concept of "Default
89// Communications Device". This means that there are two types of default
90// devices (old Wave Audio style default and Default Communications Device).
91//
92// On Windows systems which only support Wave Audio style default, uses either
93// -1 or 0 to select the default device.
94//
95// On Windows systems which support both "Default Communication Device" and
96// old Wave Audio style default, use -1 for Default Communications Device and
97// -2 for Wave Audio style default, which is what we want to use for clips.
98// It's not clear yet whether the -2 index is handled properly on other OSes.
99
100#ifdef WIN32
101static const int kDefaultAudioDeviceId = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102#else
103static const int kDefaultAudioDeviceId = 0;
104#endif
105
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106// Parameter used for NACK.
107// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
108static const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000109
110// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000111// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000112
113// Recommended bitrates:
114// 8-12 kb/s for NB speech,
115// 16-20 kb/s for WB speech,
116// 28-40 kb/s for FB speech,
117// 48-64 kb/s for FB mono music, and
118// 64-128 kb/s for FB stereo music.
119// The current implementation applies the following values to mono signals,
120// and multiplies them by 2 for stereo.
121static const int kOpusBitrateNb = 12000;
122static const int kOpusBitrateWb = 20000;
123static const int kOpusBitrateFb = 32000;
124
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000125// Opus bitrate should be in the range between 6000 and 510000.
126static const int kOpusMinBitrate = 6000;
127static const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000128
wu@webrtc.orgde305012013-10-31 15:40:38 +0000129// Default audio dscp value.
130// See http://tools.ietf.org/html/rfc2474 for details.
131// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000132static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000133
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000134// Ensure we open the file in a writeable path on ChromeOS and Android. This
135// workaround can be removed when it's possible to specify a filename for audio
136// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000137//
138// TODO(grunell): Use a string in the options instead of hardcoding it here
139// and let the embedder choose the filename (crbug.com/264223).
140//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000141// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
142// below.
143#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000144static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000145#elif defined(ANDROID)
146static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000147#else
148static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
149#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000150
151// Dumps an AudioCodec in RFC 2327-ish format.
152static std::string ToString(const AudioCodec& codec) {
153 std::stringstream ss;
154 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
155 << " (" << codec.id << ")";
156 return ss.str();
157}
Minyue Li7100dcd2015-03-27 05:05:59 +0100158
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000159static std::string ToString(const webrtc::CodecInst& codec) {
160 std::stringstream ss;
161 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
162 << " (" << codec.pltype << ")";
163 return ss.str();
164}
165
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000166static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000167 const char* delim = "\r\n";
168 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
169 LOG_V(sev) << tok;
170 }
171}
172
173// Severity is an integer because it comes is assumed to be from command line.
174static int SeverityToFilter(int severity) {
175 int filter = webrtc::kTraceNone;
176 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000177 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000178 filter |= webrtc::kTraceAll;
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200179 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000180 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000181 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200182 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000183 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000184 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200185 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000186 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000187 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
188 }
189 return filter;
190}
191
Minyue Li7100dcd2015-03-27 05:05:59 +0100192static bool IsCodec(const AudioCodec& codec, const char* ref_name) {
193 return (_stricmp(codec.name.c_str(), ref_name) == 0);
194}
195
196static bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
197 return (_stricmp(codec.plname, ref_name) == 0);
198}
199
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000200static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
201 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100202 if (IsCodec(codec, kCodecPrefs[i].name) &&
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000203 kCodecPrefs[i].clockrate == codec.plfreq) {
204 return kCodecPrefs[i].is_multi_rate;
205 }
206 }
207 return false;
208}
209
210static bool FindCodec(const std::vector<AudioCodec>& codecs,
211 const AudioCodec& codec,
212 AudioCodec* found_codec) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200213 for (const AudioCodec& c : codecs) {
214 if (c.Matches(codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000215 if (found_codec != NULL) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200216 *found_codec = c;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000217 }
218 return true;
219 }
220 }
221 return false;
222}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000223
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000224static bool IsNackEnabled(const AudioCodec& codec) {
225 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
226 kParamValueEmpty));
227}
228
Brave Yao5225dd82015-03-26 07:39:19 +0800229static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
230 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
231 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
232 if (packet_size_ms && packet_size_ms <= ptime_ms) {
233 selected_packet_size_ms = packet_size_ms;
234 }
235 }
236 return selected_packet_size_ms;
237}
238
239// If the AudioCodec param kCodecParamPTime is set, then we will set it to codec
240// pacsize if it's valid, or we will pick the next smallest value we support.
241// TODO(Brave): Query supported packet sizes from ACM when the API is ready.
242static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
243 for (const CodecPref& codec_pref : kCodecPrefs) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100244 if ((IsCodec(*codec, codec_pref.name) &&
Brave Yao5225dd82015-03-26 07:39:19 +0800245 codec_pref.clockrate == codec->plfreq) ||
Minyue Li7100dcd2015-03-27 05:05:59 +0100246 IsCodec(*codec, kG722CodecName)) {
Brave Yao5225dd82015-03-26 07:39:19 +0800247 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
248 if (packet_size_ms) {
249 // Convert unit from milli-seconds to samples.
250 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
251 return true;
252 }
253 }
254 }
255 return false;
256}
257
Minyue Li7100dcd2015-03-27 05:05:59 +0100258// Return true if codec.params[feature] == "1", false otherwise.
259static bool IsCodecFeatureEnabled(const AudioCodec& codec,
260 const char* feature) {
261 int value;
262 return codec.GetParam(feature, &value) && value == 1;
263}
264
265// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
266// otherwise. If the value (either from params or codec.bitrate) <=0, use the
267// default configuration. If the value is beyond feasible bit rate of Opus,
268// clamp it. Returns the Opus bit rate for operation.
269static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
270 int bitrate = 0;
271 bool use_param = true;
272 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
273 bitrate = codec.bitrate;
274 use_param = false;
275 }
276 if (bitrate <= 0) {
277 if (max_playback_rate <= 8000) {
278 bitrate = kOpusBitrateNb;
279 } else if (max_playback_rate <= 16000) {
280 bitrate = kOpusBitrateWb;
281 } else {
282 bitrate = kOpusBitrateFb;
283 }
284
285 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
286 bitrate *= 2;
287 }
288 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
289 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
290 std::string rate_source =
291 use_param ? "Codec parameter \"maxaveragebitrate\"" :
292 "Supplied Opus bitrate";
293 LOG(LS_WARNING) << rate_source
294 << " is invalid and is replaced by: "
295 << bitrate;
296 }
297 return bitrate;
298}
299
300// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
301// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
302static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
303 int value;
304 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
305 return value;
306 }
307 return kOpusDefaultMaxPlaybackRate;
308}
309
310static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
311 bool* enable_codec_fec, int* max_playback_rate,
312 bool* enable_codec_dtx) {
313 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
314 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
315 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
316
317 // If OPUS, change what we send according to the "stereo" codec
318 // parameter, and not the "channels" parameter. We set
319 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
320 // the bitrate is not specified, i.e. is <= zero, we set it to the
321 // appropriate default value for mono or stereo Opus.
322
323 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
324 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
325}
326
327// Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
328// which says that G722 should be advertised as 8 kHz although it is a 16 kHz
329// codec.
330static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
331 if (IsCodec(*voe_codec, kG722CodecName)) {
332 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
333 // has changed, and this special case is no longer needed.
henrikg91d6ede2015-09-17 00:24:34 -0700334 RTC_DCHECK(voe_codec->plfreq != new_plfreq);
Minyue Li7100dcd2015-03-27 05:05:59 +0100335 voe_codec->plfreq = new_plfreq;
336 }
337}
338
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000339// Gets the default set of options applied to the engine. Historically, these
340// were supplied as a combination of flags from the channel manager (ec, agc,
341// ns, and highpass) and the rest hardcoded in InitInternal.
342static AudioOptions GetDefaultEngineOptions() {
343 AudioOptions options;
344 options.echo_cancellation.Set(true);
345 options.auto_gain_control.Set(true);
346 options.noise_suppression.Set(true);
347 options.highpass_filter.Set(true);
348 options.stereo_swapping.Set(false);
Henrik Lundin64dad832015-05-11 12:44:23 +0200349 options.audio_jitter_buffer_max_packets.Set(50);
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200350 options.audio_jitter_buffer_fast_accelerate.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000351 options.typing_detection.Set(true);
352 options.conference_mode.Set(false);
353 options.adjust_agc_delta.Set(0);
354 options.experimental_agc.Set(false);
Henrik Lundin441f6342015-06-09 16:03:13 +0200355 options.extended_filter_aec.Set(false);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100356 options.delay_agnostic_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000357 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000358 options.aec_dump.Set(false);
359 return options;
360}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000361
Minyue Li7100dcd2015-03-27 05:05:59 +0100362static std::string GetEnableString(bool enable) {
363 return enable ? "enable" : "disable";
Brave Yao5225dd82015-03-26 07:39:19 +0800364}
365
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000366WebRtcVoiceEngine::WebRtcVoiceEngine()
367 : voe_wrapper_(new VoEWrapper()),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000368 tracing_(new VoETraceWrapper()),
369 adm_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000370 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
371 is_dumping_aec_(false),
372 desired_local_monitor_enable_(false),
373 tx_processor_ssrc_(0),
374 rx_processor_ssrc_(0) {
375 Construct();
376}
377
378WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000379 VoETraceWrapper* tracing)
380 : voe_wrapper_(voe_wrapper),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000381 tracing_(tracing),
382 adm_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000383 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
384 is_dumping_aec_(false),
385 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000386 tx_processor_ssrc_(0),
387 rx_processor_ssrc_(0) {
388 Construct();
389}
390
391void WebRtcVoiceEngine::Construct() {
392 SetTraceFilter(log_filter_);
393 initialized_ = false;
394 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
395 SetTraceOptions("");
396 if (tracing_->SetTraceCallback(this) == -1) {
397 LOG_RTCERR0(SetTraceCallback);
398 }
399 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
400 LOG_RTCERR0(RegisterVoiceEngineObserver);
401 }
402 // Clear the default agc state.
403 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
404
405 // Load our audio codec list.
406 ConstructCodecs();
407
408 // Load our RTP Header extensions.
409 rtp_header_extensions_.push_back(
410 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
411 kRtpAudioLevelHeaderExtensionDefaultId));
412 rtp_header_extensions_.push_back(
413 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
414 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
415 options_ = GetDefaultEngineOptions();
416}
417
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000418void WebRtcVoiceEngine::ConstructCodecs() {
419 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
420 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
421 for (int i = 0; i < ncodecs; ++i) {
422 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000423 if (GetVoeCodec(i, &voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000424 // Skip uncompressed formats.
Minyue Li7100dcd2015-03-27 05:05:59 +0100425 if (IsCodec(voe_codec, kL16CodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000426 continue;
427 }
428
429 const CodecPref* pref = NULL;
430 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100431 if (IsCodec(voe_codec, kCodecPrefs[j].name) &&
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000432 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
433 kCodecPrefs[j].channels == voe_codec.channels) {
434 pref = &kCodecPrefs[j];
435 break;
436 }
437 }
438
439 if (pref) {
440 // Use the payload type that we've configured in our pref table;
441 // use the offset in our pref table to determine the sort order.
442 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
443 voe_codec.rate, voe_codec.channels,
444 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
445 LOG(LS_INFO) << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100446 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000447 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000448 codec.bitrate = 0;
449 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100450 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000451 // Only add fmtp parameters that differ from the spec.
452 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
453 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000454 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000455 }
456 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
457 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000458 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000459 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000460 codec.SetParam(kCodecParamUseInbandFec, 1);
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000461
462 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000463 // when they can be set to values other than the default.
464 }
465 codecs_.push_back(codec);
466 } else {
467 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
468 }
469 }
470 }
471 // Make sure they are in local preference order.
472 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
473}
474
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000475bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst* codec) {
476 if (voe_wrapper_->codec()->GetCodec(index, *codec) == -1) {
477 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000478 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000479 // Change the sample rate of G722 to 8000 to match SDP.
480 MaybeFixupG722(codec, 8000);
481 return true;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000482}
483
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000484WebRtcVoiceEngine::~WebRtcVoiceEngine() {
485 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
486 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
487 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
488 }
489 if (adm_) {
490 voe_wrapper_.reset();
491 adm_->Release();
492 adm_ = NULL;
493 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000494
495 // Test to see if the media processor was deregistered properly
henrikg91d6ede2015-09-17 00:24:34 -0700496 RTC_DCHECK(SignalRxMediaFrame.is_empty());
497 RTC_DCHECK(SignalTxMediaFrame.is_empty());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000498
499 tracing_->SetTraceCallback(NULL);
500}
501
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000502bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
henrikg91d6ede2015-09-17 00:24:34 -0700503 RTC_DCHECK(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000504 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
505 bool res = InitInternal();
506 if (res) {
507 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
508 } else {
509 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
510 Terminate();
511 }
512 return res;
513}
514
515bool WebRtcVoiceEngine::InitInternal() {
516 // Temporarily turn logging level up for the Init call
517 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000518 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000519 SetTraceFilter(extended_filter);
520 SetTraceOptions("");
521
522 // Init WebRtc VoiceEngine.
523 if (voe_wrapper_->base()->Init(adm_) == -1) {
524 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
525 SetTraceFilter(old_filter);
526 return false;
527 }
528
529 SetTraceFilter(old_filter);
530 SetTraceOptions(log_options_);
531
532 // Log the VoiceEngine version info
533 char buffer[1024] = "";
534 voe_wrapper_->base()->GetVersion(buffer);
535 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000536 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000537
538 // Save the default AGC configuration settings. This must happen before
539 // calling SetOptions or the default will be overwritten.
540 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
541 LOG_RTCERR0(GetAgcConfig);
542 return false;
543 }
544
545 // Set defaults for options, so that ApplyOptions applies them explicitly
546 // when we clear option (channel) overrides. External clients can still
547 // modify the defaults via SetOptions (on the media engine).
548 if (!SetOptions(GetDefaultEngineOptions())) {
549 return false;
550 }
551
552 // Print our codec list again for the call diagnostic log
553 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200554 for (const AudioCodec& codec : codecs_) {
555 LOG(LS_INFO) << ToString(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000556 }
557
558 // Disable the DTMF playout when a tone is sent.
559 // PlayDtmfTone will be used if local playout is needed.
560 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
561 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
562 }
563
564 initialized_ = true;
565 return true;
566}
567
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000568void WebRtcVoiceEngine::Terminate() {
569 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
570 initialized_ = false;
571
572 StopAecDump();
573
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000574 voe_wrapper_->base()->Terminate();
575 desired_local_monitor_enable_ = false;
576}
577
578int WebRtcVoiceEngine::GetCapabilities() {
579 return AUDIO_SEND | AUDIO_RECV;
580}
581
Fredrik Solenberg709ed672015-09-15 12:26:33 +0200582VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel(webrtc::Call* call,
Jelena Marusicc28a8962015-05-29 15:05:44 +0200583 const AudioOptions& options) {
Fredrik Solenbergb071a192015-09-17 16:42:56 +0200584 WebRtcVoiceMediaChannel* ch =
585 new WebRtcVoiceMediaChannel(this, options, call);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000586 if (!ch->valid()) {
587 delete ch;
Jelena Marusicc28a8962015-05-29 15:05:44 +0200588 return nullptr;
589 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000590 return ch;
591}
592
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000593bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
594 if (!ApplyOptions(options)) {
595 return false;
596 }
597 options_ = options;
598 return true;
599}
600
601bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
602 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
603 if (!ApplyOptions(overrides)) {
604 return false;
605 }
606 option_overrides_ = overrides;
607 return true;
608}
609
610bool WebRtcVoiceEngine::ClearOptionOverrides() {
611 LOG(LS_INFO) << "Clearing option overrides.";
612 AudioOptions options = options_;
613 // Only call ApplyOptions if |options_overrides_| contains overrided options.
614 // ApplyOptions affects NS, AGC other options that is shared between
615 // all WebRtcVoiceEngineChannels.
616 if (option_overrides_ == AudioOptions()) {
617 return true;
618 }
619
620 if (!ApplyOptions(options)) {
621 return false;
622 }
623 option_overrides_ = AudioOptions();
624 return true;
625}
626
627// AudioOptions defaults are set in InitInternal (for options with corresponding
628// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
629bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
630 AudioOptions options = options_in; // The options are modified below.
631 // kEcConference is AEC with high suppression.
632 webrtc::EcModes ec_mode = webrtc::kEcConference;
633 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
634 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
635 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
636 bool aecm_comfort_noise = false;
637 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
638 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
639 << aecm_comfort_noise << " (default is false).";
640 }
641
642#if defined(IOS)
643 // On iOS, VPIO provides built-in EC and AGC.
644 options.echo_cancellation.Set(false);
645 options.auto_gain_control.Set(false);
henrika86d907c2015-09-07 16:09:50 +0200646 LOG(LS_INFO) << "Always disable AEC and AGC on iOS. Use built-in instead.";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000647#elif defined(ANDROID)
648 ec_mode = webrtc::kEcAecm;
649#endif
650
651#if defined(IOS) || defined(ANDROID)
652 // Set the AGC mode for iOS as well despite disabling it above, to avoid
653 // unsupported configuration errors from webrtc.
654 agc_mode = webrtc::kAgcFixedDigital;
655 options.typing_detection.Set(false);
656 options.experimental_agc.Set(false);
Henrik Lundin441f6342015-06-09 16:03:13 +0200657 options.extended_filter_aec.Set(false);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000658 options.experimental_ns.Set(false);
659#endif
660
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100661 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
662 // where the feature is not supported.
663 bool use_delay_agnostic_aec = false;
664#if !defined(IOS)
665 if (options.delay_agnostic_aec.Get(&use_delay_agnostic_aec)) {
666 if (use_delay_agnostic_aec) {
667 options.echo_cancellation.Set(true);
Henrik Lundin441f6342015-06-09 16:03:13 +0200668 options.extended_filter_aec.Set(true);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100669 ec_mode = webrtc::kEcConference;
670 }
671 }
672#endif
673
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000674 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
675
676 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
677
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000678 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000679 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000680 // Check if platform supports built-in EC. Currently only supported on
681 // Android and in combination with Java based audio layer.
682 // TODO(henrika): investigate possibility to support built-in EC also
683 // in combination with Open SL ES audio.
684 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
Bjorn Volcker73f72102015-06-03 14:50:15 +0200685 if (built_in_aec) {
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200686 // Built-in EC exists on this device and use_delay_agnostic_aec is not
687 // overriding it. Enable/Disable it according to the echo_cancellation
688 // audio option.
Bjorn Volcker73f72102015-06-03 14:50:15 +0200689 const bool enable_built_in_aec =
690 echo_cancellation && !use_delay_agnostic_aec;
691 if (voe_wrapper_->hw()->EnableBuiltInAEC(enable_built_in_aec) == 0 &&
692 enable_built_in_aec) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100693 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000694 // i.e., replace the software EC with the built-in EC.
695 options.echo_cancellation.Set(false);
bjornv@webrtc.org3f118232015-03-16 14:22:03 +0000696 echo_cancellation = false;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000697 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
698 }
699 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000700 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
701 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
702 return false;
703 } else {
henrika86d907c2015-09-07 16:09:50 +0200704 LOG(LS_INFO) << "Echo control set to " << echo_cancellation
705 << " with mode " << ec_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000706 }
707#if !defined(ANDROID)
708 // TODO(ajm): Remove the error return on Android from webrtc.
709 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
710 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
711 return false;
712 }
713#endif
714 if (ec_mode == webrtc::kEcAecm) {
715 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
716 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
717 return false;
718 }
719 }
720 }
721
722 bool auto_gain_control;
723 if (options.auto_gain_control.Get(&auto_gain_control)) {
724 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
725 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
726 return false;
727 } else {
henrika86d907c2015-09-07 16:09:50 +0200728 LOG(LS_INFO) << "Auto gain set to " << auto_gain_control << " with mode "
729 << agc_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000730 }
731 }
732
733 if (options.tx_agc_target_dbov.IsSet() ||
734 options.tx_agc_digital_compression_gain.IsSet() ||
735 options.tx_agc_limiter.IsSet()) {
736 // Override default_agc_config_. Generally, an unset option means "leave
737 // the VoE bits alone" in this function, so we want whatever is set to be
738 // stored as the new "default". If we didn't, then setting e.g.
739 // tx_agc_target_dbov would reset digital compression gain and limiter
740 // settings.
741 // Also, if we don't update default_agc_config_, then adjust_agc_delta
742 // would be an offset from the original values, and not whatever was set
743 // explicitly.
744 default_agc_config_.targetLeveldBOv =
745 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
746 default_agc_config_.targetLeveldBOv);
747 default_agc_config_.digitalCompressionGaindB =
748 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
749 default_agc_config_.digitalCompressionGaindB);
750 default_agc_config_.limiterEnable =
751 options.tx_agc_limiter.GetWithDefaultIfUnset(
752 default_agc_config_.limiterEnable);
753 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
754 LOG_RTCERR3(SetAgcConfig,
755 default_agc_config_.targetLeveldBOv,
756 default_agc_config_.digitalCompressionGaindB,
757 default_agc_config_.limiterEnable);
758 return false;
759 }
760 }
761
762 bool noise_suppression;
763 if (options.noise_suppression.Get(&noise_suppression)) {
764 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
765 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
766 return false;
767 } else {
768 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
769 << " with mode " << ns_mode;
770 }
771 }
772
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000773 bool highpass_filter;
774 if (options.highpass_filter.Get(&highpass_filter)) {
775 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
776 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
777 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
778 return false;
779 }
780 }
781
782 bool stereo_swapping;
783 if (options.stereo_swapping.Get(&stereo_swapping)) {
784 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
785 voep->EnableStereoChannelSwapping(stereo_swapping);
786 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
787 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
788 return false;
789 }
790 }
791
Henrik Lundin64dad832015-05-11 12:44:23 +0200792 int audio_jitter_buffer_max_packets;
793 if (options.audio_jitter_buffer_max_packets.Get(
794 &audio_jitter_buffer_max_packets)) {
795 LOG(LS_INFO) << "NetEq capacity is " << audio_jitter_buffer_max_packets;
796 voe_config_.Set<webrtc::NetEqCapacityConfig>(
797 new webrtc::NetEqCapacityConfig(audio_jitter_buffer_max_packets));
798 }
799
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200800 bool audio_jitter_buffer_fast_accelerate;
801 if (options.audio_jitter_buffer_fast_accelerate.Get(
802 &audio_jitter_buffer_fast_accelerate)) {
803 LOG(LS_INFO) << "NetEq fast mode? " << audio_jitter_buffer_fast_accelerate;
804 voe_config_.Set<webrtc::NetEqFastAccelerate>(
805 new webrtc::NetEqFastAccelerate(audio_jitter_buffer_fast_accelerate));
806 }
807
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000808 bool typing_detection;
809 if (options.typing_detection.Get(&typing_detection)) {
810 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
811 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
812 // In case of error, log the info and continue
813 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
814 }
815 }
816
817 int adjust_agc_delta;
818 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
819 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
820 if (!AdjustAgcLevel(adjust_agc_delta)) {
821 return false;
822 }
823 }
824
825 bool aec_dump;
826 if (options.aec_dump.Get(&aec_dump)) {
827 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
828 if (aec_dump)
829 StartAecDump(kAecDumpByAudioOptionFilename);
830 else
831 StopAecDump();
832 }
833
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000834 webrtc::Config config;
835
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100836 delay_agnostic_aec_.SetFrom(options.delay_agnostic_aec);
837 bool delay_agnostic_aec;
838 if (delay_agnostic_aec_.Get(&delay_agnostic_aec)) {
839 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << delay_agnostic_aec;
henrik.lundin0f133b92015-07-02 00:17:55 -0700840 config.Set<webrtc::DelayAgnostic>(
841 new webrtc::DelayAgnostic(delay_agnostic_aec));
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100842 }
843
Henrik Lundin441f6342015-06-09 16:03:13 +0200844 extended_filter_aec_.SetFrom(options.extended_filter_aec);
845 bool extended_filter;
846 if (extended_filter_aec_.Get(&extended_filter)) {
847 LOG(LS_INFO) << "Extended filter aec is enabled? " << extended_filter;
848 config.Set<webrtc::ExtendedFilter>(
849 new webrtc::ExtendedFilter(extended_filter));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000850 }
851
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000852 experimental_ns_.SetFrom(options.experimental_ns);
853 bool experimental_ns;
854 if (experimental_ns_.Get(&experimental_ns)) {
855 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
856 config.Set<webrtc::ExperimentalNs>(
857 new webrtc::ExperimentalNs(experimental_ns));
858 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000859
860 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
861 // returns NULL on audio_processing().
862 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
863 if (audioproc) {
864 audioproc->SetExtraOptions(config);
865 }
866
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000867 uint32 recording_sample_rate;
868 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
869 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
870 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
871 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
872 }
873 }
874
875 uint32 playout_sample_rate;
876 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
877 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
878 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
879 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
880 }
881 }
882
883 return true;
884}
885
886bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
887 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
888 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
889 LOG_RTCERR1(SetDelayOffsetMs, offset);
890 return false;
891 }
892
893 return true;
894}
895
896struct ResumeEntry {
897 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
898 : channel(c),
899 playout(p),
900 send(s) {
901 }
902
903 WebRtcVoiceMediaChannel *channel;
904 bool playout;
905 SendFlags send;
906};
907
908// TODO(juberti): Refactor this so that the core logic can be used to set the
909// soundclip device. At that time, reinstate the soundclip pause/resume code.
910bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
911 const Device* out_device) {
912#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000913 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000914 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000915 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000916 kDefaultAudioDeviceId;
917 // The device manager uses -1 as the default device, which was the case for
918 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
919#ifndef WIN32
920 if (-1 == in_id) {
921 in_id = kDefaultAudioDeviceId;
922 }
923 if (-1 == out_id) {
924 out_id = kDefaultAudioDeviceId;
925 }
926#endif
927
928 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
929 in_device->name : "Default device";
930 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
931 out_device->name : "Default device";
932 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
933 << ") and speaker to (id=" << out_id << ", name=" << out_name
934 << ")";
935
936 // If we're running the local monitor, we need to stop it first.
937 bool ret = true;
938 if (!PauseLocalMonitor()) {
939 LOG(LS_WARNING) << "Failed to pause local monitor";
940 ret = false;
941 }
942
943 // Must also pause all audio playback and capture.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200944 for (WebRtcVoiceMediaChannel* channel : channels_) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000945 if (!channel->PausePlayout()) {
946 LOG(LS_WARNING) << "Failed to pause playout";
947 ret = false;
948 }
949 if (!channel->PauseSend()) {
950 LOG(LS_WARNING) << "Failed to pause send";
951 ret = false;
952 }
953 }
954
955 // Find the recording device id in VoiceEngine and set recording device.
956 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
957 ret = false;
958 }
959 if (ret) {
960 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
961 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
962 ret = false;
963 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +0000964 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
965 if (ap)
966 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000967 }
968
969 // Find the playout device id in VoiceEngine and set playout device.
970 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
971 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
972 ret = false;
973 }
974 if (ret) {
975 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000976 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000977 ret = false;
978 }
979 }
980
981 // Resume all audio playback and capture.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200982 for (WebRtcVoiceMediaChannel* channel : channels_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000983 if (!channel->ResumePlayout()) {
984 LOG(LS_WARNING) << "Failed to resume playout";
985 ret = false;
986 }
987 if (!channel->ResumeSend()) {
988 LOG(LS_WARNING) << "Failed to resume send";
989 ret = false;
990 }
991 }
992
993 // Resume local monitor.
994 if (!ResumeLocalMonitor()) {
995 LOG(LS_WARNING) << "Failed to resume local monitor";
996 ret = false;
997 }
998
999 if (ret) {
1000 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1001 << ") and speaker to (id="<< out_id << " name=" << out_name
1002 << ")";
1003 }
1004
1005 return ret;
1006#else
1007 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001008#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001009}
1010
1011bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1012 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1013 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001014#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001015 *rtc_id = dev_id;
1016 return true;
1017#else
1018 // In Windows and Mac, we need to find the VoiceEngine device id by name
1019 // unless the input dev_id is the default device id.
1020 if (kDefaultAudioDeviceId == dev_id) {
1021 *rtc_id = dev_id;
1022 return true;
1023 }
1024
1025 // Get the number of VoiceEngine audio devices.
1026 int count = 0;
1027 if (is_input) {
1028 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1029 LOG_RTCERR0(GetNumOfRecordingDevices);
1030 return false;
1031 }
1032 } else {
1033 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1034 LOG_RTCERR0(GetNumOfPlayoutDevices);
1035 return false;
1036 }
1037 }
1038
1039 for (int i = 0; i < count; ++i) {
1040 char name[128];
1041 char guid[128];
1042 if (is_input) {
1043 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1044 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1045 } else {
1046 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1047 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1048 }
1049
1050 std::string webrtc_name(name);
1051 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1052 *rtc_id = i;
1053 return true;
1054 }
1055 }
1056 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1057 return false;
1058#endif
1059}
1060
1061bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1062 unsigned int ulevel;
1063 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1064 LOG_RTCERR1(GetSpeakerVolume, level);
1065 return false;
1066 }
1067 *level = ulevel;
1068 return true;
1069}
1070
1071bool WebRtcVoiceEngine::SetOutputVolume(int level) {
henrikg91d6ede2015-09-17 00:24:34 -07001072 RTC_DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001073 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1074 LOG_RTCERR1(SetSpeakerVolume, level);
1075 return false;
1076 }
1077 return true;
1078}
1079
1080int WebRtcVoiceEngine::GetInputLevel() {
1081 unsigned int ulevel;
1082 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1083 static_cast<int>(ulevel) : -1;
1084}
1085
1086bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1087 desired_local_monitor_enable_ = enable;
1088 return ChangeLocalMonitor(desired_local_monitor_enable_);
1089}
1090
1091bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1092 // The voe file api is not available in chrome.
1093 if (!voe_wrapper_->file()) {
1094 return false;
1095 }
1096 if (enable && !monitor_) {
1097 monitor_.reset(new WebRtcMonitorStream);
1098 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1099 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1100 // Must call Stop() because there are some cases where Start will report
1101 // failure but still change the state, and if we leave VE in the on state
1102 // then it could crash later when trying to invoke methods on our monitor.
1103 voe_wrapper_->file()->StopRecordingMicrophone();
1104 monitor_.reset();
1105 return false;
1106 }
1107 } else if (!enable && monitor_) {
1108 voe_wrapper_->file()->StopRecordingMicrophone();
1109 monitor_.reset();
1110 }
1111 return true;
1112}
1113
1114bool WebRtcVoiceEngine::PauseLocalMonitor() {
1115 return ChangeLocalMonitor(false);
1116}
1117
1118bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1119 return ChangeLocalMonitor(desired_local_monitor_enable_);
1120}
1121
1122const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1123 return codecs_;
1124}
1125
1126bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1127 return FindWebRtcCodec(in, NULL);
1128}
1129
1130// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1131bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1132 webrtc::CodecInst* out) {
1133 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1134 for (int i = 0; i < ncodecs; ++i) {
1135 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001136 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001137 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1138 voe_codec.rate, voe_codec.channels, 0);
1139 bool multi_rate = IsCodecMultiRate(voe_codec);
1140 // Allow arbitrary rates for ISAC to be specified.
1141 if (multi_rate) {
1142 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1143 codec.bitrate = 0;
1144 }
1145 if (codec.Matches(in)) {
1146 if (out) {
1147 // Fixup the payload type.
1148 voe_codec.pltype = in.id;
1149
1150 // Set bitrate if specified.
1151 if (multi_rate && in.bitrate != 0) {
1152 voe_codec.rate = in.bitrate;
1153 }
1154
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001155 // Reset G722 sample rate to 16000 to match WebRTC.
1156 MaybeFixupG722(&voe_codec, 16000);
1157
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001158 // Apply codec-specific settings.
Minyue Li7100dcd2015-03-27 05:05:59 +01001159 if (IsCodec(codec, kIsacCodecName)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001160 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001161 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001162 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1163 }
1164 *out = voe_codec;
1165 }
1166 return true;
1167 }
1168 }
1169 }
1170 return false;
1171}
1172const std::vector<RtpHeaderExtension>&
1173WebRtcVoiceEngine::rtp_header_extensions() const {
1174 return rtp_header_extensions_;
1175}
1176
1177void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1178 // if min_sev == -1, we keep the current log level.
1179 if (min_sev >= 0) {
1180 SetTraceFilter(SeverityToFilter(min_sev));
1181 }
1182 log_options_ = filter;
1183 SetTraceOptions(initialized_ ? log_options_ : "");
1184}
1185
1186int WebRtcVoiceEngine::GetLastEngineError() {
1187 return voe_wrapper_->error();
1188}
1189
1190void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1191 log_filter_ = filter;
1192 tracing_->SetTraceFilter(filter);
1193}
1194
1195// We suppport three different logging settings for VoiceEngine:
1196// 1. Observer callback that goes into talk diagnostic logfile.
1197// Use --logfile and --loglevel
1198//
1199// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1200// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1201//
1202// 3. EC log and dump for debugging QualityEngine.
1203// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1204//
1205// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1206// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1207void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1208 // Set encrypted trace file.
1209 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001210 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001211 std::vector<std::string>::iterator tracefile =
1212 std::find(opts.begin(), opts.end(), "tracefile");
1213 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1214 // Write encrypted debug output (at same loglevel) to file
1215 // EncryptedTraceFile no longer supported.
1216 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1217 LOG_RTCERR1(SetTraceFile, *tracefile);
1218 }
1219 }
1220
wu@webrtc.org97077a32013-10-25 21:18:33 +00001221 // Allow trace options to override the trace filter. We default
1222 // it to log_filter_ (as a translation of libjingle log levels)
1223 // elsewhere, but this allows clients to explicitly set webrtc
1224 // log levels.
1225 std::vector<std::string>::iterator tracefilter =
1226 std::find(opts.begin(), opts.end(), "tracefilter");
1227 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001228 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001229 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1230 }
1231 }
1232
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001233 // Set AEC dump file
1234 std::vector<std::string>::iterator recordEC =
1235 std::find(opts.begin(), opts.end(), "recordEC");
1236 if (recordEC != opts.end()) {
1237 ++recordEC;
1238 if (recordEC != opts.end())
1239 StartAecDump(recordEC->c_str());
1240 else
1241 StopAecDump();
1242 }
1243}
1244
1245// Ignore spammy trace messages, mostly from the stats API when we haven't
1246// gotten RTCP info yet from the remote side.
1247bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1248 static const char* kTracesToIgnore[] = {
1249 "\tfailed to GetReportBlockInformation",
1250 "GetRecCodec() failed to get received codec",
1251 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1252 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1253 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1254 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1255 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1256 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1257 "SenderInfoReceived No received SR",
1258 "StatisticsRTP() no statistics available",
1259 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1260 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1261 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1262 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1263 NULL
1264 };
1265 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1266 if (trace.find(*p) != std::string::npos) {
1267 return true;
1268 }
1269 }
1270 return false;
1271}
1272
1273void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1274 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001275 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001276 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001277 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001278 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001279 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001281 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001282 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001283 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001284
1285 // Skip past boilerplate prefix text
1286 if (length < 72) {
1287 std::string msg(trace, length);
1288 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1289 LOG_V(sev) << msg;
1290 } else {
1291 std::string msg(trace + 71, length - 72);
1292 if (!ShouldIgnoreTrace(msg)) {
1293 LOG_V(sev) << "webrtc: " << msg;
1294 }
1295 }
1296}
1297
1298void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001299 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001300 WebRtcVoiceMediaChannel* channel = NULL;
1301 uint32 ssrc = 0;
1302 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1303 << channel_num << ".";
1304 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
henrikg91d6ede2015-09-17 00:24:34 -07001305 RTC_DCHECK(channel != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001306 channel->OnError(ssrc, err_code);
1307 } else {
1308 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1309 << " could not be found in channel list when error reported.";
1310 }
1311}
1312
1313bool WebRtcVoiceEngine::FindChannelAndSsrc(
1314 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
henrikg91d6ede2015-09-17 00:24:34 -07001315 RTC_DCHECK(channel != NULL && ssrc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001316
1317 *channel = NULL;
1318 *ssrc = 0;
1319 // Find corresponding channel and ssrc
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001320 for (WebRtcVoiceMediaChannel* ch : channels_) {
henrikg91d6ede2015-09-17 00:24:34 -07001321 RTC_DCHECK(ch != NULL);
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001322 if (ch->FindSsrc(channel_num, ssrc)) {
1323 *channel = ch;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001324 return true;
1325 }
1326 }
1327
1328 return false;
1329}
1330
1331// This method will search through the WebRtcVoiceMediaChannels and
1332// obtain the voice engine's channel number.
1333bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1334 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
henrikg91d6ede2015-09-17 00:24:34 -07001335 RTC_DCHECK(channel_num != NULL);
1336 RTC_DCHECK(direction == MPD_RX || direction == MPD_TX);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001337
1338 *channel_num = -1;
1339 // Find corresponding channel for ssrc.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001340 for (const WebRtcVoiceMediaChannel* ch : channels_) {
henrikg91d6ede2015-09-17 00:24:34 -07001341 RTC_DCHECK(ch != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001342 if (direction & MPD_RX) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001343 *channel_num = ch->GetReceiveChannelNum(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001344 }
1345 if (*channel_num == -1 && (direction & MPD_TX)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001346 *channel_num = ch->GetSendChannelNum(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001347 }
1348 if (*channel_num != -1) {
1349 return true;
1350 }
1351 }
1352 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1353 return false;
1354}
1355
1356void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001357 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001358 channels_.push_back(channel);
1359}
1360
1361void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001362 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001363 ChannelList::iterator i = std::find(channels_.begin(),
1364 channels_.end(),
1365 channel);
1366 if (i != channels_.end()) {
1367 channels_.erase(i);
1368 }
1369}
1370
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001371// Adjusts the default AGC target level by the specified delta.
1372// NB: If we start messing with other config fields, we'll want
1373// to save the current webrtc::AgcConfig as well.
1374bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1375 webrtc::AgcConfig config = default_agc_config_;
1376 config.targetLeveldBOv -= delta;
1377
1378 LOG(LS_INFO) << "Adjusting AGC level from default -"
1379 << default_agc_config_.targetLeveldBOv << "dB to -"
1380 << config.targetLeveldBOv << "dB";
1381
1382 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1383 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1384 return false;
1385 }
1386 return true;
1387}
1388
Fredrik Solenbergccb49e72015-05-19 11:37:56 +02001389bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001390 if (initialized_) {
1391 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1392 return false;
1393 }
1394 if (adm_) {
1395 adm_->Release();
1396 adm_ = NULL;
1397 }
1398 if (adm) {
1399 adm_ = adm;
1400 adm_->AddRef();
1401 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001402 return true;
1403}
1404
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001405bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1406 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001407 if (!aec_dump_file_stream) {
1408 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001409 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001410 LOG(LS_WARNING) << "Could not close file.";
1411 return false;
1412 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001413 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001414 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001415 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001416 LOG_RTCERR0(StartDebugRecording);
1417 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001418 return false;
1419 }
1420 is_dumping_aec_ = true;
1421 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001422}
1423
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001424bool WebRtcVoiceEngine::RegisterProcessor(
1425 uint32 ssrc,
1426 VoiceProcessor* voice_processor,
1427 MediaProcessorDirection direction) {
1428 bool register_with_webrtc = false;
1429 int channel_id = -1;
1430 bool success = false;
1431 uint32* processor_ssrc = NULL;
1432 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1433 if (voice_processor == NULL || !found_channel) {
1434 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1435 << " foundChannel: " << found_channel;
1436 return false;
1437 }
1438
1439 webrtc::ProcessingTypes processing_type;
1440 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001441 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001442 if (direction == MPD_RX) {
1443 processing_type = webrtc::kPlaybackAllChannelsMixed;
1444 if (SignalRxMediaFrame.is_empty()) {
1445 register_with_webrtc = true;
1446 processor_ssrc = &rx_processor_ssrc_;
1447 }
1448 SignalRxMediaFrame.connect(voice_processor,
1449 &VoiceProcessor::OnFrame);
1450 } else {
1451 processing_type = webrtc::kRecordingPerChannel;
1452 if (SignalTxMediaFrame.is_empty()) {
1453 register_with_webrtc = true;
1454 processor_ssrc = &tx_processor_ssrc_;
1455 }
1456 SignalTxMediaFrame.connect(voice_processor,
1457 &VoiceProcessor::OnFrame);
1458 }
1459 }
1460 if (register_with_webrtc) {
1461 // TODO(janahan): when registering consider instantiating a
1462 // a VoeMediaProcess object and not make the engine extend the interface.
1463 if (voe()->media() && voe()->media()->
1464 RegisterExternalMediaProcessing(channel_id,
1465 processing_type,
1466 *this) != -1) {
1467 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1468 << channel_id;
1469 *processor_ssrc = ssrc;
1470 success = true;
1471 } else {
1472 LOG_RTCERR2(RegisterExternalMediaProcessing,
1473 channel_id,
1474 processing_type);
1475 success = false;
1476 }
1477 } else {
1478 // If we don't have to register with the engine, we just needed to
1479 // connect a new processor, set success to true;
1480 success = true;
1481 }
1482 return success;
1483}
1484
1485bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1486 MediaProcessorDirection channel_direction,
1487 uint32 ssrc,
1488 VoiceProcessor* voice_processor,
1489 MediaProcessorDirection processor_direction) {
1490 bool success = true;
1491 FrameSignal* signal;
1492 webrtc::ProcessingTypes processing_type;
1493 uint32* processor_ssrc = NULL;
1494 if (channel_direction == MPD_RX) {
1495 signal = &SignalRxMediaFrame;
1496 processing_type = webrtc::kPlaybackAllChannelsMixed;
1497 processor_ssrc = &rx_processor_ssrc_;
1498 } else {
1499 signal = &SignalTxMediaFrame;
1500 processing_type = webrtc::kRecordingPerChannel;
1501 processor_ssrc = &tx_processor_ssrc_;
1502 }
1503
1504 int deregister_id = -1;
1505 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001506 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001507 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1508 signal->disconnect(voice_processor);
1509 int channel_id = -1;
1510 bool found_channel = FindChannelNumFromSsrc(ssrc,
1511 channel_direction,
1512 &channel_id);
1513 if (signal->is_empty() && found_channel) {
1514 deregister_id = channel_id;
1515 }
1516 }
1517 }
1518 if (deregister_id != -1) {
1519 if (voe()->media() &&
1520 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1521 processing_type) != -1) {
1522 *processor_ssrc = 0;
1523 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1524 << deregister_id;
1525 } else {
1526 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1527 deregister_id,
1528 processing_type);
1529 success = false;
1530 }
1531 }
1532 return success;
1533}
1534
1535bool WebRtcVoiceEngine::UnregisterProcessor(
1536 uint32 ssrc,
1537 VoiceProcessor* voice_processor,
1538 MediaProcessorDirection direction) {
1539 bool success = true;
1540 if (voice_processor == NULL) {
1541 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1542 << ssrc;
1543 return false;
1544 }
1545 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1546 success = false;
1547 }
1548 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1549 success = false;
1550 }
1551 return success;
1552}
1553
1554// Implementing method from WebRtc VoEMediaProcess interface
1555// Do not lock mux_channel_cs_ in this callback.
1556void WebRtcVoiceEngine::Process(int channel,
1557 webrtc::ProcessingTypes type,
1558 int16_t audio10ms[],
Peter Kastingdce40cf2015-08-24 14:52:23 -07001559 size_t length,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001560 int sampling_freq,
1561 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001562 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001563 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1564 if (type == webrtc::kPlaybackAllChannelsMixed) {
1565 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1566 } else if (type == webrtc::kRecordingPerChannel) {
1567 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1568 } else {
1569 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1570 << " channel: " << channel << " type: " << type
1571 << " tx_ssrc: " << tx_processor_ssrc_
1572 << " rx_ssrc: " << rx_processor_ssrc_;
1573 }
1574}
1575
1576void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1577 if (!is_dumping_aec_) {
1578 // Start dumping AEC when we are not dumping.
1579 if (voe_wrapper_->processing()->StartDebugRecording(
1580 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001581 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001582 } else {
1583 is_dumping_aec_ = true;
1584 }
1585 }
1586}
1587
1588void WebRtcVoiceEngine::StopAecDump() {
1589 if (is_dumping_aec_) {
1590 // Stop dumping AEC when we are dumping.
1591 if (voe_wrapper_->processing()->StopDebugRecording() !=
1592 webrtc::AudioProcessing::kNoError) {
1593 LOG_RTCERR0(StopDebugRecording);
1594 }
1595 is_dumping_aec_ = false;
1596 }
1597}
1598
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001599int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001600 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001601}
1602
1603int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1604 return CreateVoiceChannel(voe_wrapper_.get());
1605}
1606
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001607class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1608 : public AudioRenderer::Sink {
1609 public:
1610 WebRtcVoiceChannelRenderer(int ch,
1611 webrtc::AudioTransport* voe_audio_transport)
1612 : channel_(ch),
1613 voe_audio_transport_(voe_audio_transport),
pbos8fc7fa72015-07-15 08:02:58 -07001614 renderer_(NULL) {}
Fredrik Solenbergaaf8ff22015-05-07 16:05:53 +02001615 ~WebRtcVoiceChannelRenderer() override { Stop(); }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001616
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001617 // Starts the rendering by setting a sink to the renderer to get data
1618 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001619 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001620 // TODO(xians): Make sure Start() is called only once.
1621 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001622 rtc::CritScope lock(&lock_);
henrikg91d6ede2015-09-17 00:24:34 -07001623 RTC_DCHECK(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001624 if (renderer_ != NULL) {
henrikg91d6ede2015-09-17 00:24:34 -07001625 RTC_DCHECK(renderer_ == renderer);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001626 return;
1627 }
1628
1629 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1630 // in getUserMedia by default.
1631 renderer->AddChannel(channel_);
1632 renderer->SetSink(this);
1633 renderer_ = renderer;
1634 }
1635
1636 // Stops rendering by setting the sink of the renderer to NULL. No data
1637 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001638 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001639 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001640 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001641 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001642 return;
1643
1644 renderer_->RemoveChannel(channel_);
1645 renderer_->SetSink(NULL);
1646 renderer_ = NULL;
1647 }
1648
1649 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001650 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001651 void OnData(const void* audio_data,
1652 int bits_per_sample,
1653 int sample_rate,
1654 int number_of_channels,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001655 size_t number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001656 voe_audio_transport_->OnData(channel_,
1657 audio_data,
1658 bits_per_sample,
1659 sample_rate,
1660 number_of_channels,
1661 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001662 }
1663
1664 // Callback from the |renderer_| when it is going away. In case Start() has
1665 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001666 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001667 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001668 // Set |renderer_| to NULL to make sure no more callback will get into
1669 // the renderer.
1670 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001671 }
1672
1673 // Accessor to the VoE channel ID.
1674 int channel() const { return channel_; }
1675
1676 private:
1677 const int channel_;
1678 webrtc::AudioTransport* const voe_audio_transport_;
1679
1680 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1681 // PeerConnection will make sure invalidating the pointer before the object
1682 // goes away.
1683 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001684
1685 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001686 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001687};
1688
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001689// WebRtcVoiceMediaChannel
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001690WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine,
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001691 const AudioOptions& options,
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001692 webrtc::Call* call)
Fredrik Solenberge444a3d2015-05-07 16:42:08 +02001693 : engine_(engine),
1694 voe_channel_(engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001695 send_bitrate_setting_(false),
1696 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001697 options_(),
1698 dtmf_allowed_(false),
1699 desired_playout_(false),
1700 nack_enabled_(false),
1701 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001702 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001703 desired_send_(SEND_NOTHING),
1704 send_(SEND_NOTHING),
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001705 call_(call),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001706 default_receive_ssrc_(0) {
1707 engine->RegisterChannel(this);
1708 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1709 << voe_channel();
henrikg91d6ede2015-09-17 00:24:34 -07001710 RTC_DCHECK(nullptr != call);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001711 ConfigureSendChannel(voe_channel());
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001712 SetOptions(options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001713}
1714
1715WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1716 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1717 << voe_channel();
1718
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001719 // Remove any remaining send streams, the default channel will be deleted
1720 // later.
1721 while (!send_channels_.empty())
1722 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001723
1724 // Unregister ourselves from the engine.
1725 engine()->UnregisterChannel(this);
1726 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001727 while (!receive_channels_.empty()) {
1728 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001729 }
henrikg91d6ede2015-09-17 00:24:34 -07001730 RTC_DCHECK(receive_streams_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001731
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001732 // Delete the default channel.
1733 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001734}
1735
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001736bool WebRtcVoiceMediaChannel::SetSendParameters(
1737 const AudioSendParameters& params) {
1738 // TODO(pthatcher): Refactor this to be more clean now that we have
1739 // all the information at once.
1740 return (SetSendCodecs(params.codecs) &&
1741 SetSendRtpHeaderExtensions(params.extensions) &&
1742 SetMaxSendBandwidth(params.max_bandwidth_bps) &&
1743 SetOptions(params.options));
1744}
1745
1746bool WebRtcVoiceMediaChannel::SetRecvParameters(
1747 const AudioRecvParameters& params) {
1748 // TODO(pthatcher): Refactor this to be more clean now that we have
1749 // all the information at once.
1750 return (SetRecvCodecs(params.codecs) &&
1751 SetRecvRtpHeaderExtensions(params.extensions));
1752}
1753
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001754bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1755 LOG(LS_INFO) << "Setting voice channel options: "
1756 << options.ToString();
1757
wu@webrtc.orgde305012013-10-31 15:40:38 +00001758 // Check if DSCP value is changed from previous.
1759 bool dscp_option_changed = (options_.dscp != options.dscp);
1760
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001761 // TODO(xians): Add support to set different options for different send
1762 // streams after we support multiple APMs.
1763
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001764 // We retain all of the existing options, and apply the given ones
1765 // on top. This means there is no way to "clear" options such that
1766 // they go back to the engine default.
1767 options_.SetAll(options);
1768
1769 if (send_ != SEND_NOTHING) {
1770 if (!engine()->SetOptionOverrides(options_)) {
1771 LOG(LS_WARNING) <<
1772 "Failed to engine SetOptionOverrides during channel SetOptions.";
1773 return false;
1774 }
1775 } else {
1776 // Will be interpreted when appropriate.
1777 }
1778
wu@webrtc.org97077a32013-10-25 21:18:33 +00001779 // Receiver-side auto gain control happens per channel, so set it here from
1780 // options. Note that, like conference mode, setting it on the engine won't
1781 // have the desired effect, since voice channels don't inherit options from
1782 // the media engine when those options are applied per-channel.
1783 bool rx_auto_gain_control;
1784 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1785 if (engine()->voe()->processing()->SetRxAgcStatus(
1786 voe_channel(), rx_auto_gain_control,
1787 webrtc::kAgcFixedDigital) == -1) {
1788 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1789 return false;
1790 } else {
1791 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1792 << " with mode " << webrtc::kAgcFixedDigital;
1793 }
1794 }
1795 if (options.rx_agc_target_dbov.IsSet() ||
1796 options.rx_agc_digital_compression_gain.IsSet() ||
1797 options.rx_agc_limiter.IsSet()) {
1798 webrtc::AgcConfig config;
1799 // If only some of the options are being overridden, get the current
1800 // settings for the channel and bail if they aren't available.
1801 if (!options.rx_agc_target_dbov.IsSet() ||
1802 !options.rx_agc_digital_compression_gain.IsSet() ||
1803 !options.rx_agc_limiter.IsSet()) {
1804 if (engine()->voe()->processing()->GetRxAgcConfig(
1805 voe_channel(), config) != 0) {
1806 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1807 << "channel " << voe_channel() << ". Since not all rx "
1808 << "agc options are specified, unable to safely set rx "
1809 << "agc options.";
1810 return false;
1811 }
1812 }
1813 config.targetLeveldBOv =
1814 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1815 config.targetLeveldBOv);
1816 config.digitalCompressionGaindB =
1817 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1818 config.digitalCompressionGaindB);
1819 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1820 config.limiterEnable);
1821 if (engine()->voe()->processing()->SetRxAgcConfig(
1822 voe_channel(), config) == -1) {
1823 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1824 config.digitalCompressionGaindB, config.limiterEnable);
1825 return false;
1826 }
1827 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001828 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001829 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001830 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001831 dscp = kAudioDscpValue;
1832 if (MediaChannel::SetDscp(dscp) != 0) {
1833 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1834 }
1835 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001836
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001837 RecreateAudioReceiveStreams();
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001838
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001839 LOG(LS_INFO) << "Set voice channel options. Current options: "
1840 << options_.ToString();
1841 return true;
1842}
1843
1844bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1845 const std::vector<AudioCodec>& codecs) {
1846 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001847 LOG(LS_INFO) << "Setting receive voice codecs:";
1848
1849 std::vector<AudioCodec> new_codecs;
1850 // Find all new codecs. We allow adding new codecs but don't allow changing
1851 // the payload type of codecs that is already configured since we might
1852 // already be receiving packets with that payload type.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001853 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001854 AudioCodec old_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001855 if (FindCodec(recv_codecs_, codec, &old_codec)) {
1856 if (old_codec.id != codec.id) {
1857 LOG(LS_ERROR) << codec.name << " payload type changed.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001858 return false;
1859 }
1860 } else {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001861 new_codecs.push_back(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001862 }
1863 }
1864 if (new_codecs.empty()) {
1865 // There are no new codecs to configure. Already configured codecs are
1866 // never removed.
1867 return true;
1868 }
1869
1870 if (playout_) {
1871 // Receive codecs can not be changed while playing. So we temporarily
1872 // pause playout.
1873 PausePlayout();
1874 }
1875
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001876 bool result = SetRecvCodecsInternal(new_codecs);
1877 if (result) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001878 recv_codecs_ = codecs;
1879 }
1880
1881 if (desired_playout_ && !playout_) {
1882 ResumePlayout();
1883 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001884 return result;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001885}
1886
1887bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001888 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001889 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001890 engine()->voe()->codec()->SetVADStatus(channel, false);
1891 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001892 engine()->voe()->rtp()->SetREDStatus(channel, false);
1893 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001894
1895 // Scan through the list to figure out the codec to use for sending, along
1896 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001897 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001898 webrtc::CodecInst send_codec;
1899 memset(&send_codec, 0, sizeof(send_codec));
1900
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001901 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001902 bool enable_codec_fec = false;
Minyue Li7100dcd2015-03-27 05:05:59 +01001903 bool enable_opus_dtx = false;
minyue@webrtc.org26236952014-10-29 02:27:08 +00001904 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001905
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001906 // Set send codec (the first non-telephone-event/CN codec)
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001907 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001908 // Ignore codecs we don't know about. The negotiation step should prevent
1909 // this, but double-check to be sure.
1910 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001911 if (!engine()->FindWebRtcCodec(codec, &voe_codec)) {
1912 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001913 continue;
1914 }
1915
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001916 if (IsCodec(codec, kDtmfCodecName) || IsCodec(codec, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001917 // Skip telephone-event/CN codec, which will be handled later.
1918 continue;
1919 }
1920
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001921 // We'll use the first codec in the list to actually send audio data.
1922 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001923 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001924 // used is specified in params.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001925 if (IsCodec(codec, kRedCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001926 // Parse out the RED parameters. If we fail, just ignore RED;
1927 // we don't support all possible params/usage scenarios.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001928 if (!GetRedSendCodec(codec, codecs, &send_codec)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001929 continue;
1930 }
1931
1932 // Enable redundant encoding of the specified codec. Treat any
1933 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001934 LOG(LS_INFO) << "Enabling RED on channel " << channel;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001935 if (engine()->voe()->rtp()->SetREDStatus(channel, true, codec.id) == -1) {
1936 LOG_RTCERR3(SetREDStatus, channel, true, codec.id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001937 return false;
1938 }
1939 } else {
1940 send_codec = voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001941 nack_enabled = IsNackEnabled(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +01001942 // For Opus as the send codec, we are to determine inband FEC, maximum
1943 // playback rate, and opus internal dtx.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001944 if (IsCodec(codec, kOpusCodecName)) {
1945 GetOpusConfig(codec, &send_codec, &enable_codec_fec,
Minyue Li7100dcd2015-03-27 05:05:59 +01001946 &opus_max_playback_rate, &enable_opus_dtx);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001947 }
Brave Yao5225dd82015-03-26 07:39:19 +08001948
1949 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1950 int ptime_ms = 0;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001951 if (codec.GetParam(kCodecParamPTime, &ptime_ms)) {
Brave Yao5225dd82015-03-26 07:39:19 +08001952 if (!SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
1953 LOG(LS_WARNING) << "Failed to set packet size for codec "
1954 << send_codec.plname;
1955 return false;
1956 }
1957 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001958 }
1959 found_send_codec = true;
1960 break;
1961 }
1962
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001963 if (nack_enabled_ != nack_enabled) {
1964 SetNack(channel, nack_enabled);
1965 nack_enabled_ = nack_enabled;
1966 }
1967
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001968 if (!found_send_codec) {
1969 LOG(LS_WARNING) << "Received empty list of codecs.";
1970 return false;
1971 }
1972
1973 // Set the codec immediately, since SetVADStatus() depends on whether
1974 // the current codec is mono or stereo.
1975 if (!SetSendCodec(channel, send_codec))
1976 return false;
1977
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001978 // FEC should be enabled after SetSendCodec.
1979 if (enable_codec_fec) {
1980 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
1981 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001982 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
1983 // Enable codec internal FEC. Treat any failure as fatal internal error.
1984 LOG_RTCERR2(SetFECStatus, channel, true);
1985 return false;
1986 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001987 }
1988
Minyue Li7100dcd2015-03-27 05:05:59 +01001989 if (IsCodec(send_codec, kOpusCodecName)) {
1990 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
1991 // send codec has to be Opus.
1992
1993 // Set Opus internal DTX.
1994 LOG(LS_INFO) << "Attempt to "
1995 << GetEnableString(enable_opus_dtx)
1996 << " Opus DTX on channel "
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001997 << channel;
Minyue Li7100dcd2015-03-27 05:05:59 +01001998 if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) {
1999 LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx);
2000 return false;
2001 }
2002
2003 // If opus_max_playback_rate <= 0, the default maximum playback rate
2004 // (48 kHz) will be used.
2005 if (opus_max_playback_rate > 0) {
2006 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
2007 << opus_max_playback_rate
2008 << " Hz on channel "
2009 << channel;
2010 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
2011 channel, opus_max_playback_rate) == -1) {
2012 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate);
2013 return false;
2014 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002015 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002016 }
2017
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002018 // Always update the |send_codec_| to the currently set send codec.
2019 send_codec_.reset(new webrtc::CodecInst(send_codec));
2020
minyue@webrtc.org26236952014-10-29 02:27:08 +00002021 if (send_bitrate_setting_) {
2022 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002023 }
2024
2025 // Loop through the codecs list again to config the telephone-event/CN codec.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002026 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002027 // Ignore codecs we don't know about. The negotiation step should prevent
2028 // this, but double-check to be sure.
2029 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002030 if (!engine()->FindWebRtcCodec(codec, &voe_codec)) {
2031 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002032 continue;
2033 }
2034
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002035 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2036 // about it.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002037 if (IsCodec(codec, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002038 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002039 channel, codec.id) == -1) {
2040 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, codec.id);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002041 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002042 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002043 } else if (IsCodec(codec, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002044 // Turn voice activity detection/comfort noise on if supported.
2045 // Set the wideband CN payload type appropriately.
2046 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002047 webrtc::PayloadFrequencies cn_freq;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002048 switch (codec.clockrate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002049 case 8000:
2050 cn_freq = webrtc::kFreq8000Hz;
2051 break;
2052 case 16000:
2053 cn_freq = webrtc::kFreq16000Hz;
2054 break;
2055 case 32000:
2056 cn_freq = webrtc::kFreq32000Hz;
2057 break;
2058 default:
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002059 LOG(LS_WARNING) << "CN frequency " << codec.clockrate
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002060 << " not supported.";
2061 continue;
2062 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002063 // Set the CN payloadtype and the VAD status.
2064 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2065 if (cn_freq != webrtc::kFreq8000Hz) {
2066 if (engine()->voe()->codec()->SetSendCNPayloadType(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002067 channel, codec.id, cn_freq) == -1) {
2068 LOG_RTCERR3(SetSendCNPayloadType, channel, codec.id, cn_freq);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002069 // TODO(ajm): This failure condition will be removed from VoE.
2070 // Restore the return here when we update to a new enough webrtc.
2071 //
2072 // Not returning false because the SetSendCNPayloadType will fail if
2073 // the channel is already sending.
2074 // This can happen if the remote description is applied twice, for
2075 // example in the case of ROAP on top of JSEP, where both side will
2076 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002077 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002078 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002079 // Only turn on VAD if we have a CN payload type that matches the
2080 // clockrate for the codec we are going to use.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002081 if (codec.clockrate == send_codec.plfreq && send_codec.channels != 2) {
Minyue Li7100dcd2015-03-27 05:05:59 +01002082 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
2083 // interaction between VAD and Opus FEC.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002084 LOG(LS_INFO) << "Enabling VAD";
2085 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2086 LOG_RTCERR2(SetVADStatus, channel, true);
2087 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002088 }
2089 }
2090 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002091 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002092 return true;
2093}
2094
2095bool WebRtcVoiceMediaChannel::SetSendCodecs(
2096 const std::vector<AudioCodec>& codecs) {
2097 dtmf_allowed_ = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002098 for (const AudioCodec& codec : codecs) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002099 // Find the DTMF telephone event "codec".
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002100 if (IsCodec(codec, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002101 dtmf_allowed_ = true;
2102 }
2103 }
2104
2105 // Cache the codecs in order to configure the channel created later.
2106 send_codecs_ = codecs;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002107 for (const auto& ch : send_channels_) {
2108 if (!SetSendCodecs(ch.second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002109 return false;
2110 }
2111 }
2112
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002113 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002114 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002115 return true;
2116}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002117
2118void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2119 bool nack_enabled) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002120 for (const auto& ch : channels) {
2121 SetNack(ch.second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002122 }
2123}
2124
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002125void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002126 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002127 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002128 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2129 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002130 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002131 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2132 }
2133}
2134
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002135bool WebRtcVoiceMediaChannel::SetSendCodec(
2136 const webrtc::CodecInst& send_codec) {
2137 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2138 << ", bitrate=" << send_codec.rate;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002139 for (const auto& ch : send_channels_) {
2140 if (!SetSendCodec(ch.second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002141 return false;
2142 }
2143
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002144 return true;
2145}
2146
2147bool WebRtcVoiceMediaChannel::SetSendCodec(
2148 int channel, const webrtc::CodecInst& send_codec) {
2149 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2150 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2151
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002152 webrtc::CodecInst current_codec;
2153 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2154 (send_codec == current_codec)) {
2155 // Codec is already configured, we can return without setting it again.
2156 return true;
2157 }
2158
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002159 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2160 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002161 return false;
2162 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002163 return true;
2164}
2165
2166bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2167 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002168 if (receive_extensions_ == extensions) {
2169 return true;
2170 }
2171
2172 // The default channel may or may not be in |receive_channels_|. Set the rtp
2173 // header extensions for default channel regardless.
2174 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2175 return false;
2176 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002177
2178 // Loop through all receive channels and enable/disable the extensions.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002179 for (const auto& ch : receive_channels_) {
2180 if (!SetChannelRecvRtpHeaderExtensions(ch.second->channel(), extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002181 return false;
2182 }
2183 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002184
2185 receive_extensions_ = extensions;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002186
2187 // Recreate AudioReceiveStream:s.
2188 {
2189 std::vector<webrtc::RtpExtension> exts;
2190
2191 const RtpHeaderExtension* audio_level_extension =
2192 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2193 if (audio_level_extension) {
2194 exts.push_back({
2195 kRtpAudioLevelHeaderExtension, audio_level_extension->id});
2196 }
2197
2198 const RtpHeaderExtension* send_time_extension =
2199 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2200 if (send_time_extension) {
2201 exts.push_back({
2202 kRtpAbsoluteSenderTimeHeaderExtension, send_time_extension->id});
2203 }
2204
2205 recv_rtp_extensions_.swap(exts);
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002206 RecreateAudioReceiveStreams();
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002207 }
2208
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002209 return true;
2210}
2211
2212bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2213 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002214 const RtpHeaderExtension* audio_level_extension =
2215 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2216 if (!SetHeaderExtension(
2217 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2218 audio_level_extension)) {
2219 return false;
2220 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002221
2222 const RtpHeaderExtension* send_time_extension =
2223 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2224 if (!SetHeaderExtension(
2225 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2226 send_time_extension)) {
2227 return false;
2228 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002229
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002230 return true;
2231}
2232
2233bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2234 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002235 if (send_extensions_ == extensions) {
2236 return true;
2237 }
2238
2239 // The default channel may or may not be in |send_channels_|. Set the rtp
2240 // header extensions for default channel regardless.
2241
2242 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2243 return false;
2244 }
2245
2246 // Loop through all send channels and enable/disable the extensions.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002247 for (const auto& ch : send_channels_) {
2248 if (!SetChannelSendRtpHeaderExtensions(ch.second->channel(), extensions)) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002249 return false;
2250 }
2251 }
2252
2253 send_extensions_ = extensions;
2254 return true;
2255}
2256
2257bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2258 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002259 const RtpHeaderExtension* audio_level_extension =
2260 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002261
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002262 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002263 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002264 audio_level_extension)) {
2265 return false;
2266 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002267
2268 const RtpHeaderExtension* send_time_extension =
2269 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002270 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002271 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002272 send_time_extension)) {
2273 return false;
2274 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002275
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002276 return true;
2277}
2278
2279bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2280 desired_playout_ = playout;
2281 return ChangePlayout(desired_playout_);
2282}
2283
2284bool WebRtcVoiceMediaChannel::PausePlayout() {
2285 return ChangePlayout(false);
2286}
2287
2288bool WebRtcVoiceMediaChannel::ResumePlayout() {
2289 return ChangePlayout(desired_playout_);
2290}
2291
2292bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2293 if (playout_ == playout) {
2294 return true;
2295 }
2296
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002297 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002298 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002299 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002300 // Only toggle the default channel if we don't have any other channels.
2301 result = SetPlayout(voe_channel(), playout);
2302 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002303 for (const auto& ch : receive_channels_) {
2304 if (!SetPlayout(ch.second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002305 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002306 << ch.second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002307 result = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002308 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002309 }
2310 }
2311
2312 if (result) {
2313 playout_ = playout;
2314 }
2315 return result;
2316}
2317
2318bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2319 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002320 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002321 return ChangeSend(desired_send_);
2322 return true;
2323}
2324
2325bool WebRtcVoiceMediaChannel::PauseSend() {
2326 return ChangeSend(SEND_NOTHING);
2327}
2328
2329bool WebRtcVoiceMediaChannel::ResumeSend() {
2330 return ChangeSend(desired_send_);
2331}
2332
2333bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2334 if (send_ == send) {
2335 return true;
2336 }
2337
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002338 // Change the settings on each send channel.
2339 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002340 engine()->SetOptionOverrides(options_);
2341
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002342 // Change the settings on each send channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002343 for (const auto& ch : send_channels_) {
2344 if (!ChangeSend(ch.second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002345 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002346 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002347
2348 // Clear up the options after stopping sending.
2349 if (send == SEND_NOTHING)
2350 engine()->ClearOptionOverrides();
2351
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002352 send_ = send;
2353 return true;
2354}
2355
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002356bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2357 if (send == SEND_MICROPHONE) {
2358 if (engine()->voe()->base()->StartSend(channel) == -1) {
2359 LOG_RTCERR1(StartSend, channel);
2360 return false;
2361 }
2362 if (engine()->voe()->file() &&
2363 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2364 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2365 return false;
2366 }
2367 } else { // SEND_NOTHING
henrikg91d6ede2015-09-17 00:24:34 -07002368 RTC_DCHECK(send == SEND_NOTHING);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002369 if (engine()->voe()->base()->StopSend(channel) == -1) {
2370 LOG_RTCERR1(StopSend, channel);
2371 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002372 }
2373 }
2374
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002375 return true;
2376}
2377
solenberg1dd98f32015-09-10 01:57:14 -07002378bool WebRtcVoiceMediaChannel::SetAudioSend(uint32 ssrc, bool mute,
2379 const AudioOptions* options,
2380 AudioRenderer* renderer) {
2381 // TODO(solenberg): The state change should be fully rolled back if any one of
2382 // these calls fail.
2383 if (!SetLocalRenderer(ssrc, renderer)) {
2384 return false;
2385 }
2386 if (!MuteStream(ssrc, mute)) {
2387 return false;
2388 }
2389 if (!mute && options) {
2390 return SetOptions(*options);
2391 }
2392 return true;
2393}
2394
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002395// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002396void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2397 if (engine()->voe()->network()->RegisterExternalTransport(
2398 channel, *this) == -1) {
2399 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2400 }
2401
2402 // Enable RTCP (for quality stats and feedback messages)
2403 EnableRtcp(channel);
2404
2405 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2406 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002407
2408 // Set RTP header extension for the new channel.
2409 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002410}
2411
2412bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2413 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2414 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2415 }
2416
2417 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2418 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002419 return false;
2420 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002421
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002422 return true;
2423}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002424
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002425bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2426 // If the default channel is already used for sending create a new channel
2427 // otherwise use the default channel for sending.
2428 int channel = GetSendChannelNum(sp.first_ssrc());
2429 if (channel != -1) {
2430 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2431 return false;
2432 }
2433
2434 bool default_channel_is_available = true;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002435 for (const auto& ch : send_channels_) {
2436 if (IsDefaultChannel(ch.second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002437 default_channel_is_available = false;
2438 break;
2439 }
2440 }
2441 if (default_channel_is_available) {
2442 channel = voe_channel();
2443 } else {
2444 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002445 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002446 if (channel == -1) {
2447 LOG_RTCERR0(CreateChannel);
2448 return false;
2449 }
2450
2451 ConfigureSendChannel(channel);
2452 }
2453
2454 // Save the channel to send_channels_, so that RemoveSendStream() can still
2455 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002456 webrtc::AudioTransport* audio_transport =
2457 engine()->voe()->base()->audio_transport();
pbos8fc7fa72015-07-15 08:02:58 -07002458 send_channels_.insert(
2459 std::make_pair(sp.first_ssrc(),
2460 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002461
2462 // Set the send (local) SSRC.
2463 // If there are multiple send SSRCs, we can only set the first one here, and
2464 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2465 // (with a codec requires multiple SSRC(s)).
2466 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2467 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2468 return false;
2469 }
2470
2471 // At this point the channel's local SSRC has been updated. If the channel is
2472 // the default channel make sure that all the receive channels are updated as
2473 // well. Receive channels have to have the same SSRC as the default channel in
2474 // order to send receiver reports with this SSRC.
2475 if (IsDefaultChannel(channel)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002476 for (const auto& ch : receive_channels_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002477 // Only update the SSRC for non-default channels.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002478 if (!IsDefaultChannel(ch.second->channel())) {
2479 if (engine()->voe()->rtp()->SetLocalSSRC(ch.second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002480 sp.first_ssrc()) != 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002481 LOG_RTCERR2(SetLocalSSRC, ch.second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002482 return false;
2483 }
2484 }
2485 }
2486 }
2487
2488 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002489 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2490 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002491 }
2492
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002493 // Set the current codecs to be used for the new channel.
2494 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002495 return false;
2496
2497 return ChangeSend(channel, desired_send_);
2498}
2499
2500bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2501 ChannelMap::iterator it = send_channels_.find(ssrc);
2502 if (it == send_channels_.end()) {
2503 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2504 << " which doesn't exist.";
2505 return false;
2506 }
2507
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002508 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002509 ChangeSend(channel, SEND_NOTHING);
2510
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002511 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2512 // this will disconnect the audio renderer with the send channel.
2513 delete it->second;
2514 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002515
2516 if (IsDefaultChannel(channel)) {
2517 // Do not delete the default channel since the receive channels depend on
2518 // the default channel, recycle it instead.
2519 ChangeSend(channel, SEND_NOTHING);
2520 } else {
2521 // Clean up and delete the send channel.
2522 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2523 << " with VoiceEngine channel #" << channel << ".";
2524 if (!DeleteChannel(channel))
2525 return false;
2526 }
2527
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002528 if (send_channels_.empty())
2529 ChangeSend(SEND_NOTHING);
2530
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002531 return true;
2532}
2533
2534bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
henrikg91d6ede2015-09-17 00:24:34 -07002535 RTC_DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002536 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002537
2538 if (!VERIFY(sp.ssrcs.size() == 1))
2539 return false;
2540 uint32 ssrc = sp.first_ssrc();
2541
wu@webrtc.org78187522013-10-07 23:32:02 +00002542 if (ssrc == 0) {
2543 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2544 return false;
2545 }
2546
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002547 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2548 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002549 return false;
2550 }
2551
henrikg91d6ede2015-09-17 00:24:34 -07002552 RTC_DCHECK(receive_stream_params_.find(ssrc) == receive_stream_params_.end());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002553
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002554 // Reuse default channel for recv stream in non-conference mode call
2555 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002556 webrtc::AudioTransport* audio_transport =
2557 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002558 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002559 LOG(LS_INFO) << "Recv stream " << ssrc << " reuse default channel";
2560 default_receive_ssrc_ = ssrc;
pbos8fc7fa72015-07-15 08:02:58 -07002561 WebRtcVoiceChannelRenderer* channel_renderer =
2562 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport);
2563 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2564 receive_stream_params_[ssrc] = sp;
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002565 AddAudioReceiveStream(ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002566 return SetPlayout(voe_channel(), playout_);
2567 }
2568
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002569 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002570 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002571 if (channel == -1) {
2572 LOG_RTCERR0(CreateChannel);
2573 return false;
2574 }
2575
wu@webrtc.org78187522013-10-07 23:32:02 +00002576 if (!ConfigureRecvChannel(channel)) {
2577 DeleteChannel(channel);
2578 return false;
2579 }
2580
pbos8fc7fa72015-07-15 08:02:58 -07002581 WebRtcVoiceChannelRenderer* channel_renderer =
2582 new WebRtcVoiceChannelRenderer(channel, audio_transport);
2583 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2584 receive_stream_params_[ssrc] = sp;
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002585 AddAudioReceiveStream(ssrc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002586
2587 LOG(LS_INFO) << "New audio stream " << ssrc
2588 << " registered to VoiceEngine channel #"
2589 << channel << ".";
2590 return true;
2591}
2592
2593bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002594 // Configure to use external transport, like our default channel.
2595 if (engine()->voe()->network()->RegisterExternalTransport(
2596 channel, *this) == -1) {
2597 LOG_RTCERR2(SetExternalTransport, channel, this);
2598 return false;
2599 }
2600
2601 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002602 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002603 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2604 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002605 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002606 return false;
2607 }
2608 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002609 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002610 return false;
2611 }
2612
Minyue2013aec2015-05-13 14:14:42 +02002613 // Associate receive channel to default channel (so the receive channel can
2614 // obtain RTT from the send channel)
2615 engine()->voe()->base()->AssociateSendChannel(channel, voe_channel());
2616 LOG(LS_INFO) << "VoiceEngine channel #"
2617 << channel << " is associated with channel #"
2618 << voe_channel() << ".";
2619
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002620 // Use the same recv payload types as our default channel.
2621 ResetRecvCodecs(channel);
2622 if (!recv_codecs_.empty()) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002623 for (const auto& codec : recv_codecs_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002624 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002625 if (engine()->FindWebRtcCodec(codec, &voe_codec)) {
2626 voe_codec.pltype = codec.id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002627 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2628 if (engine()->voe()->codec()->GetRecPayloadType(
2629 voe_channel(), voe_codec) != -1) {
2630 if (engine()->voe()->codec()->SetRecPayloadType(
2631 channel, voe_codec) == -1) {
2632 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2633 return false;
2634 }
2635 }
2636 }
2637 }
2638 }
2639
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002640 if (InConferenceMode()) {
2641 // To be in par with the video, voe_channel() is not used for receiving in
2642 // a conference call.
2643 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2644 // This is the first stream in a multi user meeting. We can now
2645 // disable playback of the default stream. This since the default
2646 // stream will probably have received some initial packets before
2647 // the new stream was added. This will mean that the CN state from
2648 // the default channel will be mixed in with the other streams
2649 // throughout the whole meeting, which might be disturbing.
2650 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2651 SetPlayout(voe_channel(), false);
2652 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002653 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002654 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002655
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002656 // Set RTP header extension for the new channel.
2657 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2658 return false;
2659 }
2660
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002661 return SetPlayout(channel, playout_);
2662}
2663
2664bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
henrikg91d6ede2015-09-17 00:24:34 -07002665 RTC_DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002666 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002667 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002668 if (it == receive_channels_.end()) {
2669 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2670 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002671 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002672 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002673
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002674 RemoveAudioReceiveStream(ssrc);
pbos8fc7fa72015-07-15 08:02:58 -07002675 receive_stream_params_.erase(ssrc);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002676
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002677 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2678 // will disconnect the audio renderer with the receive channel.
2679 // Cache the channel before the deletion.
2680 const int channel = it->second->channel();
2681 delete it->second;
2682 receive_channels_.erase(it);
2683
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002684 if (ssrc == default_receive_ssrc_) {
henrikg91d6ede2015-09-17 00:24:34 -07002685 RTC_DCHECK(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002686 // Recycle the default channel is for recv stream.
2687 if (playout_)
2688 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002689
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002690 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002691 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002692 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002693
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002694 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002695 << " with VoiceEngine channel #" << channel << ".";
2696 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002697 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002698
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002699 bool enable_default_channel_playout = false;
2700 if (receive_channels_.empty()) {
2701 // The last stream was removed. We can now enable the default
2702 // channel for new channels to be played out immediately without
2703 // waiting for AddStream messages.
2704 // We do this for both conference mode and non-conference mode.
2705 // TODO(oja): Does the default channel still have it's CN state?
2706 enable_default_channel_playout = true;
2707 }
2708 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2709 default_receive_ssrc_ != 0) {
2710 // Only the default channel is active, enable the playout on default
2711 // channel.
2712 enable_default_channel_playout = true;
2713 }
2714 if (enable_default_channel_playout && playout_) {
2715 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2716 SetPlayout(voe_channel(), true);
2717 }
2718
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002719 return true;
2720}
2721
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002722bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2723 AudioRenderer* renderer) {
2724 ChannelMap::iterator it = receive_channels_.find(ssrc);
2725 if (it == receive_channels_.end()) {
2726 if (renderer) {
2727 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002728 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002729 return false;
2730 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002731
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002732 // The channel likely has gone away, do nothing.
2733 return true;
2734 }
2735
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002736 if (renderer)
2737 it->second->Start(renderer);
2738 else
2739 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002740
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002741 return true;
2742}
2743
2744bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2745 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002746 ChannelMap::iterator it = send_channels_.find(ssrc);
2747 if (it == send_channels_.end()) {
2748 if (renderer) {
2749 // Return an error if trying to set a valid renderer with an invalid ssrc.
2750 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2751 return false;
2752 }
2753
2754 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002755 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002756 }
2757
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002758 if (renderer)
2759 it->second->Start(renderer);
2760 else
2761 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002762
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002763 return true;
2764}
2765
2766bool WebRtcVoiceMediaChannel::GetActiveStreams(
2767 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002768 // In conference mode, the default channel should not be in
2769 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002770 actives->clear();
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002771 for (const auto& ch : receive_channels_) {
2772 int level = GetOutputLevel(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002773 if (level > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002774 actives->push_back(std::make_pair(ch.first, level));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002775 }
2776 }
2777 return true;
2778}
2779
2780int WebRtcVoiceMediaChannel::GetOutputLevel() {
2781 // return the highest output level of all streams
2782 int highest = GetOutputLevel(voe_channel());
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002783 for (const auto& ch : receive_channels_) {
2784 int level = GetOutputLevel(ch.second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002785 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002786 }
2787 return highest;
2788}
2789
2790int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2791 int ret;
2792 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2793 // In case of error, log the info and continue
2794 LOG_RTCERR0(TimeSinceLastTyping);
2795 ret = -1;
2796 } else {
2797 ret *= 1000; // We return ms, webrtc returns seconds.
2798 }
2799 return ret;
2800}
2801
2802void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2803 int cost_per_typing, int reporting_threshold, int penalty_decay,
2804 int type_event_delay) {
2805 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2806 time_window, cost_per_typing,
2807 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2808 // In case of error, log the info and continue
2809 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2810 cost_per_typing, reporting_threshold, penalty_decay,
2811 type_event_delay);
2812 }
2813}
2814
2815bool WebRtcVoiceMediaChannel::SetOutputScaling(
2816 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002817 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002818 // Collect the channels to scale the output volume.
2819 std::vector<int> channels;
2820 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002821 // Default channel is not in receive_channels_ if it is not being used for
2822 // playout.
2823 if (default_receive_ssrc_ == 0)
2824 channels.push_back(voe_channel());
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002825 for (const auto& ch : receive_channels_) {
2826 channels.push_back(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002827 }
2828 } else { // Collect only the channel of the specified ssrc.
2829 int channel = GetReceiveChannelNum(ssrc);
2830 if (-1 == channel) {
2831 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2832 return false;
2833 }
2834 channels.push_back(channel);
2835 }
2836
2837 // Scale the output volume for the collected channels. We first normalize to
2838 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002839 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002840 if (scale > 0.0001f) {
2841 left /= scale;
2842 right /= scale;
2843 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002844 for (int ch_id : channels) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002845 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002846 ch_id, scale)) {
2847 LOG_RTCERR2(SetChannelOutputVolumeScaling, ch_id, scale);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002848 return false;
2849 }
2850 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002851 ch_id, static_cast<float>(left), static_cast<float>(right))) {
2852 LOG_RTCERR3(SetOutputVolumePan, ch_id, left, right);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002853 // Do not return if fails. SetOutputVolumePan is not available for all
2854 // pltforms.
2855 }
2856 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2857 << " right=" << right * scale
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002858 << " for channel " << ch_id << " and ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002859 }
2860 return true;
2861}
2862
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002863bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2864 return dtmf_allowed_;
2865}
2866
2867bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2868 int duration, int flags) {
2869 if (!dtmf_allowed_) {
2870 return false;
2871 }
2872
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002873 // Send the event.
2874 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002875 int channel = -1;
2876 if (ssrc == 0) {
2877 bool default_channel_is_inuse = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002878 for (const auto& ch : send_channels_) {
2879 if (IsDefaultChannel(ch.second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002880 default_channel_is_inuse = true;
2881 break;
2882 }
2883 }
2884 if (default_channel_is_inuse) {
2885 channel = voe_channel();
2886 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002887 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002888 }
2889 } else {
2890 channel = GetSendChannelNum(ssrc);
2891 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002892 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002893 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2894 << ssrc << " is not in use.";
2895 return false;
2896 }
2897 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002898 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2899 channel, event, true, duration) == -1) {
2900 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002901 return false;
2902 }
2903 }
2904
2905 // Play the event.
2906 if (flags & cricket::DF_PLAY) {
2907 // Play DTMF tone locally.
2908 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
2909 LOG_RTCERR2(PlayDtmfTone, event, duration);
2910 return false;
2911 }
2912 }
2913
2914 return true;
2915}
2916
wu@webrtc.orga9890802013-12-13 00:21:03 +00002917void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002918 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrikg91d6ede2015-09-17 00:24:34 -07002919 RTC_DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002920
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002921 // Forward packet to Call as well.
2922 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2923 packet_time.not_before);
2924 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
2925 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
2926 webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002927
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002928 // Pick which channel to send this packet to. If this packet doesn't match
2929 // any multiplexed streams, just send it to the default channel. Otherwise,
2930 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002931 int which_channel =
2932 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002933 if (which_channel == -1) {
2934 which_channel = voe_channel();
2935 }
2936
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002937 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002938 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002939 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002940 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002941}
2942
wu@webrtc.orga9890802013-12-13 00:21:03 +00002943void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002944 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrikg91d6ede2015-09-17 00:24:34 -07002945 RTC_DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002946
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002947 // Forward packet to Call as well.
2948 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2949 packet_time.not_before);
2950 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
2951 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
2952 webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002953
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002954 // Sending channels need all RTCP packets with feedback information.
2955 // Even sender reports can contain attached report blocks.
2956 // Receiving channels need sender reports in order to create
2957 // correct receiver reports.
2958 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002959 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002960 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2961 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002962 }
2963
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002964 // If it is a sender report, find the channel that is listening.
2965 bool has_sent_to_default_channel = false;
2966 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002967 int which_channel =
2968 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002969 if (which_channel != -1) {
2970 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002971 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002972
2973 if (IsDefaultChannel(which_channel))
2974 has_sent_to_default_channel = true;
2975 }
2976 }
2977
2978 // SR may continue RR and any RR entry may correspond to any one of the send
2979 // channels. So all RTCP packets must be forwarded all send channels. VoE
2980 // will filter out RR internally.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002981 for (const auto& ch : send_channels_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002982 // Make sure not sending the same packet to default channel more than once.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002983 if (IsDefaultChannel(ch.second->channel()) &&
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002984 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002985 continue;
2986
2987 engine()->voe()->network()->ReceivedRTCPPacket(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002988 ch.second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002989 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002990}
2991
2992bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002993 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
2994 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002995 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2996 return false;
2997 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002998 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
2999 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003000 return false;
3001 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003002 // We set the AGC to mute state only when all the channels are muted.
3003 // This implementation is not ideal, instead we should signal the AGC when
3004 // the mic channel is muted/unmuted. We can't do it today because there
3005 // is no good way to know which stream is mapping to the mic channel.
3006 bool all_muted = muted;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003007 for (const auto& ch : send_channels_) {
3008 if (!all_muted) {
3009 break;
3010 }
3011 if (engine()->voe()->volume()->GetInputMute(ch.second->channel(),
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003012 all_muted)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003013 LOG_RTCERR1(GetInputMute, ch.second->channel());
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003014 return false;
3015 }
3016 }
3017
3018 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3019 if (ap)
3020 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003021 return true;
3022}
3023
minyue@webrtc.org26236952014-10-29 02:27:08 +00003024// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3025// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003026bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003027 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003028
minyue@webrtc.org26236952014-10-29 02:27:08 +00003029 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003030}
3031
minyue@webrtc.org26236952014-10-29 02:27:08 +00003032bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3033 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003034
minyue@webrtc.org26236952014-10-29 02:27:08 +00003035 send_bitrate_setting_ = true;
3036 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003037
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003038 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003039 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003040 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003041 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003042 }
3043
minyue@webrtc.org26236952014-10-29 02:27:08 +00003044 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003045 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3046 // SetMaxSendBandwith(0), the second call removes the previous limit.
3047 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003048 return true;
3049
3050 webrtc::CodecInst codec = *send_codec_;
3051 bool is_multi_rate = IsCodecMultiRate(codec);
3052
3053 if (is_multi_rate) {
3054 // If codec is multi-rate then just set the bitrate.
3055 codec.rate = bps;
3056 if (!SetSendCodec(codec)) {
3057 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3058 << " to bitrate " << bps << " bps.";
3059 return false;
3060 }
3061 return true;
3062 } else {
3063 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3064 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3065 // fixed bitrate then ignore.
3066 if (bps < codec.rate) {
3067 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3068 << " to bitrate " << bps << " bps"
3069 << ", requires at least " << codec.rate << " bps.";
3070 return false;
3071 }
3072 return true;
3073 }
3074}
3075
3076bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003077 bool echo_metrics_on = false;
3078 // These can take on valid negative values, so use the lowest possible level
3079 // as default rather than -1.
3080 int echo_return_loss = -100;
3081 int echo_return_loss_enhancement = -100;
3082 // These can also be negative, but in practice -1 is only used to signal
3083 // insufficient data, since the resolution is limited to multiples of 4 ms.
3084 int echo_delay_median_ms = -1;
3085 int echo_delay_std_ms = -1;
3086 if (engine()->voe()->processing()->GetEcMetricsStatus(
3087 echo_metrics_on) != -1 && echo_metrics_on) {
3088 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3089 // here, but it appears to be unsuitable currently. Revisit after this is
3090 // investigated: http://b/issue?id=5666755
3091 int erl, erle, rerl, anlp;
3092 if (engine()->voe()->processing()->GetEchoMetrics(
3093 erl, erle, rerl, anlp) != -1) {
3094 echo_return_loss = erl;
3095 echo_return_loss_enhancement = erle;
3096 }
3097
3098 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003099 float dummy;
3100 if (engine()->voe()->processing()->GetEcDelayMetrics(
3101 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003102 echo_delay_median_ms = median;
3103 echo_delay_std_ms = std;
3104 }
3105 }
3106
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003107 webrtc::CallStatistics cs;
3108 unsigned int ssrc;
3109 webrtc::CodecInst codec;
3110 unsigned int level;
3111
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003112 for (const auto& ch : send_channels_) {
3113 const int channel = ch.second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003114
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003115 // Fill in the sender info, based on what we know, and what the
3116 // remote side told us it got from its RTCP report.
3117 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003118
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003119 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3120 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3121 continue;
3122 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003123
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003124 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003125 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3126 sinfo.bytes_sent = cs.bytesSent;
3127 sinfo.packets_sent = cs.packetsSent;
3128 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3129 // returns 0 to indicate an error value.
3130 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3131
3132 // Get data from the last remote RTCP report. Use default values if no data
3133 // available.
3134 sinfo.fraction_lost = -1.0;
3135 sinfo.jitter_ms = -1;
3136 sinfo.packets_lost = -1;
3137 sinfo.ext_seqnum = -1;
3138 std::vector<webrtc::ReportBlock> receive_blocks;
3139 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3140 channel, &receive_blocks) != -1 &&
3141 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003142 for (const webrtc::ReportBlock& block : receive_blocks) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003143 // Lookup report for send ssrc only.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003144 if (block.source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003145 // Convert Q8 to floating point.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003146 sinfo.fraction_lost = static_cast<float>(block.fraction_lost) / 256;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003147 // Convert samples to milliseconds.
3148 if (codec.plfreq / 1000 > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003149 sinfo.jitter_ms = block.interarrival_jitter / (codec.plfreq / 1000);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003150 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003151 sinfo.packets_lost = block.cumulative_num_packets_lost;
3152 sinfo.ext_seqnum = block.extended_highest_sequence_number;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003153 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003154 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003155 }
3156 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003157
3158 // Local speech level.
3159 sinfo.audio_level = (engine()->voe()->volume()->
3160 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3161
3162 // TODO(xians): We are injecting the same APM logging to all the send
3163 // channels here because there is no good way to know which send channel
3164 // is using the APM. The correct fix is to allow the send channels to have
3165 // their own APM so that we can feed the correct APM logging to different
3166 // send channels. See issue crbug/264611 .
3167 sinfo.echo_return_loss = echo_return_loss;
3168 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3169 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3170 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003171 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3172 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003173 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003174
3175 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003176 }
3177
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003178 // Build the list of receivers, one for each receiving channel, or 1 in
3179 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003180 std::vector<int> channels;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003181 for (const auto& ch : receive_channels_) {
3182 channels.push_back(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003183 }
3184 if (channels.empty()) {
3185 channels.push_back(voe_channel());
3186 }
3187
3188 // Get the SSRC and stats for each receiver, based on our own calculations.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003189 for (int ch_id : channels) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003190 memset(&cs, 0, sizeof(cs));
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003191 if (engine()->voe()->rtp()->GetRemoteSSRC(ch_id, ssrc) != -1 &&
3192 engine()->voe()->rtp()->GetRTCPStatistics(ch_id, cs) != -1 &&
3193 engine()->voe()->codec()->GetRecCodec(ch_id, codec) != -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003194 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003195 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003196 rinfo.bytes_rcvd = cs.bytesReceived;
3197 rinfo.packets_rcvd = cs.packetsReceived;
3198 // The next four fields are from the most recently sent RTCP report.
3199 // Convert Q8 to floating point.
3200 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3201 rinfo.packets_lost = cs.cumulativeLost;
3202 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003203 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003204 if (codec.pltype != -1) {
3205 rinfo.codec_name = codec.plname;
3206 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003207 // Convert samples to milliseconds.
3208 if (codec.plfreq / 1000 > 0) {
3209 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3210 }
3211
3212 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3213 webrtc::NetworkStatistics ns;
3214 if (engine()->voe()->neteq() &&
3215 engine()->voe()->neteq()->GetNetworkStatistics(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003216 ch_id, ns) != -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003217 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3218 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3219 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003220 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003221 rinfo.speech_expand_rate =
3222 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3223 rinfo.secondary_decoded_rate =
3224 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
Henrik Lundin8e6fd462015-06-02 09:24:52 +02003225 rinfo.accelerate_rate =
3226 static_cast<float>(ns.currentAccelerateRate) / (1 << 14);
3227 rinfo.preemptive_expand_rate =
3228 static_cast<float>(ns.currentPreemptiveRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003229 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003230
3231 webrtc::AudioDecodingCallStats ds;
3232 if (engine()->voe()->neteq() &&
3233 engine()->voe()->neteq()->GetDecodingCallStatistics(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003234 ch_id, &ds) != -1) {
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003235 rinfo.decoding_calls_to_silence_generator =
3236 ds.calls_to_silence_generator;
3237 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3238 rinfo.decoding_normal = ds.decoded_normal;
3239 rinfo.decoding_plc = ds.decoded_plc;
3240 rinfo.decoding_cng = ds.decoded_cng;
3241 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3242 }
3243
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003244 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003245 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003246 int playout_buffer_delay_ms = 0;
3247 engine()->voe()->sync()->GetDelayEstimate(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003248 ch_id, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003249 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3250 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003251 }
3252
3253 // Get speech level.
3254 rinfo.audio_level = (engine()->voe()->volume()->
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003255 GetSpeechOutputLevelFullRange(ch_id, level) != -1) ? level : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003256 info->receivers.push_back(rinfo);
3257 }
3258 }
3259
3260 return true;
3261}
3262
3263void WebRtcVoiceMediaChannel::GetLastMediaError(
3264 uint32* ssrc, VoiceMediaChannel::Error* error) {
henrikg91d6ede2015-09-17 00:24:34 -07003265 RTC_DCHECK(ssrc != NULL);
3266 RTC_DCHECK(error != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003267 FindSsrc(voe_channel(), ssrc);
3268 *error = WebRtcErrorToChannelError(GetLastEngineError());
3269}
3270
3271bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003272 rtc::CritScope lock(&receive_channels_cs_);
henrikg91d6ede2015-09-17 00:24:34 -07003273 RTC_DCHECK(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003274 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003275 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3276 // This means the error is not limited to a specific channel. Signal the
3277 // message using ssrc=0. If the current channel is sending, use this
3278 // channel for sending the message.
3279 *ssrc = 0;
3280 return true;
3281 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003282 // Check whether this is a sending channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003283 for (const auto& ch : send_channels_) {
3284 if (ch.second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003285 // This is a sending channel.
3286 uint32 local_ssrc = 0;
3287 if (engine()->voe()->rtp()->GetLocalSSRC(
3288 channel_num, local_ssrc) != -1) {
3289 *ssrc = local_ssrc;
3290 }
3291 return true;
3292 }
3293 }
3294
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003295 // Check whether this is a receiving channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003296 for (const auto& ch : receive_channels_) {
3297 if (ch.second->channel() == channel_num) {
3298 *ssrc = ch.first;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003299 return true;
3300 }
3301 }
3302 }
3303 return false;
3304}
3305
3306void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003307 if (error == VE_TYPING_NOISE_WARNING) {
3308 typing_noise_detected_ = true;
3309 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3310 typing_noise_detected_ = false;
3311 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003312 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3313}
3314
3315int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3316 unsigned int ulevel;
3317 int ret =
3318 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3319 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3320}
3321
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003322int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) const {
3323 ChannelMap::const_iterator it = receive_channels_.find(ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003324 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003325 return it->second->channel();
pbos8fc7fa72015-07-15 08:02:58 -07003326 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003327}
3328
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003329int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) const {
3330 ChannelMap::const_iterator it = send_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003331 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003332 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003333
3334 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003335}
3336
3337bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3338 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3339 // Get the RED encodings from the parameter with no name. This may
3340 // change based on what is discussed on the Jingle list.
3341 // The encoding parameter is of the form "a/b"; we only support where
3342 // a == b. Verify this and parse out the value into red_pt.
3343 // If the parameter value is absent (as it will be until we wire up the
3344 // signaling of this message), use the second codec specified (i.e. the
3345 // one after "red") as the encoding parameter.
3346 int red_pt = -1;
3347 std::string red_params;
3348 CodecParameterMap::const_iterator it = red_codec.params.find("");
3349 if (it != red_codec.params.end()) {
3350 red_params = it->second;
3351 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003352 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003353 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003354 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003355 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3356 return false;
3357 }
3358 } else if (red_codec.params.empty()) {
3359 LOG(LS_WARNING) << "RED params not present, using defaults";
3360 if (all_codecs.size() > 1) {
3361 red_pt = all_codecs[1].id;
3362 }
3363 }
3364
3365 // Try to find red_pt in |codecs|.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003366 for (const AudioCodec& codec : all_codecs) {
3367 if (codec.id == red_pt) {
3368 // If we find the right codec, that will be the codec we pass to
3369 // SetSendCodec, with the desired payload type.
3370 if (engine()->FindWebRtcCodec(codec, send_codec)) {
3371 return true;
3372 } else {
3373 break;
3374 }
3375 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003376 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003377 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3378 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003379}
3380
3381bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3382 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003383 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003384 return false;
3385 }
3386 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3387 // what we want to do with them.
3388 // engine()->voe().EnableVQMon(voe_channel(), true);
3389 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3390 return true;
3391}
3392
3393bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3394 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3395 for (int i = 0; i < ncodecs; ++i) {
3396 webrtc::CodecInst voe_codec;
3397 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3398 voe_codec.pltype = -1;
3399 if (engine()->voe()->codec()->SetRecPayloadType(
3400 channel, voe_codec) == -1) {
3401 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3402 return false;
3403 }
3404 }
3405 }
3406 return true;
3407}
3408
3409bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3410 if (playout) {
3411 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3412 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3413 LOG_RTCERR1(StartPlayout, channel);
3414 return false;
3415 }
3416 } else {
3417 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3418 engine()->voe()->base()->StopPlayout(channel);
3419 }
3420 return true;
3421}
3422
3423uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3424 bool rtcp) {
3425 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3426 uint32 ssrc = 0;
3427 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003428 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003429 }
3430 return ssrc;
3431}
3432
3433// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3434VoiceMediaChannel::Error
3435 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3436 switch (err_code) {
3437 case 0:
3438 return ERROR_NONE;
3439 case VE_CANNOT_START_RECORDING:
3440 case VE_MIC_VOL_ERROR:
3441 case VE_GET_MIC_VOL_ERROR:
3442 case VE_CANNOT_ACCESS_MIC_VOL:
3443 return ERROR_REC_DEVICE_OPEN_FAILED;
3444 case VE_SATURATION_WARNING:
3445 return ERROR_REC_DEVICE_SATURATION;
3446 case VE_REC_DEVICE_REMOVED:
3447 return ERROR_REC_DEVICE_REMOVED;
3448 case VE_RUNTIME_REC_WARNING:
3449 case VE_RUNTIME_REC_ERROR:
3450 return ERROR_REC_RUNTIME_ERROR;
3451 case VE_CANNOT_START_PLAYOUT:
3452 case VE_SPEAKER_VOL_ERROR:
3453 case VE_GET_SPEAKER_VOL_ERROR:
3454 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3455 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3456 case VE_RUNTIME_PLAY_WARNING:
3457 case VE_RUNTIME_PLAY_ERROR:
3458 return ERROR_PLAY_RUNTIME_ERROR;
3459 case VE_TYPING_NOISE_WARNING:
3460 return ERROR_REC_TYPING_NOISE_DETECTED;
3461 default:
3462 return VoiceMediaChannel::ERROR_OTHER;
3463 }
3464}
3465
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003466bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3467 int channel_id, const RtpHeaderExtension* extension) {
3468 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003469 int id = 0;
3470 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003471 if (extension) {
3472 enable = true;
3473 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003474 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003475 }
3476 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003477 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003478 return false;
3479 }
3480 return true;
3481}
3482
Fredrik Solenberg709ed672015-09-15 12:26:33 +02003483void WebRtcVoiceMediaChannel::RecreateAudioReceiveStreams() {
henrikg91d6ede2015-09-17 00:24:34 -07003484 RTC_DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg709ed672015-09-15 12:26:33 +02003485 for (const auto& it : receive_channels_) {
3486 RemoveAudioReceiveStream(it.first);
3487 }
3488 for (const auto& it : receive_channels_) {
3489 AddAudioReceiveStream(it.first);
3490 }
3491}
3492
3493void WebRtcVoiceMediaChannel::AddAudioReceiveStream(uint32 ssrc) {
henrikg91d6ede2015-09-17 00:24:34 -07003494 RTC_DCHECK(thread_checker_.CalledOnValidThread());
pbos8fc7fa72015-07-15 08:02:58 -07003495 WebRtcVoiceChannelRenderer* channel = receive_channels_[ssrc];
henrikg91d6ede2015-09-17 00:24:34 -07003496 RTC_DCHECK(channel != nullptr);
3497 RTC_DCHECK(receive_streams_.find(ssrc) == receive_streams_.end());
pbos8fc7fa72015-07-15 08:02:58 -07003498 webrtc::AudioReceiveStream::Config config;
3499 config.rtp.remote_ssrc = ssrc;
3500 // Only add RTP extensions if we support combined A/V BWE.
pbos6bb1b6e2015-07-24 07:10:18 -07003501 config.rtp.extensions = recv_rtp_extensions_;
3502 config.combined_audio_video_bwe =
3503 options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false);
pbos8fc7fa72015-07-15 08:02:58 -07003504 config.voe_channel_id = channel->channel();
3505 config.sync_group = receive_stream_params_[ssrc].sync_label;
3506 webrtc::AudioReceiveStream* s = call_->CreateAudioReceiveStream(config);
3507 receive_streams_.insert(std::make_pair(ssrc, s));
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003508}
3509
Fredrik Solenberg709ed672015-09-15 12:26:33 +02003510void WebRtcVoiceMediaChannel::RemoveAudioReceiveStream(uint32 ssrc) {
henrikg91d6ede2015-09-17 00:24:34 -07003511 RTC_DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg709ed672015-09-15 12:26:33 +02003512 auto stream_it = receive_streams_.find(ssrc);
3513 if (stream_it != receive_streams_.end()) {
3514 call_->DestroyAudioReceiveStream(stream_it->second);
3515 receive_streams_.erase(stream_it);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003516 }
3517}
3518
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003519bool WebRtcVoiceMediaChannel::SetRecvCodecsInternal(
3520 const std::vector<AudioCodec>& new_codecs) {
3521 for (const AudioCodec& codec : new_codecs) {
3522 webrtc::CodecInst voe_codec;
3523 if (engine()->FindWebRtcCodec(codec, &voe_codec)) {
3524 LOG(LS_INFO) << ToString(codec);
3525 voe_codec.pltype = codec.id;
3526 if (default_receive_ssrc_ == 0) {
3527 // Set the receive codecs on the default channel explicitly if the
3528 // default channel is not used by |receive_channels_|, this happens in
3529 // conference mode or in non-conference mode when there is no playout
3530 // channel.
3531 // TODO(xians): Figure out how we use the default channel in conference
3532 // mode.
3533 if (engine()->voe()->codec()->SetRecPayloadType(
3534 voe_channel(), voe_codec) == -1) {
3535 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
3536 return false;
3537 }
3538 }
3539
3540 // Set the receive codecs on all receiving channels.
3541 for (const auto& ch : receive_channels_) {
3542 if (engine()->voe()->codec()->SetRecPayloadType(
3543 ch.second->channel(), voe_codec) == -1) {
3544 LOG_RTCERR2(SetRecPayloadType, ch.second->channel(),
3545 ToString(voe_codec));
3546 return false;
3547 }
3548 }
3549 } else {
3550 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
3551 return false;
3552 }
3553 }
3554 return true;
3555}
3556
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003557} // namespace cricket
3558
3559#endif // HAVE_WEBRTC_VOICE