blob: 93f4b97b14ad38cecf9c0aeedfd732606c5b3624 [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.
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200334 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
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200496 DCHECK(SignalRxMediaFrame.is_empty());
497 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) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200503 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
Jelena Marusicc28a8962015-05-29 15:05:44 +0200582VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel(
583 const AudioOptions& options) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000584 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
585 if (!ch->valid()) {
586 delete ch;
Jelena Marusicc28a8962015-05-29 15:05:44 +0200587 return nullptr;
588 }
589 if (!ch->SetOptions(options)) {
590 LOG(LS_WARNING) << "Failed to set options while creating channel.";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000591 }
592 return ch;
593}
594
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000595bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
596 if (!ApplyOptions(options)) {
597 return false;
598 }
599 options_ = options;
600 return true;
601}
602
603bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
604 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
605 if (!ApplyOptions(overrides)) {
606 return false;
607 }
608 option_overrides_ = overrides;
609 return true;
610}
611
612bool WebRtcVoiceEngine::ClearOptionOverrides() {
613 LOG(LS_INFO) << "Clearing option overrides.";
614 AudioOptions options = options_;
615 // Only call ApplyOptions if |options_overrides_| contains overrided options.
616 // ApplyOptions affects NS, AGC other options that is shared between
617 // all WebRtcVoiceEngineChannels.
618 if (option_overrides_ == AudioOptions()) {
619 return true;
620 }
621
622 if (!ApplyOptions(options)) {
623 return false;
624 }
625 option_overrides_ = AudioOptions();
626 return true;
627}
628
629// AudioOptions defaults are set in InitInternal (for options with corresponding
630// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
631bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
632 AudioOptions options = options_in; // The options are modified below.
633 // kEcConference is AEC with high suppression.
634 webrtc::EcModes ec_mode = webrtc::kEcConference;
635 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
636 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
637 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
638 bool aecm_comfort_noise = false;
639 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
640 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
641 << aecm_comfort_noise << " (default is false).";
642 }
643
644#if defined(IOS)
645 // On iOS, VPIO provides built-in EC and AGC.
646 options.echo_cancellation.Set(false);
647 options.auto_gain_control.Set(false);
henrika86d907c2015-09-07 16:09:50 +0200648 LOG(LS_INFO) << "Always disable AEC and AGC on iOS. Use built-in instead.";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000649#elif defined(ANDROID)
650 ec_mode = webrtc::kEcAecm;
651#endif
652
653#if defined(IOS) || defined(ANDROID)
654 // Set the AGC mode for iOS as well despite disabling it above, to avoid
655 // unsupported configuration errors from webrtc.
656 agc_mode = webrtc::kAgcFixedDigital;
657 options.typing_detection.Set(false);
658 options.experimental_agc.Set(false);
Henrik Lundin441f6342015-06-09 16:03:13 +0200659 options.extended_filter_aec.Set(false);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000660 options.experimental_ns.Set(false);
661#endif
662
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100663 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
664 // where the feature is not supported.
665 bool use_delay_agnostic_aec = false;
666#if !defined(IOS)
667 if (options.delay_agnostic_aec.Get(&use_delay_agnostic_aec)) {
668 if (use_delay_agnostic_aec) {
669 options.echo_cancellation.Set(true);
Henrik Lundin441f6342015-06-09 16:03:13 +0200670 options.extended_filter_aec.Set(true);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100671 ec_mode = webrtc::kEcConference;
672 }
673 }
674#endif
675
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000676 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
677
678 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
679
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000680 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000681 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000682 // Check if platform supports built-in EC. Currently only supported on
683 // Android and in combination with Java based audio layer.
684 // TODO(henrika): investigate possibility to support built-in EC also
685 // in combination with Open SL ES audio.
686 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
Bjorn Volcker73f72102015-06-03 14:50:15 +0200687 if (built_in_aec) {
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200688 // Built-in EC exists on this device and use_delay_agnostic_aec is not
689 // overriding it. Enable/Disable it according to the echo_cancellation
690 // audio option.
Bjorn Volcker73f72102015-06-03 14:50:15 +0200691 const bool enable_built_in_aec =
692 echo_cancellation && !use_delay_agnostic_aec;
693 if (voe_wrapper_->hw()->EnableBuiltInAEC(enable_built_in_aec) == 0 &&
694 enable_built_in_aec) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100695 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000696 // i.e., replace the software EC with the built-in EC.
697 options.echo_cancellation.Set(false);
bjornv@webrtc.org3f118232015-03-16 14:22:03 +0000698 echo_cancellation = false;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000699 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
700 }
701 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000702 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
703 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
704 return false;
705 } else {
henrika86d907c2015-09-07 16:09:50 +0200706 LOG(LS_INFO) << "Echo control set to " << echo_cancellation
707 << " with mode " << ec_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000708 }
709#if !defined(ANDROID)
710 // TODO(ajm): Remove the error return on Android from webrtc.
711 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
712 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
713 return false;
714 }
715#endif
716 if (ec_mode == webrtc::kEcAecm) {
717 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
718 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
719 return false;
720 }
721 }
722 }
723
724 bool auto_gain_control;
725 if (options.auto_gain_control.Get(&auto_gain_control)) {
726 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
727 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
728 return false;
729 } else {
henrika86d907c2015-09-07 16:09:50 +0200730 LOG(LS_INFO) << "Auto gain set to " << auto_gain_control << " with mode "
731 << agc_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000732 }
733 }
734
735 if (options.tx_agc_target_dbov.IsSet() ||
736 options.tx_agc_digital_compression_gain.IsSet() ||
737 options.tx_agc_limiter.IsSet()) {
738 // Override default_agc_config_. Generally, an unset option means "leave
739 // the VoE bits alone" in this function, so we want whatever is set to be
740 // stored as the new "default". If we didn't, then setting e.g.
741 // tx_agc_target_dbov would reset digital compression gain and limiter
742 // settings.
743 // Also, if we don't update default_agc_config_, then adjust_agc_delta
744 // would be an offset from the original values, and not whatever was set
745 // explicitly.
746 default_agc_config_.targetLeveldBOv =
747 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
748 default_agc_config_.targetLeveldBOv);
749 default_agc_config_.digitalCompressionGaindB =
750 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
751 default_agc_config_.digitalCompressionGaindB);
752 default_agc_config_.limiterEnable =
753 options.tx_agc_limiter.GetWithDefaultIfUnset(
754 default_agc_config_.limiterEnable);
755 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
756 LOG_RTCERR3(SetAgcConfig,
757 default_agc_config_.targetLeveldBOv,
758 default_agc_config_.digitalCompressionGaindB,
759 default_agc_config_.limiterEnable);
760 return false;
761 }
762 }
763
764 bool noise_suppression;
765 if (options.noise_suppression.Get(&noise_suppression)) {
766 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
767 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
768 return false;
769 } else {
770 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
771 << " with mode " << ns_mode;
772 }
773 }
774
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000775 bool highpass_filter;
776 if (options.highpass_filter.Get(&highpass_filter)) {
777 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
778 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
779 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
780 return false;
781 }
782 }
783
784 bool stereo_swapping;
785 if (options.stereo_swapping.Get(&stereo_swapping)) {
786 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
787 voep->EnableStereoChannelSwapping(stereo_swapping);
788 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
789 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
790 return false;
791 }
792 }
793
Henrik Lundin64dad832015-05-11 12:44:23 +0200794 int audio_jitter_buffer_max_packets;
795 if (options.audio_jitter_buffer_max_packets.Get(
796 &audio_jitter_buffer_max_packets)) {
797 LOG(LS_INFO) << "NetEq capacity is " << audio_jitter_buffer_max_packets;
798 voe_config_.Set<webrtc::NetEqCapacityConfig>(
799 new webrtc::NetEqCapacityConfig(audio_jitter_buffer_max_packets));
800 }
801
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200802 bool audio_jitter_buffer_fast_accelerate;
803 if (options.audio_jitter_buffer_fast_accelerate.Get(
804 &audio_jitter_buffer_fast_accelerate)) {
805 LOG(LS_INFO) << "NetEq fast mode? " << audio_jitter_buffer_fast_accelerate;
806 voe_config_.Set<webrtc::NetEqFastAccelerate>(
807 new webrtc::NetEqFastAccelerate(audio_jitter_buffer_fast_accelerate));
808 }
809
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000810 bool typing_detection;
811 if (options.typing_detection.Get(&typing_detection)) {
812 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
813 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
814 // In case of error, log the info and continue
815 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
816 }
817 }
818
819 int adjust_agc_delta;
820 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
821 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
822 if (!AdjustAgcLevel(adjust_agc_delta)) {
823 return false;
824 }
825 }
826
827 bool aec_dump;
828 if (options.aec_dump.Get(&aec_dump)) {
829 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
830 if (aec_dump)
831 StartAecDump(kAecDumpByAudioOptionFilename);
832 else
833 StopAecDump();
834 }
835
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000836 webrtc::Config config;
837
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100838 delay_agnostic_aec_.SetFrom(options.delay_agnostic_aec);
839 bool delay_agnostic_aec;
840 if (delay_agnostic_aec_.Get(&delay_agnostic_aec)) {
841 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << delay_agnostic_aec;
henrik.lundin0f133b92015-07-02 00:17:55 -0700842 config.Set<webrtc::DelayAgnostic>(
843 new webrtc::DelayAgnostic(delay_agnostic_aec));
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100844 }
845
Henrik Lundin441f6342015-06-09 16:03:13 +0200846 extended_filter_aec_.SetFrom(options.extended_filter_aec);
847 bool extended_filter;
848 if (extended_filter_aec_.Get(&extended_filter)) {
849 LOG(LS_INFO) << "Extended filter aec is enabled? " << extended_filter;
850 config.Set<webrtc::ExtendedFilter>(
851 new webrtc::ExtendedFilter(extended_filter));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000852 }
853
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000854 experimental_ns_.SetFrom(options.experimental_ns);
855 bool experimental_ns;
856 if (experimental_ns_.Get(&experimental_ns)) {
857 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
858 config.Set<webrtc::ExperimentalNs>(
859 new webrtc::ExperimentalNs(experimental_ns));
860 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000861
862 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
863 // returns NULL on audio_processing().
864 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
865 if (audioproc) {
866 audioproc->SetExtraOptions(config);
867 }
868
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000869 uint32 recording_sample_rate;
870 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
871 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
872 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
873 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
874 }
875 }
876
877 uint32 playout_sample_rate;
878 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
879 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
880 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
881 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
882 }
883 }
884
885 return true;
886}
887
888bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
889 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
890 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
891 LOG_RTCERR1(SetDelayOffsetMs, offset);
892 return false;
893 }
894
895 return true;
896}
897
898struct ResumeEntry {
899 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
900 : channel(c),
901 playout(p),
902 send(s) {
903 }
904
905 WebRtcVoiceMediaChannel *channel;
906 bool playout;
907 SendFlags send;
908};
909
910// TODO(juberti): Refactor this so that the core logic can be used to set the
911// soundclip device. At that time, reinstate the soundclip pause/resume code.
912bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
913 const Device* out_device) {
914#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000915 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000916 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000917 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000918 kDefaultAudioDeviceId;
919 // The device manager uses -1 as the default device, which was the case for
920 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
921#ifndef WIN32
922 if (-1 == in_id) {
923 in_id = kDefaultAudioDeviceId;
924 }
925 if (-1 == out_id) {
926 out_id = kDefaultAudioDeviceId;
927 }
928#endif
929
930 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
931 in_device->name : "Default device";
932 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
933 out_device->name : "Default device";
934 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
935 << ") and speaker to (id=" << out_id << ", name=" << out_name
936 << ")";
937
938 // If we're running the local monitor, we need to stop it first.
939 bool ret = true;
940 if (!PauseLocalMonitor()) {
941 LOG(LS_WARNING) << "Failed to pause local monitor";
942 ret = false;
943 }
944
945 // Must also pause all audio playback and capture.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200946 for (WebRtcVoiceMediaChannel* channel : channels_) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000947 if (!channel->PausePlayout()) {
948 LOG(LS_WARNING) << "Failed to pause playout";
949 ret = false;
950 }
951 if (!channel->PauseSend()) {
952 LOG(LS_WARNING) << "Failed to pause send";
953 ret = false;
954 }
955 }
956
957 // Find the recording device id in VoiceEngine and set recording device.
958 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
959 ret = false;
960 }
961 if (ret) {
962 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
963 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
964 ret = false;
965 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +0000966 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
967 if (ap)
968 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000969 }
970
971 // Find the playout device id in VoiceEngine and set playout device.
972 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
973 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
974 ret = false;
975 }
976 if (ret) {
977 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000978 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000979 ret = false;
980 }
981 }
982
983 // Resume all audio playback and capture.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200984 for (WebRtcVoiceMediaChannel* channel : channels_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000985 if (!channel->ResumePlayout()) {
986 LOG(LS_WARNING) << "Failed to resume playout";
987 ret = false;
988 }
989 if (!channel->ResumeSend()) {
990 LOG(LS_WARNING) << "Failed to resume send";
991 ret = false;
992 }
993 }
994
995 // Resume local monitor.
996 if (!ResumeLocalMonitor()) {
997 LOG(LS_WARNING) << "Failed to resume local monitor";
998 ret = false;
999 }
1000
1001 if (ret) {
1002 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1003 << ") and speaker to (id="<< out_id << " name=" << out_name
1004 << ")";
1005 }
1006
1007 return ret;
1008#else
1009 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001010#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011}
1012
1013bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1014 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1015 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001016#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001017 *rtc_id = dev_id;
1018 return true;
1019#else
1020 // In Windows and Mac, we need to find the VoiceEngine device id by name
1021 // unless the input dev_id is the default device id.
1022 if (kDefaultAudioDeviceId == dev_id) {
1023 *rtc_id = dev_id;
1024 return true;
1025 }
1026
1027 // Get the number of VoiceEngine audio devices.
1028 int count = 0;
1029 if (is_input) {
1030 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1031 LOG_RTCERR0(GetNumOfRecordingDevices);
1032 return false;
1033 }
1034 } else {
1035 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1036 LOG_RTCERR0(GetNumOfPlayoutDevices);
1037 return false;
1038 }
1039 }
1040
1041 for (int i = 0; i < count; ++i) {
1042 char name[128];
1043 char guid[128];
1044 if (is_input) {
1045 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1046 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1047 } else {
1048 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1049 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1050 }
1051
1052 std::string webrtc_name(name);
1053 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1054 *rtc_id = i;
1055 return true;
1056 }
1057 }
1058 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1059 return false;
1060#endif
1061}
1062
1063bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1064 unsigned int ulevel;
1065 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1066 LOG_RTCERR1(GetSpeakerVolume, level);
1067 return false;
1068 }
1069 *level = ulevel;
1070 return true;
1071}
1072
1073bool WebRtcVoiceEngine::SetOutputVolume(int level) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001074 DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001075 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1076 LOG_RTCERR1(SetSpeakerVolume, level);
1077 return false;
1078 }
1079 return true;
1080}
1081
1082int WebRtcVoiceEngine::GetInputLevel() {
1083 unsigned int ulevel;
1084 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1085 static_cast<int>(ulevel) : -1;
1086}
1087
1088bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1089 desired_local_monitor_enable_ = enable;
1090 return ChangeLocalMonitor(desired_local_monitor_enable_);
1091}
1092
1093bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1094 // The voe file api is not available in chrome.
1095 if (!voe_wrapper_->file()) {
1096 return false;
1097 }
1098 if (enable && !monitor_) {
1099 monitor_.reset(new WebRtcMonitorStream);
1100 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1101 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1102 // Must call Stop() because there are some cases where Start will report
1103 // failure but still change the state, and if we leave VE in the on state
1104 // then it could crash later when trying to invoke methods on our monitor.
1105 voe_wrapper_->file()->StopRecordingMicrophone();
1106 monitor_.reset();
1107 return false;
1108 }
1109 } else if (!enable && monitor_) {
1110 voe_wrapper_->file()->StopRecordingMicrophone();
1111 monitor_.reset();
1112 }
1113 return true;
1114}
1115
1116bool WebRtcVoiceEngine::PauseLocalMonitor() {
1117 return ChangeLocalMonitor(false);
1118}
1119
1120bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1121 return ChangeLocalMonitor(desired_local_monitor_enable_);
1122}
1123
1124const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1125 return codecs_;
1126}
1127
1128bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1129 return FindWebRtcCodec(in, NULL);
1130}
1131
1132// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1133bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1134 webrtc::CodecInst* out) {
1135 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1136 for (int i = 0; i < ncodecs; ++i) {
1137 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001138 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001139 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1140 voe_codec.rate, voe_codec.channels, 0);
1141 bool multi_rate = IsCodecMultiRate(voe_codec);
1142 // Allow arbitrary rates for ISAC to be specified.
1143 if (multi_rate) {
1144 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1145 codec.bitrate = 0;
1146 }
1147 if (codec.Matches(in)) {
1148 if (out) {
1149 // Fixup the payload type.
1150 voe_codec.pltype = in.id;
1151
1152 // Set bitrate if specified.
1153 if (multi_rate && in.bitrate != 0) {
1154 voe_codec.rate = in.bitrate;
1155 }
1156
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001157 // Reset G722 sample rate to 16000 to match WebRTC.
1158 MaybeFixupG722(&voe_codec, 16000);
1159
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001160 // Apply codec-specific settings.
Minyue Li7100dcd2015-03-27 05:05:59 +01001161 if (IsCodec(codec, kIsacCodecName)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001162 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001163 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001164 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1165 }
1166 *out = voe_codec;
1167 }
1168 return true;
1169 }
1170 }
1171 }
1172 return false;
1173}
1174const std::vector<RtpHeaderExtension>&
1175WebRtcVoiceEngine::rtp_header_extensions() const {
1176 return rtp_header_extensions_;
1177}
1178
1179void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1180 // if min_sev == -1, we keep the current log level.
1181 if (min_sev >= 0) {
1182 SetTraceFilter(SeverityToFilter(min_sev));
1183 }
1184 log_options_ = filter;
1185 SetTraceOptions(initialized_ ? log_options_ : "");
1186}
1187
1188int WebRtcVoiceEngine::GetLastEngineError() {
1189 return voe_wrapper_->error();
1190}
1191
1192void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1193 log_filter_ = filter;
1194 tracing_->SetTraceFilter(filter);
1195}
1196
1197// We suppport three different logging settings for VoiceEngine:
1198// 1. Observer callback that goes into talk diagnostic logfile.
1199// Use --logfile and --loglevel
1200//
1201// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1202// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1203//
1204// 3. EC log and dump for debugging QualityEngine.
1205// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1206//
1207// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1208// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1209void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1210 // Set encrypted trace file.
1211 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001212 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001213 std::vector<std::string>::iterator tracefile =
1214 std::find(opts.begin(), opts.end(), "tracefile");
1215 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1216 // Write encrypted debug output (at same loglevel) to file
1217 // EncryptedTraceFile no longer supported.
1218 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1219 LOG_RTCERR1(SetTraceFile, *tracefile);
1220 }
1221 }
1222
wu@webrtc.org97077a32013-10-25 21:18:33 +00001223 // Allow trace options to override the trace filter. We default
1224 // it to log_filter_ (as a translation of libjingle log levels)
1225 // elsewhere, but this allows clients to explicitly set webrtc
1226 // log levels.
1227 std::vector<std::string>::iterator tracefilter =
1228 std::find(opts.begin(), opts.end(), "tracefilter");
1229 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001230 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001231 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1232 }
1233 }
1234
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001235 // Set AEC dump file
1236 std::vector<std::string>::iterator recordEC =
1237 std::find(opts.begin(), opts.end(), "recordEC");
1238 if (recordEC != opts.end()) {
1239 ++recordEC;
1240 if (recordEC != opts.end())
1241 StartAecDump(recordEC->c_str());
1242 else
1243 StopAecDump();
1244 }
1245}
1246
1247// Ignore spammy trace messages, mostly from the stats API when we haven't
1248// gotten RTCP info yet from the remote side.
1249bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1250 static const char* kTracesToIgnore[] = {
1251 "\tfailed to GetReportBlockInformation",
1252 "GetRecCodec() failed to get received codec",
1253 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1254 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1255 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1256 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1257 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1258 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1259 "SenderInfoReceived No received SR",
1260 "StatisticsRTP() no statistics available",
1261 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1262 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1263 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1264 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1265 NULL
1266 };
1267 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1268 if (trace.find(*p) != std::string::npos) {
1269 return true;
1270 }
1271 }
1272 return false;
1273}
1274
1275void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1276 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001277 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001278 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001279 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001281 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001282 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001283 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001284 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001285 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001286
1287 // Skip past boilerplate prefix text
1288 if (length < 72) {
1289 std::string msg(trace, length);
1290 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1291 LOG_V(sev) << msg;
1292 } else {
1293 std::string msg(trace + 71, length - 72);
1294 if (!ShouldIgnoreTrace(msg)) {
1295 LOG_V(sev) << "webrtc: " << msg;
1296 }
1297 }
1298}
1299
1300void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001301 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001302 WebRtcVoiceMediaChannel* channel = NULL;
1303 uint32 ssrc = 0;
1304 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1305 << channel_num << ".";
1306 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001307 DCHECK(channel != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001308 channel->OnError(ssrc, err_code);
1309 } else {
1310 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1311 << " could not be found in channel list when error reported.";
1312 }
1313}
1314
1315bool WebRtcVoiceEngine::FindChannelAndSsrc(
1316 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001317 DCHECK(channel != NULL && ssrc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001318
1319 *channel = NULL;
1320 *ssrc = 0;
1321 // Find corresponding channel and ssrc
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001322 for (WebRtcVoiceMediaChannel* ch : channels_) {
1323 DCHECK(ch != NULL);
1324 if (ch->FindSsrc(channel_num, ssrc)) {
1325 *channel = ch;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001326 return true;
1327 }
1328 }
1329
1330 return false;
1331}
1332
1333// This method will search through the WebRtcVoiceMediaChannels and
1334// obtain the voice engine's channel number.
1335bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1336 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001337 DCHECK(channel_num != NULL);
1338 DCHECK(direction == MPD_RX || direction == MPD_TX);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001339
1340 *channel_num = -1;
1341 // Find corresponding channel for ssrc.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001342 for (const WebRtcVoiceMediaChannel* ch : channels_) {
1343 DCHECK(ch != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001344 if (direction & MPD_RX) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001345 *channel_num = ch->GetReceiveChannelNum(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001346 }
1347 if (*channel_num == -1 && (direction & MPD_TX)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001348 *channel_num = ch->GetSendChannelNum(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349 }
1350 if (*channel_num != -1) {
1351 return true;
1352 }
1353 }
1354 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1355 return false;
1356}
1357
1358void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001359 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001360 channels_.push_back(channel);
1361}
1362
1363void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001364 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001365 ChannelList::iterator i = std::find(channels_.begin(),
1366 channels_.end(),
1367 channel);
1368 if (i != channels_.end()) {
1369 channels_.erase(i);
1370 }
1371}
1372
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001373// Adjusts the default AGC target level by the specified delta.
1374// NB: If we start messing with other config fields, we'll want
1375// to save the current webrtc::AgcConfig as well.
1376bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1377 webrtc::AgcConfig config = default_agc_config_;
1378 config.targetLeveldBOv -= delta;
1379
1380 LOG(LS_INFO) << "Adjusting AGC level from default -"
1381 << default_agc_config_.targetLeveldBOv << "dB to -"
1382 << config.targetLeveldBOv << "dB";
1383
1384 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1385 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1386 return false;
1387 }
1388 return true;
1389}
1390
Fredrik Solenbergccb49e72015-05-19 11:37:56 +02001391bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392 if (initialized_) {
1393 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1394 return false;
1395 }
1396 if (adm_) {
1397 adm_->Release();
1398 adm_ = NULL;
1399 }
1400 if (adm) {
1401 adm_ = adm;
1402 adm_->AddRef();
1403 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001404 return true;
1405}
1406
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001407bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1408 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001409 if (!aec_dump_file_stream) {
1410 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001411 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001412 LOG(LS_WARNING) << "Could not close file.";
1413 return false;
1414 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001415 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001416 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001417 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001418 LOG_RTCERR0(StartDebugRecording);
1419 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001420 return false;
1421 }
1422 is_dumping_aec_ = true;
1423 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001424}
1425
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001426bool WebRtcVoiceEngine::RegisterProcessor(
1427 uint32 ssrc,
1428 VoiceProcessor* voice_processor,
1429 MediaProcessorDirection direction) {
1430 bool register_with_webrtc = false;
1431 int channel_id = -1;
1432 bool success = false;
1433 uint32* processor_ssrc = NULL;
1434 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1435 if (voice_processor == NULL || !found_channel) {
1436 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1437 << " foundChannel: " << found_channel;
1438 return false;
1439 }
1440
1441 webrtc::ProcessingTypes processing_type;
1442 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001443 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001444 if (direction == MPD_RX) {
1445 processing_type = webrtc::kPlaybackAllChannelsMixed;
1446 if (SignalRxMediaFrame.is_empty()) {
1447 register_with_webrtc = true;
1448 processor_ssrc = &rx_processor_ssrc_;
1449 }
1450 SignalRxMediaFrame.connect(voice_processor,
1451 &VoiceProcessor::OnFrame);
1452 } else {
1453 processing_type = webrtc::kRecordingPerChannel;
1454 if (SignalTxMediaFrame.is_empty()) {
1455 register_with_webrtc = true;
1456 processor_ssrc = &tx_processor_ssrc_;
1457 }
1458 SignalTxMediaFrame.connect(voice_processor,
1459 &VoiceProcessor::OnFrame);
1460 }
1461 }
1462 if (register_with_webrtc) {
1463 // TODO(janahan): when registering consider instantiating a
1464 // a VoeMediaProcess object and not make the engine extend the interface.
1465 if (voe()->media() && voe()->media()->
1466 RegisterExternalMediaProcessing(channel_id,
1467 processing_type,
1468 *this) != -1) {
1469 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1470 << channel_id;
1471 *processor_ssrc = ssrc;
1472 success = true;
1473 } else {
1474 LOG_RTCERR2(RegisterExternalMediaProcessing,
1475 channel_id,
1476 processing_type);
1477 success = false;
1478 }
1479 } else {
1480 // If we don't have to register with the engine, we just needed to
1481 // connect a new processor, set success to true;
1482 success = true;
1483 }
1484 return success;
1485}
1486
1487bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1488 MediaProcessorDirection channel_direction,
1489 uint32 ssrc,
1490 VoiceProcessor* voice_processor,
1491 MediaProcessorDirection processor_direction) {
1492 bool success = true;
1493 FrameSignal* signal;
1494 webrtc::ProcessingTypes processing_type;
1495 uint32* processor_ssrc = NULL;
1496 if (channel_direction == MPD_RX) {
1497 signal = &SignalRxMediaFrame;
1498 processing_type = webrtc::kPlaybackAllChannelsMixed;
1499 processor_ssrc = &rx_processor_ssrc_;
1500 } else {
1501 signal = &SignalTxMediaFrame;
1502 processing_type = webrtc::kRecordingPerChannel;
1503 processor_ssrc = &tx_processor_ssrc_;
1504 }
1505
1506 int deregister_id = -1;
1507 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001508 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001509 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1510 signal->disconnect(voice_processor);
1511 int channel_id = -1;
1512 bool found_channel = FindChannelNumFromSsrc(ssrc,
1513 channel_direction,
1514 &channel_id);
1515 if (signal->is_empty() && found_channel) {
1516 deregister_id = channel_id;
1517 }
1518 }
1519 }
1520 if (deregister_id != -1) {
1521 if (voe()->media() &&
1522 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1523 processing_type) != -1) {
1524 *processor_ssrc = 0;
1525 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1526 << deregister_id;
1527 } else {
1528 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1529 deregister_id,
1530 processing_type);
1531 success = false;
1532 }
1533 }
1534 return success;
1535}
1536
1537bool WebRtcVoiceEngine::UnregisterProcessor(
1538 uint32 ssrc,
1539 VoiceProcessor* voice_processor,
1540 MediaProcessorDirection direction) {
1541 bool success = true;
1542 if (voice_processor == NULL) {
1543 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1544 << ssrc;
1545 return false;
1546 }
1547 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1548 success = false;
1549 }
1550 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1551 success = false;
1552 }
1553 return success;
1554}
1555
1556// Implementing method from WebRtc VoEMediaProcess interface
1557// Do not lock mux_channel_cs_ in this callback.
1558void WebRtcVoiceEngine::Process(int channel,
1559 webrtc::ProcessingTypes type,
1560 int16_t audio10ms[],
Peter Kastingdce40cf2015-08-24 14:52:23 -07001561 size_t length,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001562 int sampling_freq,
1563 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001564 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001565 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1566 if (type == webrtc::kPlaybackAllChannelsMixed) {
1567 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1568 } else if (type == webrtc::kRecordingPerChannel) {
1569 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1570 } else {
1571 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1572 << " channel: " << channel << " type: " << type
1573 << " tx_ssrc: " << tx_processor_ssrc_
1574 << " rx_ssrc: " << rx_processor_ssrc_;
1575 }
1576}
1577
1578void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1579 if (!is_dumping_aec_) {
1580 // Start dumping AEC when we are not dumping.
1581 if (voe_wrapper_->processing()->StartDebugRecording(
1582 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001583 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001584 } else {
1585 is_dumping_aec_ = true;
1586 }
1587 }
1588}
1589
1590void WebRtcVoiceEngine::StopAecDump() {
1591 if (is_dumping_aec_) {
1592 // Stop dumping AEC when we are dumping.
1593 if (voe_wrapper_->processing()->StopDebugRecording() !=
1594 webrtc::AudioProcessing::kNoError) {
1595 LOG_RTCERR0(StopDebugRecording);
1596 }
1597 is_dumping_aec_ = false;
1598 }
1599}
1600
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001601int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001602 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001603}
1604
1605int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1606 return CreateVoiceChannel(voe_wrapper_.get());
1607}
1608
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001609class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1610 : public AudioRenderer::Sink {
1611 public:
1612 WebRtcVoiceChannelRenderer(int ch,
1613 webrtc::AudioTransport* voe_audio_transport)
1614 : channel_(ch),
1615 voe_audio_transport_(voe_audio_transport),
pbos8fc7fa72015-07-15 08:02:58 -07001616 renderer_(NULL) {}
Fredrik Solenbergaaf8ff22015-05-07 16:05:53 +02001617 ~WebRtcVoiceChannelRenderer() override { Stop(); }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001618
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001619 // Starts the rendering by setting a sink to the renderer to get data
1620 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001621 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001622 // TODO(xians): Make sure Start() is called only once.
1623 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001624 rtc::CritScope lock(&lock_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001625 DCHECK(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001626 if (renderer_ != NULL) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001627 DCHECK(renderer_ == renderer);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001628 return;
1629 }
1630
1631 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1632 // in getUserMedia by default.
1633 renderer->AddChannel(channel_);
1634 renderer->SetSink(this);
1635 renderer_ = renderer;
1636 }
1637
1638 // Stops rendering by setting the sink of the renderer to NULL. No data
1639 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001640 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001641 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001642 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001643 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001644 return;
1645
1646 renderer_->RemoveChannel(channel_);
1647 renderer_->SetSink(NULL);
1648 renderer_ = NULL;
1649 }
1650
1651 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001652 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001653 void OnData(const void* audio_data,
1654 int bits_per_sample,
1655 int sample_rate,
1656 int number_of_channels,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001657 size_t number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001658 voe_audio_transport_->OnData(channel_,
1659 audio_data,
1660 bits_per_sample,
1661 sample_rate,
1662 number_of_channels,
1663 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001664 }
1665
1666 // Callback from the |renderer_| when it is going away. In case Start() has
1667 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001668 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001669 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001670 // Set |renderer_| to NULL to make sure no more callback will get into
1671 // the renderer.
1672 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001673 }
1674
1675 // Accessor to the VoE channel ID.
1676 int channel() const { return channel_; }
1677
1678 private:
1679 const int channel_;
1680 webrtc::AudioTransport* const voe_audio_transport_;
1681
1682 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1683 // PeerConnection will make sure invalidating the pointer before the object
1684 // goes away.
1685 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001686
1687 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001688 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001689};
1690
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001691// WebRtcVoiceMediaChannel
Fredrik Solenberge444a3d2015-05-07 16:42:08 +02001692WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine)
1693 : 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 Solenberg4b60c732015-05-07 14:07:48 +02001705 call_(nullptr),
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();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001710 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001711}
1712
1713WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1714 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1715 << voe_channel();
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001716 DCHECK(receive_streams_.empty() || call_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001717
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001718 // Remove any remaining send streams, the default channel will be deleted
1719 // later.
1720 while (!send_channels_.empty())
1721 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001722
1723 // Unregister ourselves from the engine.
1724 engine()->UnregisterChannel(this);
1725 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001726 while (!receive_channels_.empty()) {
1727 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001728 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001729 DCHECK(receive_streams_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001730
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001731 // Delete the default channel.
1732 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001733}
1734
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001735bool WebRtcVoiceMediaChannel::SetSendParameters(
1736 const AudioSendParameters& params) {
1737 // TODO(pthatcher): Refactor this to be more clean now that we have
1738 // all the information at once.
1739 return (SetSendCodecs(params.codecs) &&
1740 SetSendRtpHeaderExtensions(params.extensions) &&
1741 SetMaxSendBandwidth(params.max_bandwidth_bps) &&
1742 SetOptions(params.options));
1743}
1744
1745bool WebRtcVoiceMediaChannel::SetRecvParameters(
1746 const AudioRecvParameters& params) {
1747 // TODO(pthatcher): Refactor this to be more clean now that we have
1748 // all the information at once.
1749 return (SetRecvCodecs(params.codecs) &&
1750 SetRecvRtpHeaderExtensions(params.extensions));
1751}
1752
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001753bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1754 LOG(LS_INFO) << "Setting voice channel options: "
1755 << options.ToString();
1756
wu@webrtc.orgde305012013-10-31 15:40:38 +00001757 // Check if DSCP value is changed from previous.
1758 bool dscp_option_changed = (options_.dscp != options.dscp);
1759
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001760 // TODO(xians): Add support to set different options for different send
1761 // streams after we support multiple APMs.
1762
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001763 // We retain all of the existing options, and apply the given ones
1764 // on top. This means there is no way to "clear" options such that
1765 // they go back to the engine default.
1766 options_.SetAll(options);
1767
1768 if (send_ != SEND_NOTHING) {
1769 if (!engine()->SetOptionOverrides(options_)) {
1770 LOG(LS_WARNING) <<
1771 "Failed to engine SetOptionOverrides during channel SetOptions.";
1772 return false;
1773 }
1774 } else {
1775 // Will be interpreted when appropriate.
1776 }
1777
wu@webrtc.org97077a32013-10-25 21:18:33 +00001778 // Receiver-side auto gain control happens per channel, so set it here from
1779 // options. Note that, like conference mode, setting it on the engine won't
1780 // have the desired effect, since voice channels don't inherit options from
1781 // the media engine when those options are applied per-channel.
1782 bool rx_auto_gain_control;
1783 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1784 if (engine()->voe()->processing()->SetRxAgcStatus(
1785 voe_channel(), rx_auto_gain_control,
1786 webrtc::kAgcFixedDigital) == -1) {
1787 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1788 return false;
1789 } else {
1790 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1791 << " with mode " << webrtc::kAgcFixedDigital;
1792 }
1793 }
1794 if (options.rx_agc_target_dbov.IsSet() ||
1795 options.rx_agc_digital_compression_gain.IsSet() ||
1796 options.rx_agc_limiter.IsSet()) {
1797 webrtc::AgcConfig config;
1798 // If only some of the options are being overridden, get the current
1799 // settings for the channel and bail if they aren't available.
1800 if (!options.rx_agc_target_dbov.IsSet() ||
1801 !options.rx_agc_digital_compression_gain.IsSet() ||
1802 !options.rx_agc_limiter.IsSet()) {
1803 if (engine()->voe()->processing()->GetRxAgcConfig(
1804 voe_channel(), config) != 0) {
1805 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1806 << "channel " << voe_channel() << ". Since not all rx "
1807 << "agc options are specified, unable to safely set rx "
1808 << "agc options.";
1809 return false;
1810 }
1811 }
1812 config.targetLeveldBOv =
1813 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1814 config.targetLeveldBOv);
1815 config.digitalCompressionGaindB =
1816 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1817 config.digitalCompressionGaindB);
1818 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1819 config.limiterEnable);
1820 if (engine()->voe()->processing()->SetRxAgcConfig(
1821 voe_channel(), config) == -1) {
1822 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1823 config.digitalCompressionGaindB, config.limiterEnable);
1824 return false;
1825 }
1826 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001827 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001828 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001829 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001830 dscp = kAudioDscpValue;
1831 if (MediaChannel::SetDscp(dscp) != 0) {
1832 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1833 }
1834 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001835
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001836 SetCall(call_);
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001837
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001838 LOG(LS_INFO) << "Set voice channel options. Current options: "
1839 << options_.ToString();
1840 return true;
1841}
1842
1843bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1844 const std::vector<AudioCodec>& codecs) {
1845 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001846 LOG(LS_INFO) << "Setting receive voice codecs:";
1847
1848 std::vector<AudioCodec> new_codecs;
1849 // Find all new codecs. We allow adding new codecs but don't allow changing
1850 // the payload type of codecs that is already configured since we might
1851 // already be receiving packets with that payload type.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001852 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001853 AudioCodec old_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001854 if (FindCodec(recv_codecs_, codec, &old_codec)) {
1855 if (old_codec.id != codec.id) {
1856 LOG(LS_ERROR) << codec.name << " payload type changed.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001857 return false;
1858 }
1859 } else {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001860 new_codecs.push_back(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001861 }
1862 }
1863 if (new_codecs.empty()) {
1864 // There are no new codecs to configure. Already configured codecs are
1865 // never removed.
1866 return true;
1867 }
1868
1869 if (playout_) {
1870 // Receive codecs can not be changed while playing. So we temporarily
1871 // pause playout.
1872 PausePlayout();
1873 }
1874
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001875 bool result = SetRecvCodecsInternal(new_codecs);
1876 if (result) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001877 recv_codecs_ = codecs;
1878 }
1879
1880 if (desired_playout_ && !playout_) {
1881 ResumePlayout();
1882 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001883 return result;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001884}
1885
1886bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001887 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001888 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001889 engine()->voe()->codec()->SetVADStatus(channel, false);
1890 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001891 engine()->voe()->rtp()->SetREDStatus(channel, false);
1892 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001893
1894 // Scan through the list to figure out the codec to use for sending, along
1895 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001896 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001897 webrtc::CodecInst send_codec;
1898 memset(&send_codec, 0, sizeof(send_codec));
1899
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001900 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001901 bool enable_codec_fec = false;
Minyue Li7100dcd2015-03-27 05:05:59 +01001902 bool enable_opus_dtx = false;
minyue@webrtc.org26236952014-10-29 02:27:08 +00001903 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001904
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001905 // Set send codec (the first non-telephone-event/CN codec)
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001906 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001907 // Ignore codecs we don't know about. The negotiation step should prevent
1908 // this, but double-check to be sure.
1909 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001910 if (!engine()->FindWebRtcCodec(codec, &voe_codec)) {
1911 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001912 continue;
1913 }
1914
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001915 if (IsCodec(codec, kDtmfCodecName) || IsCodec(codec, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001916 // Skip telephone-event/CN codec, which will be handled later.
1917 continue;
1918 }
1919
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001920 // We'll use the first codec in the list to actually send audio data.
1921 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001922 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001923 // used is specified in params.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001924 if (IsCodec(codec, kRedCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001925 // Parse out the RED parameters. If we fail, just ignore RED;
1926 // we don't support all possible params/usage scenarios.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001927 if (!GetRedSendCodec(codec, codecs, &send_codec)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001928 continue;
1929 }
1930
1931 // Enable redundant encoding of the specified codec. Treat any
1932 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001933 LOG(LS_INFO) << "Enabling RED on channel " << channel;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001934 if (engine()->voe()->rtp()->SetREDStatus(channel, true, codec.id) == -1) {
1935 LOG_RTCERR3(SetREDStatus, channel, true, codec.id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001936 return false;
1937 }
1938 } else {
1939 send_codec = voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001940 nack_enabled = IsNackEnabled(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +01001941 // For Opus as the send codec, we are to determine inband FEC, maximum
1942 // playback rate, and opus internal dtx.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001943 if (IsCodec(codec, kOpusCodecName)) {
1944 GetOpusConfig(codec, &send_codec, &enable_codec_fec,
Minyue Li7100dcd2015-03-27 05:05:59 +01001945 &opus_max_playback_rate, &enable_opus_dtx);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001946 }
Brave Yao5225dd82015-03-26 07:39:19 +08001947
1948 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1949 int ptime_ms = 0;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001950 if (codec.GetParam(kCodecParamPTime, &ptime_ms)) {
Brave Yao5225dd82015-03-26 07:39:19 +08001951 if (!SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
1952 LOG(LS_WARNING) << "Failed to set packet size for codec "
1953 << send_codec.plname;
1954 return false;
1955 }
1956 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001957 }
1958 found_send_codec = true;
1959 break;
1960 }
1961
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001962 if (nack_enabled_ != nack_enabled) {
1963 SetNack(channel, nack_enabled);
1964 nack_enabled_ = nack_enabled;
1965 }
1966
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001967 if (!found_send_codec) {
1968 LOG(LS_WARNING) << "Received empty list of codecs.";
1969 return false;
1970 }
1971
1972 // Set the codec immediately, since SetVADStatus() depends on whether
1973 // the current codec is mono or stereo.
1974 if (!SetSendCodec(channel, send_codec))
1975 return false;
1976
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001977 // FEC should be enabled after SetSendCodec.
1978 if (enable_codec_fec) {
1979 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
1980 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001981 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
1982 // Enable codec internal FEC. Treat any failure as fatal internal error.
1983 LOG_RTCERR2(SetFECStatus, channel, true);
1984 return false;
1985 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001986 }
1987
Minyue Li7100dcd2015-03-27 05:05:59 +01001988 if (IsCodec(send_codec, kOpusCodecName)) {
1989 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
1990 // send codec has to be Opus.
1991
1992 // Set Opus internal DTX.
1993 LOG(LS_INFO) << "Attempt to "
1994 << GetEnableString(enable_opus_dtx)
1995 << " Opus DTX on channel "
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001996 << channel;
Minyue Li7100dcd2015-03-27 05:05:59 +01001997 if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) {
1998 LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx);
1999 return false;
2000 }
2001
2002 // If opus_max_playback_rate <= 0, the default maximum playback rate
2003 // (48 kHz) will be used.
2004 if (opus_max_playback_rate > 0) {
2005 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
2006 << opus_max_playback_rate
2007 << " Hz on channel "
2008 << channel;
2009 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
2010 channel, opus_max_playback_rate) == -1) {
2011 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate);
2012 return false;
2013 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002014 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002015 }
2016
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002017 // Always update the |send_codec_| to the currently set send codec.
2018 send_codec_.reset(new webrtc::CodecInst(send_codec));
2019
minyue@webrtc.org26236952014-10-29 02:27:08 +00002020 if (send_bitrate_setting_) {
2021 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002022 }
2023
2024 // Loop through the codecs list again to config the telephone-event/CN codec.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002025 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002026 // Ignore codecs we don't know about. The negotiation step should prevent
2027 // this, but double-check to be sure.
2028 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002029 if (!engine()->FindWebRtcCodec(codec, &voe_codec)) {
2030 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002031 continue;
2032 }
2033
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002034 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2035 // about it.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002036 if (IsCodec(codec, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002037 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002038 channel, codec.id) == -1) {
2039 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, codec.id);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002040 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002041 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002042 } else if (IsCodec(codec, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002043 // Turn voice activity detection/comfort noise on if supported.
2044 // Set the wideband CN payload type appropriately.
2045 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002046 webrtc::PayloadFrequencies cn_freq;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002047 switch (codec.clockrate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002048 case 8000:
2049 cn_freq = webrtc::kFreq8000Hz;
2050 break;
2051 case 16000:
2052 cn_freq = webrtc::kFreq16000Hz;
2053 break;
2054 case 32000:
2055 cn_freq = webrtc::kFreq32000Hz;
2056 break;
2057 default:
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002058 LOG(LS_WARNING) << "CN frequency " << codec.clockrate
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002059 << " not supported.";
2060 continue;
2061 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002062 // Set the CN payloadtype and the VAD status.
2063 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2064 if (cn_freq != webrtc::kFreq8000Hz) {
2065 if (engine()->voe()->codec()->SetSendCNPayloadType(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002066 channel, codec.id, cn_freq) == -1) {
2067 LOG_RTCERR3(SetSendCNPayloadType, channel, codec.id, cn_freq);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002068 // TODO(ajm): This failure condition will be removed from VoE.
2069 // Restore the return here when we update to a new enough webrtc.
2070 //
2071 // Not returning false because the SetSendCNPayloadType will fail if
2072 // the channel is already sending.
2073 // This can happen if the remote description is applied twice, for
2074 // example in the case of ROAP on top of JSEP, where both side will
2075 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002076 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002077 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002078 // Only turn on VAD if we have a CN payload type that matches the
2079 // clockrate for the codec we are going to use.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002080 if (codec.clockrate == send_codec.plfreq && send_codec.channels != 2) {
Minyue Li7100dcd2015-03-27 05:05:59 +01002081 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
2082 // interaction between VAD and Opus FEC.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002083 LOG(LS_INFO) << "Enabling VAD";
2084 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2085 LOG_RTCERR2(SetVADStatus, channel, true);
2086 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002087 }
2088 }
2089 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002090 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002091 return true;
2092}
2093
2094bool WebRtcVoiceMediaChannel::SetSendCodecs(
2095 const std::vector<AudioCodec>& codecs) {
2096 dtmf_allowed_ = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002097 for (const AudioCodec& codec : codecs) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002098 // Find the DTMF telephone event "codec".
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002099 if (IsCodec(codec, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002100 dtmf_allowed_ = true;
2101 }
2102 }
2103
2104 // Cache the codecs in order to configure the channel created later.
2105 send_codecs_ = codecs;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002106 for (const auto& ch : send_channels_) {
2107 if (!SetSendCodecs(ch.second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002108 return false;
2109 }
2110 }
2111
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002112 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002113 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002114 return true;
2115}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002116
2117void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2118 bool nack_enabled) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002119 for (const auto& ch : channels) {
2120 SetNack(ch.second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002121 }
2122}
2123
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002124void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002125 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002126 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002127 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2128 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002129 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002130 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2131 }
2132}
2133
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002134bool WebRtcVoiceMediaChannel::SetSendCodec(
2135 const webrtc::CodecInst& send_codec) {
2136 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2137 << ", bitrate=" << send_codec.rate;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002138 for (const auto& ch : send_channels_) {
2139 if (!SetSendCodec(ch.second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002140 return false;
2141 }
2142
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002143 return true;
2144}
2145
2146bool WebRtcVoiceMediaChannel::SetSendCodec(
2147 int channel, const webrtc::CodecInst& send_codec) {
2148 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2149 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2150
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002151 webrtc::CodecInst current_codec;
2152 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2153 (send_codec == current_codec)) {
2154 // Codec is already configured, we can return without setting it again.
2155 return true;
2156 }
2157
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002158 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2159 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002160 return false;
2161 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002162 return true;
2163}
2164
2165bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2166 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002167 if (receive_extensions_ == extensions) {
2168 return true;
2169 }
2170
2171 // The default channel may or may not be in |receive_channels_|. Set the rtp
2172 // header extensions for default channel regardless.
2173 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2174 return false;
2175 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002176
2177 // Loop through all receive channels and enable/disable the extensions.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002178 for (const auto& ch : receive_channels_) {
2179 if (!SetChannelRecvRtpHeaderExtensions(ch.second->channel(), extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002180 return false;
2181 }
2182 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002183
2184 receive_extensions_ = extensions;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002185
2186 // Recreate AudioReceiveStream:s.
2187 {
2188 std::vector<webrtc::RtpExtension> exts;
2189
2190 const RtpHeaderExtension* audio_level_extension =
2191 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2192 if (audio_level_extension) {
2193 exts.push_back({
2194 kRtpAudioLevelHeaderExtension, audio_level_extension->id});
2195 }
2196
2197 const RtpHeaderExtension* send_time_extension =
2198 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2199 if (send_time_extension) {
2200 exts.push_back({
2201 kRtpAbsoluteSenderTimeHeaderExtension, send_time_extension->id});
2202 }
2203
2204 recv_rtp_extensions_.swap(exts);
2205 SetCall(call_);
2206 }
2207
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002208 return true;
2209}
2210
2211bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2212 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002213 const RtpHeaderExtension* audio_level_extension =
2214 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2215 if (!SetHeaderExtension(
2216 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2217 audio_level_extension)) {
2218 return false;
2219 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002220
2221 const RtpHeaderExtension* send_time_extension =
2222 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2223 if (!SetHeaderExtension(
2224 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2225 send_time_extension)) {
2226 return false;
2227 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002228
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002229 return true;
2230}
2231
2232bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2233 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002234 if (send_extensions_ == extensions) {
2235 return true;
2236 }
2237
2238 // The default channel may or may not be in |send_channels_|. Set the rtp
2239 // header extensions for default channel regardless.
2240
2241 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2242 return false;
2243 }
2244
2245 // Loop through all send channels and enable/disable the extensions.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002246 for (const auto& ch : send_channels_) {
2247 if (!SetChannelSendRtpHeaderExtensions(ch.second->channel(), extensions)) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002248 return false;
2249 }
2250 }
2251
2252 send_extensions_ = extensions;
2253 return true;
2254}
2255
2256bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2257 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002258 const RtpHeaderExtension* audio_level_extension =
2259 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002260
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002261 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002262 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002263 audio_level_extension)) {
2264 return false;
2265 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002266
2267 const RtpHeaderExtension* send_time_extension =
2268 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002269 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002270 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002271 send_time_extension)) {
2272 return false;
2273 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002274
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002275 return true;
2276}
2277
2278bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2279 desired_playout_ = playout;
2280 return ChangePlayout(desired_playout_);
2281}
2282
2283bool WebRtcVoiceMediaChannel::PausePlayout() {
2284 return ChangePlayout(false);
2285}
2286
2287bool WebRtcVoiceMediaChannel::ResumePlayout() {
2288 return ChangePlayout(desired_playout_);
2289}
2290
2291bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2292 if (playout_ == playout) {
2293 return true;
2294 }
2295
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002296 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002297 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002298 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002299 // Only toggle the default channel if we don't have any other channels.
2300 result = SetPlayout(voe_channel(), playout);
2301 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002302 for (const auto& ch : receive_channels_) {
2303 if (!SetPlayout(ch.second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002304 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002305 << ch.second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002306 result = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002307 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002308 }
2309 }
2310
2311 if (result) {
2312 playout_ = playout;
2313 }
2314 return result;
2315}
2316
2317bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2318 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002319 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002320 return ChangeSend(desired_send_);
2321 return true;
2322}
2323
2324bool WebRtcVoiceMediaChannel::PauseSend() {
2325 return ChangeSend(SEND_NOTHING);
2326}
2327
2328bool WebRtcVoiceMediaChannel::ResumeSend() {
2329 return ChangeSend(desired_send_);
2330}
2331
2332bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2333 if (send_ == send) {
2334 return true;
2335 }
2336
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002337 // Change the settings on each send channel.
2338 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002339 engine()->SetOptionOverrides(options_);
2340
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002341 // Change the settings on each send channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002342 for (const auto& ch : send_channels_) {
2343 if (!ChangeSend(ch.second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002344 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002345 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002346
2347 // Clear up the options after stopping sending.
2348 if (send == SEND_NOTHING)
2349 engine()->ClearOptionOverrides();
2350
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002351 send_ = send;
2352 return true;
2353}
2354
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002355bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2356 if (send == SEND_MICROPHONE) {
2357 if (engine()->voe()->base()->StartSend(channel) == -1) {
2358 LOG_RTCERR1(StartSend, channel);
2359 return false;
2360 }
2361 if (engine()->voe()->file() &&
2362 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2363 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2364 return false;
2365 }
2366 } else { // SEND_NOTHING
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002367 DCHECK(send == SEND_NOTHING);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002368 if (engine()->voe()->base()->StopSend(channel) == -1) {
2369 LOG_RTCERR1(StopSend, channel);
2370 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002371 }
2372 }
2373
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002374 return true;
2375}
2376
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002377// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002378void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2379 if (engine()->voe()->network()->RegisterExternalTransport(
2380 channel, *this) == -1) {
2381 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2382 }
2383
2384 // Enable RTCP (for quality stats and feedback messages)
2385 EnableRtcp(channel);
2386
2387 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2388 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002389
2390 // Set RTP header extension for the new channel.
2391 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002392}
2393
2394bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2395 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2396 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2397 }
2398
2399 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2400 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002401 return false;
2402 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002403
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002404 return true;
2405}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002406
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002407bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2408 // If the default channel is already used for sending create a new channel
2409 // otherwise use the default channel for sending.
2410 int channel = GetSendChannelNum(sp.first_ssrc());
2411 if (channel != -1) {
2412 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2413 return false;
2414 }
2415
2416 bool default_channel_is_available = true;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002417 for (const auto& ch : send_channels_) {
2418 if (IsDefaultChannel(ch.second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002419 default_channel_is_available = false;
2420 break;
2421 }
2422 }
2423 if (default_channel_is_available) {
2424 channel = voe_channel();
2425 } else {
2426 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002427 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002428 if (channel == -1) {
2429 LOG_RTCERR0(CreateChannel);
2430 return false;
2431 }
2432
2433 ConfigureSendChannel(channel);
2434 }
2435
2436 // Save the channel to send_channels_, so that RemoveSendStream() can still
2437 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002438 webrtc::AudioTransport* audio_transport =
2439 engine()->voe()->base()->audio_transport();
pbos8fc7fa72015-07-15 08:02:58 -07002440 send_channels_.insert(
2441 std::make_pair(sp.first_ssrc(),
2442 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002443
2444 // Set the send (local) SSRC.
2445 // If there are multiple send SSRCs, we can only set the first one here, and
2446 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2447 // (with a codec requires multiple SSRC(s)).
2448 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2449 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2450 return false;
2451 }
2452
2453 // At this point the channel's local SSRC has been updated. If the channel is
2454 // the default channel make sure that all the receive channels are updated as
2455 // well. Receive channels have to have the same SSRC as the default channel in
2456 // order to send receiver reports with this SSRC.
2457 if (IsDefaultChannel(channel)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002458 for (const auto& ch : receive_channels_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002459 // Only update the SSRC for non-default channels.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002460 if (!IsDefaultChannel(ch.second->channel())) {
2461 if (engine()->voe()->rtp()->SetLocalSSRC(ch.second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002462 sp.first_ssrc()) != 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002463 LOG_RTCERR2(SetLocalSSRC, ch.second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002464 return false;
2465 }
2466 }
2467 }
2468 }
2469
2470 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002471 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2472 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002473 }
2474
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002475 // Set the current codecs to be used for the new channel.
2476 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002477 return false;
2478
2479 return ChangeSend(channel, desired_send_);
2480}
2481
2482bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2483 ChannelMap::iterator it = send_channels_.find(ssrc);
2484 if (it == send_channels_.end()) {
2485 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2486 << " which doesn't exist.";
2487 return false;
2488 }
2489
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002490 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002491 ChangeSend(channel, SEND_NOTHING);
2492
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002493 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2494 // this will disconnect the audio renderer with the send channel.
2495 delete it->second;
2496 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002497
2498 if (IsDefaultChannel(channel)) {
2499 // Do not delete the default channel since the receive channels depend on
2500 // the default channel, recycle it instead.
2501 ChangeSend(channel, SEND_NOTHING);
2502 } else {
2503 // Clean up and delete the send channel.
2504 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2505 << " with VoiceEngine channel #" << channel << ".";
2506 if (!DeleteChannel(channel))
2507 return false;
2508 }
2509
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002510 if (send_channels_.empty())
2511 ChangeSend(SEND_NOTHING);
2512
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002513 return true;
2514}
2515
2516bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002517 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002518 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002519
2520 if (!VERIFY(sp.ssrcs.size() == 1))
2521 return false;
2522 uint32 ssrc = sp.first_ssrc();
2523
wu@webrtc.org78187522013-10-07 23:32:02 +00002524 if (ssrc == 0) {
2525 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2526 return false;
2527 }
2528
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002529 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2530 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002531 return false;
2532 }
2533
pbos8fc7fa72015-07-15 08:02:58 -07002534 DCHECK(receive_stream_params_.find(ssrc) == receive_stream_params_.end());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002535
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002536 // Reuse default channel for recv stream in non-conference mode call
2537 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002538 webrtc::AudioTransport* audio_transport =
2539 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002540 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002541 LOG(LS_INFO) << "Recv stream " << ssrc << " reuse default channel";
2542 default_receive_ssrc_ = ssrc;
pbos8fc7fa72015-07-15 08:02:58 -07002543 WebRtcVoiceChannelRenderer* channel_renderer =
2544 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport);
2545 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2546 receive_stream_params_[ssrc] = sp;
2547 TryAddAudioRecvStream(ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002548 return SetPlayout(voe_channel(), playout_);
2549 }
2550
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002551 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002552 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002553 if (channel == -1) {
2554 LOG_RTCERR0(CreateChannel);
2555 return false;
2556 }
2557
wu@webrtc.org78187522013-10-07 23:32:02 +00002558 if (!ConfigureRecvChannel(channel)) {
2559 DeleteChannel(channel);
2560 return false;
2561 }
2562
pbos8fc7fa72015-07-15 08:02:58 -07002563 WebRtcVoiceChannelRenderer* channel_renderer =
2564 new WebRtcVoiceChannelRenderer(channel, audio_transport);
2565 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2566 receive_stream_params_[ssrc] = sp;
2567 TryAddAudioRecvStream(ssrc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002568
2569 LOG(LS_INFO) << "New audio stream " << ssrc
2570 << " registered to VoiceEngine channel #"
2571 << channel << ".";
2572 return true;
2573}
2574
2575bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002576 // Configure to use external transport, like our default channel.
2577 if (engine()->voe()->network()->RegisterExternalTransport(
2578 channel, *this) == -1) {
2579 LOG_RTCERR2(SetExternalTransport, channel, this);
2580 return false;
2581 }
2582
2583 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002584 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002585 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2586 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002587 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002588 return false;
2589 }
2590 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002591 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002592 return false;
2593 }
2594
Minyue2013aec2015-05-13 14:14:42 +02002595 // Associate receive channel to default channel (so the receive channel can
2596 // obtain RTT from the send channel)
2597 engine()->voe()->base()->AssociateSendChannel(channel, voe_channel());
2598 LOG(LS_INFO) << "VoiceEngine channel #"
2599 << channel << " is associated with channel #"
2600 << voe_channel() << ".";
2601
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002602 // Use the same recv payload types as our default channel.
2603 ResetRecvCodecs(channel);
2604 if (!recv_codecs_.empty()) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002605 for (const auto& codec : recv_codecs_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002606 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002607 if (engine()->FindWebRtcCodec(codec, &voe_codec)) {
2608 voe_codec.pltype = codec.id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002609 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2610 if (engine()->voe()->codec()->GetRecPayloadType(
2611 voe_channel(), voe_codec) != -1) {
2612 if (engine()->voe()->codec()->SetRecPayloadType(
2613 channel, voe_codec) == -1) {
2614 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2615 return false;
2616 }
2617 }
2618 }
2619 }
2620 }
2621
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002622 if (InConferenceMode()) {
2623 // To be in par with the video, voe_channel() is not used for receiving in
2624 // a conference call.
2625 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2626 // This is the first stream in a multi user meeting. We can now
2627 // disable playback of the default stream. This since the default
2628 // stream will probably have received some initial packets before
2629 // the new stream was added. This will mean that the CN state from
2630 // the default channel will be mixed in with the other streams
2631 // throughout the whole meeting, which might be disturbing.
2632 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2633 SetPlayout(voe_channel(), false);
2634 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002635 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002636 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002637
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002638 // Set RTP header extension for the new channel.
2639 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2640 return false;
2641 }
2642
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002643 return SetPlayout(channel, playout_);
2644}
2645
2646bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002647 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002648 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002649 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002650 if (it == receive_channels_.end()) {
2651 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2652 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002653 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002654 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002655
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002656 TryRemoveAudioRecvStream(ssrc);
pbos8fc7fa72015-07-15 08:02:58 -07002657 receive_stream_params_.erase(ssrc);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002658
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002659 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2660 // will disconnect the audio renderer with the receive channel.
2661 // Cache the channel before the deletion.
2662 const int channel = it->second->channel();
2663 delete it->second;
2664 receive_channels_.erase(it);
2665
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002666 if (ssrc == default_receive_ssrc_) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002667 DCHECK(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002668 // Recycle the default channel is for recv stream.
2669 if (playout_)
2670 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002671
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002672 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002673 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002674 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002675
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002676 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002677 << " with VoiceEngine channel #" << channel << ".";
2678 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002679 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002680
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002681 bool enable_default_channel_playout = false;
2682 if (receive_channels_.empty()) {
2683 // The last stream was removed. We can now enable the default
2684 // channel for new channels to be played out immediately without
2685 // waiting for AddStream messages.
2686 // We do this for both conference mode and non-conference mode.
2687 // TODO(oja): Does the default channel still have it's CN state?
2688 enable_default_channel_playout = true;
2689 }
2690 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2691 default_receive_ssrc_ != 0) {
2692 // Only the default channel is active, enable the playout on default
2693 // channel.
2694 enable_default_channel_playout = true;
2695 }
2696 if (enable_default_channel_playout && playout_) {
2697 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2698 SetPlayout(voe_channel(), true);
2699 }
2700
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002701 return true;
2702}
2703
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002704bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2705 AudioRenderer* renderer) {
2706 ChannelMap::iterator it = receive_channels_.find(ssrc);
2707 if (it == receive_channels_.end()) {
2708 if (renderer) {
2709 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002710 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002711 return false;
2712 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002713
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002714 // The channel likely has gone away, do nothing.
2715 return true;
2716 }
2717
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002718 if (renderer)
2719 it->second->Start(renderer);
2720 else
2721 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002722
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002723 return true;
2724}
2725
2726bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2727 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002728 ChannelMap::iterator it = send_channels_.find(ssrc);
2729 if (it == send_channels_.end()) {
2730 if (renderer) {
2731 // Return an error if trying to set a valid renderer with an invalid ssrc.
2732 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2733 return false;
2734 }
2735
2736 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002737 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002738 }
2739
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002740 if (renderer)
2741 it->second->Start(renderer);
2742 else
2743 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002744
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002745 return true;
2746}
2747
2748bool WebRtcVoiceMediaChannel::GetActiveStreams(
2749 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002750 // In conference mode, the default channel should not be in
2751 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002752 actives->clear();
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002753 for (const auto& ch : receive_channels_) {
2754 int level = GetOutputLevel(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002755 if (level > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002756 actives->push_back(std::make_pair(ch.first, level));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002757 }
2758 }
2759 return true;
2760}
2761
2762int WebRtcVoiceMediaChannel::GetOutputLevel() {
2763 // return the highest output level of all streams
2764 int highest = GetOutputLevel(voe_channel());
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002765 for (const auto& ch : receive_channels_) {
2766 int level = GetOutputLevel(ch.second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002767 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002768 }
2769 return highest;
2770}
2771
2772int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2773 int ret;
2774 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2775 // In case of error, log the info and continue
2776 LOG_RTCERR0(TimeSinceLastTyping);
2777 ret = -1;
2778 } else {
2779 ret *= 1000; // We return ms, webrtc returns seconds.
2780 }
2781 return ret;
2782}
2783
2784void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2785 int cost_per_typing, int reporting_threshold, int penalty_decay,
2786 int type_event_delay) {
2787 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2788 time_window, cost_per_typing,
2789 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2790 // In case of error, log the info and continue
2791 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2792 cost_per_typing, reporting_threshold, penalty_decay,
2793 type_event_delay);
2794 }
2795}
2796
2797bool WebRtcVoiceMediaChannel::SetOutputScaling(
2798 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002799 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002800 // Collect the channels to scale the output volume.
2801 std::vector<int> channels;
2802 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002803 // Default channel is not in receive_channels_ if it is not being used for
2804 // playout.
2805 if (default_receive_ssrc_ == 0)
2806 channels.push_back(voe_channel());
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002807 for (const auto& ch : receive_channels_) {
2808 channels.push_back(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002809 }
2810 } else { // Collect only the channel of the specified ssrc.
2811 int channel = GetReceiveChannelNum(ssrc);
2812 if (-1 == channel) {
2813 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2814 return false;
2815 }
2816 channels.push_back(channel);
2817 }
2818
2819 // Scale the output volume for the collected channels. We first normalize to
2820 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002821 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002822 if (scale > 0.0001f) {
2823 left /= scale;
2824 right /= scale;
2825 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002826 for (int ch_id : channels) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002827 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002828 ch_id, scale)) {
2829 LOG_RTCERR2(SetChannelOutputVolumeScaling, ch_id, scale);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002830 return false;
2831 }
2832 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002833 ch_id, static_cast<float>(left), static_cast<float>(right))) {
2834 LOG_RTCERR3(SetOutputVolumePan, ch_id, left, right);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002835 // Do not return if fails. SetOutputVolumePan is not available for all
2836 // pltforms.
2837 }
2838 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2839 << " right=" << right * scale
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002840 << " for channel " << ch_id << " and ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002841 }
2842 return true;
2843}
2844
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002845bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2846 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2847 return true;
2848}
2849
2850bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2851 bool play, bool loop) {
2852 if (!ringback_tone_) {
2853 return false;
2854 }
2855
2856 // The voe file api is not available in chrome.
2857 if (!engine()->voe()->file()) {
2858 return false;
2859 }
2860
2861 // Determine which VoiceEngine channel to play on.
2862 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2863 if (channel == -1) {
2864 return false;
2865 }
2866
2867 // Make sure the ringtone is cued properly, and play it out.
2868 if (play) {
2869 ringback_tone_->set_loop(loop);
2870 ringback_tone_->Rewind();
2871 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2872 ringback_tone_.get()) == -1) {
2873 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2874 LOG(LS_ERROR) << "Unable to start ringback tone";
2875 return false;
2876 }
2877 ringback_channels_.insert(channel);
2878 LOG(LS_INFO) << "Started ringback on channel " << channel;
2879 } else {
2880 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2881 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2882 LOG_RTCERR1(StopPlayingFileLocally, channel);
2883 return false;
2884 }
2885 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2886 ringback_channels_.erase(channel);
2887 }
2888
2889 return true;
2890}
2891
2892bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2893 return dtmf_allowed_;
2894}
2895
2896bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2897 int duration, int flags) {
2898 if (!dtmf_allowed_) {
2899 return false;
2900 }
2901
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002902 // Send the event.
2903 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002904 int channel = -1;
2905 if (ssrc == 0) {
2906 bool default_channel_is_inuse = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002907 for (const auto& ch : send_channels_) {
2908 if (IsDefaultChannel(ch.second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002909 default_channel_is_inuse = true;
2910 break;
2911 }
2912 }
2913 if (default_channel_is_inuse) {
2914 channel = voe_channel();
2915 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002916 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002917 }
2918 } else {
2919 channel = GetSendChannelNum(ssrc);
2920 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002921 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002922 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2923 << ssrc << " is not in use.";
2924 return false;
2925 }
2926 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002927 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2928 channel, event, true, duration) == -1) {
2929 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002930 return false;
2931 }
2932 }
2933
2934 // Play the event.
2935 if (flags & cricket::DF_PLAY) {
2936 // Play DTMF tone locally.
2937 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
2938 LOG_RTCERR2(PlayDtmfTone, event, duration);
2939 return false;
2940 }
2941 }
2942
2943 return true;
2944}
2945
wu@webrtc.orga9890802013-12-13 00:21:03 +00002946void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002947 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002948 DCHECK(thread_checker_.CalledOnValidThread());
2949
2950 // If hooked up to a "Call", forward packet there too.
2951 if (call_) {
2952 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
2953 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
2954 }
2955
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002956 // Pick which channel to send this packet to. If this packet doesn't match
2957 // any multiplexed streams, just send it to the default channel. Otherwise,
2958 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002959 int which_channel =
2960 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002961 if (which_channel == -1) {
2962 which_channel = voe_channel();
2963 }
2964
2965 // Stop any ringback that might be playing on the channel.
2966 // It's possible the ringback has already stopped, ih which case we'll just
2967 // use the opportunity to remove the channel from ringback_channels_.
2968 if (engine()->voe()->file()) {
2969 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
2970 if (it != ringback_channels_.end()) {
2971 if (engine()->voe()->file()->IsPlayingFileLocally(
2972 which_channel) == 1) {
2973 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
2974 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
2975 << " due to incoming media";
2976 }
2977 ringback_channels_.erase(which_channel);
2978 }
2979 }
2980
2981 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002982 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002983 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002984 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002985}
2986
wu@webrtc.orga9890802013-12-13 00:21:03 +00002987void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002988 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002989 DCHECK(thread_checker_.CalledOnValidThread());
2990
2991 // If hooked up to a "Call", forward packet there too.
2992 if (call_) {
2993 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
2994 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
2995 }
2996
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002997 // Sending channels need all RTCP packets with feedback information.
2998 // Even sender reports can contain attached report blocks.
2999 // Receiving channels need sender reports in order to create
3000 // correct receiver reports.
3001 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003002 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003003 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3004 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003005 }
3006
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003007 // If it is a sender report, find the channel that is listening.
3008 bool has_sent_to_default_channel = false;
3009 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003010 int which_channel =
3011 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003012 if (which_channel != -1) {
3013 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003014 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003015
3016 if (IsDefaultChannel(which_channel))
3017 has_sent_to_default_channel = true;
3018 }
3019 }
3020
3021 // SR may continue RR and any RR entry may correspond to any one of the send
3022 // channels. So all RTCP packets must be forwarded all send channels. VoE
3023 // will filter out RR internally.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003024 for (const auto& ch : send_channels_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003025 // Make sure not sending the same packet to default channel more than once.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003026 if (IsDefaultChannel(ch.second->channel()) &&
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003027 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003028 continue;
3029
3030 engine()->voe()->network()->ReceivedRTCPPacket(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003031 ch.second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003032 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003033}
3034
3035bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003036 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3037 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003038 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3039 return false;
3040 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003041 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3042 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003043 return false;
3044 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003045 // We set the AGC to mute state only when all the channels are muted.
3046 // This implementation is not ideal, instead we should signal the AGC when
3047 // the mic channel is muted/unmuted. We can't do it today because there
3048 // is no good way to know which stream is mapping to the mic channel.
3049 bool all_muted = muted;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003050 for (const auto& ch : send_channels_) {
3051 if (!all_muted) {
3052 break;
3053 }
3054 if (engine()->voe()->volume()->GetInputMute(ch.second->channel(),
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003055 all_muted)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003056 LOG_RTCERR1(GetInputMute, ch.second->channel());
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003057 return false;
3058 }
3059 }
3060
3061 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3062 if (ap)
3063 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003064 return true;
3065}
3066
minyue@webrtc.org26236952014-10-29 02:27:08 +00003067// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3068// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003069bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003070 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003071
minyue@webrtc.org26236952014-10-29 02:27:08 +00003072 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003073}
3074
minyue@webrtc.org26236952014-10-29 02:27:08 +00003075bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3076 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003077
minyue@webrtc.org26236952014-10-29 02:27:08 +00003078 send_bitrate_setting_ = true;
3079 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003080
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003081 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003082 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003083 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003084 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003085 }
3086
minyue@webrtc.org26236952014-10-29 02:27:08 +00003087 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003088 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3089 // SetMaxSendBandwith(0), the second call removes the previous limit.
3090 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003091 return true;
3092
3093 webrtc::CodecInst codec = *send_codec_;
3094 bool is_multi_rate = IsCodecMultiRate(codec);
3095
3096 if (is_multi_rate) {
3097 // If codec is multi-rate then just set the bitrate.
3098 codec.rate = bps;
3099 if (!SetSendCodec(codec)) {
3100 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3101 << " to bitrate " << bps << " bps.";
3102 return false;
3103 }
3104 return true;
3105 } else {
3106 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3107 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3108 // fixed bitrate then ignore.
3109 if (bps < codec.rate) {
3110 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3111 << " to bitrate " << bps << " bps"
3112 << ", requires at least " << codec.rate << " bps.";
3113 return false;
3114 }
3115 return true;
3116 }
3117}
3118
3119bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003120 bool echo_metrics_on = false;
3121 // These can take on valid negative values, so use the lowest possible level
3122 // as default rather than -1.
3123 int echo_return_loss = -100;
3124 int echo_return_loss_enhancement = -100;
3125 // These can also be negative, but in practice -1 is only used to signal
3126 // insufficient data, since the resolution is limited to multiples of 4 ms.
3127 int echo_delay_median_ms = -1;
3128 int echo_delay_std_ms = -1;
3129 if (engine()->voe()->processing()->GetEcMetricsStatus(
3130 echo_metrics_on) != -1 && echo_metrics_on) {
3131 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3132 // here, but it appears to be unsuitable currently. Revisit after this is
3133 // investigated: http://b/issue?id=5666755
3134 int erl, erle, rerl, anlp;
3135 if (engine()->voe()->processing()->GetEchoMetrics(
3136 erl, erle, rerl, anlp) != -1) {
3137 echo_return_loss = erl;
3138 echo_return_loss_enhancement = erle;
3139 }
3140
3141 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003142 float dummy;
3143 if (engine()->voe()->processing()->GetEcDelayMetrics(
3144 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003145 echo_delay_median_ms = median;
3146 echo_delay_std_ms = std;
3147 }
3148 }
3149
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003150 webrtc::CallStatistics cs;
3151 unsigned int ssrc;
3152 webrtc::CodecInst codec;
3153 unsigned int level;
3154
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003155 for (const auto& ch : send_channels_) {
3156 const int channel = ch.second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003157
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003158 // Fill in the sender info, based on what we know, and what the
3159 // remote side told us it got from its RTCP report.
3160 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003161
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003162 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3163 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3164 continue;
3165 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003166
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003167 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003168 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3169 sinfo.bytes_sent = cs.bytesSent;
3170 sinfo.packets_sent = cs.packetsSent;
3171 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3172 // returns 0 to indicate an error value.
3173 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3174
3175 // Get data from the last remote RTCP report. Use default values if no data
3176 // available.
3177 sinfo.fraction_lost = -1.0;
3178 sinfo.jitter_ms = -1;
3179 sinfo.packets_lost = -1;
3180 sinfo.ext_seqnum = -1;
3181 std::vector<webrtc::ReportBlock> receive_blocks;
3182 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3183 channel, &receive_blocks) != -1 &&
3184 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003185 for (const webrtc::ReportBlock& block : receive_blocks) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003186 // Lookup report for send ssrc only.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003187 if (block.source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003188 // Convert Q8 to floating point.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003189 sinfo.fraction_lost = static_cast<float>(block.fraction_lost) / 256;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003190 // Convert samples to milliseconds.
3191 if (codec.plfreq / 1000 > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003192 sinfo.jitter_ms = block.interarrival_jitter / (codec.plfreq / 1000);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003193 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003194 sinfo.packets_lost = block.cumulative_num_packets_lost;
3195 sinfo.ext_seqnum = block.extended_highest_sequence_number;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003196 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003197 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003198 }
3199 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003200
3201 // Local speech level.
3202 sinfo.audio_level = (engine()->voe()->volume()->
3203 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3204
3205 // TODO(xians): We are injecting the same APM logging to all the send
3206 // channels here because there is no good way to know which send channel
3207 // is using the APM. The correct fix is to allow the send channels to have
3208 // their own APM so that we can feed the correct APM logging to different
3209 // send channels. See issue crbug/264611 .
3210 sinfo.echo_return_loss = echo_return_loss;
3211 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3212 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3213 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003214 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3215 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003216 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003217
3218 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003219 }
3220
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003221 // Build the list of receivers, one for each receiving channel, or 1 in
3222 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003223 std::vector<int> channels;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003224 for (const auto& ch : receive_channels_) {
3225 channels.push_back(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003226 }
3227 if (channels.empty()) {
3228 channels.push_back(voe_channel());
3229 }
3230
3231 // Get the SSRC and stats for each receiver, based on our own calculations.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003232 for (int ch_id : channels) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003233 memset(&cs, 0, sizeof(cs));
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003234 if (engine()->voe()->rtp()->GetRemoteSSRC(ch_id, ssrc) != -1 &&
3235 engine()->voe()->rtp()->GetRTCPStatistics(ch_id, cs) != -1 &&
3236 engine()->voe()->codec()->GetRecCodec(ch_id, codec) != -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003237 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003238 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003239 rinfo.bytes_rcvd = cs.bytesReceived;
3240 rinfo.packets_rcvd = cs.packetsReceived;
3241 // The next four fields are from the most recently sent RTCP report.
3242 // Convert Q8 to floating point.
3243 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3244 rinfo.packets_lost = cs.cumulativeLost;
3245 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003246 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003247 if (codec.pltype != -1) {
3248 rinfo.codec_name = codec.plname;
3249 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003250 // Convert samples to milliseconds.
3251 if (codec.plfreq / 1000 > 0) {
3252 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3253 }
3254
3255 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3256 webrtc::NetworkStatistics ns;
3257 if (engine()->voe()->neteq() &&
3258 engine()->voe()->neteq()->GetNetworkStatistics(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003259 ch_id, ns) != -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003260 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3261 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3262 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003263 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003264 rinfo.speech_expand_rate =
3265 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3266 rinfo.secondary_decoded_rate =
3267 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
Henrik Lundin8e6fd462015-06-02 09:24:52 +02003268 rinfo.accelerate_rate =
3269 static_cast<float>(ns.currentAccelerateRate) / (1 << 14);
3270 rinfo.preemptive_expand_rate =
3271 static_cast<float>(ns.currentPreemptiveRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003272 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003273
3274 webrtc::AudioDecodingCallStats ds;
3275 if (engine()->voe()->neteq() &&
3276 engine()->voe()->neteq()->GetDecodingCallStatistics(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003277 ch_id, &ds) != -1) {
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003278 rinfo.decoding_calls_to_silence_generator =
3279 ds.calls_to_silence_generator;
3280 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3281 rinfo.decoding_normal = ds.decoded_normal;
3282 rinfo.decoding_plc = ds.decoded_plc;
3283 rinfo.decoding_cng = ds.decoded_cng;
3284 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3285 }
3286
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003287 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003288 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003289 int playout_buffer_delay_ms = 0;
3290 engine()->voe()->sync()->GetDelayEstimate(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003291 ch_id, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003292 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3293 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003294 }
3295
3296 // Get speech level.
3297 rinfo.audio_level = (engine()->voe()->volume()->
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003298 GetSpeechOutputLevelFullRange(ch_id, level) != -1) ? level : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003299 info->receivers.push_back(rinfo);
3300 }
3301 }
3302
3303 return true;
3304}
3305
3306void WebRtcVoiceMediaChannel::GetLastMediaError(
3307 uint32* ssrc, VoiceMediaChannel::Error* error) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003308 DCHECK(ssrc != NULL);
3309 DCHECK(error != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003310 FindSsrc(voe_channel(), ssrc);
3311 *error = WebRtcErrorToChannelError(GetLastEngineError());
3312}
3313
3314bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003315 rtc::CritScope lock(&receive_channels_cs_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003316 DCHECK(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003317 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003318 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3319 // This means the error is not limited to a specific channel. Signal the
3320 // message using ssrc=0. If the current channel is sending, use this
3321 // channel for sending the message.
3322 *ssrc = 0;
3323 return true;
3324 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003325 // Check whether this is a sending channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003326 for (const auto& ch : send_channels_) {
3327 if (ch.second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003328 // This is a sending channel.
3329 uint32 local_ssrc = 0;
3330 if (engine()->voe()->rtp()->GetLocalSSRC(
3331 channel_num, local_ssrc) != -1) {
3332 *ssrc = local_ssrc;
3333 }
3334 return true;
3335 }
3336 }
3337
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003338 // Check whether this is a receiving channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003339 for (const auto& ch : receive_channels_) {
3340 if (ch.second->channel() == channel_num) {
3341 *ssrc = ch.first;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003342 return true;
3343 }
3344 }
3345 }
3346 return false;
3347}
3348
3349void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003350 if (error == VE_TYPING_NOISE_WARNING) {
3351 typing_noise_detected_ = true;
3352 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3353 typing_noise_detected_ = false;
3354 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003355 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3356}
3357
3358int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3359 unsigned int ulevel;
3360 int ret =
3361 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3362 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3363}
3364
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003365int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) const {
3366 ChannelMap::const_iterator it = receive_channels_.find(ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003367 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003368 return it->second->channel();
pbos8fc7fa72015-07-15 08:02:58 -07003369 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003370}
3371
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003372int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) const {
3373 ChannelMap::const_iterator it = send_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003374 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003375 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003376
3377 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003378}
3379
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003380void WebRtcVoiceMediaChannel::SetCall(webrtc::Call* call) {
3381 DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003382 for (const auto& it : receive_channels_) {
3383 TryRemoveAudioRecvStream(it.first);
3384 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003385 call_ = call;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003386 for (const auto& it : receive_channels_) {
3387 TryAddAudioRecvStream(it.first);
3388 }
3389}
3390
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003391bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3392 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3393 // Get the RED encodings from the parameter with no name. This may
3394 // change based on what is discussed on the Jingle list.
3395 // The encoding parameter is of the form "a/b"; we only support where
3396 // a == b. Verify this and parse out the value into red_pt.
3397 // If the parameter value is absent (as it will be until we wire up the
3398 // signaling of this message), use the second codec specified (i.e. the
3399 // one after "red") as the encoding parameter.
3400 int red_pt = -1;
3401 std::string red_params;
3402 CodecParameterMap::const_iterator it = red_codec.params.find("");
3403 if (it != red_codec.params.end()) {
3404 red_params = it->second;
3405 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003406 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003407 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003408 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003409 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3410 return false;
3411 }
3412 } else if (red_codec.params.empty()) {
3413 LOG(LS_WARNING) << "RED params not present, using defaults";
3414 if (all_codecs.size() > 1) {
3415 red_pt = all_codecs[1].id;
3416 }
3417 }
3418
3419 // Try to find red_pt in |codecs|.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003420 for (const AudioCodec& codec : all_codecs) {
3421 if (codec.id == red_pt) {
3422 // If we find the right codec, that will be the codec we pass to
3423 // SetSendCodec, with the desired payload type.
3424 if (engine()->FindWebRtcCodec(codec, send_codec)) {
3425 return true;
3426 } else {
3427 break;
3428 }
3429 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003430 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003431 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3432 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003433}
3434
3435bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3436 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003437 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003438 return false;
3439 }
3440 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3441 // what we want to do with them.
3442 // engine()->voe().EnableVQMon(voe_channel(), true);
3443 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3444 return true;
3445}
3446
3447bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3448 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3449 for (int i = 0; i < ncodecs; ++i) {
3450 webrtc::CodecInst voe_codec;
3451 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3452 voe_codec.pltype = -1;
3453 if (engine()->voe()->codec()->SetRecPayloadType(
3454 channel, voe_codec) == -1) {
3455 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3456 return false;
3457 }
3458 }
3459 }
3460 return true;
3461}
3462
3463bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3464 if (playout) {
3465 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3466 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3467 LOG_RTCERR1(StartPlayout, channel);
3468 return false;
3469 }
3470 } else {
3471 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3472 engine()->voe()->base()->StopPlayout(channel);
3473 }
3474 return true;
3475}
3476
3477uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3478 bool rtcp) {
3479 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3480 uint32 ssrc = 0;
3481 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003482 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003483 }
3484 return ssrc;
3485}
3486
3487// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3488VoiceMediaChannel::Error
3489 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3490 switch (err_code) {
3491 case 0:
3492 return ERROR_NONE;
3493 case VE_CANNOT_START_RECORDING:
3494 case VE_MIC_VOL_ERROR:
3495 case VE_GET_MIC_VOL_ERROR:
3496 case VE_CANNOT_ACCESS_MIC_VOL:
3497 return ERROR_REC_DEVICE_OPEN_FAILED;
3498 case VE_SATURATION_WARNING:
3499 return ERROR_REC_DEVICE_SATURATION;
3500 case VE_REC_DEVICE_REMOVED:
3501 return ERROR_REC_DEVICE_REMOVED;
3502 case VE_RUNTIME_REC_WARNING:
3503 case VE_RUNTIME_REC_ERROR:
3504 return ERROR_REC_RUNTIME_ERROR;
3505 case VE_CANNOT_START_PLAYOUT:
3506 case VE_SPEAKER_VOL_ERROR:
3507 case VE_GET_SPEAKER_VOL_ERROR:
3508 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3509 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3510 case VE_RUNTIME_PLAY_WARNING:
3511 case VE_RUNTIME_PLAY_ERROR:
3512 return ERROR_PLAY_RUNTIME_ERROR;
3513 case VE_TYPING_NOISE_WARNING:
3514 return ERROR_REC_TYPING_NOISE_DETECTED;
3515 default:
3516 return VoiceMediaChannel::ERROR_OTHER;
3517 }
3518}
3519
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003520bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3521 int channel_id, const RtpHeaderExtension* extension) {
3522 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003523 int id = 0;
3524 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003525 if (extension) {
3526 enable = true;
3527 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003528 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003529 }
3530 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003531 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003532 return false;
3533 }
3534 return true;
3535}
3536
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003537void WebRtcVoiceMediaChannel::TryAddAudioRecvStream(uint32 ssrc) {
3538 DCHECK(thread_checker_.CalledOnValidThread());
pbos8fc7fa72015-07-15 08:02:58 -07003539 WebRtcVoiceChannelRenderer* channel = receive_channels_[ssrc];
3540 DCHECK(channel != nullptr);
3541 DCHECK(receive_streams_.find(ssrc) == receive_streams_.end());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003542 // If we are hooked up to a webrtc::Call, create an AudioReceiveStream too.
pbos8fc7fa72015-07-15 08:02:58 -07003543 if (!call_) {
3544 return;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003545 }
pbos8fc7fa72015-07-15 08:02:58 -07003546 webrtc::AudioReceiveStream::Config config;
3547 config.rtp.remote_ssrc = ssrc;
3548 // Only add RTP extensions if we support combined A/V BWE.
pbos6bb1b6e2015-07-24 07:10:18 -07003549 config.rtp.extensions = recv_rtp_extensions_;
3550 config.combined_audio_video_bwe =
3551 options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false);
pbos8fc7fa72015-07-15 08:02:58 -07003552 config.voe_channel_id = channel->channel();
3553 config.sync_group = receive_stream_params_[ssrc].sync_label;
3554 webrtc::AudioReceiveStream* s = call_->CreateAudioReceiveStream(config);
3555 receive_streams_.insert(std::make_pair(ssrc, s));
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003556}
3557
3558void WebRtcVoiceMediaChannel::TryRemoveAudioRecvStream(uint32 ssrc) {
3559 DCHECK(thread_checker_.CalledOnValidThread());
3560 // If we are hooked up to a webrtc::Call, assume there is an
3561 // AudioReceiveStream to destroy too.
3562 if (call_) {
3563 auto stream_it = receive_streams_.find(ssrc);
3564 if (stream_it != receive_streams_.end()) {
3565 call_->DestroyAudioReceiveStream(stream_it->second);
3566 receive_streams_.erase(stream_it);
3567 }
3568 }
3569}
3570
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003571bool WebRtcVoiceMediaChannel::SetRecvCodecsInternal(
3572 const std::vector<AudioCodec>& new_codecs) {
3573 for (const AudioCodec& codec : new_codecs) {
3574 webrtc::CodecInst voe_codec;
3575 if (engine()->FindWebRtcCodec(codec, &voe_codec)) {
3576 LOG(LS_INFO) << ToString(codec);
3577 voe_codec.pltype = codec.id;
3578 if (default_receive_ssrc_ == 0) {
3579 // Set the receive codecs on the default channel explicitly if the
3580 // default channel is not used by |receive_channels_|, this happens in
3581 // conference mode or in non-conference mode when there is no playout
3582 // channel.
3583 // TODO(xians): Figure out how we use the default channel in conference
3584 // mode.
3585 if (engine()->voe()->codec()->SetRecPayloadType(
3586 voe_channel(), voe_codec) == -1) {
3587 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
3588 return false;
3589 }
3590 }
3591
3592 // Set the receive codecs on all receiving channels.
3593 for (const auto& ch : receive_channels_) {
3594 if (engine()->voe()->codec()->SetRecPayloadType(
3595 ch.second->channel(), voe_codec) == -1) {
3596 LOG_RTCERR2(SetRecPayloadType, ch.second->channel(),
3597 ToString(voe_codec));
3598 return false;
3599 }
3600 }
3601 } else {
3602 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
3603 return false;
3604 }
3605 }
3606 return true;
3607}
3608
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003609int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003610 size_t res = 0;
3611 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003612 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003613}
3614
3615int WebRtcSoundclipStream::Rewind() {
3616 mem_.Rewind();
3617 // Return -1 to keep VoiceEngine from looping.
3618 return (loop_) ? 0 : -1;
3619}
3620
3621} // namespace cricket
3622
3623#endif // HAVE_WEBRTC_VOICE