blob: b01bfab3d85eeffb06c81ac1959b46178cb7d258 [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
Fredrik Solenberg709ed672015-09-15 12:26:33 +0200582VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel(webrtc::Call* call,
Jelena Marusicc28a8962015-05-29 15:05:44 +0200583 const AudioOptions& options) {
Fredrik Solenberg709ed672015-09-15 12:26:33 +0200584 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this, call);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000585 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 Solenberg709ed672015-09-15 12:26:33 +02001692WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine,
1693 webrtc::Call* call)
Fredrik Solenberge444a3d2015-05-07 16:42:08 +02001694 : engine_(engine),
1695 voe_channel_(engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001696 send_bitrate_setting_(false),
1697 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001698 options_(),
1699 dtmf_allowed_(false),
1700 desired_playout_(false),
1701 nack_enabled_(false),
1702 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001703 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001704 desired_send_(SEND_NOTHING),
1705 send_(SEND_NOTHING),
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001706 call_(call),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001707 default_receive_ssrc_(0) {
1708 engine->RegisterChannel(this);
1709 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1710 << voe_channel();
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001711 DCHECK(nullptr != call);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001712 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001713}
1714
1715WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1716 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1717 << voe_channel();
1718
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001719 // Remove any remaining send streams, the default channel will be deleted
1720 // later.
1721 while (!send_channels_.empty())
1722 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001723
1724 // Unregister ourselves from the engine.
1725 engine()->UnregisterChannel(this);
1726 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001727 while (!receive_channels_.empty()) {
1728 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001729 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001730 DCHECK(receive_streams_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001731
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001732 // Delete the default channel.
1733 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001734}
1735
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001736bool WebRtcVoiceMediaChannel::SetSendParameters(
1737 const AudioSendParameters& params) {
1738 // TODO(pthatcher): Refactor this to be more clean now that we have
1739 // all the information at once.
1740 return (SetSendCodecs(params.codecs) &&
1741 SetSendRtpHeaderExtensions(params.extensions) &&
1742 SetMaxSendBandwidth(params.max_bandwidth_bps) &&
1743 SetOptions(params.options));
1744}
1745
1746bool WebRtcVoiceMediaChannel::SetRecvParameters(
1747 const AudioRecvParameters& params) {
1748 // TODO(pthatcher): Refactor this to be more clean now that we have
1749 // all the information at once.
1750 return (SetRecvCodecs(params.codecs) &&
1751 SetRecvRtpHeaderExtensions(params.extensions));
1752}
1753
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001754bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1755 LOG(LS_INFO) << "Setting voice channel options: "
1756 << options.ToString();
1757
wu@webrtc.orgde305012013-10-31 15:40:38 +00001758 // Check if DSCP value is changed from previous.
1759 bool dscp_option_changed = (options_.dscp != options.dscp);
1760
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001761 // TODO(xians): Add support to set different options for different send
1762 // streams after we support multiple APMs.
1763
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001764 // We retain all of the existing options, and apply the given ones
1765 // on top. This means there is no way to "clear" options such that
1766 // they go back to the engine default.
1767 options_.SetAll(options);
1768
1769 if (send_ != SEND_NOTHING) {
1770 if (!engine()->SetOptionOverrides(options_)) {
1771 LOG(LS_WARNING) <<
1772 "Failed to engine SetOptionOverrides during channel SetOptions.";
1773 return false;
1774 }
1775 } else {
1776 // Will be interpreted when appropriate.
1777 }
1778
wu@webrtc.org97077a32013-10-25 21:18:33 +00001779 // Receiver-side auto gain control happens per channel, so set it here from
1780 // options. Note that, like conference mode, setting it on the engine won't
1781 // have the desired effect, since voice channels don't inherit options from
1782 // the media engine when those options are applied per-channel.
1783 bool rx_auto_gain_control;
1784 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1785 if (engine()->voe()->processing()->SetRxAgcStatus(
1786 voe_channel(), rx_auto_gain_control,
1787 webrtc::kAgcFixedDigital) == -1) {
1788 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1789 return false;
1790 } else {
1791 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1792 << " with mode " << webrtc::kAgcFixedDigital;
1793 }
1794 }
1795 if (options.rx_agc_target_dbov.IsSet() ||
1796 options.rx_agc_digital_compression_gain.IsSet() ||
1797 options.rx_agc_limiter.IsSet()) {
1798 webrtc::AgcConfig config;
1799 // If only some of the options are being overridden, get the current
1800 // settings for the channel and bail if they aren't available.
1801 if (!options.rx_agc_target_dbov.IsSet() ||
1802 !options.rx_agc_digital_compression_gain.IsSet() ||
1803 !options.rx_agc_limiter.IsSet()) {
1804 if (engine()->voe()->processing()->GetRxAgcConfig(
1805 voe_channel(), config) != 0) {
1806 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1807 << "channel " << voe_channel() << ". Since not all rx "
1808 << "agc options are specified, unable to safely set rx "
1809 << "agc options.";
1810 return false;
1811 }
1812 }
1813 config.targetLeveldBOv =
1814 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1815 config.targetLeveldBOv);
1816 config.digitalCompressionGaindB =
1817 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1818 config.digitalCompressionGaindB);
1819 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1820 config.limiterEnable);
1821 if (engine()->voe()->processing()->SetRxAgcConfig(
1822 voe_channel(), config) == -1) {
1823 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1824 config.digitalCompressionGaindB, config.limiterEnable);
1825 return false;
1826 }
1827 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001828 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001829 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001830 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001831 dscp = kAudioDscpValue;
1832 if (MediaChannel::SetDscp(dscp) != 0) {
1833 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1834 }
1835 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001836
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001837 RecreateAudioReceiveStreams();
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001838
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001839 LOG(LS_INFO) << "Set voice channel options. Current options: "
1840 << options_.ToString();
1841 return true;
1842}
1843
1844bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1845 const std::vector<AudioCodec>& codecs) {
1846 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001847 LOG(LS_INFO) << "Setting receive voice codecs:";
1848
1849 std::vector<AudioCodec> new_codecs;
1850 // Find all new codecs. We allow adding new codecs but don't allow changing
1851 // the payload type of codecs that is already configured since we might
1852 // already be receiving packets with that payload type.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001853 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001854 AudioCodec old_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001855 if (FindCodec(recv_codecs_, codec, &old_codec)) {
1856 if (old_codec.id != codec.id) {
1857 LOG(LS_ERROR) << codec.name << " payload type changed.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001858 return false;
1859 }
1860 } else {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001861 new_codecs.push_back(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001862 }
1863 }
1864 if (new_codecs.empty()) {
1865 // There are no new codecs to configure. Already configured codecs are
1866 // never removed.
1867 return true;
1868 }
1869
1870 if (playout_) {
1871 // Receive codecs can not be changed while playing. So we temporarily
1872 // pause playout.
1873 PausePlayout();
1874 }
1875
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001876 bool result = SetRecvCodecsInternal(new_codecs);
1877 if (result) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001878 recv_codecs_ = codecs;
1879 }
1880
1881 if (desired_playout_ && !playout_) {
1882 ResumePlayout();
1883 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001884 return result;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001885}
1886
1887bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001888 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001889 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001890 engine()->voe()->codec()->SetVADStatus(channel, false);
1891 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001892 engine()->voe()->rtp()->SetREDStatus(channel, false);
1893 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001894
1895 // Scan through the list to figure out the codec to use for sending, along
1896 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001897 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001898 webrtc::CodecInst send_codec;
1899 memset(&send_codec, 0, sizeof(send_codec));
1900
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001901 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001902 bool enable_codec_fec = false;
Minyue Li7100dcd2015-03-27 05:05:59 +01001903 bool enable_opus_dtx = false;
minyue@webrtc.org26236952014-10-29 02:27:08 +00001904 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001905
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001906 // Set send codec (the first non-telephone-event/CN codec)
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001907 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001908 // Ignore codecs we don't know about. The negotiation step should prevent
1909 // this, but double-check to be sure.
1910 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001911 if (!engine()->FindWebRtcCodec(codec, &voe_codec)) {
1912 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001913 continue;
1914 }
1915
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001916 if (IsCodec(codec, kDtmfCodecName) || IsCodec(codec, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001917 // Skip telephone-event/CN codec, which will be handled later.
1918 continue;
1919 }
1920
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001921 // We'll use the first codec in the list to actually send audio data.
1922 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001923 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001924 // used is specified in params.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001925 if (IsCodec(codec, kRedCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001926 // Parse out the RED parameters. If we fail, just ignore RED;
1927 // we don't support all possible params/usage scenarios.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001928 if (!GetRedSendCodec(codec, codecs, &send_codec)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001929 continue;
1930 }
1931
1932 // Enable redundant encoding of the specified codec. Treat any
1933 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001934 LOG(LS_INFO) << "Enabling RED on channel " << channel;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001935 if (engine()->voe()->rtp()->SetREDStatus(channel, true, codec.id) == -1) {
1936 LOG_RTCERR3(SetREDStatus, channel, true, codec.id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001937 return false;
1938 }
1939 } else {
1940 send_codec = voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001941 nack_enabled = IsNackEnabled(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +01001942 // For Opus as the send codec, we are to determine inband FEC, maximum
1943 // playback rate, and opus internal dtx.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001944 if (IsCodec(codec, kOpusCodecName)) {
1945 GetOpusConfig(codec, &send_codec, &enable_codec_fec,
Minyue Li7100dcd2015-03-27 05:05:59 +01001946 &opus_max_playback_rate, &enable_opus_dtx);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001947 }
Brave Yao5225dd82015-03-26 07:39:19 +08001948
1949 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1950 int ptime_ms = 0;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001951 if (codec.GetParam(kCodecParamPTime, &ptime_ms)) {
Brave Yao5225dd82015-03-26 07:39:19 +08001952 if (!SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
1953 LOG(LS_WARNING) << "Failed to set packet size for codec "
1954 << send_codec.plname;
1955 return false;
1956 }
1957 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001958 }
1959 found_send_codec = true;
1960 break;
1961 }
1962
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001963 if (nack_enabled_ != nack_enabled) {
1964 SetNack(channel, nack_enabled);
1965 nack_enabled_ = nack_enabled;
1966 }
1967
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001968 if (!found_send_codec) {
1969 LOG(LS_WARNING) << "Received empty list of codecs.";
1970 return false;
1971 }
1972
1973 // Set the codec immediately, since SetVADStatus() depends on whether
1974 // the current codec is mono or stereo.
1975 if (!SetSendCodec(channel, send_codec))
1976 return false;
1977
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001978 // FEC should be enabled after SetSendCodec.
1979 if (enable_codec_fec) {
1980 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
1981 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001982 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
1983 // Enable codec internal FEC. Treat any failure as fatal internal error.
1984 LOG_RTCERR2(SetFECStatus, channel, true);
1985 return false;
1986 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001987 }
1988
Minyue Li7100dcd2015-03-27 05:05:59 +01001989 if (IsCodec(send_codec, kOpusCodecName)) {
1990 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
1991 // send codec has to be Opus.
1992
1993 // Set Opus internal DTX.
1994 LOG(LS_INFO) << "Attempt to "
1995 << GetEnableString(enable_opus_dtx)
1996 << " Opus DTX on channel "
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001997 << channel;
Minyue Li7100dcd2015-03-27 05:05:59 +01001998 if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) {
1999 LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx);
2000 return false;
2001 }
2002
2003 // If opus_max_playback_rate <= 0, the default maximum playback rate
2004 // (48 kHz) will be used.
2005 if (opus_max_playback_rate > 0) {
2006 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
2007 << opus_max_playback_rate
2008 << " Hz on channel "
2009 << channel;
2010 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
2011 channel, opus_max_playback_rate) == -1) {
2012 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate);
2013 return false;
2014 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002015 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002016 }
2017
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002018 // Always update the |send_codec_| to the currently set send codec.
2019 send_codec_.reset(new webrtc::CodecInst(send_codec));
2020
minyue@webrtc.org26236952014-10-29 02:27:08 +00002021 if (send_bitrate_setting_) {
2022 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002023 }
2024
2025 // Loop through the codecs list again to config the telephone-event/CN codec.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002026 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002027 // Ignore codecs we don't know about. The negotiation step should prevent
2028 // this, but double-check to be sure.
2029 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002030 if (!engine()->FindWebRtcCodec(codec, &voe_codec)) {
2031 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002032 continue;
2033 }
2034
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002035 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2036 // about it.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002037 if (IsCodec(codec, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002038 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002039 channel, codec.id) == -1) {
2040 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, codec.id);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002041 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002042 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002043 } else if (IsCodec(codec, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002044 // Turn voice activity detection/comfort noise on if supported.
2045 // Set the wideband CN payload type appropriately.
2046 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002047 webrtc::PayloadFrequencies cn_freq;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002048 switch (codec.clockrate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002049 case 8000:
2050 cn_freq = webrtc::kFreq8000Hz;
2051 break;
2052 case 16000:
2053 cn_freq = webrtc::kFreq16000Hz;
2054 break;
2055 case 32000:
2056 cn_freq = webrtc::kFreq32000Hz;
2057 break;
2058 default:
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002059 LOG(LS_WARNING) << "CN frequency " << codec.clockrate
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002060 << " not supported.";
2061 continue;
2062 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002063 // Set the CN payloadtype and the VAD status.
2064 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2065 if (cn_freq != webrtc::kFreq8000Hz) {
2066 if (engine()->voe()->codec()->SetSendCNPayloadType(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002067 channel, codec.id, cn_freq) == -1) {
2068 LOG_RTCERR3(SetSendCNPayloadType, channel, codec.id, cn_freq);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002069 // TODO(ajm): This failure condition will be removed from VoE.
2070 // Restore the return here when we update to a new enough webrtc.
2071 //
2072 // Not returning false because the SetSendCNPayloadType will fail if
2073 // the channel is already sending.
2074 // This can happen if the remote description is applied twice, for
2075 // example in the case of ROAP on top of JSEP, where both side will
2076 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002077 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002078 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002079 // Only turn on VAD if we have a CN payload type that matches the
2080 // clockrate for the codec we are going to use.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002081 if (codec.clockrate == send_codec.plfreq && send_codec.channels != 2) {
Minyue Li7100dcd2015-03-27 05:05:59 +01002082 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
2083 // interaction between VAD and Opus FEC.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002084 LOG(LS_INFO) << "Enabling VAD";
2085 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2086 LOG_RTCERR2(SetVADStatus, channel, true);
2087 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002088 }
2089 }
2090 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002091 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002092 return true;
2093}
2094
2095bool WebRtcVoiceMediaChannel::SetSendCodecs(
2096 const std::vector<AudioCodec>& codecs) {
2097 dtmf_allowed_ = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002098 for (const AudioCodec& codec : codecs) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002099 // Find the DTMF telephone event "codec".
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002100 if (IsCodec(codec, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002101 dtmf_allowed_ = true;
2102 }
2103 }
2104
2105 // Cache the codecs in order to configure the channel created later.
2106 send_codecs_ = codecs;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002107 for (const auto& ch : send_channels_) {
2108 if (!SetSendCodecs(ch.second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002109 return false;
2110 }
2111 }
2112
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002113 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002114 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002115 return true;
2116}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002117
2118void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2119 bool nack_enabled) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002120 for (const auto& ch : channels) {
2121 SetNack(ch.second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002122 }
2123}
2124
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002125void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002126 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002127 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002128 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2129 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002130 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002131 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2132 }
2133}
2134
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002135bool WebRtcVoiceMediaChannel::SetSendCodec(
2136 const webrtc::CodecInst& send_codec) {
2137 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2138 << ", bitrate=" << send_codec.rate;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002139 for (const auto& ch : send_channels_) {
2140 if (!SetSendCodec(ch.second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002141 return false;
2142 }
2143
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002144 return true;
2145}
2146
2147bool WebRtcVoiceMediaChannel::SetSendCodec(
2148 int channel, const webrtc::CodecInst& send_codec) {
2149 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2150 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2151
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002152 webrtc::CodecInst current_codec;
2153 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2154 (send_codec == current_codec)) {
2155 // Codec is already configured, we can return without setting it again.
2156 return true;
2157 }
2158
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002159 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2160 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002161 return false;
2162 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002163 return true;
2164}
2165
2166bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2167 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002168 if (receive_extensions_ == extensions) {
2169 return true;
2170 }
2171
2172 // The default channel may or may not be in |receive_channels_|. Set the rtp
2173 // header extensions for default channel regardless.
2174 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2175 return false;
2176 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002177
2178 // Loop through all receive channels and enable/disable the extensions.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002179 for (const auto& ch : receive_channels_) {
2180 if (!SetChannelRecvRtpHeaderExtensions(ch.second->channel(), extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002181 return false;
2182 }
2183 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002184
2185 receive_extensions_ = extensions;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002186
2187 // Recreate AudioReceiveStream:s.
2188 {
2189 std::vector<webrtc::RtpExtension> exts;
2190
2191 const RtpHeaderExtension* audio_level_extension =
2192 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2193 if (audio_level_extension) {
2194 exts.push_back({
2195 kRtpAudioLevelHeaderExtension, audio_level_extension->id});
2196 }
2197
2198 const RtpHeaderExtension* send_time_extension =
2199 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2200 if (send_time_extension) {
2201 exts.push_back({
2202 kRtpAbsoluteSenderTimeHeaderExtension, send_time_extension->id});
2203 }
2204
2205 recv_rtp_extensions_.swap(exts);
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002206 RecreateAudioReceiveStreams();
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002207 }
2208
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002209 return true;
2210}
2211
2212bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2213 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002214 const RtpHeaderExtension* audio_level_extension =
2215 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2216 if (!SetHeaderExtension(
2217 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2218 audio_level_extension)) {
2219 return false;
2220 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002221
2222 const RtpHeaderExtension* send_time_extension =
2223 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2224 if (!SetHeaderExtension(
2225 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2226 send_time_extension)) {
2227 return false;
2228 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002229
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002230 return true;
2231}
2232
2233bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2234 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002235 if (send_extensions_ == extensions) {
2236 return true;
2237 }
2238
2239 // The default channel may or may not be in |send_channels_|. Set the rtp
2240 // header extensions for default channel regardless.
2241
2242 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2243 return false;
2244 }
2245
2246 // Loop through all send channels and enable/disable the extensions.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002247 for (const auto& ch : send_channels_) {
2248 if (!SetChannelSendRtpHeaderExtensions(ch.second->channel(), extensions)) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002249 return false;
2250 }
2251 }
2252
2253 send_extensions_ = extensions;
2254 return true;
2255}
2256
2257bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2258 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002259 const RtpHeaderExtension* audio_level_extension =
2260 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002261
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002262 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002263 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002264 audio_level_extension)) {
2265 return false;
2266 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002267
2268 const RtpHeaderExtension* send_time_extension =
2269 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002270 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002271 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002272 send_time_extension)) {
2273 return false;
2274 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002275
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002276 return true;
2277}
2278
2279bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2280 desired_playout_ = playout;
2281 return ChangePlayout(desired_playout_);
2282}
2283
2284bool WebRtcVoiceMediaChannel::PausePlayout() {
2285 return ChangePlayout(false);
2286}
2287
2288bool WebRtcVoiceMediaChannel::ResumePlayout() {
2289 return ChangePlayout(desired_playout_);
2290}
2291
2292bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2293 if (playout_ == playout) {
2294 return true;
2295 }
2296
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002297 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002298 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002299 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002300 // Only toggle the default channel if we don't have any other channels.
2301 result = SetPlayout(voe_channel(), playout);
2302 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002303 for (const auto& ch : receive_channels_) {
2304 if (!SetPlayout(ch.second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002305 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002306 << ch.second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002307 result = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002308 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002309 }
2310 }
2311
2312 if (result) {
2313 playout_ = playout;
2314 }
2315 return result;
2316}
2317
2318bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2319 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002320 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002321 return ChangeSend(desired_send_);
2322 return true;
2323}
2324
2325bool WebRtcVoiceMediaChannel::PauseSend() {
2326 return ChangeSend(SEND_NOTHING);
2327}
2328
2329bool WebRtcVoiceMediaChannel::ResumeSend() {
2330 return ChangeSend(desired_send_);
2331}
2332
2333bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2334 if (send_ == send) {
2335 return true;
2336 }
2337
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002338 // Change the settings on each send channel.
2339 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002340 engine()->SetOptionOverrides(options_);
2341
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002342 // Change the settings on each send channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002343 for (const auto& ch : send_channels_) {
2344 if (!ChangeSend(ch.second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002345 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002346 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002347
2348 // Clear up the options after stopping sending.
2349 if (send == SEND_NOTHING)
2350 engine()->ClearOptionOverrides();
2351
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002352 send_ = send;
2353 return true;
2354}
2355
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002356bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2357 if (send == SEND_MICROPHONE) {
2358 if (engine()->voe()->base()->StartSend(channel) == -1) {
2359 LOG_RTCERR1(StartSend, channel);
2360 return false;
2361 }
2362 if (engine()->voe()->file() &&
2363 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2364 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2365 return false;
2366 }
2367 } else { // SEND_NOTHING
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002368 DCHECK(send == SEND_NOTHING);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002369 if (engine()->voe()->base()->StopSend(channel) == -1) {
2370 LOG_RTCERR1(StopSend, channel);
2371 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002372 }
2373 }
2374
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002375 return true;
2376}
2377
solenberg1dd98f32015-09-10 01:57:14 -07002378bool WebRtcVoiceMediaChannel::SetAudioSend(uint32 ssrc, bool mute,
2379 const AudioOptions* options,
2380 AudioRenderer* renderer) {
2381 // TODO(solenberg): The state change should be fully rolled back if any one of
2382 // these calls fail.
2383 if (!SetLocalRenderer(ssrc, renderer)) {
2384 return false;
2385 }
2386 if (!MuteStream(ssrc, mute)) {
2387 return false;
2388 }
2389 if (!mute && options) {
2390 return SetOptions(*options);
2391 }
2392 return true;
2393}
2394
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002395// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002396void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2397 if (engine()->voe()->network()->RegisterExternalTransport(
2398 channel, *this) == -1) {
2399 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2400 }
2401
2402 // Enable RTCP (for quality stats and feedback messages)
2403 EnableRtcp(channel);
2404
2405 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2406 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002407
2408 // Set RTP header extension for the new channel.
2409 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002410}
2411
2412bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2413 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2414 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2415 }
2416
2417 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2418 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002419 return false;
2420 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002421
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002422 return true;
2423}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002424
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002425bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2426 // If the default channel is already used for sending create a new channel
2427 // otherwise use the default channel for sending.
2428 int channel = GetSendChannelNum(sp.first_ssrc());
2429 if (channel != -1) {
2430 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2431 return false;
2432 }
2433
2434 bool default_channel_is_available = true;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002435 for (const auto& ch : send_channels_) {
2436 if (IsDefaultChannel(ch.second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002437 default_channel_is_available = false;
2438 break;
2439 }
2440 }
2441 if (default_channel_is_available) {
2442 channel = voe_channel();
2443 } else {
2444 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002445 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002446 if (channel == -1) {
2447 LOG_RTCERR0(CreateChannel);
2448 return false;
2449 }
2450
2451 ConfigureSendChannel(channel);
2452 }
2453
2454 // Save the channel to send_channels_, so that RemoveSendStream() can still
2455 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002456 webrtc::AudioTransport* audio_transport =
2457 engine()->voe()->base()->audio_transport();
pbos8fc7fa72015-07-15 08:02:58 -07002458 send_channels_.insert(
2459 std::make_pair(sp.first_ssrc(),
2460 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002461
2462 // Set the send (local) SSRC.
2463 // If there are multiple send SSRCs, we can only set the first one here, and
2464 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2465 // (with a codec requires multiple SSRC(s)).
2466 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2467 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2468 return false;
2469 }
2470
2471 // At this point the channel's local SSRC has been updated. If the channel is
2472 // the default channel make sure that all the receive channels are updated as
2473 // well. Receive channels have to have the same SSRC as the default channel in
2474 // order to send receiver reports with this SSRC.
2475 if (IsDefaultChannel(channel)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002476 for (const auto& ch : receive_channels_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002477 // Only update the SSRC for non-default channels.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002478 if (!IsDefaultChannel(ch.second->channel())) {
2479 if (engine()->voe()->rtp()->SetLocalSSRC(ch.second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002480 sp.first_ssrc()) != 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002481 LOG_RTCERR2(SetLocalSSRC, ch.second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002482 return false;
2483 }
2484 }
2485 }
2486 }
2487
2488 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002489 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2490 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002491 }
2492
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002493 // Set the current codecs to be used for the new channel.
2494 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002495 return false;
2496
2497 return ChangeSend(channel, desired_send_);
2498}
2499
2500bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2501 ChannelMap::iterator it = send_channels_.find(ssrc);
2502 if (it == send_channels_.end()) {
2503 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2504 << " which doesn't exist.";
2505 return false;
2506 }
2507
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002508 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002509 ChangeSend(channel, SEND_NOTHING);
2510
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002511 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2512 // this will disconnect the audio renderer with the send channel.
2513 delete it->second;
2514 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002515
2516 if (IsDefaultChannel(channel)) {
2517 // Do not delete the default channel since the receive channels depend on
2518 // the default channel, recycle it instead.
2519 ChangeSend(channel, SEND_NOTHING);
2520 } else {
2521 // Clean up and delete the send channel.
2522 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2523 << " with VoiceEngine channel #" << channel << ".";
2524 if (!DeleteChannel(channel))
2525 return false;
2526 }
2527
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002528 if (send_channels_.empty())
2529 ChangeSend(SEND_NOTHING);
2530
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002531 return true;
2532}
2533
2534bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002535 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002536 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002537
2538 if (!VERIFY(sp.ssrcs.size() == 1))
2539 return false;
2540 uint32 ssrc = sp.first_ssrc();
2541
wu@webrtc.org78187522013-10-07 23:32:02 +00002542 if (ssrc == 0) {
2543 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2544 return false;
2545 }
2546
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002547 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2548 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002549 return false;
2550 }
2551
pbos8fc7fa72015-07-15 08:02:58 -07002552 DCHECK(receive_stream_params_.find(ssrc) == receive_stream_params_.end());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002553
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002554 // Reuse default channel for recv stream in non-conference mode call
2555 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002556 webrtc::AudioTransport* audio_transport =
2557 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002558 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002559 LOG(LS_INFO) << "Recv stream " << ssrc << " reuse default channel";
2560 default_receive_ssrc_ = ssrc;
pbos8fc7fa72015-07-15 08:02:58 -07002561 WebRtcVoiceChannelRenderer* channel_renderer =
2562 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport);
2563 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2564 receive_stream_params_[ssrc] = sp;
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002565 AddAudioReceiveStream(ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002566 return SetPlayout(voe_channel(), playout_);
2567 }
2568
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002569 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002570 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002571 if (channel == -1) {
2572 LOG_RTCERR0(CreateChannel);
2573 return false;
2574 }
2575
wu@webrtc.org78187522013-10-07 23:32:02 +00002576 if (!ConfigureRecvChannel(channel)) {
2577 DeleteChannel(channel);
2578 return false;
2579 }
2580
pbos8fc7fa72015-07-15 08:02:58 -07002581 WebRtcVoiceChannelRenderer* channel_renderer =
2582 new WebRtcVoiceChannelRenderer(channel, audio_transport);
2583 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2584 receive_stream_params_[ssrc] = sp;
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002585 AddAudioReceiveStream(ssrc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002586
2587 LOG(LS_INFO) << "New audio stream " << ssrc
2588 << " registered to VoiceEngine channel #"
2589 << channel << ".";
2590 return true;
2591}
2592
2593bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002594 // Configure to use external transport, like our default channel.
2595 if (engine()->voe()->network()->RegisterExternalTransport(
2596 channel, *this) == -1) {
2597 LOG_RTCERR2(SetExternalTransport, channel, this);
2598 return false;
2599 }
2600
2601 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002602 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002603 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2604 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002605 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002606 return false;
2607 }
2608 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002609 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002610 return false;
2611 }
2612
Minyue2013aec2015-05-13 14:14:42 +02002613 // Associate receive channel to default channel (so the receive channel can
2614 // obtain RTT from the send channel)
2615 engine()->voe()->base()->AssociateSendChannel(channel, voe_channel());
2616 LOG(LS_INFO) << "VoiceEngine channel #"
2617 << channel << " is associated with channel #"
2618 << voe_channel() << ".";
2619
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002620 // Use the same recv payload types as our default channel.
2621 ResetRecvCodecs(channel);
2622 if (!recv_codecs_.empty()) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002623 for (const auto& codec : recv_codecs_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002624 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002625 if (engine()->FindWebRtcCodec(codec, &voe_codec)) {
2626 voe_codec.pltype = codec.id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002627 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2628 if (engine()->voe()->codec()->GetRecPayloadType(
2629 voe_channel(), voe_codec) != -1) {
2630 if (engine()->voe()->codec()->SetRecPayloadType(
2631 channel, voe_codec) == -1) {
2632 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2633 return false;
2634 }
2635 }
2636 }
2637 }
2638 }
2639
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002640 if (InConferenceMode()) {
2641 // To be in par with the video, voe_channel() is not used for receiving in
2642 // a conference call.
2643 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2644 // This is the first stream in a multi user meeting. We can now
2645 // disable playback of the default stream. This since the default
2646 // stream will probably have received some initial packets before
2647 // the new stream was added. This will mean that the CN state from
2648 // the default channel will be mixed in with the other streams
2649 // throughout the whole meeting, which might be disturbing.
2650 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2651 SetPlayout(voe_channel(), false);
2652 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002653 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002654 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002655
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002656 // Set RTP header extension for the new channel.
2657 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2658 return false;
2659 }
2660
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002661 return SetPlayout(channel, playout_);
2662}
2663
2664bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002665 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002666 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002667 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002668 if (it == receive_channels_.end()) {
2669 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2670 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002671 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002672 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002673
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002674 RemoveAudioReceiveStream(ssrc);
pbos8fc7fa72015-07-15 08:02:58 -07002675 receive_stream_params_.erase(ssrc);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002676
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002677 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2678 // will disconnect the audio renderer with the receive channel.
2679 // Cache the channel before the deletion.
2680 const int channel = it->second->channel();
2681 delete it->second;
2682 receive_channels_.erase(it);
2683
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002684 if (ssrc == default_receive_ssrc_) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002685 DCHECK(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002686 // Recycle the default channel is for recv stream.
2687 if (playout_)
2688 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002689
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002690 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002691 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002692 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002693
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002694 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002695 << " with VoiceEngine channel #" << channel << ".";
2696 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002697 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002698
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002699 bool enable_default_channel_playout = false;
2700 if (receive_channels_.empty()) {
2701 // The last stream was removed. We can now enable the default
2702 // channel for new channels to be played out immediately without
2703 // waiting for AddStream messages.
2704 // We do this for both conference mode and non-conference mode.
2705 // TODO(oja): Does the default channel still have it's CN state?
2706 enable_default_channel_playout = true;
2707 }
2708 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2709 default_receive_ssrc_ != 0) {
2710 // Only the default channel is active, enable the playout on default
2711 // channel.
2712 enable_default_channel_playout = true;
2713 }
2714 if (enable_default_channel_playout && playout_) {
2715 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2716 SetPlayout(voe_channel(), true);
2717 }
2718
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002719 return true;
2720}
2721
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002722bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2723 AudioRenderer* renderer) {
2724 ChannelMap::iterator it = receive_channels_.find(ssrc);
2725 if (it == receive_channels_.end()) {
2726 if (renderer) {
2727 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002728 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002729 return false;
2730 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002731
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002732 // The channel likely has gone away, do nothing.
2733 return true;
2734 }
2735
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002736 if (renderer)
2737 it->second->Start(renderer);
2738 else
2739 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002740
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002741 return true;
2742}
2743
2744bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2745 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002746 ChannelMap::iterator it = send_channels_.find(ssrc);
2747 if (it == send_channels_.end()) {
2748 if (renderer) {
2749 // Return an error if trying to set a valid renderer with an invalid ssrc.
2750 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2751 return false;
2752 }
2753
2754 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002755 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002756 }
2757
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002758 if (renderer)
2759 it->second->Start(renderer);
2760 else
2761 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002762
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002763 return true;
2764}
2765
2766bool WebRtcVoiceMediaChannel::GetActiveStreams(
2767 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002768 // In conference mode, the default channel should not be in
2769 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002770 actives->clear();
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002771 for (const auto& ch : receive_channels_) {
2772 int level = GetOutputLevel(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002773 if (level > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002774 actives->push_back(std::make_pair(ch.first, level));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002775 }
2776 }
2777 return true;
2778}
2779
2780int WebRtcVoiceMediaChannel::GetOutputLevel() {
2781 // return the highest output level of all streams
2782 int highest = GetOutputLevel(voe_channel());
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002783 for (const auto& ch : receive_channels_) {
2784 int level = GetOutputLevel(ch.second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002785 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002786 }
2787 return highest;
2788}
2789
2790int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2791 int ret;
2792 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2793 // In case of error, log the info and continue
2794 LOG_RTCERR0(TimeSinceLastTyping);
2795 ret = -1;
2796 } else {
2797 ret *= 1000; // We return ms, webrtc returns seconds.
2798 }
2799 return ret;
2800}
2801
2802void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2803 int cost_per_typing, int reporting_threshold, int penalty_decay,
2804 int type_event_delay) {
2805 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2806 time_window, cost_per_typing,
2807 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2808 // In case of error, log the info and continue
2809 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2810 cost_per_typing, reporting_threshold, penalty_decay,
2811 type_event_delay);
2812 }
2813}
2814
2815bool WebRtcVoiceMediaChannel::SetOutputScaling(
2816 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002817 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002818 // Collect the channels to scale the output volume.
2819 std::vector<int> channels;
2820 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002821 // Default channel is not in receive_channels_ if it is not being used for
2822 // playout.
2823 if (default_receive_ssrc_ == 0)
2824 channels.push_back(voe_channel());
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002825 for (const auto& ch : receive_channels_) {
2826 channels.push_back(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002827 }
2828 } else { // Collect only the channel of the specified ssrc.
2829 int channel = GetReceiveChannelNum(ssrc);
2830 if (-1 == channel) {
2831 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2832 return false;
2833 }
2834 channels.push_back(channel);
2835 }
2836
2837 // Scale the output volume for the collected channels. We first normalize to
2838 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002839 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002840 if (scale > 0.0001f) {
2841 left /= scale;
2842 right /= scale;
2843 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002844 for (int ch_id : channels) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002845 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002846 ch_id, scale)) {
2847 LOG_RTCERR2(SetChannelOutputVolumeScaling, ch_id, scale);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002848 return false;
2849 }
2850 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002851 ch_id, static_cast<float>(left), static_cast<float>(right))) {
2852 LOG_RTCERR3(SetOutputVolumePan, ch_id, left, right);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002853 // Do not return if fails. SetOutputVolumePan is not available for all
2854 // pltforms.
2855 }
2856 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2857 << " right=" << right * scale
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002858 << " for channel " << ch_id << " and ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002859 }
2860 return true;
2861}
2862
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002863bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2864 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2865 return true;
2866}
2867
2868bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2869 bool play, bool loop) {
2870 if (!ringback_tone_) {
2871 return false;
2872 }
2873
2874 // The voe file api is not available in chrome.
2875 if (!engine()->voe()->file()) {
2876 return false;
2877 }
2878
2879 // Determine which VoiceEngine channel to play on.
2880 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2881 if (channel == -1) {
2882 return false;
2883 }
2884
2885 // Make sure the ringtone is cued properly, and play it out.
2886 if (play) {
2887 ringback_tone_->set_loop(loop);
2888 ringback_tone_->Rewind();
2889 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2890 ringback_tone_.get()) == -1) {
2891 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2892 LOG(LS_ERROR) << "Unable to start ringback tone";
2893 return false;
2894 }
2895 ringback_channels_.insert(channel);
2896 LOG(LS_INFO) << "Started ringback on channel " << channel;
2897 } else {
2898 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2899 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2900 LOG_RTCERR1(StopPlayingFileLocally, channel);
2901 return false;
2902 }
2903 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2904 ringback_channels_.erase(channel);
2905 }
2906
2907 return true;
2908}
2909
2910bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2911 return dtmf_allowed_;
2912}
2913
2914bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2915 int duration, int flags) {
2916 if (!dtmf_allowed_) {
2917 return false;
2918 }
2919
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002920 // Send the event.
2921 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002922 int channel = -1;
2923 if (ssrc == 0) {
2924 bool default_channel_is_inuse = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002925 for (const auto& ch : send_channels_) {
2926 if (IsDefaultChannel(ch.second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002927 default_channel_is_inuse = true;
2928 break;
2929 }
2930 }
2931 if (default_channel_is_inuse) {
2932 channel = voe_channel();
2933 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002934 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002935 }
2936 } else {
2937 channel = GetSendChannelNum(ssrc);
2938 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002939 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002940 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2941 << ssrc << " is not in use.";
2942 return false;
2943 }
2944 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002945 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2946 channel, event, true, duration) == -1) {
2947 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002948 return false;
2949 }
2950 }
2951
2952 // Play the event.
2953 if (flags & cricket::DF_PLAY) {
2954 // Play DTMF tone locally.
2955 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
2956 LOG_RTCERR2(PlayDtmfTone, event, duration);
2957 return false;
2958 }
2959 }
2960
2961 return true;
2962}
2963
wu@webrtc.orga9890802013-12-13 00:21:03 +00002964void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002965 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002966 DCHECK(thread_checker_.CalledOnValidThread());
2967
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002968 // Forward packet to Call as well.
2969 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2970 packet_time.not_before);
2971 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
2972 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
2973 webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002974
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002975 // Pick which channel to send this packet to. If this packet doesn't match
2976 // any multiplexed streams, just send it to the default channel. Otherwise,
2977 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002978 int which_channel =
2979 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002980 if (which_channel == -1) {
2981 which_channel = voe_channel();
2982 }
2983
2984 // Stop any ringback that might be playing on the channel.
2985 // It's possible the ringback has already stopped, ih which case we'll just
2986 // use the opportunity to remove the channel from ringback_channels_.
2987 if (engine()->voe()->file()) {
2988 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
2989 if (it != ringback_channels_.end()) {
2990 if (engine()->voe()->file()->IsPlayingFileLocally(
2991 which_channel) == 1) {
2992 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
2993 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
2994 << " due to incoming media";
2995 }
2996 ringback_channels_.erase(which_channel);
2997 }
2998 }
2999
3000 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003001 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003002 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003003 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003004}
3005
wu@webrtc.orga9890802013-12-13 00:21:03 +00003006void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003007 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003008 DCHECK(thread_checker_.CalledOnValidThread());
3009
Fredrik Solenberg709ed672015-09-15 12:26:33 +02003010 // Forward packet to Call as well.
3011 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
3012 packet_time.not_before);
3013 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3014 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
3015 webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003016
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003017 // Sending channels need all RTCP packets with feedback information.
3018 // Even sender reports can contain attached report blocks.
3019 // Receiving channels need sender reports in order to create
3020 // correct receiver reports.
3021 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003022 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003023 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3024 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003025 }
3026
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003027 // If it is a sender report, find the channel that is listening.
3028 bool has_sent_to_default_channel = false;
3029 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003030 int which_channel =
3031 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003032 if (which_channel != -1) {
3033 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003034 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003035
3036 if (IsDefaultChannel(which_channel))
3037 has_sent_to_default_channel = true;
3038 }
3039 }
3040
3041 // SR may continue RR and any RR entry may correspond to any one of the send
3042 // channels. So all RTCP packets must be forwarded all send channels. VoE
3043 // will filter out RR internally.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003044 for (const auto& ch : send_channels_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003045 // Make sure not sending the same packet to default channel more than once.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003046 if (IsDefaultChannel(ch.second->channel()) &&
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003047 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003048 continue;
3049
3050 engine()->voe()->network()->ReceivedRTCPPacket(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003051 ch.second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003052 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003053}
3054
3055bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003056 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3057 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003058 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3059 return false;
3060 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003061 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3062 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003063 return false;
3064 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003065 // We set the AGC to mute state only when all the channels are muted.
3066 // This implementation is not ideal, instead we should signal the AGC when
3067 // the mic channel is muted/unmuted. We can't do it today because there
3068 // is no good way to know which stream is mapping to the mic channel.
3069 bool all_muted = muted;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003070 for (const auto& ch : send_channels_) {
3071 if (!all_muted) {
3072 break;
3073 }
3074 if (engine()->voe()->volume()->GetInputMute(ch.second->channel(),
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003075 all_muted)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003076 LOG_RTCERR1(GetInputMute, ch.second->channel());
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003077 return false;
3078 }
3079 }
3080
3081 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3082 if (ap)
3083 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003084 return true;
3085}
3086
minyue@webrtc.org26236952014-10-29 02:27:08 +00003087// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3088// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003089bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003090 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003091
minyue@webrtc.org26236952014-10-29 02:27:08 +00003092 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003093}
3094
minyue@webrtc.org26236952014-10-29 02:27:08 +00003095bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3096 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003097
minyue@webrtc.org26236952014-10-29 02:27:08 +00003098 send_bitrate_setting_ = true;
3099 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003100
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003101 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003102 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003103 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003104 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003105 }
3106
minyue@webrtc.org26236952014-10-29 02:27:08 +00003107 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003108 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3109 // SetMaxSendBandwith(0), the second call removes the previous limit.
3110 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003111 return true;
3112
3113 webrtc::CodecInst codec = *send_codec_;
3114 bool is_multi_rate = IsCodecMultiRate(codec);
3115
3116 if (is_multi_rate) {
3117 // If codec is multi-rate then just set the bitrate.
3118 codec.rate = bps;
3119 if (!SetSendCodec(codec)) {
3120 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3121 << " to bitrate " << bps << " bps.";
3122 return false;
3123 }
3124 return true;
3125 } else {
3126 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3127 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3128 // fixed bitrate then ignore.
3129 if (bps < codec.rate) {
3130 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3131 << " to bitrate " << bps << " bps"
3132 << ", requires at least " << codec.rate << " bps.";
3133 return false;
3134 }
3135 return true;
3136 }
3137}
3138
3139bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003140 bool echo_metrics_on = false;
3141 // These can take on valid negative values, so use the lowest possible level
3142 // as default rather than -1.
3143 int echo_return_loss = -100;
3144 int echo_return_loss_enhancement = -100;
3145 // These can also be negative, but in practice -1 is only used to signal
3146 // insufficient data, since the resolution is limited to multiples of 4 ms.
3147 int echo_delay_median_ms = -1;
3148 int echo_delay_std_ms = -1;
3149 if (engine()->voe()->processing()->GetEcMetricsStatus(
3150 echo_metrics_on) != -1 && echo_metrics_on) {
3151 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3152 // here, but it appears to be unsuitable currently. Revisit after this is
3153 // investigated: http://b/issue?id=5666755
3154 int erl, erle, rerl, anlp;
3155 if (engine()->voe()->processing()->GetEchoMetrics(
3156 erl, erle, rerl, anlp) != -1) {
3157 echo_return_loss = erl;
3158 echo_return_loss_enhancement = erle;
3159 }
3160
3161 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003162 float dummy;
3163 if (engine()->voe()->processing()->GetEcDelayMetrics(
3164 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003165 echo_delay_median_ms = median;
3166 echo_delay_std_ms = std;
3167 }
3168 }
3169
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003170 webrtc::CallStatistics cs;
3171 unsigned int ssrc;
3172 webrtc::CodecInst codec;
3173 unsigned int level;
3174
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003175 for (const auto& ch : send_channels_) {
3176 const int channel = ch.second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003177
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003178 // Fill in the sender info, based on what we know, and what the
3179 // remote side told us it got from its RTCP report.
3180 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003181
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003182 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3183 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3184 continue;
3185 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003186
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003187 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003188 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3189 sinfo.bytes_sent = cs.bytesSent;
3190 sinfo.packets_sent = cs.packetsSent;
3191 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3192 // returns 0 to indicate an error value.
3193 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3194
3195 // Get data from the last remote RTCP report. Use default values if no data
3196 // available.
3197 sinfo.fraction_lost = -1.0;
3198 sinfo.jitter_ms = -1;
3199 sinfo.packets_lost = -1;
3200 sinfo.ext_seqnum = -1;
3201 std::vector<webrtc::ReportBlock> receive_blocks;
3202 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3203 channel, &receive_blocks) != -1 &&
3204 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003205 for (const webrtc::ReportBlock& block : receive_blocks) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003206 // Lookup report for send ssrc only.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003207 if (block.source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003208 // Convert Q8 to floating point.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003209 sinfo.fraction_lost = static_cast<float>(block.fraction_lost) / 256;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003210 // Convert samples to milliseconds.
3211 if (codec.plfreq / 1000 > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003212 sinfo.jitter_ms = block.interarrival_jitter / (codec.plfreq / 1000);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003213 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003214 sinfo.packets_lost = block.cumulative_num_packets_lost;
3215 sinfo.ext_seqnum = block.extended_highest_sequence_number;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003216 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003217 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003218 }
3219 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003220
3221 // Local speech level.
3222 sinfo.audio_level = (engine()->voe()->volume()->
3223 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3224
3225 // TODO(xians): We are injecting the same APM logging to all the send
3226 // channels here because there is no good way to know which send channel
3227 // is using the APM. The correct fix is to allow the send channels to have
3228 // their own APM so that we can feed the correct APM logging to different
3229 // send channels. See issue crbug/264611 .
3230 sinfo.echo_return_loss = echo_return_loss;
3231 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3232 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3233 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003234 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3235 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003236 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003237
3238 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003239 }
3240
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003241 // Build the list of receivers, one for each receiving channel, or 1 in
3242 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003243 std::vector<int> channels;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003244 for (const auto& ch : receive_channels_) {
3245 channels.push_back(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003246 }
3247 if (channels.empty()) {
3248 channels.push_back(voe_channel());
3249 }
3250
3251 // Get the SSRC and stats for each receiver, based on our own calculations.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003252 for (int ch_id : channels) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003253 memset(&cs, 0, sizeof(cs));
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003254 if (engine()->voe()->rtp()->GetRemoteSSRC(ch_id, ssrc) != -1 &&
3255 engine()->voe()->rtp()->GetRTCPStatistics(ch_id, cs) != -1 &&
3256 engine()->voe()->codec()->GetRecCodec(ch_id, codec) != -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003257 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003258 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003259 rinfo.bytes_rcvd = cs.bytesReceived;
3260 rinfo.packets_rcvd = cs.packetsReceived;
3261 // The next four fields are from the most recently sent RTCP report.
3262 // Convert Q8 to floating point.
3263 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3264 rinfo.packets_lost = cs.cumulativeLost;
3265 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003266 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003267 if (codec.pltype != -1) {
3268 rinfo.codec_name = codec.plname;
3269 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003270 // Convert samples to milliseconds.
3271 if (codec.plfreq / 1000 > 0) {
3272 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3273 }
3274
3275 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3276 webrtc::NetworkStatistics ns;
3277 if (engine()->voe()->neteq() &&
3278 engine()->voe()->neteq()->GetNetworkStatistics(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003279 ch_id, ns) != -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003280 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3281 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3282 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003283 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003284 rinfo.speech_expand_rate =
3285 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3286 rinfo.secondary_decoded_rate =
3287 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
Henrik Lundin8e6fd462015-06-02 09:24:52 +02003288 rinfo.accelerate_rate =
3289 static_cast<float>(ns.currentAccelerateRate) / (1 << 14);
3290 rinfo.preemptive_expand_rate =
3291 static_cast<float>(ns.currentPreemptiveRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003292 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003293
3294 webrtc::AudioDecodingCallStats ds;
3295 if (engine()->voe()->neteq() &&
3296 engine()->voe()->neteq()->GetDecodingCallStatistics(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003297 ch_id, &ds) != -1) {
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003298 rinfo.decoding_calls_to_silence_generator =
3299 ds.calls_to_silence_generator;
3300 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3301 rinfo.decoding_normal = ds.decoded_normal;
3302 rinfo.decoding_plc = ds.decoded_plc;
3303 rinfo.decoding_cng = ds.decoded_cng;
3304 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3305 }
3306
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003307 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003308 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003309 int playout_buffer_delay_ms = 0;
3310 engine()->voe()->sync()->GetDelayEstimate(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003311 ch_id, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003312 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3313 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003314 }
3315
3316 // Get speech level.
3317 rinfo.audio_level = (engine()->voe()->volume()->
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003318 GetSpeechOutputLevelFullRange(ch_id, level) != -1) ? level : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003319 info->receivers.push_back(rinfo);
3320 }
3321 }
3322
3323 return true;
3324}
3325
3326void WebRtcVoiceMediaChannel::GetLastMediaError(
3327 uint32* ssrc, VoiceMediaChannel::Error* error) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003328 DCHECK(ssrc != NULL);
3329 DCHECK(error != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003330 FindSsrc(voe_channel(), ssrc);
3331 *error = WebRtcErrorToChannelError(GetLastEngineError());
3332}
3333
3334bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003335 rtc::CritScope lock(&receive_channels_cs_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003336 DCHECK(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003337 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003338 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3339 // This means the error is not limited to a specific channel. Signal the
3340 // message using ssrc=0. If the current channel is sending, use this
3341 // channel for sending the message.
3342 *ssrc = 0;
3343 return true;
3344 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003345 // Check whether this is a sending channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003346 for (const auto& ch : send_channels_) {
3347 if (ch.second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003348 // This is a sending channel.
3349 uint32 local_ssrc = 0;
3350 if (engine()->voe()->rtp()->GetLocalSSRC(
3351 channel_num, local_ssrc) != -1) {
3352 *ssrc = local_ssrc;
3353 }
3354 return true;
3355 }
3356 }
3357
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003358 // Check whether this is a receiving channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003359 for (const auto& ch : receive_channels_) {
3360 if (ch.second->channel() == channel_num) {
3361 *ssrc = ch.first;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003362 return true;
3363 }
3364 }
3365 }
3366 return false;
3367}
3368
3369void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003370 if (error == VE_TYPING_NOISE_WARNING) {
3371 typing_noise_detected_ = true;
3372 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3373 typing_noise_detected_ = false;
3374 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003375 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3376}
3377
3378int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3379 unsigned int ulevel;
3380 int ret =
3381 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3382 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3383}
3384
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003385int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) const {
3386 ChannelMap::const_iterator it = receive_channels_.find(ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003387 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003388 return it->second->channel();
pbos8fc7fa72015-07-15 08:02:58 -07003389 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003390}
3391
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003392int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) const {
3393 ChannelMap::const_iterator it = send_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003394 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003395 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003396
3397 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003398}
3399
3400bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3401 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3402 // Get the RED encodings from the parameter with no name. This may
3403 // change based on what is discussed on the Jingle list.
3404 // The encoding parameter is of the form "a/b"; we only support where
3405 // a == b. Verify this and parse out the value into red_pt.
3406 // If the parameter value is absent (as it will be until we wire up the
3407 // signaling of this message), use the second codec specified (i.e. the
3408 // one after "red") as the encoding parameter.
3409 int red_pt = -1;
3410 std::string red_params;
3411 CodecParameterMap::const_iterator it = red_codec.params.find("");
3412 if (it != red_codec.params.end()) {
3413 red_params = it->second;
3414 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003415 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003416 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003417 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003418 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3419 return false;
3420 }
3421 } else if (red_codec.params.empty()) {
3422 LOG(LS_WARNING) << "RED params not present, using defaults";
3423 if (all_codecs.size() > 1) {
3424 red_pt = all_codecs[1].id;
3425 }
3426 }
3427
3428 // Try to find red_pt in |codecs|.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003429 for (const AudioCodec& codec : all_codecs) {
3430 if (codec.id == red_pt) {
3431 // If we find the right codec, that will be the codec we pass to
3432 // SetSendCodec, with the desired payload type.
3433 if (engine()->FindWebRtcCodec(codec, send_codec)) {
3434 return true;
3435 } else {
3436 break;
3437 }
3438 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003439 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003440 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3441 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003442}
3443
3444bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3445 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003446 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003447 return false;
3448 }
3449 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3450 // what we want to do with them.
3451 // engine()->voe().EnableVQMon(voe_channel(), true);
3452 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3453 return true;
3454}
3455
3456bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3457 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3458 for (int i = 0; i < ncodecs; ++i) {
3459 webrtc::CodecInst voe_codec;
3460 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3461 voe_codec.pltype = -1;
3462 if (engine()->voe()->codec()->SetRecPayloadType(
3463 channel, voe_codec) == -1) {
3464 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3465 return false;
3466 }
3467 }
3468 }
3469 return true;
3470}
3471
3472bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3473 if (playout) {
3474 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3475 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3476 LOG_RTCERR1(StartPlayout, channel);
3477 return false;
3478 }
3479 } else {
3480 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3481 engine()->voe()->base()->StopPlayout(channel);
3482 }
3483 return true;
3484}
3485
3486uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3487 bool rtcp) {
3488 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3489 uint32 ssrc = 0;
3490 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003491 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003492 }
3493 return ssrc;
3494}
3495
3496// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3497VoiceMediaChannel::Error
3498 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3499 switch (err_code) {
3500 case 0:
3501 return ERROR_NONE;
3502 case VE_CANNOT_START_RECORDING:
3503 case VE_MIC_VOL_ERROR:
3504 case VE_GET_MIC_VOL_ERROR:
3505 case VE_CANNOT_ACCESS_MIC_VOL:
3506 return ERROR_REC_DEVICE_OPEN_FAILED;
3507 case VE_SATURATION_WARNING:
3508 return ERROR_REC_DEVICE_SATURATION;
3509 case VE_REC_DEVICE_REMOVED:
3510 return ERROR_REC_DEVICE_REMOVED;
3511 case VE_RUNTIME_REC_WARNING:
3512 case VE_RUNTIME_REC_ERROR:
3513 return ERROR_REC_RUNTIME_ERROR;
3514 case VE_CANNOT_START_PLAYOUT:
3515 case VE_SPEAKER_VOL_ERROR:
3516 case VE_GET_SPEAKER_VOL_ERROR:
3517 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3518 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3519 case VE_RUNTIME_PLAY_WARNING:
3520 case VE_RUNTIME_PLAY_ERROR:
3521 return ERROR_PLAY_RUNTIME_ERROR;
3522 case VE_TYPING_NOISE_WARNING:
3523 return ERROR_REC_TYPING_NOISE_DETECTED;
3524 default:
3525 return VoiceMediaChannel::ERROR_OTHER;
3526 }
3527}
3528
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003529bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3530 int channel_id, const RtpHeaderExtension* extension) {
3531 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003532 int id = 0;
3533 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003534 if (extension) {
3535 enable = true;
3536 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003537 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003538 }
3539 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003540 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003541 return false;
3542 }
3543 return true;
3544}
3545
Fredrik Solenberg709ed672015-09-15 12:26:33 +02003546void WebRtcVoiceMediaChannel::RecreateAudioReceiveStreams() {
3547 DCHECK(thread_checker_.CalledOnValidThread());
3548 for (const auto& it : receive_channels_) {
3549 RemoveAudioReceiveStream(it.first);
3550 }
3551 for (const auto& it : receive_channels_) {
3552 AddAudioReceiveStream(it.first);
3553 }
3554}
3555
3556void WebRtcVoiceMediaChannel::AddAudioReceiveStream(uint32 ssrc) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003557 DCHECK(thread_checker_.CalledOnValidThread());
pbos8fc7fa72015-07-15 08:02:58 -07003558 WebRtcVoiceChannelRenderer* channel = receive_channels_[ssrc];
3559 DCHECK(channel != nullptr);
3560 DCHECK(receive_streams_.find(ssrc) == receive_streams_.end());
pbos8fc7fa72015-07-15 08:02:58 -07003561 webrtc::AudioReceiveStream::Config config;
3562 config.rtp.remote_ssrc = ssrc;
3563 // Only add RTP extensions if we support combined A/V BWE.
pbos6bb1b6e2015-07-24 07:10:18 -07003564 config.rtp.extensions = recv_rtp_extensions_;
3565 config.combined_audio_video_bwe =
3566 options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false);
pbos8fc7fa72015-07-15 08:02:58 -07003567 config.voe_channel_id = channel->channel();
3568 config.sync_group = receive_stream_params_[ssrc].sync_label;
3569 webrtc::AudioReceiveStream* s = call_->CreateAudioReceiveStream(config);
3570 receive_streams_.insert(std::make_pair(ssrc, s));
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003571}
3572
Fredrik Solenberg709ed672015-09-15 12:26:33 +02003573void WebRtcVoiceMediaChannel::RemoveAudioReceiveStream(uint32 ssrc) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003574 DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg709ed672015-09-15 12:26:33 +02003575 auto stream_it = receive_streams_.find(ssrc);
3576 if (stream_it != receive_streams_.end()) {
3577 call_->DestroyAudioReceiveStream(stream_it->second);
3578 receive_streams_.erase(stream_it);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003579 }
3580}
3581
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003582bool WebRtcVoiceMediaChannel::SetRecvCodecsInternal(
3583 const std::vector<AudioCodec>& new_codecs) {
3584 for (const AudioCodec& codec : new_codecs) {
3585 webrtc::CodecInst voe_codec;
3586 if (engine()->FindWebRtcCodec(codec, &voe_codec)) {
3587 LOG(LS_INFO) << ToString(codec);
3588 voe_codec.pltype = codec.id;
3589 if (default_receive_ssrc_ == 0) {
3590 // Set the receive codecs on the default channel explicitly if the
3591 // default channel is not used by |receive_channels_|, this happens in
3592 // conference mode or in non-conference mode when there is no playout
3593 // channel.
3594 // TODO(xians): Figure out how we use the default channel in conference
3595 // mode.
3596 if (engine()->voe()->codec()->SetRecPayloadType(
3597 voe_channel(), voe_codec) == -1) {
3598 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
3599 return false;
3600 }
3601 }
3602
3603 // Set the receive codecs on all receiving channels.
3604 for (const auto& ch : receive_channels_) {
3605 if (engine()->voe()->codec()->SetRecPayloadType(
3606 ch.second->channel(), voe_codec) == -1) {
3607 LOG_RTCERR2(SetRecPayloadType, ch.second->channel(),
3608 ToString(voe_codec));
3609 return false;
3610 }
3611 }
3612 } else {
3613 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
3614 return false;
3615 }
3616 }
3617 return true;
3618}
3619
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003620int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003621 size_t res = 0;
3622 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003623 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003624}
3625
3626int WebRtcSoundclipStream::Rewind() {
3627 mem_.Rewind();
3628 // Return -1 to keep VoiceEngine from looping.
3629 return (loop_) ? 0 : -1;
3630}
3631
3632} // namespace cricket
3633
3634#endif // HAVE_WEBRTC_VOICE