blob: 43cbc2e929dbbccd87e1434f8d6698ab47dcbf22 [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
solenberg1dd98f32015-09-10 01:57:14 -07002377bool WebRtcVoiceMediaChannel::SetAudioSend(uint32 ssrc, bool mute,
2378 const AudioOptions* options,
2379 AudioRenderer* renderer) {
2380 // TODO(solenberg): The state change should be fully rolled back if any one of
2381 // these calls fail.
2382 if (!SetLocalRenderer(ssrc, renderer)) {
2383 return false;
2384 }
2385 if (!MuteStream(ssrc, mute)) {
2386 return false;
2387 }
2388 if (!mute && options) {
2389 return SetOptions(*options);
2390 }
2391 return true;
2392}
2393
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002394// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002395void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2396 if (engine()->voe()->network()->RegisterExternalTransport(
2397 channel, *this) == -1) {
2398 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2399 }
2400
2401 // Enable RTCP (for quality stats and feedback messages)
2402 EnableRtcp(channel);
2403
2404 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2405 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002406
2407 // Set RTP header extension for the new channel.
2408 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002409}
2410
2411bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2412 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2413 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2414 }
2415
2416 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2417 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002418 return false;
2419 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002420
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002421 return true;
2422}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002423
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002424bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2425 // If the default channel is already used for sending create a new channel
2426 // otherwise use the default channel for sending.
2427 int channel = GetSendChannelNum(sp.first_ssrc());
2428 if (channel != -1) {
2429 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2430 return false;
2431 }
2432
2433 bool default_channel_is_available = true;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002434 for (const auto& ch : send_channels_) {
2435 if (IsDefaultChannel(ch.second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002436 default_channel_is_available = false;
2437 break;
2438 }
2439 }
2440 if (default_channel_is_available) {
2441 channel = voe_channel();
2442 } else {
2443 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002444 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002445 if (channel == -1) {
2446 LOG_RTCERR0(CreateChannel);
2447 return false;
2448 }
2449
2450 ConfigureSendChannel(channel);
2451 }
2452
2453 // Save the channel to send_channels_, so that RemoveSendStream() can still
2454 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002455 webrtc::AudioTransport* audio_transport =
2456 engine()->voe()->base()->audio_transport();
pbos8fc7fa72015-07-15 08:02:58 -07002457 send_channels_.insert(
2458 std::make_pair(sp.first_ssrc(),
2459 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002460
2461 // Set the send (local) SSRC.
2462 // If there are multiple send SSRCs, we can only set the first one here, and
2463 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2464 // (with a codec requires multiple SSRC(s)).
2465 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2466 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2467 return false;
2468 }
2469
2470 // At this point the channel's local SSRC has been updated. If the channel is
2471 // the default channel make sure that all the receive channels are updated as
2472 // well. Receive channels have to have the same SSRC as the default channel in
2473 // order to send receiver reports with this SSRC.
2474 if (IsDefaultChannel(channel)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002475 for (const auto& ch : receive_channels_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002476 // Only update the SSRC for non-default channels.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002477 if (!IsDefaultChannel(ch.second->channel())) {
2478 if (engine()->voe()->rtp()->SetLocalSSRC(ch.second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002479 sp.first_ssrc()) != 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002480 LOG_RTCERR2(SetLocalSSRC, ch.second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002481 return false;
2482 }
2483 }
2484 }
2485 }
2486
2487 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002488 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2489 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002490 }
2491
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002492 // Set the current codecs to be used for the new channel.
2493 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002494 return false;
2495
2496 return ChangeSend(channel, desired_send_);
2497}
2498
2499bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2500 ChannelMap::iterator it = send_channels_.find(ssrc);
2501 if (it == send_channels_.end()) {
2502 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2503 << " which doesn't exist.";
2504 return false;
2505 }
2506
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002507 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002508 ChangeSend(channel, SEND_NOTHING);
2509
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002510 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2511 // this will disconnect the audio renderer with the send channel.
2512 delete it->second;
2513 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002514
2515 if (IsDefaultChannel(channel)) {
2516 // Do not delete the default channel since the receive channels depend on
2517 // the default channel, recycle it instead.
2518 ChangeSend(channel, SEND_NOTHING);
2519 } else {
2520 // Clean up and delete the send channel.
2521 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2522 << " with VoiceEngine channel #" << channel << ".";
2523 if (!DeleteChannel(channel))
2524 return false;
2525 }
2526
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002527 if (send_channels_.empty())
2528 ChangeSend(SEND_NOTHING);
2529
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002530 return true;
2531}
2532
2533bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002534 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002535 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002536
2537 if (!VERIFY(sp.ssrcs.size() == 1))
2538 return false;
2539 uint32 ssrc = sp.first_ssrc();
2540
wu@webrtc.org78187522013-10-07 23:32:02 +00002541 if (ssrc == 0) {
2542 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2543 return false;
2544 }
2545
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002546 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2547 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002548 return false;
2549 }
2550
pbos8fc7fa72015-07-15 08:02:58 -07002551 DCHECK(receive_stream_params_.find(ssrc) == receive_stream_params_.end());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002552
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002553 // Reuse default channel for recv stream in non-conference mode call
2554 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002555 webrtc::AudioTransport* audio_transport =
2556 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002557 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002558 LOG(LS_INFO) << "Recv stream " << ssrc << " reuse default channel";
2559 default_receive_ssrc_ = ssrc;
pbos8fc7fa72015-07-15 08:02:58 -07002560 WebRtcVoiceChannelRenderer* channel_renderer =
2561 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport);
2562 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2563 receive_stream_params_[ssrc] = sp;
2564 TryAddAudioRecvStream(ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002565 return SetPlayout(voe_channel(), playout_);
2566 }
2567
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002568 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002569 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002570 if (channel == -1) {
2571 LOG_RTCERR0(CreateChannel);
2572 return false;
2573 }
2574
wu@webrtc.org78187522013-10-07 23:32:02 +00002575 if (!ConfigureRecvChannel(channel)) {
2576 DeleteChannel(channel);
2577 return false;
2578 }
2579
pbos8fc7fa72015-07-15 08:02:58 -07002580 WebRtcVoiceChannelRenderer* channel_renderer =
2581 new WebRtcVoiceChannelRenderer(channel, audio_transport);
2582 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2583 receive_stream_params_[ssrc] = sp;
2584 TryAddAudioRecvStream(ssrc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002585
2586 LOG(LS_INFO) << "New audio stream " << ssrc
2587 << " registered to VoiceEngine channel #"
2588 << channel << ".";
2589 return true;
2590}
2591
2592bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002593 // Configure to use external transport, like our default channel.
2594 if (engine()->voe()->network()->RegisterExternalTransport(
2595 channel, *this) == -1) {
2596 LOG_RTCERR2(SetExternalTransport, channel, this);
2597 return false;
2598 }
2599
2600 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002601 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002602 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2603 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002604 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002605 return false;
2606 }
2607 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002608 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002609 return false;
2610 }
2611
Minyue2013aec2015-05-13 14:14:42 +02002612 // Associate receive channel to default channel (so the receive channel can
2613 // obtain RTT from the send channel)
2614 engine()->voe()->base()->AssociateSendChannel(channel, voe_channel());
2615 LOG(LS_INFO) << "VoiceEngine channel #"
2616 << channel << " is associated with channel #"
2617 << voe_channel() << ".";
2618
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002619 // Use the same recv payload types as our default channel.
2620 ResetRecvCodecs(channel);
2621 if (!recv_codecs_.empty()) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002622 for (const auto& codec : recv_codecs_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002623 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002624 if (engine()->FindWebRtcCodec(codec, &voe_codec)) {
2625 voe_codec.pltype = codec.id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002626 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2627 if (engine()->voe()->codec()->GetRecPayloadType(
2628 voe_channel(), voe_codec) != -1) {
2629 if (engine()->voe()->codec()->SetRecPayloadType(
2630 channel, voe_codec) == -1) {
2631 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2632 return false;
2633 }
2634 }
2635 }
2636 }
2637 }
2638
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002639 if (InConferenceMode()) {
2640 // To be in par with the video, voe_channel() is not used for receiving in
2641 // a conference call.
2642 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2643 // This is the first stream in a multi user meeting. We can now
2644 // disable playback of the default stream. This since the default
2645 // stream will probably have received some initial packets before
2646 // the new stream was added. This will mean that the CN state from
2647 // the default channel will be mixed in with the other streams
2648 // throughout the whole meeting, which might be disturbing.
2649 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2650 SetPlayout(voe_channel(), false);
2651 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002652 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002653 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002654
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002655 // Set RTP header extension for the new channel.
2656 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2657 return false;
2658 }
2659
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002660 return SetPlayout(channel, playout_);
2661}
2662
2663bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002664 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002665 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002666 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002667 if (it == receive_channels_.end()) {
2668 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2669 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002670 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002671 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002672
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002673 TryRemoveAudioRecvStream(ssrc);
pbos8fc7fa72015-07-15 08:02:58 -07002674 receive_stream_params_.erase(ssrc);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002675
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002676 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2677 // will disconnect the audio renderer with the receive channel.
2678 // Cache the channel before the deletion.
2679 const int channel = it->second->channel();
2680 delete it->second;
2681 receive_channels_.erase(it);
2682
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002683 if (ssrc == default_receive_ssrc_) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002684 DCHECK(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002685 // Recycle the default channel is for recv stream.
2686 if (playout_)
2687 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002688
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002689 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002690 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002691 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002692
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002693 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002694 << " with VoiceEngine channel #" << channel << ".";
2695 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002696 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002697
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002698 bool enable_default_channel_playout = false;
2699 if (receive_channels_.empty()) {
2700 // The last stream was removed. We can now enable the default
2701 // channel for new channels to be played out immediately without
2702 // waiting for AddStream messages.
2703 // We do this for both conference mode and non-conference mode.
2704 // TODO(oja): Does the default channel still have it's CN state?
2705 enable_default_channel_playout = true;
2706 }
2707 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2708 default_receive_ssrc_ != 0) {
2709 // Only the default channel is active, enable the playout on default
2710 // channel.
2711 enable_default_channel_playout = true;
2712 }
2713 if (enable_default_channel_playout && playout_) {
2714 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2715 SetPlayout(voe_channel(), true);
2716 }
2717
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002718 return true;
2719}
2720
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002721bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2722 AudioRenderer* renderer) {
2723 ChannelMap::iterator it = receive_channels_.find(ssrc);
2724 if (it == receive_channels_.end()) {
2725 if (renderer) {
2726 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002727 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002728 return false;
2729 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002730
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002731 // The channel likely has gone away, do nothing.
2732 return true;
2733 }
2734
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002735 if (renderer)
2736 it->second->Start(renderer);
2737 else
2738 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002739
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002740 return true;
2741}
2742
2743bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2744 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002745 ChannelMap::iterator it = send_channels_.find(ssrc);
2746 if (it == send_channels_.end()) {
2747 if (renderer) {
2748 // Return an error if trying to set a valid renderer with an invalid ssrc.
2749 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2750 return false;
2751 }
2752
2753 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002754 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002755 }
2756
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002757 if (renderer)
2758 it->second->Start(renderer);
2759 else
2760 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002761
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002762 return true;
2763}
2764
2765bool WebRtcVoiceMediaChannel::GetActiveStreams(
2766 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002767 // In conference mode, the default channel should not be in
2768 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002769 actives->clear();
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002770 for (const auto& ch : receive_channels_) {
2771 int level = GetOutputLevel(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002772 if (level > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002773 actives->push_back(std::make_pair(ch.first, level));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002774 }
2775 }
2776 return true;
2777}
2778
2779int WebRtcVoiceMediaChannel::GetOutputLevel() {
2780 // return the highest output level of all streams
2781 int highest = GetOutputLevel(voe_channel());
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002782 for (const auto& ch : receive_channels_) {
2783 int level = GetOutputLevel(ch.second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002784 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002785 }
2786 return highest;
2787}
2788
2789int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2790 int ret;
2791 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2792 // In case of error, log the info and continue
2793 LOG_RTCERR0(TimeSinceLastTyping);
2794 ret = -1;
2795 } else {
2796 ret *= 1000; // We return ms, webrtc returns seconds.
2797 }
2798 return ret;
2799}
2800
2801void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2802 int cost_per_typing, int reporting_threshold, int penalty_decay,
2803 int type_event_delay) {
2804 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2805 time_window, cost_per_typing,
2806 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2807 // In case of error, log the info and continue
2808 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2809 cost_per_typing, reporting_threshold, penalty_decay,
2810 type_event_delay);
2811 }
2812}
2813
2814bool WebRtcVoiceMediaChannel::SetOutputScaling(
2815 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002816 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002817 // Collect the channels to scale the output volume.
2818 std::vector<int> channels;
2819 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002820 // Default channel is not in receive_channels_ if it is not being used for
2821 // playout.
2822 if (default_receive_ssrc_ == 0)
2823 channels.push_back(voe_channel());
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002824 for (const auto& ch : receive_channels_) {
2825 channels.push_back(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002826 }
2827 } else { // Collect only the channel of the specified ssrc.
2828 int channel = GetReceiveChannelNum(ssrc);
2829 if (-1 == channel) {
2830 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2831 return false;
2832 }
2833 channels.push_back(channel);
2834 }
2835
2836 // Scale the output volume for the collected channels. We first normalize to
2837 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002838 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002839 if (scale > 0.0001f) {
2840 left /= scale;
2841 right /= scale;
2842 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002843 for (int ch_id : channels) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002844 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002845 ch_id, scale)) {
2846 LOG_RTCERR2(SetChannelOutputVolumeScaling, ch_id, scale);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002847 return false;
2848 }
2849 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002850 ch_id, static_cast<float>(left), static_cast<float>(right))) {
2851 LOG_RTCERR3(SetOutputVolumePan, ch_id, left, right);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002852 // Do not return if fails. SetOutputVolumePan is not available for all
2853 // pltforms.
2854 }
2855 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2856 << " right=" << right * scale
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002857 << " for channel " << ch_id << " and ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002858 }
2859 return true;
2860}
2861
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002862bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2863 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2864 return true;
2865}
2866
2867bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2868 bool play, bool loop) {
2869 if (!ringback_tone_) {
2870 return false;
2871 }
2872
2873 // The voe file api is not available in chrome.
2874 if (!engine()->voe()->file()) {
2875 return false;
2876 }
2877
2878 // Determine which VoiceEngine channel to play on.
2879 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2880 if (channel == -1) {
2881 return false;
2882 }
2883
2884 // Make sure the ringtone is cued properly, and play it out.
2885 if (play) {
2886 ringback_tone_->set_loop(loop);
2887 ringback_tone_->Rewind();
2888 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2889 ringback_tone_.get()) == -1) {
2890 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2891 LOG(LS_ERROR) << "Unable to start ringback tone";
2892 return false;
2893 }
2894 ringback_channels_.insert(channel);
2895 LOG(LS_INFO) << "Started ringback on channel " << channel;
2896 } else {
2897 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2898 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2899 LOG_RTCERR1(StopPlayingFileLocally, channel);
2900 return false;
2901 }
2902 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2903 ringback_channels_.erase(channel);
2904 }
2905
2906 return true;
2907}
2908
2909bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2910 return dtmf_allowed_;
2911}
2912
2913bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2914 int duration, int flags) {
2915 if (!dtmf_allowed_) {
2916 return false;
2917 }
2918
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002919 // Send the event.
2920 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002921 int channel = -1;
2922 if (ssrc == 0) {
2923 bool default_channel_is_inuse = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002924 for (const auto& ch : send_channels_) {
2925 if (IsDefaultChannel(ch.second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002926 default_channel_is_inuse = true;
2927 break;
2928 }
2929 }
2930 if (default_channel_is_inuse) {
2931 channel = voe_channel();
2932 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002933 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002934 }
2935 } else {
2936 channel = GetSendChannelNum(ssrc);
2937 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002938 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002939 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2940 << ssrc << " is not in use.";
2941 return false;
2942 }
2943 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002944 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2945 channel, event, true, duration) == -1) {
2946 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002947 return false;
2948 }
2949 }
2950
2951 // Play the event.
2952 if (flags & cricket::DF_PLAY) {
2953 // Play DTMF tone locally.
2954 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
2955 LOG_RTCERR2(PlayDtmfTone, event, duration);
2956 return false;
2957 }
2958 }
2959
2960 return true;
2961}
2962
wu@webrtc.orga9890802013-12-13 00:21:03 +00002963void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002964 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002965 DCHECK(thread_checker_.CalledOnValidThread());
2966
2967 // If hooked up to a "Call", forward packet there too.
2968 if (call_) {
stefan68786d22015-09-08 05:36:15 -07002969 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2970 packet_time.not_before);
2971 call_->Receiver()->DeliverPacket(
2972 webrtc::MediaType::AUDIO,
2973 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
2974 webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002975 }
2976
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002977 // Pick which channel to send this packet to. If this packet doesn't match
2978 // any multiplexed streams, just send it to the default channel. Otherwise,
2979 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002980 int which_channel =
2981 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002982 if (which_channel == -1) {
2983 which_channel = voe_channel();
2984 }
2985
2986 // Stop any ringback that might be playing on the channel.
2987 // It's possible the ringback has already stopped, ih which case we'll just
2988 // use the opportunity to remove the channel from ringback_channels_.
2989 if (engine()->voe()->file()) {
2990 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
2991 if (it != ringback_channels_.end()) {
2992 if (engine()->voe()->file()->IsPlayingFileLocally(
2993 which_channel) == 1) {
2994 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
2995 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
2996 << " due to incoming media";
2997 }
2998 ringback_channels_.erase(which_channel);
2999 }
3000 }
3001
3002 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003003 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003004 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003005 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003006}
3007
wu@webrtc.orga9890802013-12-13 00:21:03 +00003008void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003009 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003010 DCHECK(thread_checker_.CalledOnValidThread());
3011
3012 // If hooked up to a "Call", forward packet there too.
3013 if (call_) {
stefan68786d22015-09-08 05:36:15 -07003014 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
3015 packet_time.not_before);
3016 call_->Receiver()->DeliverPacket(
3017 webrtc::MediaType::AUDIO,
3018 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
3019 webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003020 }
3021
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003022 // Sending channels need all RTCP packets with feedback information.
3023 // Even sender reports can contain attached report blocks.
3024 // Receiving channels need sender reports in order to create
3025 // correct receiver reports.
3026 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003027 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003028 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3029 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003030 }
3031
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003032 // If it is a sender report, find the channel that is listening.
3033 bool has_sent_to_default_channel = false;
3034 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003035 int which_channel =
3036 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003037 if (which_channel != -1) {
3038 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003039 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003040
3041 if (IsDefaultChannel(which_channel))
3042 has_sent_to_default_channel = true;
3043 }
3044 }
3045
3046 // SR may continue RR and any RR entry may correspond to any one of the send
3047 // channels. So all RTCP packets must be forwarded all send channels. VoE
3048 // will filter out RR internally.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003049 for (const auto& ch : send_channels_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003050 // Make sure not sending the same packet to default channel more than once.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003051 if (IsDefaultChannel(ch.second->channel()) &&
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003052 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003053 continue;
3054
3055 engine()->voe()->network()->ReceivedRTCPPacket(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003056 ch.second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003057 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003058}
3059
3060bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003061 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3062 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003063 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3064 return false;
3065 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003066 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3067 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003068 return false;
3069 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003070 // We set the AGC to mute state only when all the channels are muted.
3071 // This implementation is not ideal, instead we should signal the AGC when
3072 // the mic channel is muted/unmuted. We can't do it today because there
3073 // is no good way to know which stream is mapping to the mic channel.
3074 bool all_muted = muted;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003075 for (const auto& ch : send_channels_) {
3076 if (!all_muted) {
3077 break;
3078 }
3079 if (engine()->voe()->volume()->GetInputMute(ch.second->channel(),
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003080 all_muted)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003081 LOG_RTCERR1(GetInputMute, ch.second->channel());
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003082 return false;
3083 }
3084 }
3085
3086 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3087 if (ap)
3088 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003089 return true;
3090}
3091
minyue@webrtc.org26236952014-10-29 02:27:08 +00003092// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3093// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003094bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003095 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003096
minyue@webrtc.org26236952014-10-29 02:27:08 +00003097 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003098}
3099
minyue@webrtc.org26236952014-10-29 02:27:08 +00003100bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3101 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003102
minyue@webrtc.org26236952014-10-29 02:27:08 +00003103 send_bitrate_setting_ = true;
3104 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003105
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003106 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003107 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003108 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003109 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003110 }
3111
minyue@webrtc.org26236952014-10-29 02:27:08 +00003112 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003113 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3114 // SetMaxSendBandwith(0), the second call removes the previous limit.
3115 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003116 return true;
3117
3118 webrtc::CodecInst codec = *send_codec_;
3119 bool is_multi_rate = IsCodecMultiRate(codec);
3120
3121 if (is_multi_rate) {
3122 // If codec is multi-rate then just set the bitrate.
3123 codec.rate = bps;
3124 if (!SetSendCodec(codec)) {
3125 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3126 << " to bitrate " << bps << " bps.";
3127 return false;
3128 }
3129 return true;
3130 } else {
3131 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3132 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3133 // fixed bitrate then ignore.
3134 if (bps < codec.rate) {
3135 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3136 << " to bitrate " << bps << " bps"
3137 << ", requires at least " << codec.rate << " bps.";
3138 return false;
3139 }
3140 return true;
3141 }
3142}
3143
3144bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003145 bool echo_metrics_on = false;
3146 // These can take on valid negative values, so use the lowest possible level
3147 // as default rather than -1.
3148 int echo_return_loss = -100;
3149 int echo_return_loss_enhancement = -100;
3150 // These can also be negative, but in practice -1 is only used to signal
3151 // insufficient data, since the resolution is limited to multiples of 4 ms.
3152 int echo_delay_median_ms = -1;
3153 int echo_delay_std_ms = -1;
3154 if (engine()->voe()->processing()->GetEcMetricsStatus(
3155 echo_metrics_on) != -1 && echo_metrics_on) {
3156 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3157 // here, but it appears to be unsuitable currently. Revisit after this is
3158 // investigated: http://b/issue?id=5666755
3159 int erl, erle, rerl, anlp;
3160 if (engine()->voe()->processing()->GetEchoMetrics(
3161 erl, erle, rerl, anlp) != -1) {
3162 echo_return_loss = erl;
3163 echo_return_loss_enhancement = erle;
3164 }
3165
3166 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003167 float dummy;
3168 if (engine()->voe()->processing()->GetEcDelayMetrics(
3169 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003170 echo_delay_median_ms = median;
3171 echo_delay_std_ms = std;
3172 }
3173 }
3174
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003175 webrtc::CallStatistics cs;
3176 unsigned int ssrc;
3177 webrtc::CodecInst codec;
3178 unsigned int level;
3179
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003180 for (const auto& ch : send_channels_) {
3181 const int channel = ch.second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003182
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003183 // Fill in the sender info, based on what we know, and what the
3184 // remote side told us it got from its RTCP report.
3185 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003186
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003187 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3188 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3189 continue;
3190 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003191
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003192 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003193 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3194 sinfo.bytes_sent = cs.bytesSent;
3195 sinfo.packets_sent = cs.packetsSent;
3196 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3197 // returns 0 to indicate an error value.
3198 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3199
3200 // Get data from the last remote RTCP report. Use default values if no data
3201 // available.
3202 sinfo.fraction_lost = -1.0;
3203 sinfo.jitter_ms = -1;
3204 sinfo.packets_lost = -1;
3205 sinfo.ext_seqnum = -1;
3206 std::vector<webrtc::ReportBlock> receive_blocks;
3207 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3208 channel, &receive_blocks) != -1 &&
3209 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003210 for (const webrtc::ReportBlock& block : receive_blocks) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003211 // Lookup report for send ssrc only.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003212 if (block.source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003213 // Convert Q8 to floating point.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003214 sinfo.fraction_lost = static_cast<float>(block.fraction_lost) / 256;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003215 // Convert samples to milliseconds.
3216 if (codec.plfreq / 1000 > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003217 sinfo.jitter_ms = block.interarrival_jitter / (codec.plfreq / 1000);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003218 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003219 sinfo.packets_lost = block.cumulative_num_packets_lost;
3220 sinfo.ext_seqnum = block.extended_highest_sequence_number;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003221 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003222 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003223 }
3224 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003225
3226 // Local speech level.
3227 sinfo.audio_level = (engine()->voe()->volume()->
3228 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3229
3230 // TODO(xians): We are injecting the same APM logging to all the send
3231 // channels here because there is no good way to know which send channel
3232 // is using the APM. The correct fix is to allow the send channels to have
3233 // their own APM so that we can feed the correct APM logging to different
3234 // send channels. See issue crbug/264611 .
3235 sinfo.echo_return_loss = echo_return_loss;
3236 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3237 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3238 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003239 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3240 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003241 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003242
3243 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003244 }
3245
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003246 // Build the list of receivers, one for each receiving channel, or 1 in
3247 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003248 std::vector<int> channels;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003249 for (const auto& ch : receive_channels_) {
3250 channels.push_back(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003251 }
3252 if (channels.empty()) {
3253 channels.push_back(voe_channel());
3254 }
3255
3256 // Get the SSRC and stats for each receiver, based on our own calculations.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003257 for (int ch_id : channels) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003258 memset(&cs, 0, sizeof(cs));
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003259 if (engine()->voe()->rtp()->GetRemoteSSRC(ch_id, ssrc) != -1 &&
3260 engine()->voe()->rtp()->GetRTCPStatistics(ch_id, cs) != -1 &&
3261 engine()->voe()->codec()->GetRecCodec(ch_id, codec) != -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003262 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003263 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003264 rinfo.bytes_rcvd = cs.bytesReceived;
3265 rinfo.packets_rcvd = cs.packetsReceived;
3266 // The next four fields are from the most recently sent RTCP report.
3267 // Convert Q8 to floating point.
3268 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3269 rinfo.packets_lost = cs.cumulativeLost;
3270 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003271 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003272 if (codec.pltype != -1) {
3273 rinfo.codec_name = codec.plname;
3274 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003275 // Convert samples to milliseconds.
3276 if (codec.plfreq / 1000 > 0) {
3277 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3278 }
3279
3280 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3281 webrtc::NetworkStatistics ns;
3282 if (engine()->voe()->neteq() &&
3283 engine()->voe()->neteq()->GetNetworkStatistics(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003284 ch_id, ns) != -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003285 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3286 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3287 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003288 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003289 rinfo.speech_expand_rate =
3290 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3291 rinfo.secondary_decoded_rate =
3292 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
Henrik Lundin8e6fd462015-06-02 09:24:52 +02003293 rinfo.accelerate_rate =
3294 static_cast<float>(ns.currentAccelerateRate) / (1 << 14);
3295 rinfo.preemptive_expand_rate =
3296 static_cast<float>(ns.currentPreemptiveRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003297 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003298
3299 webrtc::AudioDecodingCallStats ds;
3300 if (engine()->voe()->neteq() &&
3301 engine()->voe()->neteq()->GetDecodingCallStatistics(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003302 ch_id, &ds) != -1) {
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003303 rinfo.decoding_calls_to_silence_generator =
3304 ds.calls_to_silence_generator;
3305 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3306 rinfo.decoding_normal = ds.decoded_normal;
3307 rinfo.decoding_plc = ds.decoded_plc;
3308 rinfo.decoding_cng = ds.decoded_cng;
3309 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3310 }
3311
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003312 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003313 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003314 int playout_buffer_delay_ms = 0;
3315 engine()->voe()->sync()->GetDelayEstimate(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003316 ch_id, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003317 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3318 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003319 }
3320
3321 // Get speech level.
3322 rinfo.audio_level = (engine()->voe()->volume()->
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003323 GetSpeechOutputLevelFullRange(ch_id, level) != -1) ? level : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003324 info->receivers.push_back(rinfo);
3325 }
3326 }
3327
3328 return true;
3329}
3330
3331void WebRtcVoiceMediaChannel::GetLastMediaError(
3332 uint32* ssrc, VoiceMediaChannel::Error* error) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003333 DCHECK(ssrc != NULL);
3334 DCHECK(error != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003335 FindSsrc(voe_channel(), ssrc);
3336 *error = WebRtcErrorToChannelError(GetLastEngineError());
3337}
3338
3339bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003340 rtc::CritScope lock(&receive_channels_cs_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003341 DCHECK(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003342 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003343 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3344 // This means the error is not limited to a specific channel. Signal the
3345 // message using ssrc=0. If the current channel is sending, use this
3346 // channel for sending the message.
3347 *ssrc = 0;
3348 return true;
3349 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003350 // Check whether this is a sending channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003351 for (const auto& ch : send_channels_) {
3352 if (ch.second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003353 // This is a sending channel.
3354 uint32 local_ssrc = 0;
3355 if (engine()->voe()->rtp()->GetLocalSSRC(
3356 channel_num, local_ssrc) != -1) {
3357 *ssrc = local_ssrc;
3358 }
3359 return true;
3360 }
3361 }
3362
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003363 // Check whether this is a receiving channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003364 for (const auto& ch : receive_channels_) {
3365 if (ch.second->channel() == channel_num) {
3366 *ssrc = ch.first;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003367 return true;
3368 }
3369 }
3370 }
3371 return false;
3372}
3373
3374void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003375 if (error == VE_TYPING_NOISE_WARNING) {
3376 typing_noise_detected_ = true;
3377 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3378 typing_noise_detected_ = false;
3379 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003380 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3381}
3382
3383int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3384 unsigned int ulevel;
3385 int ret =
3386 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3387 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3388}
3389
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003390int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) const {
3391 ChannelMap::const_iterator it = receive_channels_.find(ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003392 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003393 return it->second->channel();
pbos8fc7fa72015-07-15 08:02:58 -07003394 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003395}
3396
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003397int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) const {
3398 ChannelMap::const_iterator it = send_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003399 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003400 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003401
3402 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003403}
3404
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003405void WebRtcVoiceMediaChannel::SetCall(webrtc::Call* call) {
3406 DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003407 for (const auto& it : receive_channels_) {
3408 TryRemoveAudioRecvStream(it.first);
3409 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003410 call_ = call;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003411 for (const auto& it : receive_channels_) {
3412 TryAddAudioRecvStream(it.first);
3413 }
3414}
3415
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003416bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3417 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3418 // Get the RED encodings from the parameter with no name. This may
3419 // change based on what is discussed on the Jingle list.
3420 // The encoding parameter is of the form "a/b"; we only support where
3421 // a == b. Verify this and parse out the value into red_pt.
3422 // If the parameter value is absent (as it will be until we wire up the
3423 // signaling of this message), use the second codec specified (i.e. the
3424 // one after "red") as the encoding parameter.
3425 int red_pt = -1;
3426 std::string red_params;
3427 CodecParameterMap::const_iterator it = red_codec.params.find("");
3428 if (it != red_codec.params.end()) {
3429 red_params = it->second;
3430 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003431 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003432 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003433 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003434 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3435 return false;
3436 }
3437 } else if (red_codec.params.empty()) {
3438 LOG(LS_WARNING) << "RED params not present, using defaults";
3439 if (all_codecs.size() > 1) {
3440 red_pt = all_codecs[1].id;
3441 }
3442 }
3443
3444 // Try to find red_pt in |codecs|.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003445 for (const AudioCodec& codec : all_codecs) {
3446 if (codec.id == red_pt) {
3447 // If we find the right codec, that will be the codec we pass to
3448 // SetSendCodec, with the desired payload type.
3449 if (engine()->FindWebRtcCodec(codec, send_codec)) {
3450 return true;
3451 } else {
3452 break;
3453 }
3454 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003455 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003456 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3457 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003458}
3459
3460bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3461 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003462 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003463 return false;
3464 }
3465 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3466 // what we want to do with them.
3467 // engine()->voe().EnableVQMon(voe_channel(), true);
3468 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3469 return true;
3470}
3471
3472bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3473 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3474 for (int i = 0; i < ncodecs; ++i) {
3475 webrtc::CodecInst voe_codec;
3476 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3477 voe_codec.pltype = -1;
3478 if (engine()->voe()->codec()->SetRecPayloadType(
3479 channel, voe_codec) == -1) {
3480 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3481 return false;
3482 }
3483 }
3484 }
3485 return true;
3486}
3487
3488bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3489 if (playout) {
3490 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3491 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3492 LOG_RTCERR1(StartPlayout, channel);
3493 return false;
3494 }
3495 } else {
3496 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3497 engine()->voe()->base()->StopPlayout(channel);
3498 }
3499 return true;
3500}
3501
3502uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3503 bool rtcp) {
3504 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3505 uint32 ssrc = 0;
3506 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003507 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003508 }
3509 return ssrc;
3510}
3511
3512// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3513VoiceMediaChannel::Error
3514 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3515 switch (err_code) {
3516 case 0:
3517 return ERROR_NONE;
3518 case VE_CANNOT_START_RECORDING:
3519 case VE_MIC_VOL_ERROR:
3520 case VE_GET_MIC_VOL_ERROR:
3521 case VE_CANNOT_ACCESS_MIC_VOL:
3522 return ERROR_REC_DEVICE_OPEN_FAILED;
3523 case VE_SATURATION_WARNING:
3524 return ERROR_REC_DEVICE_SATURATION;
3525 case VE_REC_DEVICE_REMOVED:
3526 return ERROR_REC_DEVICE_REMOVED;
3527 case VE_RUNTIME_REC_WARNING:
3528 case VE_RUNTIME_REC_ERROR:
3529 return ERROR_REC_RUNTIME_ERROR;
3530 case VE_CANNOT_START_PLAYOUT:
3531 case VE_SPEAKER_VOL_ERROR:
3532 case VE_GET_SPEAKER_VOL_ERROR:
3533 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3534 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3535 case VE_RUNTIME_PLAY_WARNING:
3536 case VE_RUNTIME_PLAY_ERROR:
3537 return ERROR_PLAY_RUNTIME_ERROR;
3538 case VE_TYPING_NOISE_WARNING:
3539 return ERROR_REC_TYPING_NOISE_DETECTED;
3540 default:
3541 return VoiceMediaChannel::ERROR_OTHER;
3542 }
3543}
3544
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003545bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3546 int channel_id, const RtpHeaderExtension* extension) {
3547 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003548 int id = 0;
3549 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003550 if (extension) {
3551 enable = true;
3552 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003553 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003554 }
3555 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003556 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003557 return false;
3558 }
3559 return true;
3560}
3561
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003562void WebRtcVoiceMediaChannel::TryAddAudioRecvStream(uint32 ssrc) {
3563 DCHECK(thread_checker_.CalledOnValidThread());
pbos8fc7fa72015-07-15 08:02:58 -07003564 WebRtcVoiceChannelRenderer* channel = receive_channels_[ssrc];
3565 DCHECK(channel != nullptr);
3566 DCHECK(receive_streams_.find(ssrc) == receive_streams_.end());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003567 // If we are hooked up to a webrtc::Call, create an AudioReceiveStream too.
pbos8fc7fa72015-07-15 08:02:58 -07003568 if (!call_) {
3569 return;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003570 }
pbos8fc7fa72015-07-15 08:02:58 -07003571 webrtc::AudioReceiveStream::Config config;
3572 config.rtp.remote_ssrc = ssrc;
3573 // Only add RTP extensions if we support combined A/V BWE.
pbos6bb1b6e2015-07-24 07:10:18 -07003574 config.rtp.extensions = recv_rtp_extensions_;
3575 config.combined_audio_video_bwe =
3576 options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false);
pbos8fc7fa72015-07-15 08:02:58 -07003577 config.voe_channel_id = channel->channel();
3578 config.sync_group = receive_stream_params_[ssrc].sync_label;
3579 webrtc::AudioReceiveStream* s = call_->CreateAudioReceiveStream(config);
3580 receive_streams_.insert(std::make_pair(ssrc, s));
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003581}
3582
3583void WebRtcVoiceMediaChannel::TryRemoveAudioRecvStream(uint32 ssrc) {
3584 DCHECK(thread_checker_.CalledOnValidThread());
3585 // If we are hooked up to a webrtc::Call, assume there is an
3586 // AudioReceiveStream to destroy too.
3587 if (call_) {
3588 auto stream_it = receive_streams_.find(ssrc);
3589 if (stream_it != receive_streams_.end()) {
3590 call_->DestroyAudioReceiveStream(stream_it->second);
3591 receive_streams_.erase(stream_it);
3592 }
3593 }
3594}
3595
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003596bool WebRtcVoiceMediaChannel::SetRecvCodecsInternal(
3597 const std::vector<AudioCodec>& new_codecs) {
3598 for (const AudioCodec& codec : new_codecs) {
3599 webrtc::CodecInst voe_codec;
3600 if (engine()->FindWebRtcCodec(codec, &voe_codec)) {
3601 LOG(LS_INFO) << ToString(codec);
3602 voe_codec.pltype = codec.id;
3603 if (default_receive_ssrc_ == 0) {
3604 // Set the receive codecs on the default channel explicitly if the
3605 // default channel is not used by |receive_channels_|, this happens in
3606 // conference mode or in non-conference mode when there is no playout
3607 // channel.
3608 // TODO(xians): Figure out how we use the default channel in conference
3609 // mode.
3610 if (engine()->voe()->codec()->SetRecPayloadType(
3611 voe_channel(), voe_codec) == -1) {
3612 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
3613 return false;
3614 }
3615 }
3616
3617 // Set the receive codecs on all receiving channels.
3618 for (const auto& ch : receive_channels_) {
3619 if (engine()->voe()->codec()->SetRecPayloadType(
3620 ch.second->channel(), voe_codec) == -1) {
3621 LOG_RTCERR2(SetRecPayloadType, ch.second->channel(),
3622 ToString(voe_codec));
3623 return false;
3624 }
3625 }
3626 } else {
3627 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
3628 return false;
3629 }
3630 }
3631 return true;
3632}
3633
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003634int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003635 size_t res = 0;
3636 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003637 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003638}
3639
3640int WebRtcSoundclipStream::Rewind() {
3641 mem_.Rewind();
3642 // Return -1 to keep VoiceEngine from looping.
3643 return (loop_) ? 0 : -1;
3644}
3645
3646} // namespace cricket
3647
3648#endif // HAVE_WEBRTC_VOICE