blob: 358645d853f5e07ee5a5eb303e9e8fef9928cd6c [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#ifdef HAVE_CONFIG_H
29#include <config.h>
30#endif
31
32#ifdef HAVE_WEBRTC_VOICE
33
34#include "talk/media/webrtc/webrtcvoiceengine.h"
35
36#include <algorithm>
37#include <cstdio>
38#include <string>
39#include <vector>
40
Thiago Farinaef883092015-04-06 10:36:41 +000041#include "talk/media/base/audioframe.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000042#include "talk/media/base/audiorenderer.h"
43#include "talk/media/base/constants.h"
44#include "talk/media/base/streamparams.h"
45#include "talk/media/base/voiceprocessor.h"
46#include "talk/media/webrtc/webrtcvoe.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000047#include "webrtc/base/base64.h"
48#include "webrtc/base/byteorder.h"
49#include "webrtc/base/common.h"
50#include "webrtc/base/helpers.h"
51#include "webrtc/base/logging.h"
52#include "webrtc/base/stringencode.h"
53#include "webrtc/base/stringutils.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000054#include "webrtc/common.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055#include "webrtc/modules/audio_processing/include/audio_processing.h"
56
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057namespace cricket {
58
Brave Yao5225dd82015-03-26 07:39:19 +080059static const int kMaxNumPacketSize = 6;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000060struct CodecPref {
61 const char* name;
62 int clockrate;
63 int channels;
64 int payload_type;
65 bool is_multi_rate;
Brave Yao5225dd82015-03-26 07:39:19 +080066 int packet_sizes_ms[kMaxNumPacketSize];
henrike@webrtc.org28e20752013-07-10 00:45:36 +000067};
Brave Yao5225dd82015-03-26 07:39:19 +080068// Note: keep the supported packet sizes in ascending order.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000069static const CodecPref kCodecPrefs[] = {
Brave Yao5225dd82015-03-26 07:39:19 +080070 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
71 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
72 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +000073 // G722 should be advertised as 8000 Hz because of the RFC "bug".
Brave Yao5225dd82015-03-26 07:39:19 +080074 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
75 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
76 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
77 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
Brave Yao5225dd82015-03-26 07:39:19 +080078 { kCnCodecName, 32000, 1, 106, false, { } },
79 { kCnCodecName, 16000, 1, 105, false, { } },
80 { kCnCodecName, 8000, 1, 13, false, { } },
81 { kRedCodecName, 8000, 1, 127, false, { } },
82 { kDtmfCodecName, 8000, 1, 126, false, { } },
henrike@webrtc.org28e20752013-07-10 00:45:36 +000083};
84
85// For Linux/Mac, using the default device is done by specifying index 0 for
86// VoE 4.0 and not -1 (which was the case for VoE 3.5).
87//
88// On Windows Vista and newer, Microsoft introduced the concept of "Default
89// Communications Device". This means that there are two types of default
90// devices (old Wave Audio style default and Default Communications Device).
91//
92// On Windows systems which only support Wave Audio style default, uses either
93// -1 or 0 to select the default device.
94//
95// On Windows systems which support both "Default Communication Device" and
96// old Wave Audio style default, use -1 for Default Communications Device and
97// -2 for Wave Audio style default, which is what we want to use for clips.
98// It's not clear yet whether the -2 index is handled properly on other OSes.
99
100#ifdef WIN32
101static const int kDefaultAudioDeviceId = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102#else
103static const int kDefaultAudioDeviceId = 0;
104#endif
105
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106// Parameter used for NACK.
107// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
108static const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000109
110// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000111// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000112
113// Recommended bitrates:
114// 8-12 kb/s for NB speech,
115// 16-20 kb/s for WB speech,
116// 28-40 kb/s for FB speech,
117// 48-64 kb/s for FB mono music, and
118// 64-128 kb/s for FB stereo music.
119// The current implementation applies the following values to mono signals,
120// and multiplies them by 2 for stereo.
121static const int kOpusBitrateNb = 12000;
122static const int kOpusBitrateWb = 20000;
123static const int kOpusBitrateFb = 32000;
124
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000125// Opus bitrate should be in the range between 6000 and 510000.
126static const int kOpusMinBitrate = 6000;
127static const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000128
wu@webrtc.orgde305012013-10-31 15:40:38 +0000129// Default audio dscp value.
130// See http://tools.ietf.org/html/rfc2474 for details.
131// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000132static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000133
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000134// Ensure we open the file in a writeable path on ChromeOS and Android. This
135// workaround can be removed when it's possible to specify a filename for audio
136// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000137//
138// TODO(grunell): Use a string in the options instead of hardcoding it here
139// and let the embedder choose the filename (crbug.com/264223).
140//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000141// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
142// below.
143#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000144static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000145#elif defined(ANDROID)
146static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000147#else
148static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
149#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000150
151// Dumps an AudioCodec in RFC 2327-ish format.
152static std::string ToString(const AudioCodec& codec) {
153 std::stringstream ss;
154 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
155 << " (" << codec.id << ")";
156 return ss.str();
157}
Minyue Li7100dcd2015-03-27 05:05:59 +0100158
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000159static std::string ToString(const webrtc::CodecInst& codec) {
160 std::stringstream ss;
161 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
162 << " (" << codec.pltype << ")";
163 return ss.str();
164}
165
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000166static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000167 const char* delim = "\r\n";
168 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
169 LOG_V(sev) << tok;
170 }
171}
172
173// Severity is an integer because it comes is assumed to be from command line.
174static int SeverityToFilter(int severity) {
175 int filter = webrtc::kTraceNone;
176 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000177 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000178 filter |= webrtc::kTraceAll;
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200179 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000180 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000181 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200182 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000183 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000184 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200185 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000186 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000187 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
188 }
189 return filter;
190}
191
Minyue Li7100dcd2015-03-27 05:05:59 +0100192static bool IsCodec(const AudioCodec& codec, const char* ref_name) {
193 return (_stricmp(codec.name.c_str(), ref_name) == 0);
194}
195
196static bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
197 return (_stricmp(codec.plname, ref_name) == 0);
198}
199
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000200static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
201 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100202 if (IsCodec(codec, kCodecPrefs[i].name) &&
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000203 kCodecPrefs[i].clockrate == codec.plfreq) {
204 return kCodecPrefs[i].is_multi_rate;
205 }
206 }
207 return false;
208}
209
210static bool FindCodec(const std::vector<AudioCodec>& codecs,
211 const AudioCodec& codec,
212 AudioCodec* found_codec) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200213 for (const AudioCodec& c : codecs) {
214 if (c.Matches(codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000215 if (found_codec != NULL) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200216 *found_codec = c;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000217 }
218 return true;
219 }
220 }
221 return false;
222}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000223
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000224static bool IsNackEnabled(const AudioCodec& codec) {
225 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
226 kParamValueEmpty));
227}
228
Brave Yao5225dd82015-03-26 07:39:19 +0800229static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
230 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
231 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
232 if (packet_size_ms && packet_size_ms <= ptime_ms) {
233 selected_packet_size_ms = packet_size_ms;
234 }
235 }
236 return selected_packet_size_ms;
237}
238
239// If the AudioCodec param kCodecParamPTime is set, then we will set it to codec
240// pacsize if it's valid, or we will pick the next smallest value we support.
241// TODO(Brave): Query supported packet sizes from ACM when the API is ready.
242static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
243 for (const CodecPref& codec_pref : kCodecPrefs) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100244 if ((IsCodec(*codec, codec_pref.name) &&
Brave Yao5225dd82015-03-26 07:39:19 +0800245 codec_pref.clockrate == codec->plfreq) ||
Minyue Li7100dcd2015-03-27 05:05:59 +0100246 IsCodec(*codec, kG722CodecName)) {
Brave Yao5225dd82015-03-26 07:39:19 +0800247 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
248 if (packet_size_ms) {
249 // Convert unit from milli-seconds to samples.
250 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
251 return true;
252 }
253 }
254 }
255 return false;
256}
257
Minyue Li7100dcd2015-03-27 05:05:59 +0100258// Return true if codec.params[feature] == "1", false otherwise.
259static bool IsCodecFeatureEnabled(const AudioCodec& codec,
260 const char* feature) {
261 int value;
262 return codec.GetParam(feature, &value) && value == 1;
263}
264
265// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
266// otherwise. If the value (either from params or codec.bitrate) <=0, use the
267// default configuration. If the value is beyond feasible bit rate of Opus,
268// clamp it. Returns the Opus bit rate for operation.
269static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
270 int bitrate = 0;
271 bool use_param = true;
272 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
273 bitrate = codec.bitrate;
274 use_param = false;
275 }
276 if (bitrate <= 0) {
277 if (max_playback_rate <= 8000) {
278 bitrate = kOpusBitrateNb;
279 } else if (max_playback_rate <= 16000) {
280 bitrate = kOpusBitrateWb;
281 } else {
282 bitrate = kOpusBitrateFb;
283 }
284
285 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
286 bitrate *= 2;
287 }
288 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
289 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
290 std::string rate_source =
291 use_param ? "Codec parameter \"maxaveragebitrate\"" :
292 "Supplied Opus bitrate";
293 LOG(LS_WARNING) << rate_source
294 << " is invalid and is replaced by: "
295 << bitrate;
296 }
297 return bitrate;
298}
299
300// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
301// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
302static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
303 int value;
304 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
305 return value;
306 }
307 return kOpusDefaultMaxPlaybackRate;
308}
309
310static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
311 bool* enable_codec_fec, int* max_playback_rate,
312 bool* enable_codec_dtx) {
313 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
314 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
315 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
316
317 // If OPUS, change what we send according to the "stereo" codec
318 // parameter, and not the "channels" parameter. We set
319 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
320 // the bitrate is not specified, i.e. is <= zero, we set it to the
321 // appropriate default value for mono or stereo Opus.
322
323 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
324 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
325}
326
327// Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
328// which says that G722 should be advertised as 8 kHz although it is a 16 kHz
329// codec.
330static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
331 if (IsCodec(*voe_codec, kG722CodecName)) {
332 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
333 // has changed, and this special case is no longer needed.
henrikg91d6ede2015-09-17 00:24:34 -0700334 RTC_DCHECK(voe_codec->plfreq != new_plfreq);
Minyue Li7100dcd2015-03-27 05:05:59 +0100335 voe_codec->plfreq = new_plfreq;
336 }
337}
338
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000339// Gets the default set of options applied to the engine. Historically, these
340// were supplied as a combination of flags from the channel manager (ec, agc,
341// ns, and highpass) and the rest hardcoded in InitInternal.
342static AudioOptions GetDefaultEngineOptions() {
343 AudioOptions options;
344 options.echo_cancellation.Set(true);
345 options.auto_gain_control.Set(true);
346 options.noise_suppression.Set(true);
347 options.highpass_filter.Set(true);
348 options.stereo_swapping.Set(false);
Henrik Lundin64dad832015-05-11 12:44:23 +0200349 options.audio_jitter_buffer_max_packets.Set(50);
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200350 options.audio_jitter_buffer_fast_accelerate.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000351 options.typing_detection.Set(true);
352 options.conference_mode.Set(false);
353 options.adjust_agc_delta.Set(0);
354 options.experimental_agc.Set(false);
Henrik Lundin441f6342015-06-09 16:03:13 +0200355 options.extended_filter_aec.Set(false);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100356 options.delay_agnostic_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000357 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000358 options.aec_dump.Set(false);
359 return options;
360}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000361
Minyue Li7100dcd2015-03-27 05:05:59 +0100362static std::string GetEnableString(bool enable) {
363 return enable ? "enable" : "disable";
Brave Yao5225dd82015-03-26 07:39:19 +0800364}
365
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000366WebRtcVoiceEngine::WebRtcVoiceEngine()
367 : voe_wrapper_(new VoEWrapper()),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000368 tracing_(new VoETraceWrapper()),
369 adm_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000370 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
371 is_dumping_aec_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000372 tx_processor_ssrc_(0),
373 rx_processor_ssrc_(0) {
374 Construct();
375}
376
377WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000378 VoETraceWrapper* tracing)
379 : voe_wrapper_(voe_wrapper),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000380 tracing_(tracing),
381 adm_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000382 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
383 is_dumping_aec_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000384 tx_processor_ssrc_(0),
385 rx_processor_ssrc_(0) {
386 Construct();
387}
388
389void WebRtcVoiceEngine::Construct() {
390 SetTraceFilter(log_filter_);
391 initialized_ = false;
392 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
393 SetTraceOptions("");
394 if (tracing_->SetTraceCallback(this) == -1) {
395 LOG_RTCERR0(SetTraceCallback);
396 }
397 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
398 LOG_RTCERR0(RegisterVoiceEngineObserver);
399 }
400 // Clear the default agc state.
401 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
402
403 // Load our audio codec list.
404 ConstructCodecs();
405
406 // Load our RTP Header extensions.
407 rtp_header_extensions_.push_back(
408 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
409 kRtpAudioLevelHeaderExtensionDefaultId));
410 rtp_header_extensions_.push_back(
411 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
412 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
413 options_ = GetDefaultEngineOptions();
414}
415
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000416void WebRtcVoiceEngine::ConstructCodecs() {
417 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
418 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
419 for (int i = 0; i < ncodecs; ++i) {
420 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000421 if (GetVoeCodec(i, &voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000422 // Skip uncompressed formats.
Minyue Li7100dcd2015-03-27 05:05:59 +0100423 if (IsCodec(voe_codec, kL16CodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000424 continue;
425 }
426
427 const CodecPref* pref = NULL;
428 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100429 if (IsCodec(voe_codec, kCodecPrefs[j].name) &&
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000430 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
431 kCodecPrefs[j].channels == voe_codec.channels) {
432 pref = &kCodecPrefs[j];
433 break;
434 }
435 }
436
437 if (pref) {
438 // Use the payload type that we've configured in our pref table;
439 // use the offset in our pref table to determine the sort order.
440 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
441 voe_codec.rate, voe_codec.channels,
442 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
443 LOG(LS_INFO) << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100444 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000445 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000446 codec.bitrate = 0;
447 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100448 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000449 // Only add fmtp parameters that differ from the spec.
450 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
451 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000452 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000453 }
454 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
455 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000456 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000457 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000458 codec.SetParam(kCodecParamUseInbandFec, 1);
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000459
460 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000461 // when they can be set to values other than the default.
462 }
463 codecs_.push_back(codec);
464 } else {
465 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
466 }
467 }
468 }
469 // Make sure they are in local preference order.
470 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
471}
472
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000473bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst* codec) {
474 if (voe_wrapper_->codec()->GetCodec(index, *codec) == -1) {
475 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000476 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000477 // Change the sample rate of G722 to 8000 to match SDP.
478 MaybeFixupG722(codec, 8000);
479 return true;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000480}
481
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000482WebRtcVoiceEngine::~WebRtcVoiceEngine() {
483 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
484 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
485 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
486 }
487 if (adm_) {
488 voe_wrapper_.reset();
489 adm_->Release();
490 adm_ = NULL;
491 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000492
493 // Test to see if the media processor was deregistered properly
henrikg91d6ede2015-09-17 00:24:34 -0700494 RTC_DCHECK(SignalRxMediaFrame.is_empty());
495 RTC_DCHECK(SignalTxMediaFrame.is_empty());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000496
497 tracing_->SetTraceCallback(NULL);
498}
499
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000500bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
henrikg91d6ede2015-09-17 00:24:34 -0700501 RTC_DCHECK(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000502 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
503 bool res = InitInternal();
504 if (res) {
505 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
506 } else {
507 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
508 Terminate();
509 }
510 return res;
511}
512
513bool WebRtcVoiceEngine::InitInternal() {
514 // Temporarily turn logging level up for the Init call
515 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000516 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000517 SetTraceFilter(extended_filter);
518 SetTraceOptions("");
519
520 // Init WebRtc VoiceEngine.
521 if (voe_wrapper_->base()->Init(adm_) == -1) {
522 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
523 SetTraceFilter(old_filter);
524 return false;
525 }
526
527 SetTraceFilter(old_filter);
528 SetTraceOptions(log_options_);
529
530 // Log the VoiceEngine version info
531 char buffer[1024] = "";
532 voe_wrapper_->base()->GetVersion(buffer);
533 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000534 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000535
536 // Save the default AGC configuration settings. This must happen before
537 // calling SetOptions or the default will be overwritten.
538 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
539 LOG_RTCERR0(GetAgcConfig);
540 return false;
541 }
542
543 // Set defaults for options, so that ApplyOptions applies them explicitly
544 // when we clear option (channel) overrides. External clients can still
545 // modify the defaults via SetOptions (on the media engine).
546 if (!SetOptions(GetDefaultEngineOptions())) {
547 return false;
548 }
549
550 // Print our codec list again for the call diagnostic log
551 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200552 for (const AudioCodec& codec : codecs_) {
553 LOG(LS_INFO) << ToString(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000554 }
555
556 // Disable the DTMF playout when a tone is sent.
557 // PlayDtmfTone will be used if local playout is needed.
558 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
559 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
560 }
561
562 initialized_ = true;
563 return true;
564}
565
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000566void WebRtcVoiceEngine::Terminate() {
567 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
568 initialized_ = false;
569
570 StopAecDump();
571
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000572 voe_wrapper_->base()->Terminate();
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000573}
574
575int WebRtcVoiceEngine::GetCapabilities() {
576 return AUDIO_SEND | AUDIO_RECV;
577}
578
Fredrik Solenberg709ed672015-09-15 12:26:33 +0200579VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel(webrtc::Call* call,
Jelena Marusicc28a8962015-05-29 15:05:44 +0200580 const AudioOptions& options) {
Fredrik Solenbergb071a192015-09-17 16:42:56 +0200581 WebRtcVoiceMediaChannel* ch =
582 new WebRtcVoiceMediaChannel(this, options, call);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000583 if (!ch->valid()) {
584 delete ch;
Jelena Marusicc28a8962015-05-29 15:05:44 +0200585 return nullptr;
586 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000587 return ch;
588}
589
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000590bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
591 if (!ApplyOptions(options)) {
592 return false;
593 }
594 options_ = options;
595 return true;
596}
597
598bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
599 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
600 if (!ApplyOptions(overrides)) {
601 return false;
602 }
603 option_overrides_ = overrides;
604 return true;
605}
606
607bool WebRtcVoiceEngine::ClearOptionOverrides() {
608 LOG(LS_INFO) << "Clearing option overrides.";
609 AudioOptions options = options_;
610 // Only call ApplyOptions if |options_overrides_| contains overrided options.
611 // ApplyOptions affects NS, AGC other options that is shared between
612 // all WebRtcVoiceEngineChannels.
613 if (option_overrides_ == AudioOptions()) {
614 return true;
615 }
616
617 if (!ApplyOptions(options)) {
618 return false;
619 }
620 option_overrides_ = AudioOptions();
621 return true;
622}
623
624// AudioOptions defaults are set in InitInternal (for options with corresponding
625// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
626bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
627 AudioOptions options = options_in; // The options are modified below.
628 // kEcConference is AEC with high suppression.
629 webrtc::EcModes ec_mode = webrtc::kEcConference;
630 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
631 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
632 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
633 bool aecm_comfort_noise = false;
634 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
635 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
636 << aecm_comfort_noise << " (default is false).";
637 }
638
639#if defined(IOS)
640 // On iOS, VPIO provides built-in EC and AGC.
641 options.echo_cancellation.Set(false);
642 options.auto_gain_control.Set(false);
henrika86d907c2015-09-07 16:09:50 +0200643 LOG(LS_INFO) << "Always disable AEC and AGC on iOS. Use built-in instead.";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000644#elif defined(ANDROID)
645 ec_mode = webrtc::kEcAecm;
646#endif
647
648#if defined(IOS) || defined(ANDROID)
649 // Set the AGC mode for iOS as well despite disabling it above, to avoid
650 // unsupported configuration errors from webrtc.
651 agc_mode = webrtc::kAgcFixedDigital;
652 options.typing_detection.Set(false);
653 options.experimental_agc.Set(false);
Henrik Lundin441f6342015-06-09 16:03:13 +0200654 options.extended_filter_aec.Set(false);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000655 options.experimental_ns.Set(false);
656#endif
657
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100658 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
659 // where the feature is not supported.
660 bool use_delay_agnostic_aec = false;
661#if !defined(IOS)
662 if (options.delay_agnostic_aec.Get(&use_delay_agnostic_aec)) {
663 if (use_delay_agnostic_aec) {
664 options.echo_cancellation.Set(true);
Henrik Lundin441f6342015-06-09 16:03:13 +0200665 options.extended_filter_aec.Set(true);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100666 ec_mode = webrtc::kEcConference;
667 }
668 }
669#endif
670
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000671 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
672
673 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
674
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000675 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000676 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000677 // Check if platform supports built-in EC. Currently only supported on
678 // Android and in combination with Java based audio layer.
679 // TODO(henrika): investigate possibility to support built-in EC also
680 // in combination with Open SL ES audio.
681 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
Bjorn Volcker73f72102015-06-03 14:50:15 +0200682 if (built_in_aec) {
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200683 // Built-in EC exists on this device and use_delay_agnostic_aec is not
684 // overriding it. Enable/Disable it according to the echo_cancellation
685 // audio option.
Bjorn Volcker73f72102015-06-03 14:50:15 +0200686 const bool enable_built_in_aec =
687 echo_cancellation && !use_delay_agnostic_aec;
688 if (voe_wrapper_->hw()->EnableBuiltInAEC(enable_built_in_aec) == 0 &&
689 enable_built_in_aec) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100690 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000691 // i.e., replace the software EC with the built-in EC.
692 options.echo_cancellation.Set(false);
bjornv@webrtc.org3f118232015-03-16 14:22:03 +0000693 echo_cancellation = false;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000694 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
695 }
696 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000697 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
698 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
699 return false;
700 } else {
henrika86d907c2015-09-07 16:09:50 +0200701 LOG(LS_INFO) << "Echo control set to " << echo_cancellation
702 << " with mode " << ec_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000703 }
704#if !defined(ANDROID)
705 // TODO(ajm): Remove the error return on Android from webrtc.
706 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
707 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
708 return false;
709 }
710#endif
711 if (ec_mode == webrtc::kEcAecm) {
712 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
713 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
714 return false;
715 }
716 }
717 }
718
719 bool auto_gain_control;
720 if (options.auto_gain_control.Get(&auto_gain_control)) {
721 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
722 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
723 return false;
724 } else {
henrika86d907c2015-09-07 16:09:50 +0200725 LOG(LS_INFO) << "Auto gain set to " << auto_gain_control << " with mode "
726 << agc_mode;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000727 }
728 }
729
730 if (options.tx_agc_target_dbov.IsSet() ||
731 options.tx_agc_digital_compression_gain.IsSet() ||
732 options.tx_agc_limiter.IsSet()) {
733 // Override default_agc_config_. Generally, an unset option means "leave
734 // the VoE bits alone" in this function, so we want whatever is set to be
735 // stored as the new "default". If we didn't, then setting e.g.
736 // tx_agc_target_dbov would reset digital compression gain and limiter
737 // settings.
738 // Also, if we don't update default_agc_config_, then adjust_agc_delta
739 // would be an offset from the original values, and not whatever was set
740 // explicitly.
741 default_agc_config_.targetLeveldBOv =
742 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
743 default_agc_config_.targetLeveldBOv);
744 default_agc_config_.digitalCompressionGaindB =
745 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
746 default_agc_config_.digitalCompressionGaindB);
747 default_agc_config_.limiterEnable =
748 options.tx_agc_limiter.GetWithDefaultIfUnset(
749 default_agc_config_.limiterEnable);
750 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
751 LOG_RTCERR3(SetAgcConfig,
752 default_agc_config_.targetLeveldBOv,
753 default_agc_config_.digitalCompressionGaindB,
754 default_agc_config_.limiterEnable);
755 return false;
756 }
757 }
758
759 bool noise_suppression;
760 if (options.noise_suppression.Get(&noise_suppression)) {
761 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
762 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
763 return false;
764 } else {
765 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
766 << " with mode " << ns_mode;
767 }
768 }
769
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000770 bool highpass_filter;
771 if (options.highpass_filter.Get(&highpass_filter)) {
772 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
773 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
774 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
775 return false;
776 }
777 }
778
779 bool stereo_swapping;
780 if (options.stereo_swapping.Get(&stereo_swapping)) {
781 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
782 voep->EnableStereoChannelSwapping(stereo_swapping);
783 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
784 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
785 return false;
786 }
787 }
788
Henrik Lundin64dad832015-05-11 12:44:23 +0200789 int audio_jitter_buffer_max_packets;
790 if (options.audio_jitter_buffer_max_packets.Get(
791 &audio_jitter_buffer_max_packets)) {
792 LOG(LS_INFO) << "NetEq capacity is " << audio_jitter_buffer_max_packets;
793 voe_config_.Set<webrtc::NetEqCapacityConfig>(
794 new webrtc::NetEqCapacityConfig(audio_jitter_buffer_max_packets));
795 }
796
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200797 bool audio_jitter_buffer_fast_accelerate;
798 if (options.audio_jitter_buffer_fast_accelerate.Get(
799 &audio_jitter_buffer_fast_accelerate)) {
800 LOG(LS_INFO) << "NetEq fast mode? " << audio_jitter_buffer_fast_accelerate;
801 voe_config_.Set<webrtc::NetEqFastAccelerate>(
802 new webrtc::NetEqFastAccelerate(audio_jitter_buffer_fast_accelerate));
803 }
804
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000805 bool typing_detection;
806 if (options.typing_detection.Get(&typing_detection)) {
807 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
808 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
809 // In case of error, log the info and continue
810 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
811 }
812 }
813
814 int adjust_agc_delta;
815 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
816 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
817 if (!AdjustAgcLevel(adjust_agc_delta)) {
818 return false;
819 }
820 }
821
822 bool aec_dump;
823 if (options.aec_dump.Get(&aec_dump)) {
824 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
825 if (aec_dump)
826 StartAecDump(kAecDumpByAudioOptionFilename);
827 else
828 StopAecDump();
829 }
830
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000831 webrtc::Config config;
832
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100833 delay_agnostic_aec_.SetFrom(options.delay_agnostic_aec);
834 bool delay_agnostic_aec;
835 if (delay_agnostic_aec_.Get(&delay_agnostic_aec)) {
836 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << delay_agnostic_aec;
henrik.lundin0f133b92015-07-02 00:17:55 -0700837 config.Set<webrtc::DelayAgnostic>(
838 new webrtc::DelayAgnostic(delay_agnostic_aec));
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100839 }
840
Henrik Lundin441f6342015-06-09 16:03:13 +0200841 extended_filter_aec_.SetFrom(options.extended_filter_aec);
842 bool extended_filter;
843 if (extended_filter_aec_.Get(&extended_filter)) {
844 LOG(LS_INFO) << "Extended filter aec is enabled? " << extended_filter;
845 config.Set<webrtc::ExtendedFilter>(
846 new webrtc::ExtendedFilter(extended_filter));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000847 }
848
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000849 experimental_ns_.SetFrom(options.experimental_ns);
850 bool experimental_ns;
851 if (experimental_ns_.Get(&experimental_ns)) {
852 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
853 config.Set<webrtc::ExperimentalNs>(
854 new webrtc::ExperimentalNs(experimental_ns));
855 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000856
857 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
858 // returns NULL on audio_processing().
859 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
860 if (audioproc) {
861 audioproc->SetExtraOptions(config);
862 }
863
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000864 uint32 recording_sample_rate;
865 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
866 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
867 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
868 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
869 }
870 }
871
872 uint32 playout_sample_rate;
873 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
874 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
875 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
876 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
877 }
878 }
879
880 return true;
881}
882
883bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
884 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
885 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
886 LOG_RTCERR1(SetDelayOffsetMs, offset);
887 return false;
888 }
889
890 return true;
891}
892
893struct ResumeEntry {
894 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
895 : channel(c),
896 playout(p),
897 send(s) {
898 }
899
900 WebRtcVoiceMediaChannel *channel;
901 bool playout;
902 SendFlags send;
903};
904
905// TODO(juberti): Refactor this so that the core logic can be used to set the
906// soundclip device. At that time, reinstate the soundclip pause/resume code.
907bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
908 const Device* out_device) {
909#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000910 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000911 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000912 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000913 kDefaultAudioDeviceId;
914 // The device manager uses -1 as the default device, which was the case for
915 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
916#ifndef WIN32
917 if (-1 == in_id) {
918 in_id = kDefaultAudioDeviceId;
919 }
920 if (-1 == out_id) {
921 out_id = kDefaultAudioDeviceId;
922 }
923#endif
924
925 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
926 in_device->name : "Default device";
927 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
928 out_device->name : "Default device";
929 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
930 << ") and speaker to (id=" << out_id << ", name=" << out_name
931 << ")";
932
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000933 // Must also pause all audio playback and capture.
solenbergc1a1b352015-09-22 13:31:20 -0700934 bool ret = true;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200935 for (WebRtcVoiceMediaChannel* channel : channels_) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000936 if (!channel->PausePlayout()) {
937 LOG(LS_WARNING) << "Failed to pause playout";
938 ret = false;
939 }
940 if (!channel->PauseSend()) {
941 LOG(LS_WARNING) << "Failed to pause send";
942 ret = false;
943 }
944 }
945
946 // Find the recording device id in VoiceEngine and set recording device.
947 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
948 ret = false;
949 }
950 if (ret) {
951 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
952 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
953 ret = false;
954 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +0000955 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
956 if (ap)
957 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000958 }
959
960 // Find the playout device id in VoiceEngine and set playout device.
961 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
962 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
963 ret = false;
964 }
965 if (ret) {
966 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000967 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000968 ret = false;
969 }
970 }
971
972 // Resume all audio playback and capture.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200973 for (WebRtcVoiceMediaChannel* channel : channels_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000974 if (!channel->ResumePlayout()) {
975 LOG(LS_WARNING) << "Failed to resume playout";
976 ret = false;
977 }
978 if (!channel->ResumeSend()) {
979 LOG(LS_WARNING) << "Failed to resume send";
980 ret = false;
981 }
982 }
983
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000984 if (ret) {
985 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
986 << ") and speaker to (id="<< out_id << " name=" << out_name
987 << ")";
988 }
989
990 return ret;
991#else
992 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000993#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000994}
995
996bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
997 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
998 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000999#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001000 *rtc_id = dev_id;
1001 return true;
1002#else
1003 // In Windows and Mac, we need to find the VoiceEngine device id by name
1004 // unless the input dev_id is the default device id.
1005 if (kDefaultAudioDeviceId == dev_id) {
1006 *rtc_id = dev_id;
1007 return true;
1008 }
1009
1010 // Get the number of VoiceEngine audio devices.
1011 int count = 0;
1012 if (is_input) {
1013 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1014 LOG_RTCERR0(GetNumOfRecordingDevices);
1015 return false;
1016 }
1017 } else {
1018 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1019 LOG_RTCERR0(GetNumOfPlayoutDevices);
1020 return false;
1021 }
1022 }
1023
1024 for (int i = 0; i < count; ++i) {
1025 char name[128];
1026 char guid[128];
1027 if (is_input) {
1028 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1029 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1030 } else {
1031 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1032 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1033 }
1034
1035 std::string webrtc_name(name);
1036 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1037 *rtc_id = i;
1038 return true;
1039 }
1040 }
1041 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1042 return false;
1043#endif
1044}
1045
1046bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1047 unsigned int ulevel;
1048 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1049 LOG_RTCERR1(GetSpeakerVolume, level);
1050 return false;
1051 }
1052 *level = ulevel;
1053 return true;
1054}
1055
1056bool WebRtcVoiceEngine::SetOutputVolume(int level) {
henrikg91d6ede2015-09-17 00:24:34 -07001057 RTC_DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001058 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1059 LOG_RTCERR1(SetSpeakerVolume, level);
1060 return false;
1061 }
1062 return true;
1063}
1064
1065int WebRtcVoiceEngine::GetInputLevel() {
1066 unsigned int ulevel;
1067 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1068 static_cast<int>(ulevel) : -1;
1069}
1070
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001071const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1072 return codecs_;
1073}
1074
1075bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1076 return FindWebRtcCodec(in, NULL);
1077}
1078
1079// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1080bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1081 webrtc::CodecInst* out) {
1082 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1083 for (int i = 0; i < ncodecs; ++i) {
1084 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001085 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001086 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1087 voe_codec.rate, voe_codec.channels, 0);
1088 bool multi_rate = IsCodecMultiRate(voe_codec);
1089 // Allow arbitrary rates for ISAC to be specified.
1090 if (multi_rate) {
1091 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1092 codec.bitrate = 0;
1093 }
1094 if (codec.Matches(in)) {
1095 if (out) {
1096 // Fixup the payload type.
1097 voe_codec.pltype = in.id;
1098
1099 // Set bitrate if specified.
1100 if (multi_rate && in.bitrate != 0) {
1101 voe_codec.rate = in.bitrate;
1102 }
1103
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001104 // Reset G722 sample rate to 16000 to match WebRTC.
1105 MaybeFixupG722(&voe_codec, 16000);
1106
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001107 // Apply codec-specific settings.
Minyue Li7100dcd2015-03-27 05:05:59 +01001108 if (IsCodec(codec, kIsacCodecName)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001109 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001110 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001111 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1112 }
1113 *out = voe_codec;
1114 }
1115 return true;
1116 }
1117 }
1118 }
1119 return false;
1120}
1121const std::vector<RtpHeaderExtension>&
1122WebRtcVoiceEngine::rtp_header_extensions() const {
1123 return rtp_header_extensions_;
1124}
1125
1126void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1127 // if min_sev == -1, we keep the current log level.
1128 if (min_sev >= 0) {
1129 SetTraceFilter(SeverityToFilter(min_sev));
1130 }
1131 log_options_ = filter;
1132 SetTraceOptions(initialized_ ? log_options_ : "");
1133}
1134
1135int WebRtcVoiceEngine::GetLastEngineError() {
1136 return voe_wrapper_->error();
1137}
1138
1139void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1140 log_filter_ = filter;
1141 tracing_->SetTraceFilter(filter);
1142}
1143
1144// We suppport three different logging settings for VoiceEngine:
1145// 1. Observer callback that goes into talk diagnostic logfile.
1146// Use --logfile and --loglevel
1147//
1148// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1149// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1150//
1151// 3. EC log and dump for debugging QualityEngine.
1152// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1153//
1154// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1155// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1156void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1157 // Set encrypted trace file.
1158 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001159 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001160 std::vector<std::string>::iterator tracefile =
1161 std::find(opts.begin(), opts.end(), "tracefile");
1162 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1163 // Write encrypted debug output (at same loglevel) to file
1164 // EncryptedTraceFile no longer supported.
1165 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1166 LOG_RTCERR1(SetTraceFile, *tracefile);
1167 }
1168 }
1169
wu@webrtc.org97077a32013-10-25 21:18:33 +00001170 // Allow trace options to override the trace filter. We default
1171 // it to log_filter_ (as a translation of libjingle log levels)
1172 // elsewhere, but this allows clients to explicitly set webrtc
1173 // log levels.
1174 std::vector<std::string>::iterator tracefilter =
1175 std::find(opts.begin(), opts.end(), "tracefilter");
1176 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001177 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001178 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1179 }
1180 }
1181
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001182 // Set AEC dump file
1183 std::vector<std::string>::iterator recordEC =
1184 std::find(opts.begin(), opts.end(), "recordEC");
1185 if (recordEC != opts.end()) {
1186 ++recordEC;
1187 if (recordEC != opts.end())
1188 StartAecDump(recordEC->c_str());
1189 else
1190 StopAecDump();
1191 }
1192}
1193
1194// Ignore spammy trace messages, mostly from the stats API when we haven't
1195// gotten RTCP info yet from the remote side.
1196bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1197 static const char* kTracesToIgnore[] = {
1198 "\tfailed to GetReportBlockInformation",
1199 "GetRecCodec() failed to get received codec",
1200 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1201 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1202 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1203 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1204 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1205 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1206 "SenderInfoReceived No received SR",
1207 "StatisticsRTP() no statistics available",
1208 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1209 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1210 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1211 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1212 NULL
1213 };
1214 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1215 if (trace.find(*p) != std::string::npos) {
1216 return true;
1217 }
1218 }
1219 return false;
1220}
1221
1222void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1223 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001224 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001225 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001226 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001227 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001228 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001229 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001230 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001231 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001232 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001233
1234 // Skip past boilerplate prefix text
1235 if (length < 72) {
1236 std::string msg(trace, length);
1237 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1238 LOG_V(sev) << msg;
1239 } else {
1240 std::string msg(trace + 71, length - 72);
1241 if (!ShouldIgnoreTrace(msg)) {
1242 LOG_V(sev) << "webrtc: " << msg;
1243 }
1244 }
1245}
1246
1247void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001248 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001249 WebRtcVoiceMediaChannel* channel = NULL;
1250 uint32 ssrc = 0;
1251 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1252 << channel_num << ".";
1253 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
henrikg91d6ede2015-09-17 00:24:34 -07001254 RTC_DCHECK(channel != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001255 channel->OnError(ssrc, err_code);
1256 } else {
1257 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1258 << " could not be found in channel list when error reported.";
1259 }
1260}
1261
1262bool WebRtcVoiceEngine::FindChannelAndSsrc(
1263 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
henrikg91d6ede2015-09-17 00:24:34 -07001264 RTC_DCHECK(channel != NULL && ssrc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001265
1266 *channel = NULL;
1267 *ssrc = 0;
1268 // Find corresponding channel and ssrc
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001269 for (WebRtcVoiceMediaChannel* ch : channels_) {
henrikg91d6ede2015-09-17 00:24:34 -07001270 RTC_DCHECK(ch != NULL);
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001271 if (ch->FindSsrc(channel_num, ssrc)) {
1272 *channel = ch;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001273 return true;
1274 }
1275 }
1276
1277 return false;
1278}
1279
1280// This method will search through the WebRtcVoiceMediaChannels and
1281// obtain the voice engine's channel number.
1282bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1283 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
henrikg91d6ede2015-09-17 00:24:34 -07001284 RTC_DCHECK(channel_num != NULL);
1285 RTC_DCHECK(direction == MPD_RX || direction == MPD_TX);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001286
1287 *channel_num = -1;
1288 // Find corresponding channel for ssrc.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001289 for (const WebRtcVoiceMediaChannel* ch : channels_) {
henrikg91d6ede2015-09-17 00:24:34 -07001290 RTC_DCHECK(ch != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001291 if (direction & MPD_RX) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001292 *channel_num = ch->GetReceiveChannelNum(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293 }
1294 if (*channel_num == -1 && (direction & MPD_TX)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001295 *channel_num = ch->GetSendChannelNum(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001296 }
1297 if (*channel_num != -1) {
1298 return true;
1299 }
1300 }
1301 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1302 return false;
1303}
1304
1305void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001306 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001307 channels_.push_back(channel);
1308}
1309
1310void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001311 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001312 ChannelList::iterator i = std::find(channels_.begin(),
1313 channels_.end(),
1314 channel);
1315 if (i != channels_.end()) {
1316 channels_.erase(i);
1317 }
1318}
1319
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001320// Adjusts the default AGC target level by the specified delta.
1321// NB: If we start messing with other config fields, we'll want
1322// to save the current webrtc::AgcConfig as well.
1323bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1324 webrtc::AgcConfig config = default_agc_config_;
1325 config.targetLeveldBOv -= delta;
1326
1327 LOG(LS_INFO) << "Adjusting AGC level from default -"
1328 << default_agc_config_.targetLeveldBOv << "dB to -"
1329 << config.targetLeveldBOv << "dB";
1330
1331 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1332 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1333 return false;
1334 }
1335 return true;
1336}
1337
Fredrik Solenbergccb49e72015-05-19 11:37:56 +02001338bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001339 if (initialized_) {
1340 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1341 return false;
1342 }
1343 if (adm_) {
1344 adm_->Release();
1345 adm_ = NULL;
1346 }
1347 if (adm) {
1348 adm_ = adm;
1349 adm_->AddRef();
1350 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351 return true;
1352}
1353
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001354bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1355 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001356 if (!aec_dump_file_stream) {
1357 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001358 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001359 LOG(LS_WARNING) << "Could not close file.";
1360 return false;
1361 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001362 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001363 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001364 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001365 LOG_RTCERR0(StartDebugRecording);
1366 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001367 return false;
1368 }
1369 is_dumping_aec_ = true;
1370 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001371}
1372
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001373bool WebRtcVoiceEngine::RegisterProcessor(
1374 uint32 ssrc,
1375 VoiceProcessor* voice_processor,
1376 MediaProcessorDirection direction) {
1377 bool register_with_webrtc = false;
1378 int channel_id = -1;
1379 bool success = false;
1380 uint32* processor_ssrc = NULL;
1381 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1382 if (voice_processor == NULL || !found_channel) {
1383 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1384 << " foundChannel: " << found_channel;
1385 return false;
1386 }
1387
1388 webrtc::ProcessingTypes processing_type;
1389 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001390 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001391 if (direction == MPD_RX) {
1392 processing_type = webrtc::kPlaybackAllChannelsMixed;
1393 if (SignalRxMediaFrame.is_empty()) {
1394 register_with_webrtc = true;
1395 processor_ssrc = &rx_processor_ssrc_;
1396 }
1397 SignalRxMediaFrame.connect(voice_processor,
1398 &VoiceProcessor::OnFrame);
1399 } else {
1400 processing_type = webrtc::kRecordingPerChannel;
1401 if (SignalTxMediaFrame.is_empty()) {
1402 register_with_webrtc = true;
1403 processor_ssrc = &tx_processor_ssrc_;
1404 }
1405 SignalTxMediaFrame.connect(voice_processor,
1406 &VoiceProcessor::OnFrame);
1407 }
1408 }
1409 if (register_with_webrtc) {
1410 // TODO(janahan): when registering consider instantiating a
1411 // a VoeMediaProcess object and not make the engine extend the interface.
1412 if (voe()->media() && voe()->media()->
1413 RegisterExternalMediaProcessing(channel_id,
1414 processing_type,
1415 *this) != -1) {
1416 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1417 << channel_id;
1418 *processor_ssrc = ssrc;
1419 success = true;
1420 } else {
1421 LOG_RTCERR2(RegisterExternalMediaProcessing,
1422 channel_id,
1423 processing_type);
1424 success = false;
1425 }
1426 } else {
1427 // If we don't have to register with the engine, we just needed to
1428 // connect a new processor, set success to true;
1429 success = true;
1430 }
1431 return success;
1432}
1433
1434bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1435 MediaProcessorDirection channel_direction,
1436 uint32 ssrc,
1437 VoiceProcessor* voice_processor,
1438 MediaProcessorDirection processor_direction) {
1439 bool success = true;
1440 FrameSignal* signal;
1441 webrtc::ProcessingTypes processing_type;
1442 uint32* processor_ssrc = NULL;
1443 if (channel_direction == MPD_RX) {
1444 signal = &SignalRxMediaFrame;
1445 processing_type = webrtc::kPlaybackAllChannelsMixed;
1446 processor_ssrc = &rx_processor_ssrc_;
1447 } else {
1448 signal = &SignalTxMediaFrame;
1449 processing_type = webrtc::kRecordingPerChannel;
1450 processor_ssrc = &tx_processor_ssrc_;
1451 }
1452
1453 int deregister_id = -1;
1454 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001455 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001456 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1457 signal->disconnect(voice_processor);
1458 int channel_id = -1;
1459 bool found_channel = FindChannelNumFromSsrc(ssrc,
1460 channel_direction,
1461 &channel_id);
1462 if (signal->is_empty() && found_channel) {
1463 deregister_id = channel_id;
1464 }
1465 }
1466 }
1467 if (deregister_id != -1) {
1468 if (voe()->media() &&
1469 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1470 processing_type) != -1) {
1471 *processor_ssrc = 0;
1472 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1473 << deregister_id;
1474 } else {
1475 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1476 deregister_id,
1477 processing_type);
1478 success = false;
1479 }
1480 }
1481 return success;
1482}
1483
1484bool WebRtcVoiceEngine::UnregisterProcessor(
1485 uint32 ssrc,
1486 VoiceProcessor* voice_processor,
1487 MediaProcessorDirection direction) {
1488 bool success = true;
1489 if (voice_processor == NULL) {
1490 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1491 << ssrc;
1492 return false;
1493 }
1494 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1495 success = false;
1496 }
1497 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1498 success = false;
1499 }
1500 return success;
1501}
1502
1503// Implementing method from WebRtc VoEMediaProcess interface
1504// Do not lock mux_channel_cs_ in this callback.
1505void WebRtcVoiceEngine::Process(int channel,
1506 webrtc::ProcessingTypes type,
1507 int16_t audio10ms[],
Peter Kastingdce40cf2015-08-24 14:52:23 -07001508 size_t length,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001509 int sampling_freq,
1510 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001511 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001512 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1513 if (type == webrtc::kPlaybackAllChannelsMixed) {
1514 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1515 } else if (type == webrtc::kRecordingPerChannel) {
1516 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1517 } else {
1518 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1519 << " channel: " << channel << " type: " << type
1520 << " tx_ssrc: " << tx_processor_ssrc_
1521 << " rx_ssrc: " << rx_processor_ssrc_;
1522 }
1523}
1524
1525void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1526 if (!is_dumping_aec_) {
1527 // Start dumping AEC when we are not dumping.
1528 if (voe_wrapper_->processing()->StartDebugRecording(
1529 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001530 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001531 } else {
1532 is_dumping_aec_ = true;
1533 }
1534 }
1535}
1536
1537void WebRtcVoiceEngine::StopAecDump() {
1538 if (is_dumping_aec_) {
1539 // Stop dumping AEC when we are dumping.
1540 if (voe_wrapper_->processing()->StopDebugRecording() !=
1541 webrtc::AudioProcessing::kNoError) {
1542 LOG_RTCERR0(StopDebugRecording);
1543 }
1544 is_dumping_aec_ = false;
1545 }
1546}
1547
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001548int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001549 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001550}
1551
1552int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1553 return CreateVoiceChannel(voe_wrapper_.get());
1554}
1555
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001556class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1557 : public AudioRenderer::Sink {
1558 public:
1559 WebRtcVoiceChannelRenderer(int ch,
1560 webrtc::AudioTransport* voe_audio_transport)
1561 : channel_(ch),
1562 voe_audio_transport_(voe_audio_transport),
pbos8fc7fa72015-07-15 08:02:58 -07001563 renderer_(NULL) {}
Fredrik Solenbergaaf8ff22015-05-07 16:05:53 +02001564 ~WebRtcVoiceChannelRenderer() override { Stop(); }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001565
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001566 // Starts the rendering by setting a sink to the renderer to get data
1567 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001568 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001569 // TODO(xians): Make sure Start() is called only once.
1570 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001571 rtc::CritScope lock(&lock_);
henrikg91d6ede2015-09-17 00:24:34 -07001572 RTC_DCHECK(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001573 if (renderer_ != NULL) {
henrikg91d6ede2015-09-17 00:24:34 -07001574 RTC_DCHECK(renderer_ == renderer);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001575 return;
1576 }
1577
1578 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1579 // in getUserMedia by default.
1580 renderer->AddChannel(channel_);
1581 renderer->SetSink(this);
1582 renderer_ = renderer;
1583 }
1584
1585 // Stops rendering by setting the sink of the renderer to NULL. No data
1586 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001587 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001588 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001589 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001590 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001591 return;
1592
1593 renderer_->RemoveChannel(channel_);
1594 renderer_->SetSink(NULL);
1595 renderer_ = NULL;
1596 }
1597
1598 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001599 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001600 void OnData(const void* audio_data,
1601 int bits_per_sample,
1602 int sample_rate,
1603 int number_of_channels,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001604 size_t number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001605 voe_audio_transport_->OnData(channel_,
1606 audio_data,
1607 bits_per_sample,
1608 sample_rate,
1609 number_of_channels,
1610 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001611 }
1612
1613 // Callback from the |renderer_| when it is going away. In case Start() has
1614 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001615 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001616 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001617 // Set |renderer_| to NULL to make sure no more callback will get into
1618 // the renderer.
1619 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001620 }
1621
1622 // Accessor to the VoE channel ID.
1623 int channel() const { return channel_; }
1624
1625 private:
1626 const int channel_;
1627 webrtc::AudioTransport* const voe_audio_transport_;
1628
1629 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1630 // PeerConnection will make sure invalidating the pointer before the object
1631 // goes away.
1632 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001633
1634 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001635 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001636};
1637
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001638// WebRtcVoiceMediaChannel
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001639WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine,
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001640 const AudioOptions& options,
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001641 webrtc::Call* call)
Fredrik Solenberge444a3d2015-05-07 16:42:08 +02001642 : engine_(engine),
1643 voe_channel_(engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001644 send_bitrate_setting_(false),
1645 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001646 options_(),
1647 dtmf_allowed_(false),
1648 desired_playout_(false),
1649 nack_enabled_(false),
1650 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001651 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001652 desired_send_(SEND_NOTHING),
1653 send_(SEND_NOTHING),
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001654 call_(call),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001655 default_receive_ssrc_(0) {
1656 engine->RegisterChannel(this);
1657 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1658 << voe_channel();
henrikg91d6ede2015-09-17 00:24:34 -07001659 RTC_DCHECK(nullptr != call);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001660 ConfigureSendChannel(voe_channel());
Fredrik Solenbergb071a192015-09-17 16:42:56 +02001661 SetOptions(options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001662}
1663
1664WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1665 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1666 << voe_channel();
1667
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001668 // Remove any remaining send streams, the default channel will be deleted
1669 // later.
1670 while (!send_channels_.empty())
1671 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001672
1673 // Unregister ourselves from the engine.
1674 engine()->UnregisterChannel(this);
1675 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001676 while (!receive_channels_.empty()) {
1677 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001678 }
henrikg91d6ede2015-09-17 00:24:34 -07001679 RTC_DCHECK(receive_streams_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001680
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001681 // Delete the default channel.
1682 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001683}
1684
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001685bool WebRtcVoiceMediaChannel::SetSendParameters(
1686 const AudioSendParameters& params) {
1687 // TODO(pthatcher): Refactor this to be more clean now that we have
1688 // all the information at once.
1689 return (SetSendCodecs(params.codecs) &&
1690 SetSendRtpHeaderExtensions(params.extensions) &&
1691 SetMaxSendBandwidth(params.max_bandwidth_bps) &&
1692 SetOptions(params.options));
1693}
1694
1695bool WebRtcVoiceMediaChannel::SetRecvParameters(
1696 const AudioRecvParameters& params) {
1697 // TODO(pthatcher): Refactor this to be more clean now that we have
1698 // all the information at once.
1699 return (SetRecvCodecs(params.codecs) &&
1700 SetRecvRtpHeaderExtensions(params.extensions));
1701}
1702
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001703bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1704 LOG(LS_INFO) << "Setting voice channel options: "
1705 << options.ToString();
1706
wu@webrtc.orgde305012013-10-31 15:40:38 +00001707 // Check if DSCP value is changed from previous.
1708 bool dscp_option_changed = (options_.dscp != options.dscp);
1709
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001710 // TODO(xians): Add support to set different options for different send
1711 // streams after we support multiple APMs.
1712
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001713 // We retain all of the existing options, and apply the given ones
1714 // on top. This means there is no way to "clear" options such that
1715 // they go back to the engine default.
1716 options_.SetAll(options);
1717
1718 if (send_ != SEND_NOTHING) {
1719 if (!engine()->SetOptionOverrides(options_)) {
1720 LOG(LS_WARNING) <<
1721 "Failed to engine SetOptionOverrides during channel SetOptions.";
1722 return false;
1723 }
1724 } else {
1725 // Will be interpreted when appropriate.
1726 }
1727
wu@webrtc.org97077a32013-10-25 21:18:33 +00001728 // Receiver-side auto gain control happens per channel, so set it here from
1729 // options. Note that, like conference mode, setting it on the engine won't
1730 // have the desired effect, since voice channels don't inherit options from
1731 // the media engine when those options are applied per-channel.
1732 bool rx_auto_gain_control;
1733 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1734 if (engine()->voe()->processing()->SetRxAgcStatus(
1735 voe_channel(), rx_auto_gain_control,
1736 webrtc::kAgcFixedDigital) == -1) {
1737 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1738 return false;
1739 } else {
1740 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1741 << " with mode " << webrtc::kAgcFixedDigital;
1742 }
1743 }
1744 if (options.rx_agc_target_dbov.IsSet() ||
1745 options.rx_agc_digital_compression_gain.IsSet() ||
1746 options.rx_agc_limiter.IsSet()) {
1747 webrtc::AgcConfig config;
1748 // If only some of the options are being overridden, get the current
1749 // settings for the channel and bail if they aren't available.
1750 if (!options.rx_agc_target_dbov.IsSet() ||
1751 !options.rx_agc_digital_compression_gain.IsSet() ||
1752 !options.rx_agc_limiter.IsSet()) {
1753 if (engine()->voe()->processing()->GetRxAgcConfig(
1754 voe_channel(), config) != 0) {
1755 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1756 << "channel " << voe_channel() << ". Since not all rx "
1757 << "agc options are specified, unable to safely set rx "
1758 << "agc options.";
1759 return false;
1760 }
1761 }
1762 config.targetLeveldBOv =
1763 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1764 config.targetLeveldBOv);
1765 config.digitalCompressionGaindB =
1766 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1767 config.digitalCompressionGaindB);
1768 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1769 config.limiterEnable);
1770 if (engine()->voe()->processing()->SetRxAgcConfig(
1771 voe_channel(), config) == -1) {
1772 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1773 config.digitalCompressionGaindB, config.limiterEnable);
1774 return false;
1775 }
1776 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001777 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001778 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001779 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001780 dscp = kAudioDscpValue;
1781 if (MediaChannel::SetDscp(dscp) != 0) {
1782 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1783 }
1784 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001785
Fredrik Solenberg709ed672015-09-15 12:26:33 +02001786 RecreateAudioReceiveStreams();
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001787
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001788 LOG(LS_INFO) << "Set voice channel options. Current options: "
1789 << options_.ToString();
1790 return true;
1791}
1792
1793bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1794 const std::vector<AudioCodec>& codecs) {
1795 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001796 LOG(LS_INFO) << "Setting receive voice codecs:";
1797
1798 std::vector<AudioCodec> new_codecs;
1799 // Find all new codecs. We allow adding new codecs but don't allow changing
1800 // the payload type of codecs that is already configured since we might
1801 // already be receiving packets with that payload type.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001802 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001803 AudioCodec old_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001804 if (FindCodec(recv_codecs_, codec, &old_codec)) {
1805 if (old_codec.id != codec.id) {
1806 LOG(LS_ERROR) << codec.name << " payload type changed.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001807 return false;
1808 }
1809 } else {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001810 new_codecs.push_back(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001811 }
1812 }
1813 if (new_codecs.empty()) {
1814 // There are no new codecs to configure. Already configured codecs are
1815 // never removed.
1816 return true;
1817 }
1818
1819 if (playout_) {
1820 // Receive codecs can not be changed while playing. So we temporarily
1821 // pause playout.
1822 PausePlayout();
1823 }
1824
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001825 bool result = SetRecvCodecsInternal(new_codecs);
1826 if (result) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001827 recv_codecs_ = codecs;
1828 }
1829
1830 if (desired_playout_ && !playout_) {
1831 ResumePlayout();
1832 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001833 return result;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001834}
1835
1836bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001837 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001838 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001839 engine()->voe()->codec()->SetVADStatus(channel, false);
1840 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001841 engine()->voe()->rtp()->SetREDStatus(channel, false);
1842 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001843
1844 // Scan through the list to figure out the codec to use for sending, along
1845 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001846 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001847 webrtc::CodecInst send_codec;
1848 memset(&send_codec, 0, sizeof(send_codec));
1849
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001850 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001851 bool enable_codec_fec = false;
Minyue Li7100dcd2015-03-27 05:05:59 +01001852 bool enable_opus_dtx = false;
minyue@webrtc.org26236952014-10-29 02:27:08 +00001853 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001854
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001855 // Set send codec (the first non-telephone-event/CN codec)
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001856 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001857 // Ignore codecs we don't know about. The negotiation step should prevent
1858 // this, but double-check to be sure.
1859 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001860 if (!engine()->FindWebRtcCodec(codec, &voe_codec)) {
1861 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001862 continue;
1863 }
1864
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001865 if (IsCodec(codec, kDtmfCodecName) || IsCodec(codec, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001866 // Skip telephone-event/CN codec, which will be handled later.
1867 continue;
1868 }
1869
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001870 // We'll use the first codec in the list to actually send audio data.
1871 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001872 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001873 // used is specified in params.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001874 if (IsCodec(codec, kRedCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001875 // Parse out the RED parameters. If we fail, just ignore RED;
1876 // we don't support all possible params/usage scenarios.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001877 if (!GetRedSendCodec(codec, codecs, &send_codec)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001878 continue;
1879 }
1880
1881 // Enable redundant encoding of the specified codec. Treat any
1882 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001883 LOG(LS_INFO) << "Enabling RED on channel " << channel;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001884 if (engine()->voe()->rtp()->SetREDStatus(channel, true, codec.id) == -1) {
1885 LOG_RTCERR3(SetREDStatus, channel, true, codec.id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001886 return false;
1887 }
1888 } else {
1889 send_codec = voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001890 nack_enabled = IsNackEnabled(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +01001891 // For Opus as the send codec, we are to determine inband FEC, maximum
1892 // playback rate, and opus internal dtx.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001893 if (IsCodec(codec, kOpusCodecName)) {
1894 GetOpusConfig(codec, &send_codec, &enable_codec_fec,
Minyue Li7100dcd2015-03-27 05:05:59 +01001895 &opus_max_playback_rate, &enable_opus_dtx);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001896 }
Brave Yao5225dd82015-03-26 07:39:19 +08001897
1898 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1899 int ptime_ms = 0;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001900 if (codec.GetParam(kCodecParamPTime, &ptime_ms)) {
Brave Yao5225dd82015-03-26 07:39:19 +08001901 if (!SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
1902 LOG(LS_WARNING) << "Failed to set packet size for codec "
1903 << send_codec.plname;
1904 return false;
1905 }
1906 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001907 }
1908 found_send_codec = true;
1909 break;
1910 }
1911
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001912 if (nack_enabled_ != nack_enabled) {
1913 SetNack(channel, nack_enabled);
1914 nack_enabled_ = nack_enabled;
1915 }
1916
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001917 if (!found_send_codec) {
1918 LOG(LS_WARNING) << "Received empty list of codecs.";
1919 return false;
1920 }
1921
1922 // Set the codec immediately, since SetVADStatus() depends on whether
1923 // the current codec is mono or stereo.
1924 if (!SetSendCodec(channel, send_codec))
1925 return false;
1926
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001927 // FEC should be enabled after SetSendCodec.
1928 if (enable_codec_fec) {
1929 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
1930 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001931 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
1932 // Enable codec internal FEC. Treat any failure as fatal internal error.
1933 LOG_RTCERR2(SetFECStatus, channel, true);
1934 return false;
1935 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001936 }
1937
Minyue Li7100dcd2015-03-27 05:05:59 +01001938 if (IsCodec(send_codec, kOpusCodecName)) {
1939 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
1940 // send codec has to be Opus.
1941
1942 // Set Opus internal DTX.
1943 LOG(LS_INFO) << "Attempt to "
1944 << GetEnableString(enable_opus_dtx)
1945 << " Opus DTX on channel "
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001946 << channel;
Minyue Li7100dcd2015-03-27 05:05:59 +01001947 if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) {
1948 LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx);
1949 return false;
1950 }
1951
1952 // If opus_max_playback_rate <= 0, the default maximum playback rate
1953 // (48 kHz) will be used.
1954 if (opus_max_playback_rate > 0) {
1955 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
1956 << opus_max_playback_rate
1957 << " Hz on channel "
1958 << channel;
1959 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
1960 channel, opus_max_playback_rate) == -1) {
1961 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate);
1962 return false;
1963 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001964 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001965 }
1966
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001967 // Always update the |send_codec_| to the currently set send codec.
1968 send_codec_.reset(new webrtc::CodecInst(send_codec));
1969
minyue@webrtc.org26236952014-10-29 02:27:08 +00001970 if (send_bitrate_setting_) {
1971 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001972 }
1973
1974 // Loop through the codecs list again to config the telephone-event/CN codec.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001975 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001976 // Ignore codecs we don't know about. The negotiation step should prevent
1977 // this, but double-check to be sure.
1978 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001979 if (!engine()->FindWebRtcCodec(codec, &voe_codec)) {
1980 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001981 continue;
1982 }
1983
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001984 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
1985 // about it.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001986 if (IsCodec(codec, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001987 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001988 channel, codec.id) == -1) {
1989 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, codec.id);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001990 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001991 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001992 } else if (IsCodec(codec, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001993 // Turn voice activity detection/comfort noise on if supported.
1994 // Set the wideband CN payload type appropriately.
1995 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001996 webrtc::PayloadFrequencies cn_freq;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001997 switch (codec.clockrate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001998 case 8000:
1999 cn_freq = webrtc::kFreq8000Hz;
2000 break;
2001 case 16000:
2002 cn_freq = webrtc::kFreq16000Hz;
2003 break;
2004 case 32000:
2005 cn_freq = webrtc::kFreq32000Hz;
2006 break;
2007 default:
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002008 LOG(LS_WARNING) << "CN frequency " << codec.clockrate
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002009 << " not supported.";
2010 continue;
2011 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002012 // Set the CN payloadtype and the VAD status.
2013 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2014 if (cn_freq != webrtc::kFreq8000Hz) {
2015 if (engine()->voe()->codec()->SetSendCNPayloadType(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002016 channel, codec.id, cn_freq) == -1) {
2017 LOG_RTCERR3(SetSendCNPayloadType, channel, codec.id, cn_freq);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002018 // TODO(ajm): This failure condition will be removed from VoE.
2019 // Restore the return here when we update to a new enough webrtc.
2020 //
2021 // Not returning false because the SetSendCNPayloadType will fail if
2022 // the channel is already sending.
2023 // This can happen if the remote description is applied twice, for
2024 // example in the case of ROAP on top of JSEP, where both side will
2025 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002026 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002027 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002028 // Only turn on VAD if we have a CN payload type that matches the
2029 // clockrate for the codec we are going to use.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002030 if (codec.clockrate == send_codec.plfreq && send_codec.channels != 2) {
Minyue Li7100dcd2015-03-27 05:05:59 +01002031 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
2032 // interaction between VAD and Opus FEC.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002033 LOG(LS_INFO) << "Enabling VAD";
2034 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2035 LOG_RTCERR2(SetVADStatus, channel, true);
2036 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002037 }
2038 }
2039 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002040 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002041 return true;
2042}
2043
2044bool WebRtcVoiceMediaChannel::SetSendCodecs(
2045 const std::vector<AudioCodec>& codecs) {
2046 dtmf_allowed_ = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002047 for (const AudioCodec& codec : codecs) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002048 // Find the DTMF telephone event "codec".
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002049 if (IsCodec(codec, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002050 dtmf_allowed_ = true;
2051 }
2052 }
2053
2054 // Cache the codecs in order to configure the channel created later.
2055 send_codecs_ = codecs;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002056 for (const auto& ch : send_channels_) {
2057 if (!SetSendCodecs(ch.second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002058 return false;
2059 }
2060 }
2061
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002062 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002063 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002064 return true;
2065}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002066
2067void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2068 bool nack_enabled) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002069 for (const auto& ch : channels) {
2070 SetNack(ch.second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002071 }
2072}
2073
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002074void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002075 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002076 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002077 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2078 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002079 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002080 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2081 }
2082}
2083
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002084bool WebRtcVoiceMediaChannel::SetSendCodec(
2085 const webrtc::CodecInst& send_codec) {
2086 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2087 << ", bitrate=" << send_codec.rate;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002088 for (const auto& ch : send_channels_) {
2089 if (!SetSendCodec(ch.second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002090 return false;
2091 }
2092
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002093 return true;
2094}
2095
2096bool WebRtcVoiceMediaChannel::SetSendCodec(
2097 int channel, const webrtc::CodecInst& send_codec) {
2098 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2099 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2100
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002101 webrtc::CodecInst current_codec;
2102 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2103 (send_codec == current_codec)) {
2104 // Codec is already configured, we can return without setting it again.
2105 return true;
2106 }
2107
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002108 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2109 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002110 return false;
2111 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002112 return true;
2113}
2114
2115bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2116 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002117 if (receive_extensions_ == extensions) {
2118 return true;
2119 }
2120
2121 // The default channel may or may not be in |receive_channels_|. Set the rtp
2122 // header extensions for default channel regardless.
2123 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2124 return false;
2125 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002126
2127 // Loop through all receive channels and enable/disable the extensions.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002128 for (const auto& ch : receive_channels_) {
2129 if (!SetChannelRecvRtpHeaderExtensions(ch.second->channel(), extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002130 return false;
2131 }
2132 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002133
2134 receive_extensions_ = extensions;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002135
2136 // Recreate AudioReceiveStream:s.
2137 {
2138 std::vector<webrtc::RtpExtension> exts;
2139
2140 const RtpHeaderExtension* audio_level_extension =
2141 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2142 if (audio_level_extension) {
2143 exts.push_back({
2144 kRtpAudioLevelHeaderExtension, audio_level_extension->id});
2145 }
2146
2147 const RtpHeaderExtension* send_time_extension =
2148 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2149 if (send_time_extension) {
2150 exts.push_back({
2151 kRtpAbsoluteSenderTimeHeaderExtension, send_time_extension->id});
2152 }
2153
2154 recv_rtp_extensions_.swap(exts);
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002155 RecreateAudioReceiveStreams();
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002156 }
2157
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002158 return true;
2159}
2160
2161bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2162 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002163 const RtpHeaderExtension* audio_level_extension =
2164 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2165 if (!SetHeaderExtension(
2166 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2167 audio_level_extension)) {
2168 return false;
2169 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002170
2171 const RtpHeaderExtension* send_time_extension =
2172 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2173 if (!SetHeaderExtension(
2174 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2175 send_time_extension)) {
2176 return false;
2177 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002178
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002179 return true;
2180}
2181
2182bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2183 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002184 if (send_extensions_ == extensions) {
2185 return true;
2186 }
2187
2188 // The default channel may or may not be in |send_channels_|. Set the rtp
2189 // header extensions for default channel regardless.
2190
2191 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2192 return false;
2193 }
2194
2195 // Loop through all send channels and enable/disable the extensions.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002196 for (const auto& ch : send_channels_) {
2197 if (!SetChannelSendRtpHeaderExtensions(ch.second->channel(), extensions)) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002198 return false;
2199 }
2200 }
2201
2202 send_extensions_ = extensions;
2203 return true;
2204}
2205
2206bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2207 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002208 const RtpHeaderExtension* audio_level_extension =
2209 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002210
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002211 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002212 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002213 audio_level_extension)) {
2214 return false;
2215 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002216
2217 const RtpHeaderExtension* send_time_extension =
2218 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002219 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002220 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002221 send_time_extension)) {
2222 return false;
2223 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002224
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002225 return true;
2226}
2227
2228bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2229 desired_playout_ = playout;
2230 return ChangePlayout(desired_playout_);
2231}
2232
2233bool WebRtcVoiceMediaChannel::PausePlayout() {
2234 return ChangePlayout(false);
2235}
2236
2237bool WebRtcVoiceMediaChannel::ResumePlayout() {
2238 return ChangePlayout(desired_playout_);
2239}
2240
2241bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2242 if (playout_ == playout) {
2243 return true;
2244 }
2245
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002246 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002247 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002248 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002249 // Only toggle the default channel if we don't have any other channels.
2250 result = SetPlayout(voe_channel(), playout);
2251 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002252 for (const auto& ch : receive_channels_) {
2253 if (!SetPlayout(ch.second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002254 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002255 << ch.second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002256 result = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002257 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002258 }
2259 }
2260
2261 if (result) {
2262 playout_ = playout;
2263 }
2264 return result;
2265}
2266
2267bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2268 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002269 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002270 return ChangeSend(desired_send_);
2271 return true;
2272}
2273
2274bool WebRtcVoiceMediaChannel::PauseSend() {
2275 return ChangeSend(SEND_NOTHING);
2276}
2277
2278bool WebRtcVoiceMediaChannel::ResumeSend() {
2279 return ChangeSend(desired_send_);
2280}
2281
2282bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2283 if (send_ == send) {
2284 return true;
2285 }
2286
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002287 // Change the settings on each send channel.
2288 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002289 engine()->SetOptionOverrides(options_);
2290
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002291 // Change the settings on each send channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002292 for (const auto& ch : send_channels_) {
2293 if (!ChangeSend(ch.second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002294 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002295 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002296
2297 // Clear up the options after stopping sending.
2298 if (send == SEND_NOTHING)
2299 engine()->ClearOptionOverrides();
2300
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002301 send_ = send;
2302 return true;
2303}
2304
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002305bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2306 if (send == SEND_MICROPHONE) {
2307 if (engine()->voe()->base()->StartSend(channel) == -1) {
2308 LOG_RTCERR1(StartSend, channel);
2309 return false;
2310 }
2311 if (engine()->voe()->file() &&
2312 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2313 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2314 return false;
2315 }
2316 } else { // SEND_NOTHING
henrikg91d6ede2015-09-17 00:24:34 -07002317 RTC_DCHECK(send == SEND_NOTHING);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002318 if (engine()->voe()->base()->StopSend(channel) == -1) {
2319 LOG_RTCERR1(StopSend, channel);
2320 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002321 }
2322 }
2323
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002324 return true;
2325}
2326
solenberg1dd98f32015-09-10 01:57:14 -07002327bool WebRtcVoiceMediaChannel::SetAudioSend(uint32 ssrc, bool mute,
2328 const AudioOptions* options,
2329 AudioRenderer* renderer) {
2330 // TODO(solenberg): The state change should be fully rolled back if any one of
2331 // these calls fail.
2332 if (!SetLocalRenderer(ssrc, renderer)) {
2333 return false;
2334 }
2335 if (!MuteStream(ssrc, mute)) {
2336 return false;
2337 }
2338 if (!mute && options) {
2339 return SetOptions(*options);
2340 }
2341 return true;
2342}
2343
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002344// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002345void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2346 if (engine()->voe()->network()->RegisterExternalTransport(
2347 channel, *this) == -1) {
2348 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2349 }
2350
2351 // Enable RTCP (for quality stats and feedback messages)
2352 EnableRtcp(channel);
2353
2354 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2355 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002356
2357 // Set RTP header extension for the new channel.
2358 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002359}
2360
2361bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2362 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2363 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2364 }
2365
2366 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2367 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002368 return false;
2369 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002370
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002371 return true;
2372}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002373
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002374bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2375 // If the default channel is already used for sending create a new channel
2376 // otherwise use the default channel for sending.
2377 int channel = GetSendChannelNum(sp.first_ssrc());
2378 if (channel != -1) {
2379 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2380 return false;
2381 }
2382
2383 bool default_channel_is_available = true;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002384 for (const auto& ch : send_channels_) {
2385 if (IsDefaultChannel(ch.second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002386 default_channel_is_available = false;
2387 break;
2388 }
2389 }
2390 if (default_channel_is_available) {
2391 channel = voe_channel();
2392 } else {
2393 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002394 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002395 if (channel == -1) {
2396 LOG_RTCERR0(CreateChannel);
2397 return false;
2398 }
2399
2400 ConfigureSendChannel(channel);
2401 }
2402
2403 // Save the channel to send_channels_, so that RemoveSendStream() can still
2404 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002405 webrtc::AudioTransport* audio_transport =
2406 engine()->voe()->base()->audio_transport();
pbos8fc7fa72015-07-15 08:02:58 -07002407 send_channels_.insert(
2408 std::make_pair(sp.first_ssrc(),
2409 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002410
2411 // Set the send (local) SSRC.
2412 // If there are multiple send SSRCs, we can only set the first one here, and
2413 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2414 // (with a codec requires multiple SSRC(s)).
2415 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2416 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2417 return false;
2418 }
2419
2420 // At this point the channel's local SSRC has been updated. If the channel is
2421 // the default channel make sure that all the receive channels are updated as
2422 // well. Receive channels have to have the same SSRC as the default channel in
2423 // order to send receiver reports with this SSRC.
2424 if (IsDefaultChannel(channel)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002425 for (const auto& ch : receive_channels_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002426 // Only update the SSRC for non-default channels.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002427 if (!IsDefaultChannel(ch.second->channel())) {
2428 if (engine()->voe()->rtp()->SetLocalSSRC(ch.second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002429 sp.first_ssrc()) != 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002430 LOG_RTCERR2(SetLocalSSRC, ch.second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002431 return false;
2432 }
2433 }
2434 }
2435 }
2436
2437 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002438 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2439 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002440 }
2441
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002442 // Set the current codecs to be used for the new channel.
2443 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002444 return false;
2445
2446 return ChangeSend(channel, desired_send_);
2447}
2448
2449bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2450 ChannelMap::iterator it = send_channels_.find(ssrc);
2451 if (it == send_channels_.end()) {
2452 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2453 << " which doesn't exist.";
2454 return false;
2455 }
2456
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002457 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002458 ChangeSend(channel, SEND_NOTHING);
2459
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002460 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2461 // this will disconnect the audio renderer with the send channel.
2462 delete it->second;
2463 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002464
2465 if (IsDefaultChannel(channel)) {
2466 // Do not delete the default channel since the receive channels depend on
2467 // the default channel, recycle it instead.
2468 ChangeSend(channel, SEND_NOTHING);
2469 } else {
2470 // Clean up and delete the send channel.
2471 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2472 << " with VoiceEngine channel #" << channel << ".";
2473 if (!DeleteChannel(channel))
2474 return false;
2475 }
2476
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002477 if (send_channels_.empty())
2478 ChangeSend(SEND_NOTHING);
2479
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002480 return true;
2481}
2482
2483bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
henrikg91d6ede2015-09-17 00:24:34 -07002484 RTC_DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002485 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002486
2487 if (!VERIFY(sp.ssrcs.size() == 1))
2488 return false;
2489 uint32 ssrc = sp.first_ssrc();
2490
wu@webrtc.org78187522013-10-07 23:32:02 +00002491 if (ssrc == 0) {
2492 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2493 return false;
2494 }
2495
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002496 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2497 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002498 return false;
2499 }
2500
henrikg91d6ede2015-09-17 00:24:34 -07002501 RTC_DCHECK(receive_stream_params_.find(ssrc) == receive_stream_params_.end());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002502
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002503 // Reuse default channel for recv stream in non-conference mode call
2504 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002505 webrtc::AudioTransport* audio_transport =
2506 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002507 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002508 LOG(LS_INFO) << "Recv stream " << ssrc << " reuse default channel";
2509 default_receive_ssrc_ = ssrc;
pbos8fc7fa72015-07-15 08:02:58 -07002510 WebRtcVoiceChannelRenderer* channel_renderer =
2511 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport);
2512 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2513 receive_stream_params_[ssrc] = sp;
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002514 AddAudioReceiveStream(ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002515 return SetPlayout(voe_channel(), playout_);
2516 }
2517
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002518 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002519 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002520 if (channel == -1) {
2521 LOG_RTCERR0(CreateChannel);
2522 return false;
2523 }
2524
wu@webrtc.org78187522013-10-07 23:32:02 +00002525 if (!ConfigureRecvChannel(channel)) {
2526 DeleteChannel(channel);
2527 return false;
2528 }
2529
pbos8fc7fa72015-07-15 08:02:58 -07002530 WebRtcVoiceChannelRenderer* channel_renderer =
2531 new WebRtcVoiceChannelRenderer(channel, audio_transport);
2532 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2533 receive_stream_params_[ssrc] = sp;
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002534 AddAudioReceiveStream(ssrc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002535
2536 LOG(LS_INFO) << "New audio stream " << ssrc
2537 << " registered to VoiceEngine channel #"
2538 << channel << ".";
2539 return true;
2540}
2541
2542bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002543 // Configure to use external transport, like our default channel.
2544 if (engine()->voe()->network()->RegisterExternalTransport(
2545 channel, *this) == -1) {
2546 LOG_RTCERR2(SetExternalTransport, channel, this);
2547 return false;
2548 }
2549
2550 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002551 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002552 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2553 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002554 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002555 return false;
2556 }
2557 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002558 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002559 return false;
2560 }
2561
Minyue2013aec2015-05-13 14:14:42 +02002562 // Associate receive channel to default channel (so the receive channel can
2563 // obtain RTT from the send channel)
2564 engine()->voe()->base()->AssociateSendChannel(channel, voe_channel());
2565 LOG(LS_INFO) << "VoiceEngine channel #"
2566 << channel << " is associated with channel #"
2567 << voe_channel() << ".";
2568
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002569 // Use the same recv payload types as our default channel.
2570 ResetRecvCodecs(channel);
2571 if (!recv_codecs_.empty()) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002572 for (const auto& codec : recv_codecs_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002573 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002574 if (engine()->FindWebRtcCodec(codec, &voe_codec)) {
2575 voe_codec.pltype = codec.id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002576 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2577 if (engine()->voe()->codec()->GetRecPayloadType(
2578 voe_channel(), voe_codec) != -1) {
2579 if (engine()->voe()->codec()->SetRecPayloadType(
2580 channel, voe_codec) == -1) {
2581 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2582 return false;
2583 }
2584 }
2585 }
2586 }
2587 }
2588
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002589 if (InConferenceMode()) {
2590 // To be in par with the video, voe_channel() is not used for receiving in
2591 // a conference call.
2592 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2593 // This is the first stream in a multi user meeting. We can now
2594 // disable playback of the default stream. This since the default
2595 // stream will probably have received some initial packets before
2596 // the new stream was added. This will mean that the CN state from
2597 // the default channel will be mixed in with the other streams
2598 // throughout the whole meeting, which might be disturbing.
2599 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2600 SetPlayout(voe_channel(), false);
2601 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002602 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002603 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002604
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002605 // Set RTP header extension for the new channel.
2606 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2607 return false;
2608 }
2609
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002610 return SetPlayout(channel, playout_);
2611}
2612
2613bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
henrikg91d6ede2015-09-17 00:24:34 -07002614 RTC_DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002615 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002616 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002617 if (it == receive_channels_.end()) {
2618 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2619 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002620 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002621 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002622
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002623 RemoveAudioReceiveStream(ssrc);
pbos8fc7fa72015-07-15 08:02:58 -07002624 receive_stream_params_.erase(ssrc);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002625
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002626 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2627 // will disconnect the audio renderer with the receive channel.
2628 // Cache the channel before the deletion.
2629 const int channel = it->second->channel();
2630 delete it->second;
2631 receive_channels_.erase(it);
2632
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002633 if (ssrc == default_receive_ssrc_) {
henrikg91d6ede2015-09-17 00:24:34 -07002634 RTC_DCHECK(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002635 // Recycle the default channel is for recv stream.
2636 if (playout_)
2637 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002638
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002639 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002640 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002641 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002642
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002643 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002644 << " with VoiceEngine channel #" << channel << ".";
2645 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002646 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002647
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002648 bool enable_default_channel_playout = false;
2649 if (receive_channels_.empty()) {
2650 // The last stream was removed. We can now enable the default
2651 // channel for new channels to be played out immediately without
2652 // waiting for AddStream messages.
2653 // We do this for both conference mode and non-conference mode.
2654 // TODO(oja): Does the default channel still have it's CN state?
2655 enable_default_channel_playout = true;
2656 }
2657 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2658 default_receive_ssrc_ != 0) {
2659 // Only the default channel is active, enable the playout on default
2660 // channel.
2661 enable_default_channel_playout = true;
2662 }
2663 if (enable_default_channel_playout && playout_) {
2664 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2665 SetPlayout(voe_channel(), true);
2666 }
2667
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002668 return true;
2669}
2670
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002671bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2672 AudioRenderer* renderer) {
2673 ChannelMap::iterator it = receive_channels_.find(ssrc);
2674 if (it == receive_channels_.end()) {
2675 if (renderer) {
2676 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002677 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002678 return false;
2679 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002680
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002681 // The channel likely has gone away, do nothing.
2682 return true;
2683 }
2684
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002685 if (renderer)
2686 it->second->Start(renderer);
2687 else
2688 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002689
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002690 return true;
2691}
2692
2693bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2694 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002695 ChannelMap::iterator it = send_channels_.find(ssrc);
2696 if (it == send_channels_.end()) {
2697 if (renderer) {
2698 // Return an error if trying to set a valid renderer with an invalid ssrc.
2699 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2700 return false;
2701 }
2702
2703 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002704 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002705 }
2706
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002707 if (renderer)
2708 it->second->Start(renderer);
2709 else
2710 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002711
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002712 return true;
2713}
2714
2715bool WebRtcVoiceMediaChannel::GetActiveStreams(
2716 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002717 // In conference mode, the default channel should not be in
2718 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002719 actives->clear();
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002720 for (const auto& ch : receive_channels_) {
2721 int level = GetOutputLevel(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002722 if (level > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002723 actives->push_back(std::make_pair(ch.first, level));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002724 }
2725 }
2726 return true;
2727}
2728
2729int WebRtcVoiceMediaChannel::GetOutputLevel() {
2730 // return the highest output level of all streams
2731 int highest = GetOutputLevel(voe_channel());
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002732 for (const auto& ch : receive_channels_) {
2733 int level = GetOutputLevel(ch.second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002734 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002735 }
2736 return highest;
2737}
2738
2739int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2740 int ret;
2741 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2742 // In case of error, log the info and continue
2743 LOG_RTCERR0(TimeSinceLastTyping);
2744 ret = -1;
2745 } else {
2746 ret *= 1000; // We return ms, webrtc returns seconds.
2747 }
2748 return ret;
2749}
2750
2751void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2752 int cost_per_typing, int reporting_threshold, int penalty_decay,
2753 int type_event_delay) {
2754 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2755 time_window, cost_per_typing,
2756 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2757 // In case of error, log the info and continue
2758 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2759 cost_per_typing, reporting_threshold, penalty_decay,
2760 type_event_delay);
2761 }
2762}
2763
2764bool WebRtcVoiceMediaChannel::SetOutputScaling(
2765 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002766 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002767 // Collect the channels to scale the output volume.
2768 std::vector<int> channels;
2769 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002770 // Default channel is not in receive_channels_ if it is not being used for
2771 // playout.
2772 if (default_receive_ssrc_ == 0)
2773 channels.push_back(voe_channel());
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002774 for (const auto& ch : receive_channels_) {
2775 channels.push_back(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002776 }
2777 } else { // Collect only the channel of the specified ssrc.
2778 int channel = GetReceiveChannelNum(ssrc);
2779 if (-1 == channel) {
2780 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2781 return false;
2782 }
2783 channels.push_back(channel);
2784 }
2785
2786 // Scale the output volume for the collected channels. We first normalize to
2787 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002788 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002789 if (scale > 0.0001f) {
2790 left /= scale;
2791 right /= scale;
2792 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002793 for (int ch_id : channels) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002794 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002795 ch_id, scale)) {
2796 LOG_RTCERR2(SetChannelOutputVolumeScaling, ch_id, scale);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002797 return false;
2798 }
2799 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002800 ch_id, static_cast<float>(left), static_cast<float>(right))) {
2801 LOG_RTCERR3(SetOutputVolumePan, ch_id, left, right);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002802 // Do not return if fails. SetOutputVolumePan is not available for all
2803 // pltforms.
2804 }
2805 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2806 << " right=" << right * scale
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002807 << " for channel " << ch_id << " and ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002808 }
2809 return true;
2810}
2811
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002812bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2813 return dtmf_allowed_;
2814}
2815
2816bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2817 int duration, int flags) {
2818 if (!dtmf_allowed_) {
2819 return false;
2820 }
2821
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002822 // Send the event.
2823 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002824 int channel = -1;
2825 if (ssrc == 0) {
2826 bool default_channel_is_inuse = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002827 for (const auto& ch : send_channels_) {
2828 if (IsDefaultChannel(ch.second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002829 default_channel_is_inuse = true;
2830 break;
2831 }
2832 }
2833 if (default_channel_is_inuse) {
2834 channel = voe_channel();
2835 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002836 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002837 }
2838 } else {
2839 channel = GetSendChannelNum(ssrc);
2840 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002841 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002842 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2843 << ssrc << " is not in use.";
2844 return false;
2845 }
2846 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002847 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2848 channel, event, true, duration) == -1) {
2849 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002850 return false;
2851 }
2852 }
2853
2854 // Play the event.
2855 if (flags & cricket::DF_PLAY) {
2856 // Play DTMF tone locally.
2857 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
2858 LOG_RTCERR2(PlayDtmfTone, event, duration);
2859 return false;
2860 }
2861 }
2862
2863 return true;
2864}
2865
wu@webrtc.orga9890802013-12-13 00:21:03 +00002866void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002867 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrikg91d6ede2015-09-17 00:24:34 -07002868 RTC_DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002869
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002870 // Forward packet to Call as well.
2871 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2872 packet_time.not_before);
2873 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
2874 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
2875 webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002876
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002877 // Pick which channel to send this packet to. If this packet doesn't match
2878 // any multiplexed streams, just send it to the default channel. Otherwise,
2879 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002880 int which_channel =
2881 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002882 if (which_channel == -1) {
2883 which_channel = voe_channel();
2884 }
2885
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002886 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00002887 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002888 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002889 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002890}
2891
wu@webrtc.orga9890802013-12-13 00:21:03 +00002892void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002893 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrikg91d6ede2015-09-17 00:24:34 -07002894 RTC_DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002895
Fredrik Solenberg709ed672015-09-15 12:26:33 +02002896 // Forward packet to Call as well.
2897 const webrtc::PacketTime webrtc_packet_time(packet_time.timestamp,
2898 packet_time.not_before);
2899 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
2900 reinterpret_cast<const uint8_t*>(packet->data()), packet->size(),
2901 webrtc_packet_time);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002902
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002903 // Sending channels need all RTCP packets with feedback information.
2904 // Even sender reports can contain attached report blocks.
2905 // Receiving channels need sender reports in order to create
2906 // correct receiver reports.
2907 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002908 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002909 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2910 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002911 }
2912
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002913 // If it is a sender report, find the channel that is listening.
2914 bool has_sent_to_default_channel = false;
2915 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002916 int which_channel =
2917 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002918 if (which_channel != -1) {
2919 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002920 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002921
2922 if (IsDefaultChannel(which_channel))
2923 has_sent_to_default_channel = true;
2924 }
2925 }
2926
2927 // SR may continue RR and any RR entry may correspond to any one of the send
2928 // channels. So all RTCP packets must be forwarded all send channels. VoE
2929 // will filter out RR internally.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002930 for (const auto& ch : send_channels_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002931 // Make sure not sending the same packet to default channel more than once.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002932 if (IsDefaultChannel(ch.second->channel()) &&
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002933 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002934 continue;
2935
2936 engine()->voe()->network()->ReceivedRTCPPacket(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002937 ch.second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002938 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002939}
2940
2941bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002942 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
2943 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002944 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2945 return false;
2946 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002947 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
2948 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002949 return false;
2950 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002951 // We set the AGC to mute state only when all the channels are muted.
2952 // This implementation is not ideal, instead we should signal the AGC when
2953 // the mic channel is muted/unmuted. We can't do it today because there
2954 // is no good way to know which stream is mapping to the mic channel.
2955 bool all_muted = muted;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002956 for (const auto& ch : send_channels_) {
2957 if (!all_muted) {
2958 break;
2959 }
2960 if (engine()->voe()->volume()->GetInputMute(ch.second->channel(),
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002961 all_muted)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002962 LOG_RTCERR1(GetInputMute, ch.second->channel());
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00002963 return false;
2964 }
2965 }
2966
2967 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
2968 if (ap)
2969 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002970 return true;
2971}
2972
minyue@webrtc.org26236952014-10-29 02:27:08 +00002973// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
2974// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002975bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002976 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002977
minyue@webrtc.org26236952014-10-29 02:27:08 +00002978 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002979}
2980
minyue@webrtc.org26236952014-10-29 02:27:08 +00002981bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
2982 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002983
minyue@webrtc.org26236952014-10-29 02:27:08 +00002984 send_bitrate_setting_ = true;
2985 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002986
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002987 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002988 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002989 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002990 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002991 }
2992
minyue@webrtc.org26236952014-10-29 02:27:08 +00002993 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00002994 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
2995 // SetMaxSendBandwith(0), the second call removes the previous limit.
2996 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002997 return true;
2998
2999 webrtc::CodecInst codec = *send_codec_;
3000 bool is_multi_rate = IsCodecMultiRate(codec);
3001
3002 if (is_multi_rate) {
3003 // If codec is multi-rate then just set the bitrate.
3004 codec.rate = bps;
3005 if (!SetSendCodec(codec)) {
3006 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3007 << " to bitrate " << bps << " bps.";
3008 return false;
3009 }
3010 return true;
3011 } else {
3012 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3013 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3014 // fixed bitrate then ignore.
3015 if (bps < codec.rate) {
3016 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3017 << " to bitrate " << bps << " bps"
3018 << ", requires at least " << codec.rate << " bps.";
3019 return false;
3020 }
3021 return true;
3022 }
3023}
3024
3025bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003026 bool echo_metrics_on = false;
3027 // These can take on valid negative values, so use the lowest possible level
3028 // as default rather than -1.
3029 int echo_return_loss = -100;
3030 int echo_return_loss_enhancement = -100;
3031 // These can also be negative, but in practice -1 is only used to signal
3032 // insufficient data, since the resolution is limited to multiples of 4 ms.
3033 int echo_delay_median_ms = -1;
3034 int echo_delay_std_ms = -1;
3035 if (engine()->voe()->processing()->GetEcMetricsStatus(
3036 echo_metrics_on) != -1 && echo_metrics_on) {
3037 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3038 // here, but it appears to be unsuitable currently. Revisit after this is
3039 // investigated: http://b/issue?id=5666755
3040 int erl, erle, rerl, anlp;
3041 if (engine()->voe()->processing()->GetEchoMetrics(
3042 erl, erle, rerl, anlp) != -1) {
3043 echo_return_loss = erl;
3044 echo_return_loss_enhancement = erle;
3045 }
3046
3047 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003048 float dummy;
3049 if (engine()->voe()->processing()->GetEcDelayMetrics(
3050 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003051 echo_delay_median_ms = median;
3052 echo_delay_std_ms = std;
3053 }
3054 }
3055
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003056 webrtc::CallStatistics cs;
3057 unsigned int ssrc;
3058 webrtc::CodecInst codec;
3059 unsigned int level;
3060
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003061 for (const auto& ch : send_channels_) {
3062 const int channel = ch.second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003063
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003064 // Fill in the sender info, based on what we know, and what the
3065 // remote side told us it got from its RTCP report.
3066 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003067
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003068 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3069 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3070 continue;
3071 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003072
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003073 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003074 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3075 sinfo.bytes_sent = cs.bytesSent;
3076 sinfo.packets_sent = cs.packetsSent;
3077 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3078 // returns 0 to indicate an error value.
3079 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3080
3081 // Get data from the last remote RTCP report. Use default values if no data
3082 // available.
3083 sinfo.fraction_lost = -1.0;
3084 sinfo.jitter_ms = -1;
3085 sinfo.packets_lost = -1;
3086 sinfo.ext_seqnum = -1;
3087 std::vector<webrtc::ReportBlock> receive_blocks;
3088 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3089 channel, &receive_blocks) != -1 &&
3090 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003091 for (const webrtc::ReportBlock& block : receive_blocks) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003092 // Lookup report for send ssrc only.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003093 if (block.source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003094 // Convert Q8 to floating point.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003095 sinfo.fraction_lost = static_cast<float>(block.fraction_lost) / 256;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003096 // Convert samples to milliseconds.
3097 if (codec.plfreq / 1000 > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003098 sinfo.jitter_ms = block.interarrival_jitter / (codec.plfreq / 1000);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003099 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003100 sinfo.packets_lost = block.cumulative_num_packets_lost;
3101 sinfo.ext_seqnum = block.extended_highest_sequence_number;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003102 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003103 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003104 }
3105 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003106
3107 // Local speech level.
3108 sinfo.audio_level = (engine()->voe()->volume()->
3109 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3110
3111 // TODO(xians): We are injecting the same APM logging to all the send
3112 // channels here because there is no good way to know which send channel
3113 // is using the APM. The correct fix is to allow the send channels to have
3114 // their own APM so that we can feed the correct APM logging to different
3115 // send channels. See issue crbug/264611 .
3116 sinfo.echo_return_loss = echo_return_loss;
3117 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3118 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3119 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003120 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3121 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003122 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003123
3124 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003125 }
3126
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003127 // Build the list of receivers, one for each receiving channel, or 1 in
3128 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003129 std::vector<int> channels;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003130 for (const auto& ch : receive_channels_) {
3131 channels.push_back(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003132 }
3133 if (channels.empty()) {
3134 channels.push_back(voe_channel());
3135 }
3136
3137 // Get the SSRC and stats for each receiver, based on our own calculations.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003138 for (int ch_id : channels) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003139 memset(&cs, 0, sizeof(cs));
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003140 if (engine()->voe()->rtp()->GetRemoteSSRC(ch_id, ssrc) != -1 &&
3141 engine()->voe()->rtp()->GetRTCPStatistics(ch_id, cs) != -1 &&
3142 engine()->voe()->codec()->GetRecCodec(ch_id, codec) != -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003143 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003144 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003145 rinfo.bytes_rcvd = cs.bytesReceived;
3146 rinfo.packets_rcvd = cs.packetsReceived;
3147 // The next four fields are from the most recently sent RTCP report.
3148 // Convert Q8 to floating point.
3149 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3150 rinfo.packets_lost = cs.cumulativeLost;
3151 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003152 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003153 if (codec.pltype != -1) {
3154 rinfo.codec_name = codec.plname;
3155 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003156 // Convert samples to milliseconds.
3157 if (codec.plfreq / 1000 > 0) {
3158 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3159 }
3160
3161 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3162 webrtc::NetworkStatistics ns;
3163 if (engine()->voe()->neteq() &&
3164 engine()->voe()->neteq()->GetNetworkStatistics(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003165 ch_id, ns) != -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003166 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3167 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3168 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003169 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003170 rinfo.speech_expand_rate =
3171 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3172 rinfo.secondary_decoded_rate =
3173 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
Henrik Lundin8e6fd462015-06-02 09:24:52 +02003174 rinfo.accelerate_rate =
3175 static_cast<float>(ns.currentAccelerateRate) / (1 << 14);
3176 rinfo.preemptive_expand_rate =
3177 static_cast<float>(ns.currentPreemptiveRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003178 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003179
3180 webrtc::AudioDecodingCallStats ds;
3181 if (engine()->voe()->neteq() &&
3182 engine()->voe()->neteq()->GetDecodingCallStatistics(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003183 ch_id, &ds) != -1) {
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003184 rinfo.decoding_calls_to_silence_generator =
3185 ds.calls_to_silence_generator;
3186 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3187 rinfo.decoding_normal = ds.decoded_normal;
3188 rinfo.decoding_plc = ds.decoded_plc;
3189 rinfo.decoding_cng = ds.decoded_cng;
3190 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3191 }
3192
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003193 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003194 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003195 int playout_buffer_delay_ms = 0;
3196 engine()->voe()->sync()->GetDelayEstimate(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003197 ch_id, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003198 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3199 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003200 }
3201
3202 // Get speech level.
3203 rinfo.audio_level = (engine()->voe()->volume()->
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003204 GetSpeechOutputLevelFullRange(ch_id, level) != -1) ? level : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003205 info->receivers.push_back(rinfo);
3206 }
3207 }
3208
3209 return true;
3210}
3211
3212void WebRtcVoiceMediaChannel::GetLastMediaError(
3213 uint32* ssrc, VoiceMediaChannel::Error* error) {
henrikg91d6ede2015-09-17 00:24:34 -07003214 RTC_DCHECK(ssrc != NULL);
3215 RTC_DCHECK(error != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003216 FindSsrc(voe_channel(), ssrc);
3217 *error = WebRtcErrorToChannelError(GetLastEngineError());
3218}
3219
3220bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003221 rtc::CritScope lock(&receive_channels_cs_);
henrikg91d6ede2015-09-17 00:24:34 -07003222 RTC_DCHECK(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003223 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003224 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3225 // This means the error is not limited to a specific channel. Signal the
3226 // message using ssrc=0. If the current channel is sending, use this
3227 // channel for sending the message.
3228 *ssrc = 0;
3229 return true;
3230 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003231 // Check whether this is a sending channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003232 for (const auto& ch : send_channels_) {
3233 if (ch.second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003234 // This is a sending channel.
3235 uint32 local_ssrc = 0;
3236 if (engine()->voe()->rtp()->GetLocalSSRC(
3237 channel_num, local_ssrc) != -1) {
3238 *ssrc = local_ssrc;
3239 }
3240 return true;
3241 }
3242 }
3243
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003244 // Check whether this is a receiving channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003245 for (const auto& ch : receive_channels_) {
3246 if (ch.second->channel() == channel_num) {
3247 *ssrc = ch.first;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003248 return true;
3249 }
3250 }
3251 }
3252 return false;
3253}
3254
3255void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003256 if (error == VE_TYPING_NOISE_WARNING) {
3257 typing_noise_detected_ = true;
3258 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3259 typing_noise_detected_ = false;
3260 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003261 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3262}
3263
3264int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3265 unsigned int ulevel;
3266 int ret =
3267 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3268 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3269}
3270
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003271int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) const {
3272 ChannelMap::const_iterator it = receive_channels_.find(ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003273 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003274 return it->second->channel();
pbos8fc7fa72015-07-15 08:02:58 -07003275 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003276}
3277
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003278int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) const {
3279 ChannelMap::const_iterator it = send_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003280 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003281 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003282
3283 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003284}
3285
3286bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3287 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3288 // Get the RED encodings from the parameter with no name. This may
3289 // change based on what is discussed on the Jingle list.
3290 // The encoding parameter is of the form "a/b"; we only support where
3291 // a == b. Verify this and parse out the value into red_pt.
3292 // If the parameter value is absent (as it will be until we wire up the
3293 // signaling of this message), use the second codec specified (i.e. the
3294 // one after "red") as the encoding parameter.
3295 int red_pt = -1;
3296 std::string red_params;
3297 CodecParameterMap::const_iterator it = red_codec.params.find("");
3298 if (it != red_codec.params.end()) {
3299 red_params = it->second;
3300 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003301 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003302 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003303 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003304 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3305 return false;
3306 }
3307 } else if (red_codec.params.empty()) {
3308 LOG(LS_WARNING) << "RED params not present, using defaults";
3309 if (all_codecs.size() > 1) {
3310 red_pt = all_codecs[1].id;
3311 }
3312 }
3313
3314 // Try to find red_pt in |codecs|.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003315 for (const AudioCodec& codec : all_codecs) {
3316 if (codec.id == red_pt) {
3317 // If we find the right codec, that will be the codec we pass to
3318 // SetSendCodec, with the desired payload type.
3319 if (engine()->FindWebRtcCodec(codec, send_codec)) {
3320 return true;
3321 } else {
3322 break;
3323 }
3324 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003325 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003326 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3327 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003328}
3329
3330bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3331 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003332 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003333 return false;
3334 }
3335 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3336 // what we want to do with them.
3337 // engine()->voe().EnableVQMon(voe_channel(), true);
3338 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3339 return true;
3340}
3341
3342bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3343 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3344 for (int i = 0; i < ncodecs; ++i) {
3345 webrtc::CodecInst voe_codec;
3346 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3347 voe_codec.pltype = -1;
3348 if (engine()->voe()->codec()->SetRecPayloadType(
3349 channel, voe_codec) == -1) {
3350 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3351 return false;
3352 }
3353 }
3354 }
3355 return true;
3356}
3357
3358bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3359 if (playout) {
3360 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3361 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3362 LOG_RTCERR1(StartPlayout, channel);
3363 return false;
3364 }
3365 } else {
3366 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3367 engine()->voe()->base()->StopPlayout(channel);
3368 }
3369 return true;
3370}
3371
3372uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3373 bool rtcp) {
3374 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3375 uint32 ssrc = 0;
3376 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003377 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003378 }
3379 return ssrc;
3380}
3381
3382// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3383VoiceMediaChannel::Error
3384 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3385 switch (err_code) {
3386 case 0:
3387 return ERROR_NONE;
3388 case VE_CANNOT_START_RECORDING:
3389 case VE_MIC_VOL_ERROR:
3390 case VE_GET_MIC_VOL_ERROR:
3391 case VE_CANNOT_ACCESS_MIC_VOL:
3392 return ERROR_REC_DEVICE_OPEN_FAILED;
3393 case VE_SATURATION_WARNING:
3394 return ERROR_REC_DEVICE_SATURATION;
3395 case VE_REC_DEVICE_REMOVED:
3396 return ERROR_REC_DEVICE_REMOVED;
3397 case VE_RUNTIME_REC_WARNING:
3398 case VE_RUNTIME_REC_ERROR:
3399 return ERROR_REC_RUNTIME_ERROR;
3400 case VE_CANNOT_START_PLAYOUT:
3401 case VE_SPEAKER_VOL_ERROR:
3402 case VE_GET_SPEAKER_VOL_ERROR:
3403 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3404 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3405 case VE_RUNTIME_PLAY_WARNING:
3406 case VE_RUNTIME_PLAY_ERROR:
3407 return ERROR_PLAY_RUNTIME_ERROR;
3408 case VE_TYPING_NOISE_WARNING:
3409 return ERROR_REC_TYPING_NOISE_DETECTED;
3410 default:
3411 return VoiceMediaChannel::ERROR_OTHER;
3412 }
3413}
3414
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003415bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3416 int channel_id, const RtpHeaderExtension* extension) {
3417 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003418 int id = 0;
3419 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003420 if (extension) {
3421 enable = true;
3422 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003423 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003424 }
3425 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003426 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003427 return false;
3428 }
3429 return true;
3430}
3431
Fredrik Solenberg709ed672015-09-15 12:26:33 +02003432void WebRtcVoiceMediaChannel::RecreateAudioReceiveStreams() {
henrikg91d6ede2015-09-17 00:24:34 -07003433 RTC_DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg709ed672015-09-15 12:26:33 +02003434 for (const auto& it : receive_channels_) {
3435 RemoveAudioReceiveStream(it.first);
3436 }
3437 for (const auto& it : receive_channels_) {
3438 AddAudioReceiveStream(it.first);
3439 }
3440}
3441
3442void WebRtcVoiceMediaChannel::AddAudioReceiveStream(uint32 ssrc) {
henrikg91d6ede2015-09-17 00:24:34 -07003443 RTC_DCHECK(thread_checker_.CalledOnValidThread());
pbos8fc7fa72015-07-15 08:02:58 -07003444 WebRtcVoiceChannelRenderer* channel = receive_channels_[ssrc];
henrikg91d6ede2015-09-17 00:24:34 -07003445 RTC_DCHECK(channel != nullptr);
3446 RTC_DCHECK(receive_streams_.find(ssrc) == receive_streams_.end());
pbos8fc7fa72015-07-15 08:02:58 -07003447 webrtc::AudioReceiveStream::Config config;
3448 config.rtp.remote_ssrc = ssrc;
3449 // Only add RTP extensions if we support combined A/V BWE.
pbos6bb1b6e2015-07-24 07:10:18 -07003450 config.rtp.extensions = recv_rtp_extensions_;
3451 config.combined_audio_video_bwe =
3452 options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false);
pbos8fc7fa72015-07-15 08:02:58 -07003453 config.voe_channel_id = channel->channel();
3454 config.sync_group = receive_stream_params_[ssrc].sync_label;
3455 webrtc::AudioReceiveStream* s = call_->CreateAudioReceiveStream(config);
3456 receive_streams_.insert(std::make_pair(ssrc, s));
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003457}
3458
Fredrik Solenberg709ed672015-09-15 12:26:33 +02003459void WebRtcVoiceMediaChannel::RemoveAudioReceiveStream(uint32 ssrc) {
henrikg91d6ede2015-09-17 00:24:34 -07003460 RTC_DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg709ed672015-09-15 12:26:33 +02003461 auto stream_it = receive_streams_.find(ssrc);
3462 if (stream_it != receive_streams_.end()) {
3463 call_->DestroyAudioReceiveStream(stream_it->second);
3464 receive_streams_.erase(stream_it);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003465 }
3466}
3467
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003468bool WebRtcVoiceMediaChannel::SetRecvCodecsInternal(
3469 const std::vector<AudioCodec>& new_codecs) {
3470 for (const AudioCodec& codec : new_codecs) {
3471 webrtc::CodecInst voe_codec;
3472 if (engine()->FindWebRtcCodec(codec, &voe_codec)) {
3473 LOG(LS_INFO) << ToString(codec);
3474 voe_codec.pltype = codec.id;
3475 if (default_receive_ssrc_ == 0) {
3476 // Set the receive codecs on the default channel explicitly if the
3477 // default channel is not used by |receive_channels_|, this happens in
3478 // conference mode or in non-conference mode when there is no playout
3479 // channel.
3480 // TODO(xians): Figure out how we use the default channel in conference
3481 // mode.
3482 if (engine()->voe()->codec()->SetRecPayloadType(
3483 voe_channel(), voe_codec) == -1) {
3484 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
3485 return false;
3486 }
3487 }
3488
3489 // Set the receive codecs on all receiving channels.
3490 for (const auto& ch : receive_channels_) {
3491 if (engine()->voe()->codec()->SetRecPayloadType(
3492 ch.second->channel(), voe_codec) == -1) {
3493 LOG_RTCERR2(SetRecPayloadType, ch.second->channel(),
3494 ToString(voe_codec));
3495 return false;
3496 }
3497 }
3498 } else {
3499 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
3500 return false;
3501 }
3502 }
3503 return true;
3504}
3505
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003506} // namespace cricket
3507
3508#endif // HAVE_WEBRTC_VOICE