blob: 391052b8d4d6f0b309586d609ffb97e9ede17438 [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
57#ifdef WIN32
58#include <objbase.h> // NOLINT
59#endif
60
61namespace cricket {
62
Brave Yao5225dd82015-03-26 07:39:19 +080063static const int kMaxNumPacketSize = 6;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064struct CodecPref {
65 const char* name;
66 int clockrate;
67 int channels;
68 int payload_type;
69 bool is_multi_rate;
Brave Yao5225dd82015-03-26 07:39:19 +080070 int packet_sizes_ms[kMaxNumPacketSize];
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071};
Brave Yao5225dd82015-03-26 07:39:19 +080072// Note: keep the supported packet sizes in ascending order.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073static const CodecPref kCodecPrefs[] = {
Brave Yao5225dd82015-03-26 07:39:19 +080074 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
75 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
76 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +000077 // G722 should be advertised as 8000 Hz because of the RFC "bug".
Brave Yao5225dd82015-03-26 07:39:19 +080078 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
79 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
80 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
81 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
Brave Yao5225dd82015-03-26 07:39:19 +080082 { kCnCodecName, 32000, 1, 106, false, { } },
83 { kCnCodecName, 16000, 1, 105, false, { } },
84 { kCnCodecName, 8000, 1, 13, false, { } },
85 { kRedCodecName, 8000, 1, 127, false, { } },
86 { kDtmfCodecName, 8000, 1, 126, false, { } },
henrike@webrtc.org28e20752013-07-10 00:45:36 +000087};
88
89// For Linux/Mac, using the default device is done by specifying index 0 for
90// VoE 4.0 and not -1 (which was the case for VoE 3.5).
91//
92// On Windows Vista and newer, Microsoft introduced the concept of "Default
93// Communications Device". This means that there are two types of default
94// devices (old Wave Audio style default and Default Communications Device).
95//
96// On Windows systems which only support Wave Audio style default, uses either
97// -1 or 0 to select the default device.
98//
99// On Windows systems which support both "Default Communication Device" and
100// old Wave Audio style default, use -1 for Default Communications Device and
101// -2 for Wave Audio style default, which is what we want to use for clips.
102// It's not clear yet whether the -2 index is handled properly on other OSes.
103
104#ifdef WIN32
105static const int kDefaultAudioDeviceId = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106#else
107static const int kDefaultAudioDeviceId = 0;
108#endif
109
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110// Parameter used for NACK.
111// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
112static const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000113
114// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000115// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000116
117// Recommended bitrates:
118// 8-12 kb/s for NB speech,
119// 16-20 kb/s for WB speech,
120// 28-40 kb/s for FB speech,
121// 48-64 kb/s for FB mono music, and
122// 64-128 kb/s for FB stereo music.
123// The current implementation applies the following values to mono signals,
124// and multiplies them by 2 for stereo.
125static const int kOpusBitrateNb = 12000;
126static const int kOpusBitrateWb = 20000;
127static const int kOpusBitrateFb = 32000;
128
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000129// Opus bitrate should be in the range between 6000 and 510000.
130static const int kOpusMinBitrate = 6000;
131static const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000132
wu@webrtc.orgde305012013-10-31 15:40:38 +0000133// Default audio dscp value.
134// See http://tools.ietf.org/html/rfc2474 for details.
135// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000136static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000137
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000138// Ensure we open the file in a writeable path on ChromeOS and Android. This
139// workaround can be removed when it's possible to specify a filename for audio
140// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000141//
142// TODO(grunell): Use a string in the options instead of hardcoding it here
143// and let the embedder choose the filename (crbug.com/264223).
144//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000145// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
146// below.
147#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000148static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000149#elif defined(ANDROID)
150static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000151#else
152static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
153#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000154
155// Dumps an AudioCodec in RFC 2327-ish format.
156static std::string ToString(const AudioCodec& codec) {
157 std::stringstream ss;
158 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
159 << " (" << codec.id << ")";
160 return ss.str();
161}
Minyue Li7100dcd2015-03-27 05:05:59 +0100162
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000163static std::string ToString(const webrtc::CodecInst& codec) {
164 std::stringstream ss;
165 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
166 << " (" << codec.pltype << ")";
167 return ss.str();
168}
169
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000170static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000171 const char* delim = "\r\n";
172 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
173 LOG_V(sev) << tok;
174 }
175}
176
177// Severity is an integer because it comes is assumed to be from command line.
178static int SeverityToFilter(int severity) {
179 int filter = webrtc::kTraceNone;
180 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000181 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000182 filter |= webrtc::kTraceAll;
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200183 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000184 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000185 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200186 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000187 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000188 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200189 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000190 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000191 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
192 }
193 return filter;
194}
195
Minyue Li7100dcd2015-03-27 05:05:59 +0100196static bool IsCodec(const AudioCodec& codec, const char* ref_name) {
197 return (_stricmp(codec.name.c_str(), ref_name) == 0);
198}
199
200static bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
201 return (_stricmp(codec.plname, ref_name) == 0);
202}
203
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000204static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
205 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100206 if (IsCodec(codec, kCodecPrefs[i].name) &&
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000207 kCodecPrefs[i].clockrate == codec.plfreq) {
208 return kCodecPrefs[i].is_multi_rate;
209 }
210 }
211 return false;
212}
213
214static bool FindCodec(const std::vector<AudioCodec>& codecs,
215 const AudioCodec& codec,
216 AudioCodec* found_codec) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200217 for (const AudioCodec& c : codecs) {
218 if (c.Matches(codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000219 if (found_codec != NULL) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200220 *found_codec = c;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000221 }
222 return true;
223 }
224 }
225 return false;
226}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000227
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000228static bool IsNackEnabled(const AudioCodec& codec) {
229 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
230 kParamValueEmpty));
231}
232
Brave Yao5225dd82015-03-26 07:39:19 +0800233static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
234 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
235 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
236 if (packet_size_ms && packet_size_ms <= ptime_ms) {
237 selected_packet_size_ms = packet_size_ms;
238 }
239 }
240 return selected_packet_size_ms;
241}
242
243// If the AudioCodec param kCodecParamPTime is set, then we will set it to codec
244// pacsize if it's valid, or we will pick the next smallest value we support.
245// TODO(Brave): Query supported packet sizes from ACM when the API is ready.
246static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
247 for (const CodecPref& codec_pref : kCodecPrefs) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100248 if ((IsCodec(*codec, codec_pref.name) &&
Brave Yao5225dd82015-03-26 07:39:19 +0800249 codec_pref.clockrate == codec->plfreq) ||
Minyue Li7100dcd2015-03-27 05:05:59 +0100250 IsCodec(*codec, kG722CodecName)) {
Brave Yao5225dd82015-03-26 07:39:19 +0800251 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
252 if (packet_size_ms) {
253 // Convert unit from milli-seconds to samples.
254 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
255 return true;
256 }
257 }
258 }
259 return false;
260}
261
Minyue Li7100dcd2015-03-27 05:05:59 +0100262// Return true if codec.params[feature] == "1", false otherwise.
263static bool IsCodecFeatureEnabled(const AudioCodec& codec,
264 const char* feature) {
265 int value;
266 return codec.GetParam(feature, &value) && value == 1;
267}
268
269// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
270// otherwise. If the value (either from params or codec.bitrate) <=0, use the
271// default configuration. If the value is beyond feasible bit rate of Opus,
272// clamp it. Returns the Opus bit rate for operation.
273static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
274 int bitrate = 0;
275 bool use_param = true;
276 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
277 bitrate = codec.bitrate;
278 use_param = false;
279 }
280 if (bitrate <= 0) {
281 if (max_playback_rate <= 8000) {
282 bitrate = kOpusBitrateNb;
283 } else if (max_playback_rate <= 16000) {
284 bitrate = kOpusBitrateWb;
285 } else {
286 bitrate = kOpusBitrateFb;
287 }
288
289 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
290 bitrate *= 2;
291 }
292 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
293 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
294 std::string rate_source =
295 use_param ? "Codec parameter \"maxaveragebitrate\"" :
296 "Supplied Opus bitrate";
297 LOG(LS_WARNING) << rate_source
298 << " is invalid and is replaced by: "
299 << bitrate;
300 }
301 return bitrate;
302}
303
304// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
305// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
306static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
307 int value;
308 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
309 return value;
310 }
311 return kOpusDefaultMaxPlaybackRate;
312}
313
314static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
315 bool* enable_codec_fec, int* max_playback_rate,
316 bool* enable_codec_dtx) {
317 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
318 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
319 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
320
321 // If OPUS, change what we send according to the "stereo" codec
322 // parameter, and not the "channels" parameter. We set
323 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
324 // the bitrate is not specified, i.e. is <= zero, we set it to the
325 // appropriate default value for mono or stereo Opus.
326
327 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
328 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
329}
330
331// Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
332// which says that G722 should be advertised as 8 kHz although it is a 16 kHz
333// codec.
334static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
335 if (IsCodec(*voe_codec, kG722CodecName)) {
336 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
337 // has changed, and this special case is no longer needed.
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200338 DCHECK(voe_codec->plfreq != new_plfreq);
Minyue Li7100dcd2015-03-27 05:05:59 +0100339 voe_codec->plfreq = new_plfreq;
340 }
341}
342
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000343// Gets the default set of options applied to the engine. Historically, these
344// were supplied as a combination of flags from the channel manager (ec, agc,
345// ns, and highpass) and the rest hardcoded in InitInternal.
346static AudioOptions GetDefaultEngineOptions() {
347 AudioOptions options;
348 options.echo_cancellation.Set(true);
349 options.auto_gain_control.Set(true);
350 options.noise_suppression.Set(true);
351 options.highpass_filter.Set(true);
352 options.stereo_swapping.Set(false);
Henrik Lundin64dad832015-05-11 12:44:23 +0200353 options.audio_jitter_buffer_max_packets.Set(50);
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200354 options.audio_jitter_buffer_fast_accelerate.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000355 options.typing_detection.Set(true);
356 options.conference_mode.Set(false);
357 options.adjust_agc_delta.Set(0);
358 options.experimental_agc.Set(false);
Henrik Lundin441f6342015-06-09 16:03:13 +0200359 options.extended_filter_aec.Set(false);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100360 options.delay_agnostic_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000361 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000362 options.aec_dump.Set(false);
363 return options;
364}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000365
Minyue Li7100dcd2015-03-27 05:05:59 +0100366static std::string GetEnableString(bool enable) {
367 return enable ? "enable" : "disable";
Brave Yao5225dd82015-03-26 07:39:19 +0800368}
369
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000370WebRtcVoiceEngine::WebRtcVoiceEngine()
371 : voe_wrapper_(new VoEWrapper()),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000372 tracing_(new VoETraceWrapper()),
373 adm_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000374 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
375 is_dumping_aec_(false),
376 desired_local_monitor_enable_(false),
377 tx_processor_ssrc_(0),
378 rx_processor_ssrc_(0) {
379 Construct();
380}
381
382WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000383 VoETraceWrapper* tracing)
384 : voe_wrapper_(voe_wrapper),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000385 tracing_(tracing),
386 adm_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000387 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
388 is_dumping_aec_(false),
389 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000390 tx_processor_ssrc_(0),
391 rx_processor_ssrc_(0) {
392 Construct();
393}
394
395void WebRtcVoiceEngine::Construct() {
396 SetTraceFilter(log_filter_);
397 initialized_ = false;
398 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
399 SetTraceOptions("");
400 if (tracing_->SetTraceCallback(this) == -1) {
401 LOG_RTCERR0(SetTraceCallback);
402 }
403 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
404 LOG_RTCERR0(RegisterVoiceEngineObserver);
405 }
406 // Clear the default agc state.
407 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
408
409 // Load our audio codec list.
410 ConstructCodecs();
411
412 // Load our RTP Header extensions.
413 rtp_header_extensions_.push_back(
414 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
415 kRtpAudioLevelHeaderExtensionDefaultId));
416 rtp_header_extensions_.push_back(
417 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
418 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
419 options_ = GetDefaultEngineOptions();
420}
421
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000422void WebRtcVoiceEngine::ConstructCodecs() {
423 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
424 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
425 for (int i = 0; i < ncodecs; ++i) {
426 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000427 if (GetVoeCodec(i, &voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000428 // Skip uncompressed formats.
Minyue Li7100dcd2015-03-27 05:05:59 +0100429 if (IsCodec(voe_codec, kL16CodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000430 continue;
431 }
432
433 const CodecPref* pref = NULL;
434 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100435 if (IsCodec(voe_codec, kCodecPrefs[j].name) &&
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000436 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
437 kCodecPrefs[j].channels == voe_codec.channels) {
438 pref = &kCodecPrefs[j];
439 break;
440 }
441 }
442
443 if (pref) {
444 // Use the payload type that we've configured in our pref table;
445 // use the offset in our pref table to determine the sort order.
446 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
447 voe_codec.rate, voe_codec.channels,
448 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
449 LOG(LS_INFO) << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100450 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000451 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000452 codec.bitrate = 0;
453 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100454 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000455 // Only add fmtp parameters that differ from the spec.
456 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
457 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000458 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000459 }
460 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
461 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000462 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000463 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000464 codec.SetParam(kCodecParamUseInbandFec, 1);
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000465
466 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000467 // when they can be set to values other than the default.
468 }
469 codecs_.push_back(codec);
470 } else {
471 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
472 }
473 }
474 }
475 // Make sure they are in local preference order.
476 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
477}
478
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000479bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst* codec) {
480 if (voe_wrapper_->codec()->GetCodec(index, *codec) == -1) {
481 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000482 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000483 // Change the sample rate of G722 to 8000 to match SDP.
484 MaybeFixupG722(codec, 8000);
485 return true;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000486}
487
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000488WebRtcVoiceEngine::~WebRtcVoiceEngine() {
489 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
490 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
491 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
492 }
493 if (adm_) {
494 voe_wrapper_.reset();
495 adm_->Release();
496 adm_ = NULL;
497 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000498
499 // Test to see if the media processor was deregistered properly
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200500 DCHECK(SignalRxMediaFrame.is_empty());
501 DCHECK(SignalTxMediaFrame.is_empty());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000502
503 tracing_->SetTraceCallback(NULL);
504}
505
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000506bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200507 DCHECK(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000508 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
509 bool res = InitInternal();
510 if (res) {
511 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
512 } else {
513 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
514 Terminate();
515 }
516 return res;
517}
518
519bool WebRtcVoiceEngine::InitInternal() {
520 // Temporarily turn logging level up for the Init call
521 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000522 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000523 SetTraceFilter(extended_filter);
524 SetTraceOptions("");
525
526 // Init WebRtc VoiceEngine.
527 if (voe_wrapper_->base()->Init(adm_) == -1) {
528 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
529 SetTraceFilter(old_filter);
530 return false;
531 }
532
533 SetTraceFilter(old_filter);
534 SetTraceOptions(log_options_);
535
536 // Log the VoiceEngine version info
537 char buffer[1024] = "";
538 voe_wrapper_->base()->GetVersion(buffer);
539 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000540 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000541
542 // Save the default AGC configuration settings. This must happen before
543 // calling SetOptions or the default will be overwritten.
544 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
545 LOG_RTCERR0(GetAgcConfig);
546 return false;
547 }
548
549 // Set defaults for options, so that ApplyOptions applies them explicitly
550 // when we clear option (channel) overrides. External clients can still
551 // modify the defaults via SetOptions (on the media engine).
552 if (!SetOptions(GetDefaultEngineOptions())) {
553 return false;
554 }
555
556 // Print our codec list again for the call diagnostic log
557 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200558 for (const AudioCodec& codec : codecs_) {
559 LOG(LS_INFO) << ToString(codec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000560 }
561
562 // Disable the DTMF playout when a tone is sent.
563 // PlayDtmfTone will be used if local playout is needed.
564 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
565 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
566 }
567
568 initialized_ = true;
569 return true;
570}
571
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000572void WebRtcVoiceEngine::Terminate() {
573 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
574 initialized_ = false;
575
576 StopAecDump();
577
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000578 voe_wrapper_->base()->Terminate();
579 desired_local_monitor_enable_ = false;
580}
581
582int WebRtcVoiceEngine::GetCapabilities() {
583 return AUDIO_SEND | AUDIO_RECV;
584}
585
Jelena Marusicc28a8962015-05-29 15:05:44 +0200586VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel(
587 const AudioOptions& options) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000588 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
589 if (!ch->valid()) {
590 delete ch;
Jelena Marusicc28a8962015-05-29 15:05:44 +0200591 return nullptr;
592 }
593 if (!ch->SetOptions(options)) {
594 LOG(LS_WARNING) << "Failed to set options while creating channel.";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000595 }
596 return ch;
597}
598
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000599bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
600 if (!ApplyOptions(options)) {
601 return false;
602 }
603 options_ = options;
604 return true;
605}
606
607bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
608 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
609 if (!ApplyOptions(overrides)) {
610 return false;
611 }
612 option_overrides_ = overrides;
613 return true;
614}
615
616bool WebRtcVoiceEngine::ClearOptionOverrides() {
617 LOG(LS_INFO) << "Clearing option overrides.";
618 AudioOptions options = options_;
619 // Only call ApplyOptions if |options_overrides_| contains overrided options.
620 // ApplyOptions affects NS, AGC other options that is shared between
621 // all WebRtcVoiceEngineChannels.
622 if (option_overrides_ == AudioOptions()) {
623 return true;
624 }
625
626 if (!ApplyOptions(options)) {
627 return false;
628 }
629 option_overrides_ = AudioOptions();
630 return true;
631}
632
633// AudioOptions defaults are set in InitInternal (for options with corresponding
634// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
635bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
636 AudioOptions options = options_in; // The options are modified below.
637 // kEcConference is AEC with high suppression.
638 webrtc::EcModes ec_mode = webrtc::kEcConference;
639 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
640 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
641 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
642 bool aecm_comfort_noise = false;
643 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
644 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
645 << aecm_comfort_noise << " (default is false).";
646 }
647
648#if defined(IOS)
649 // On iOS, VPIO provides built-in EC and AGC.
650 options.echo_cancellation.Set(false);
651 options.auto_gain_control.Set(false);
652#elif defined(ANDROID)
653 ec_mode = webrtc::kEcAecm;
654#endif
655
656#if defined(IOS) || defined(ANDROID)
657 // Set the AGC mode for iOS as well despite disabling it above, to avoid
658 // unsupported configuration errors from webrtc.
659 agc_mode = webrtc::kAgcFixedDigital;
660 options.typing_detection.Set(false);
661 options.experimental_agc.Set(false);
Henrik Lundin441f6342015-06-09 16:03:13 +0200662 options.extended_filter_aec.Set(false);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000663 options.experimental_ns.Set(false);
664#endif
665
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100666 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
667 // where the feature is not supported.
668 bool use_delay_agnostic_aec = false;
669#if !defined(IOS)
670 if (options.delay_agnostic_aec.Get(&use_delay_agnostic_aec)) {
671 if (use_delay_agnostic_aec) {
672 options.echo_cancellation.Set(true);
Henrik Lundin441f6342015-06-09 16:03:13 +0200673 options.extended_filter_aec.Set(true);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100674 ec_mode = webrtc::kEcConference;
675 }
676 }
677#endif
678
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000679 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
680
681 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
682
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000683 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000684 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000685 // Check if platform supports built-in EC. Currently only supported on
686 // Android and in combination with Java based audio layer.
687 // TODO(henrika): investigate possibility to support built-in EC also
688 // in combination with Open SL ES audio.
689 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
Bjorn Volcker73f72102015-06-03 14:50:15 +0200690 if (built_in_aec) {
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200691 // Built-in EC exists on this device and use_delay_agnostic_aec is not
692 // overriding it. Enable/Disable it according to the echo_cancellation
693 // audio option.
Bjorn Volcker73f72102015-06-03 14:50:15 +0200694 const bool enable_built_in_aec =
695 echo_cancellation && !use_delay_agnostic_aec;
696 if (voe_wrapper_->hw()->EnableBuiltInAEC(enable_built_in_aec) == 0 &&
697 enable_built_in_aec) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100698 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000699 // i.e., replace the software EC with the built-in EC.
700 options.echo_cancellation.Set(false);
bjornv@webrtc.org3f118232015-03-16 14:22:03 +0000701 echo_cancellation = false;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000702 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
703 }
704 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000705 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
706 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
707 return false;
708 } else {
709 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
710 << " with mode " << ec_mode;
711 }
712#if !defined(ANDROID)
713 // TODO(ajm): Remove the error return on Android from webrtc.
714 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
715 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
716 return false;
717 }
718#endif
719 if (ec_mode == webrtc::kEcAecm) {
720 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
721 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
722 return false;
723 }
724 }
725 }
726
727 bool auto_gain_control;
728 if (options.auto_gain_control.Get(&auto_gain_control)) {
729 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
730 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
731 return false;
732 } else {
733 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
734 << " with mode " << agc_mode;
735 }
736 }
737
738 if (options.tx_agc_target_dbov.IsSet() ||
739 options.tx_agc_digital_compression_gain.IsSet() ||
740 options.tx_agc_limiter.IsSet()) {
741 // Override default_agc_config_. Generally, an unset option means "leave
742 // the VoE bits alone" in this function, so we want whatever is set to be
743 // stored as the new "default". If we didn't, then setting e.g.
744 // tx_agc_target_dbov would reset digital compression gain and limiter
745 // settings.
746 // Also, if we don't update default_agc_config_, then adjust_agc_delta
747 // would be an offset from the original values, and not whatever was set
748 // explicitly.
749 default_agc_config_.targetLeveldBOv =
750 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
751 default_agc_config_.targetLeveldBOv);
752 default_agc_config_.digitalCompressionGaindB =
753 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
754 default_agc_config_.digitalCompressionGaindB);
755 default_agc_config_.limiterEnable =
756 options.tx_agc_limiter.GetWithDefaultIfUnset(
757 default_agc_config_.limiterEnable);
758 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
759 LOG_RTCERR3(SetAgcConfig,
760 default_agc_config_.targetLeveldBOv,
761 default_agc_config_.digitalCompressionGaindB,
762 default_agc_config_.limiterEnable);
763 return false;
764 }
765 }
766
767 bool noise_suppression;
768 if (options.noise_suppression.Get(&noise_suppression)) {
769 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
770 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
771 return false;
772 } else {
773 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
774 << " with mode " << ns_mode;
775 }
776 }
777
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000778 bool highpass_filter;
779 if (options.highpass_filter.Get(&highpass_filter)) {
780 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
781 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
782 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
783 return false;
784 }
785 }
786
787 bool stereo_swapping;
788 if (options.stereo_swapping.Get(&stereo_swapping)) {
789 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
790 voep->EnableStereoChannelSwapping(stereo_swapping);
791 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
792 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
793 return false;
794 }
795 }
796
Henrik Lundin64dad832015-05-11 12:44:23 +0200797 int audio_jitter_buffer_max_packets;
798 if (options.audio_jitter_buffer_max_packets.Get(
799 &audio_jitter_buffer_max_packets)) {
800 LOG(LS_INFO) << "NetEq capacity is " << audio_jitter_buffer_max_packets;
801 voe_config_.Set<webrtc::NetEqCapacityConfig>(
802 new webrtc::NetEqCapacityConfig(audio_jitter_buffer_max_packets));
803 }
804
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200805 bool audio_jitter_buffer_fast_accelerate;
806 if (options.audio_jitter_buffer_fast_accelerate.Get(
807 &audio_jitter_buffer_fast_accelerate)) {
808 LOG(LS_INFO) << "NetEq fast mode? " << audio_jitter_buffer_fast_accelerate;
809 voe_config_.Set<webrtc::NetEqFastAccelerate>(
810 new webrtc::NetEqFastAccelerate(audio_jitter_buffer_fast_accelerate));
811 }
812
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000813 bool typing_detection;
814 if (options.typing_detection.Get(&typing_detection)) {
815 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
816 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
817 // In case of error, log the info and continue
818 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
819 }
820 }
821
822 int adjust_agc_delta;
823 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
824 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
825 if (!AdjustAgcLevel(adjust_agc_delta)) {
826 return false;
827 }
828 }
829
830 bool aec_dump;
831 if (options.aec_dump.Get(&aec_dump)) {
832 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
833 if (aec_dump)
834 StartAecDump(kAecDumpByAudioOptionFilename);
835 else
836 StopAecDump();
837 }
838
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000839 webrtc::Config config;
840
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100841 delay_agnostic_aec_.SetFrom(options.delay_agnostic_aec);
842 bool delay_agnostic_aec;
843 if (delay_agnostic_aec_.Get(&delay_agnostic_aec)) {
844 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << delay_agnostic_aec;
henrik.lundin0f133b92015-07-02 00:17:55 -0700845 config.Set<webrtc::DelayAgnostic>(
846 new webrtc::DelayAgnostic(delay_agnostic_aec));
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100847 }
848
Henrik Lundin441f6342015-06-09 16:03:13 +0200849 extended_filter_aec_.SetFrom(options.extended_filter_aec);
850 bool extended_filter;
851 if (extended_filter_aec_.Get(&extended_filter)) {
852 LOG(LS_INFO) << "Extended filter aec is enabled? " << extended_filter;
853 config.Set<webrtc::ExtendedFilter>(
854 new webrtc::ExtendedFilter(extended_filter));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000855 }
856
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000857 experimental_ns_.SetFrom(options.experimental_ns);
858 bool experimental_ns;
859 if (experimental_ns_.Get(&experimental_ns)) {
860 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
861 config.Set<webrtc::ExperimentalNs>(
862 new webrtc::ExperimentalNs(experimental_ns));
863 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000864
865 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
866 // returns NULL on audio_processing().
867 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
868 if (audioproc) {
869 audioproc->SetExtraOptions(config);
870 }
871
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000872 uint32 recording_sample_rate;
873 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
874 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
875 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
876 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
877 }
878 }
879
880 uint32 playout_sample_rate;
881 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
882 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
883 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
884 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
885 }
886 }
887
888 return true;
889}
890
891bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
892 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
893 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
894 LOG_RTCERR1(SetDelayOffsetMs, offset);
895 return false;
896 }
897
898 return true;
899}
900
901struct ResumeEntry {
902 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
903 : channel(c),
904 playout(p),
905 send(s) {
906 }
907
908 WebRtcVoiceMediaChannel *channel;
909 bool playout;
910 SendFlags send;
911};
912
913// TODO(juberti): Refactor this so that the core logic can be used to set the
914// soundclip device. At that time, reinstate the soundclip pause/resume code.
915bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
916 const Device* out_device) {
917#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000918 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000919 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000920 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000921 kDefaultAudioDeviceId;
922 // The device manager uses -1 as the default device, which was the case for
923 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
924#ifndef WIN32
925 if (-1 == in_id) {
926 in_id = kDefaultAudioDeviceId;
927 }
928 if (-1 == out_id) {
929 out_id = kDefaultAudioDeviceId;
930 }
931#endif
932
933 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
934 in_device->name : "Default device";
935 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
936 out_device->name : "Default device";
937 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
938 << ") and speaker to (id=" << out_id << ", name=" << out_name
939 << ")";
940
941 // If we're running the local monitor, we need to stop it first.
942 bool ret = true;
943 if (!PauseLocalMonitor()) {
944 LOG(LS_WARNING) << "Failed to pause local monitor";
945 ret = false;
946 }
947
948 // Must also pause all audio playback and capture.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200949 for (WebRtcVoiceMediaChannel* channel : channels_) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000950 if (!channel->PausePlayout()) {
951 LOG(LS_WARNING) << "Failed to pause playout";
952 ret = false;
953 }
954 if (!channel->PauseSend()) {
955 LOG(LS_WARNING) << "Failed to pause send";
956 ret = false;
957 }
958 }
959
960 // Find the recording device id in VoiceEngine and set recording device.
961 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
962 ret = false;
963 }
964 if (ret) {
965 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
966 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
967 ret = false;
968 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +0000969 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
970 if (ap)
971 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000972 }
973
974 // Find the playout device id in VoiceEngine and set playout device.
975 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
976 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
977 ret = false;
978 }
979 if (ret) {
980 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000981 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000982 ret = false;
983 }
984 }
985
986 // Resume all audio playback and capture.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +0200987 for (WebRtcVoiceMediaChannel* channel : channels_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000988 if (!channel->ResumePlayout()) {
989 LOG(LS_WARNING) << "Failed to resume playout";
990 ret = false;
991 }
992 if (!channel->ResumeSend()) {
993 LOG(LS_WARNING) << "Failed to resume send";
994 ret = false;
995 }
996 }
997
998 // Resume local monitor.
999 if (!ResumeLocalMonitor()) {
1000 LOG(LS_WARNING) << "Failed to resume local monitor";
1001 ret = false;
1002 }
1003
1004 if (ret) {
1005 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1006 << ") and speaker to (id="<< out_id << " name=" << out_name
1007 << ")";
1008 }
1009
1010 return ret;
1011#else
1012 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001013#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001014}
1015
1016bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1017 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1018 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001019#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001020 *rtc_id = dev_id;
1021 return true;
1022#else
1023 // In Windows and Mac, we need to find the VoiceEngine device id by name
1024 // unless the input dev_id is the default device id.
1025 if (kDefaultAudioDeviceId == dev_id) {
1026 *rtc_id = dev_id;
1027 return true;
1028 }
1029
1030 // Get the number of VoiceEngine audio devices.
1031 int count = 0;
1032 if (is_input) {
1033 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1034 LOG_RTCERR0(GetNumOfRecordingDevices);
1035 return false;
1036 }
1037 } else {
1038 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1039 LOG_RTCERR0(GetNumOfPlayoutDevices);
1040 return false;
1041 }
1042 }
1043
1044 for (int i = 0; i < count; ++i) {
1045 char name[128];
1046 char guid[128];
1047 if (is_input) {
1048 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1049 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1050 } else {
1051 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1052 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1053 }
1054
1055 std::string webrtc_name(name);
1056 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1057 *rtc_id = i;
1058 return true;
1059 }
1060 }
1061 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1062 return false;
1063#endif
1064}
1065
1066bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1067 unsigned int ulevel;
1068 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1069 LOG_RTCERR1(GetSpeakerVolume, level);
1070 return false;
1071 }
1072 *level = ulevel;
1073 return true;
1074}
1075
1076bool WebRtcVoiceEngine::SetOutputVolume(int level) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001077 DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001078 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1079 LOG_RTCERR1(SetSpeakerVolume, level);
1080 return false;
1081 }
1082 return true;
1083}
1084
1085int WebRtcVoiceEngine::GetInputLevel() {
1086 unsigned int ulevel;
1087 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1088 static_cast<int>(ulevel) : -1;
1089}
1090
1091bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1092 desired_local_monitor_enable_ = enable;
1093 return ChangeLocalMonitor(desired_local_monitor_enable_);
1094}
1095
1096bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1097 // The voe file api is not available in chrome.
1098 if (!voe_wrapper_->file()) {
1099 return false;
1100 }
1101 if (enable && !monitor_) {
1102 monitor_.reset(new WebRtcMonitorStream);
1103 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1104 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1105 // Must call Stop() because there are some cases where Start will report
1106 // failure but still change the state, and if we leave VE in the on state
1107 // then it could crash later when trying to invoke methods on our monitor.
1108 voe_wrapper_->file()->StopRecordingMicrophone();
1109 monitor_.reset();
1110 return false;
1111 }
1112 } else if (!enable && monitor_) {
1113 voe_wrapper_->file()->StopRecordingMicrophone();
1114 monitor_.reset();
1115 }
1116 return true;
1117}
1118
1119bool WebRtcVoiceEngine::PauseLocalMonitor() {
1120 return ChangeLocalMonitor(false);
1121}
1122
1123bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1124 return ChangeLocalMonitor(desired_local_monitor_enable_);
1125}
1126
1127const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1128 return codecs_;
1129}
1130
1131bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1132 return FindWebRtcCodec(in, NULL);
1133}
1134
1135// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1136bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1137 webrtc::CodecInst* out) {
1138 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1139 for (int i = 0; i < ncodecs; ++i) {
1140 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001141 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001142 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1143 voe_codec.rate, voe_codec.channels, 0);
1144 bool multi_rate = IsCodecMultiRate(voe_codec);
1145 // Allow arbitrary rates for ISAC to be specified.
1146 if (multi_rate) {
1147 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1148 codec.bitrate = 0;
1149 }
1150 if (codec.Matches(in)) {
1151 if (out) {
1152 // Fixup the payload type.
1153 voe_codec.pltype = in.id;
1154
1155 // Set bitrate if specified.
1156 if (multi_rate && in.bitrate != 0) {
1157 voe_codec.rate = in.bitrate;
1158 }
1159
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001160 // Reset G722 sample rate to 16000 to match WebRTC.
1161 MaybeFixupG722(&voe_codec, 16000);
1162
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001163 // Apply codec-specific settings.
Minyue Li7100dcd2015-03-27 05:05:59 +01001164 if (IsCodec(codec, kIsacCodecName)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001165 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001166 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001167 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1168 }
1169 *out = voe_codec;
1170 }
1171 return true;
1172 }
1173 }
1174 }
1175 return false;
1176}
1177const std::vector<RtpHeaderExtension>&
1178WebRtcVoiceEngine::rtp_header_extensions() const {
1179 return rtp_header_extensions_;
1180}
1181
1182void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1183 // if min_sev == -1, we keep the current log level.
1184 if (min_sev >= 0) {
1185 SetTraceFilter(SeverityToFilter(min_sev));
1186 }
1187 log_options_ = filter;
1188 SetTraceOptions(initialized_ ? log_options_ : "");
1189}
1190
1191int WebRtcVoiceEngine::GetLastEngineError() {
1192 return voe_wrapper_->error();
1193}
1194
1195void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1196 log_filter_ = filter;
1197 tracing_->SetTraceFilter(filter);
1198}
1199
1200// We suppport three different logging settings for VoiceEngine:
1201// 1. Observer callback that goes into talk diagnostic logfile.
1202// Use --logfile and --loglevel
1203//
1204// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1205// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1206//
1207// 3. EC log and dump for debugging QualityEngine.
1208// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1209//
1210// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1211// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1212void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1213 // Set encrypted trace file.
1214 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001215 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001216 std::vector<std::string>::iterator tracefile =
1217 std::find(opts.begin(), opts.end(), "tracefile");
1218 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1219 // Write encrypted debug output (at same loglevel) to file
1220 // EncryptedTraceFile no longer supported.
1221 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1222 LOG_RTCERR1(SetTraceFile, *tracefile);
1223 }
1224 }
1225
wu@webrtc.org97077a32013-10-25 21:18:33 +00001226 // Allow trace options to override the trace filter. We default
1227 // it to log_filter_ (as a translation of libjingle log levels)
1228 // elsewhere, but this allows clients to explicitly set webrtc
1229 // log levels.
1230 std::vector<std::string>::iterator tracefilter =
1231 std::find(opts.begin(), opts.end(), "tracefilter");
1232 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001233 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001234 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1235 }
1236 }
1237
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001238 // Set AEC dump file
1239 std::vector<std::string>::iterator recordEC =
1240 std::find(opts.begin(), opts.end(), "recordEC");
1241 if (recordEC != opts.end()) {
1242 ++recordEC;
1243 if (recordEC != opts.end())
1244 StartAecDump(recordEC->c_str());
1245 else
1246 StopAecDump();
1247 }
1248}
1249
1250// Ignore spammy trace messages, mostly from the stats API when we haven't
1251// gotten RTCP info yet from the remote side.
1252bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1253 static const char* kTracesToIgnore[] = {
1254 "\tfailed to GetReportBlockInformation",
1255 "GetRecCodec() failed to get received codec",
1256 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1257 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1258 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1259 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1260 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1261 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1262 "SenderInfoReceived No received SR",
1263 "StatisticsRTP() no statistics available",
1264 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1265 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1266 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1267 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1268 NULL
1269 };
1270 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1271 if (trace.find(*p) != std::string::npos) {
1272 return true;
1273 }
1274 }
1275 return false;
1276}
1277
1278void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1279 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001280 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001281 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001282 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001283 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001284 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001285 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001286 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001287 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001288 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001289
1290 // Skip past boilerplate prefix text
1291 if (length < 72) {
1292 std::string msg(trace, length);
1293 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1294 LOG_V(sev) << msg;
1295 } else {
1296 std::string msg(trace + 71, length - 72);
1297 if (!ShouldIgnoreTrace(msg)) {
1298 LOG_V(sev) << "webrtc: " << msg;
1299 }
1300 }
1301}
1302
1303void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001304 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001305 WebRtcVoiceMediaChannel* channel = NULL;
1306 uint32 ssrc = 0;
1307 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1308 << channel_num << ".";
1309 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001310 DCHECK(channel != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311 channel->OnError(ssrc, err_code);
1312 } else {
1313 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1314 << " could not be found in channel list when error reported.";
1315 }
1316}
1317
1318bool WebRtcVoiceEngine::FindChannelAndSsrc(
1319 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001320 DCHECK(channel != NULL && ssrc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001321
1322 *channel = NULL;
1323 *ssrc = 0;
1324 // Find corresponding channel and ssrc
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001325 for (WebRtcVoiceMediaChannel* ch : channels_) {
1326 DCHECK(ch != NULL);
1327 if (ch->FindSsrc(channel_num, ssrc)) {
1328 *channel = ch;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001329 return true;
1330 }
1331 }
1332
1333 return false;
1334}
1335
1336// This method will search through the WebRtcVoiceMediaChannels and
1337// obtain the voice engine's channel number.
1338bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1339 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001340 DCHECK(channel_num != NULL);
1341 DCHECK(direction == MPD_RX || direction == MPD_TX);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001342
1343 *channel_num = -1;
1344 // Find corresponding channel for ssrc.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001345 for (const WebRtcVoiceMediaChannel* ch : channels_) {
1346 DCHECK(ch != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001347 if (direction & MPD_RX) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001348 *channel_num = ch->GetReceiveChannelNum(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349 }
1350 if (*channel_num == -1 && (direction & MPD_TX)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001351 *channel_num = ch->GetSendChannelNum(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001352 }
1353 if (*channel_num != -1) {
1354 return true;
1355 }
1356 }
1357 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1358 return false;
1359}
1360
1361void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001362 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001363 channels_.push_back(channel);
1364}
1365
1366void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001367 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001368 ChannelList::iterator i = std::find(channels_.begin(),
1369 channels_.end(),
1370 channel);
1371 if (i != channels_.end()) {
1372 channels_.erase(i);
1373 }
1374}
1375
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001376// Adjusts the default AGC target level by the specified delta.
1377// NB: If we start messing with other config fields, we'll want
1378// to save the current webrtc::AgcConfig as well.
1379bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1380 webrtc::AgcConfig config = default_agc_config_;
1381 config.targetLeveldBOv -= delta;
1382
1383 LOG(LS_INFO) << "Adjusting AGC level from default -"
1384 << default_agc_config_.targetLeveldBOv << "dB to -"
1385 << config.targetLeveldBOv << "dB";
1386
1387 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1388 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1389 return false;
1390 }
1391 return true;
1392}
1393
Fredrik Solenbergccb49e72015-05-19 11:37:56 +02001394bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001395 if (initialized_) {
1396 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1397 return false;
1398 }
1399 if (adm_) {
1400 adm_->Release();
1401 adm_ = NULL;
1402 }
1403 if (adm) {
1404 adm_ = adm;
1405 adm_->AddRef();
1406 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001407 return true;
1408}
1409
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001410bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1411 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001412 if (!aec_dump_file_stream) {
1413 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001414 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001415 LOG(LS_WARNING) << "Could not close file.";
1416 return false;
1417 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001418 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001419 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001420 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001421 LOG_RTCERR0(StartDebugRecording);
1422 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001423 return false;
1424 }
1425 is_dumping_aec_ = true;
1426 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001427}
1428
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001429bool WebRtcVoiceEngine::RegisterProcessor(
1430 uint32 ssrc,
1431 VoiceProcessor* voice_processor,
1432 MediaProcessorDirection direction) {
1433 bool register_with_webrtc = false;
1434 int channel_id = -1;
1435 bool success = false;
1436 uint32* processor_ssrc = NULL;
1437 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1438 if (voice_processor == NULL || !found_channel) {
1439 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1440 << " foundChannel: " << found_channel;
1441 return false;
1442 }
1443
1444 webrtc::ProcessingTypes processing_type;
1445 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001446 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001447 if (direction == MPD_RX) {
1448 processing_type = webrtc::kPlaybackAllChannelsMixed;
1449 if (SignalRxMediaFrame.is_empty()) {
1450 register_with_webrtc = true;
1451 processor_ssrc = &rx_processor_ssrc_;
1452 }
1453 SignalRxMediaFrame.connect(voice_processor,
1454 &VoiceProcessor::OnFrame);
1455 } else {
1456 processing_type = webrtc::kRecordingPerChannel;
1457 if (SignalTxMediaFrame.is_empty()) {
1458 register_with_webrtc = true;
1459 processor_ssrc = &tx_processor_ssrc_;
1460 }
1461 SignalTxMediaFrame.connect(voice_processor,
1462 &VoiceProcessor::OnFrame);
1463 }
1464 }
1465 if (register_with_webrtc) {
1466 // TODO(janahan): when registering consider instantiating a
1467 // a VoeMediaProcess object and not make the engine extend the interface.
1468 if (voe()->media() && voe()->media()->
1469 RegisterExternalMediaProcessing(channel_id,
1470 processing_type,
1471 *this) != -1) {
1472 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1473 << channel_id;
1474 *processor_ssrc = ssrc;
1475 success = true;
1476 } else {
1477 LOG_RTCERR2(RegisterExternalMediaProcessing,
1478 channel_id,
1479 processing_type);
1480 success = false;
1481 }
1482 } else {
1483 // If we don't have to register with the engine, we just needed to
1484 // connect a new processor, set success to true;
1485 success = true;
1486 }
1487 return success;
1488}
1489
1490bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1491 MediaProcessorDirection channel_direction,
1492 uint32 ssrc,
1493 VoiceProcessor* voice_processor,
1494 MediaProcessorDirection processor_direction) {
1495 bool success = true;
1496 FrameSignal* signal;
1497 webrtc::ProcessingTypes processing_type;
1498 uint32* processor_ssrc = NULL;
1499 if (channel_direction == MPD_RX) {
1500 signal = &SignalRxMediaFrame;
1501 processing_type = webrtc::kPlaybackAllChannelsMixed;
1502 processor_ssrc = &rx_processor_ssrc_;
1503 } else {
1504 signal = &SignalTxMediaFrame;
1505 processing_type = webrtc::kRecordingPerChannel;
1506 processor_ssrc = &tx_processor_ssrc_;
1507 }
1508
1509 int deregister_id = -1;
1510 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001511 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001512 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1513 signal->disconnect(voice_processor);
1514 int channel_id = -1;
1515 bool found_channel = FindChannelNumFromSsrc(ssrc,
1516 channel_direction,
1517 &channel_id);
1518 if (signal->is_empty() && found_channel) {
1519 deregister_id = channel_id;
1520 }
1521 }
1522 }
1523 if (deregister_id != -1) {
1524 if (voe()->media() &&
1525 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1526 processing_type) != -1) {
1527 *processor_ssrc = 0;
1528 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1529 << deregister_id;
1530 } else {
1531 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1532 deregister_id,
1533 processing_type);
1534 success = false;
1535 }
1536 }
1537 return success;
1538}
1539
1540bool WebRtcVoiceEngine::UnregisterProcessor(
1541 uint32 ssrc,
1542 VoiceProcessor* voice_processor,
1543 MediaProcessorDirection direction) {
1544 bool success = true;
1545 if (voice_processor == NULL) {
1546 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1547 << ssrc;
1548 return false;
1549 }
1550 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1551 success = false;
1552 }
1553 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1554 success = false;
1555 }
1556 return success;
1557}
1558
1559// Implementing method from WebRtc VoEMediaProcess interface
1560// Do not lock mux_channel_cs_ in this callback.
1561void WebRtcVoiceEngine::Process(int channel,
1562 webrtc::ProcessingTypes type,
1563 int16_t audio10ms[],
Peter Kastingdce40cf2015-08-24 14:52:23 -07001564 size_t length,
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001565 int sampling_freq,
1566 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001567 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001568 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1569 if (type == webrtc::kPlaybackAllChannelsMixed) {
1570 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1571 } else if (type == webrtc::kRecordingPerChannel) {
1572 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1573 } else {
1574 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1575 << " channel: " << channel << " type: " << type
1576 << " tx_ssrc: " << tx_processor_ssrc_
1577 << " rx_ssrc: " << rx_processor_ssrc_;
1578 }
1579}
1580
1581void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1582 if (!is_dumping_aec_) {
1583 // Start dumping AEC when we are not dumping.
1584 if (voe_wrapper_->processing()->StartDebugRecording(
1585 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001586 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001587 } else {
1588 is_dumping_aec_ = true;
1589 }
1590 }
1591}
1592
1593void WebRtcVoiceEngine::StopAecDump() {
1594 if (is_dumping_aec_) {
1595 // Stop dumping AEC when we are dumping.
1596 if (voe_wrapper_->processing()->StopDebugRecording() !=
1597 webrtc::AudioProcessing::kNoError) {
1598 LOG_RTCERR0(StopDebugRecording);
1599 }
1600 is_dumping_aec_ = false;
1601 }
1602}
1603
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001604int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001605 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001606}
1607
1608int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1609 return CreateVoiceChannel(voe_wrapper_.get());
1610}
1611
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001612class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1613 : public AudioRenderer::Sink {
1614 public:
1615 WebRtcVoiceChannelRenderer(int ch,
1616 webrtc::AudioTransport* voe_audio_transport)
1617 : channel_(ch),
1618 voe_audio_transport_(voe_audio_transport),
pbos8fc7fa72015-07-15 08:02:58 -07001619 renderer_(NULL) {}
Fredrik Solenbergaaf8ff22015-05-07 16:05:53 +02001620 ~WebRtcVoiceChannelRenderer() override { Stop(); }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001621
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001622 // Starts the rendering by setting a sink to the renderer to get data
1623 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001624 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001625 // TODO(xians): Make sure Start() is called only once.
1626 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001627 rtc::CritScope lock(&lock_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001628 DCHECK(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001629 if (renderer_ != NULL) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001630 DCHECK(renderer_ == renderer);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001631 return;
1632 }
1633
1634 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1635 // in getUserMedia by default.
1636 renderer->AddChannel(channel_);
1637 renderer->SetSink(this);
1638 renderer_ = renderer;
1639 }
1640
1641 // Stops rendering by setting the sink of the renderer to NULL. No data
1642 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001643 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001644 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001645 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001646 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001647 return;
1648
1649 renderer_->RemoveChannel(channel_);
1650 renderer_->SetSink(NULL);
1651 renderer_ = NULL;
1652 }
1653
1654 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001655 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001656 void OnData(const void* audio_data,
1657 int bits_per_sample,
1658 int sample_rate,
1659 int number_of_channels,
Peter Kastingdce40cf2015-08-24 14:52:23 -07001660 size_t number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001661 voe_audio_transport_->OnData(channel_,
1662 audio_data,
1663 bits_per_sample,
1664 sample_rate,
1665 number_of_channels,
1666 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001667 }
1668
1669 // Callback from the |renderer_| when it is going away. In case Start() has
1670 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001671 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001672 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001673 // Set |renderer_| to NULL to make sure no more callback will get into
1674 // the renderer.
1675 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001676 }
1677
1678 // Accessor to the VoE channel ID.
1679 int channel() const { return channel_; }
1680
1681 private:
1682 const int channel_;
1683 webrtc::AudioTransport* const voe_audio_transport_;
1684
1685 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1686 // PeerConnection will make sure invalidating the pointer before the object
1687 // goes away.
1688 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001689
1690 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001691 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001692};
1693
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001694// WebRtcVoiceMediaChannel
Fredrik Solenberge444a3d2015-05-07 16:42:08 +02001695WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine)
1696 : engine_(engine),
1697 voe_channel_(engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001698 send_bitrate_setting_(false),
1699 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001700 options_(),
1701 dtmf_allowed_(false),
1702 desired_playout_(false),
1703 nack_enabled_(false),
1704 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001705 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001706 desired_send_(SEND_NOTHING),
1707 send_(SEND_NOTHING),
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001708 call_(nullptr),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001709 default_receive_ssrc_(0) {
1710 engine->RegisterChannel(this);
1711 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1712 << voe_channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001713 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001714}
1715
1716WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1717 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1718 << voe_channel();
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001719 DCHECK(receive_streams_.empty() || call_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001720
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001721 // Remove any remaining send streams, the default channel will be deleted
1722 // later.
1723 while (!send_channels_.empty())
1724 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001725
1726 // Unregister ourselves from the engine.
1727 engine()->UnregisterChannel(this);
1728 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001729 while (!receive_channels_.empty()) {
1730 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001731 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001732 DCHECK(receive_streams_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001733
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001734 // Delete the default channel.
1735 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001736}
1737
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001738bool WebRtcVoiceMediaChannel::SetSendParameters(
1739 const AudioSendParameters& params) {
1740 // TODO(pthatcher): Refactor this to be more clean now that we have
1741 // all the information at once.
1742 return (SetSendCodecs(params.codecs) &&
1743 SetSendRtpHeaderExtensions(params.extensions) &&
1744 SetMaxSendBandwidth(params.max_bandwidth_bps) &&
1745 SetOptions(params.options));
1746}
1747
1748bool WebRtcVoiceMediaChannel::SetRecvParameters(
1749 const AudioRecvParameters& params) {
1750 // TODO(pthatcher): Refactor this to be more clean now that we have
1751 // all the information at once.
1752 return (SetRecvCodecs(params.codecs) &&
1753 SetRecvRtpHeaderExtensions(params.extensions));
1754}
1755
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001756bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1757 LOG(LS_INFO) << "Setting voice channel options: "
1758 << options.ToString();
1759
wu@webrtc.orgde305012013-10-31 15:40:38 +00001760 // Check if DSCP value is changed from previous.
1761 bool dscp_option_changed = (options_.dscp != options.dscp);
1762
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001763 // TODO(xians): Add support to set different options for different send
1764 // streams after we support multiple APMs.
1765
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001766 // We retain all of the existing options, and apply the given ones
1767 // on top. This means there is no way to "clear" options such that
1768 // they go back to the engine default.
1769 options_.SetAll(options);
1770
1771 if (send_ != SEND_NOTHING) {
1772 if (!engine()->SetOptionOverrides(options_)) {
1773 LOG(LS_WARNING) <<
1774 "Failed to engine SetOptionOverrides during channel SetOptions.";
1775 return false;
1776 }
1777 } else {
1778 // Will be interpreted when appropriate.
1779 }
1780
wu@webrtc.org97077a32013-10-25 21:18:33 +00001781 // Receiver-side auto gain control happens per channel, so set it here from
1782 // options. Note that, like conference mode, setting it on the engine won't
1783 // have the desired effect, since voice channels don't inherit options from
1784 // the media engine when those options are applied per-channel.
1785 bool rx_auto_gain_control;
1786 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1787 if (engine()->voe()->processing()->SetRxAgcStatus(
1788 voe_channel(), rx_auto_gain_control,
1789 webrtc::kAgcFixedDigital) == -1) {
1790 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1791 return false;
1792 } else {
1793 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1794 << " with mode " << webrtc::kAgcFixedDigital;
1795 }
1796 }
1797 if (options.rx_agc_target_dbov.IsSet() ||
1798 options.rx_agc_digital_compression_gain.IsSet() ||
1799 options.rx_agc_limiter.IsSet()) {
1800 webrtc::AgcConfig config;
1801 // If only some of the options are being overridden, get the current
1802 // settings for the channel and bail if they aren't available.
1803 if (!options.rx_agc_target_dbov.IsSet() ||
1804 !options.rx_agc_digital_compression_gain.IsSet() ||
1805 !options.rx_agc_limiter.IsSet()) {
1806 if (engine()->voe()->processing()->GetRxAgcConfig(
1807 voe_channel(), config) != 0) {
1808 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1809 << "channel " << voe_channel() << ". Since not all rx "
1810 << "agc options are specified, unable to safely set rx "
1811 << "agc options.";
1812 return false;
1813 }
1814 }
1815 config.targetLeveldBOv =
1816 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1817 config.targetLeveldBOv);
1818 config.digitalCompressionGaindB =
1819 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1820 config.digitalCompressionGaindB);
1821 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1822 config.limiterEnable);
1823 if (engine()->voe()->processing()->SetRxAgcConfig(
1824 voe_channel(), config) == -1) {
1825 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1826 config.digitalCompressionGaindB, config.limiterEnable);
1827 return false;
1828 }
1829 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001830 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001831 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001832 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001833 dscp = kAudioDscpValue;
1834 if (MediaChannel::SetDscp(dscp) != 0) {
1835 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1836 }
1837 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001838
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001839 SetCall(call_);
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001840
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001841 LOG(LS_INFO) << "Set voice channel options. Current options: "
1842 << options_.ToString();
1843 return true;
1844}
1845
1846bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1847 const std::vector<AudioCodec>& codecs) {
1848 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001849 LOG(LS_INFO) << "Setting receive voice codecs:";
1850
1851 std::vector<AudioCodec> new_codecs;
1852 // Find all new codecs. We allow adding new codecs but don't allow changing
1853 // the payload type of codecs that is already configured since we might
1854 // already be receiving packets with that payload type.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001855 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001856 AudioCodec old_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001857 if (FindCodec(recv_codecs_, codec, &old_codec)) {
1858 if (old_codec.id != codec.id) {
1859 LOG(LS_ERROR) << codec.name << " payload type changed.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001860 return false;
1861 }
1862 } else {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001863 new_codecs.push_back(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001864 }
1865 }
1866 if (new_codecs.empty()) {
1867 // There are no new codecs to configure. Already configured codecs are
1868 // never removed.
1869 return true;
1870 }
1871
1872 if (playout_) {
1873 // Receive codecs can not be changed while playing. So we temporarily
1874 // pause playout.
1875 PausePlayout();
1876 }
1877
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001878 bool result = SetRecvCodecsInternal(new_codecs);
1879 if (result) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001880 recv_codecs_ = codecs;
1881 }
1882
1883 if (desired_playout_ && !playout_) {
1884 ResumePlayout();
1885 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001886 return result;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001887}
1888
1889bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001890 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001891 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001892 engine()->voe()->codec()->SetVADStatus(channel, false);
1893 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001894 engine()->voe()->rtp()->SetREDStatus(channel, false);
1895 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001896
1897 // Scan through the list to figure out the codec to use for sending, along
1898 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001899 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001900 webrtc::CodecInst send_codec;
1901 memset(&send_codec, 0, sizeof(send_codec));
1902
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001903 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001904 bool enable_codec_fec = false;
Minyue Li7100dcd2015-03-27 05:05:59 +01001905 bool enable_opus_dtx = false;
minyue@webrtc.org26236952014-10-29 02:27:08 +00001906 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001907
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001908 // Set send codec (the first non-telephone-event/CN codec)
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001909 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001910 // Ignore codecs we don't know about. The negotiation step should prevent
1911 // this, but double-check to be sure.
1912 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001913 if (!engine()->FindWebRtcCodec(codec, &voe_codec)) {
1914 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001915 continue;
1916 }
1917
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001918 if (IsCodec(codec, kDtmfCodecName) || IsCodec(codec, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001919 // Skip telephone-event/CN codec, which will be handled later.
1920 continue;
1921 }
1922
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001923 // We'll use the first codec in the list to actually send audio data.
1924 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001925 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001926 // used is specified in params.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001927 if (IsCodec(codec, kRedCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001928 // Parse out the RED parameters. If we fail, just ignore RED;
1929 // we don't support all possible params/usage scenarios.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001930 if (!GetRedSendCodec(codec, codecs, &send_codec)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001931 continue;
1932 }
1933
1934 // Enable redundant encoding of the specified codec. Treat any
1935 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001936 LOG(LS_INFO) << "Enabling RED on channel " << channel;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001937 if (engine()->voe()->rtp()->SetREDStatus(channel, true, codec.id) == -1) {
1938 LOG_RTCERR3(SetREDStatus, channel, true, codec.id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001939 return false;
1940 }
1941 } else {
1942 send_codec = voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001943 nack_enabled = IsNackEnabled(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +01001944 // For Opus as the send codec, we are to determine inband FEC, maximum
1945 // playback rate, and opus internal dtx.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001946 if (IsCodec(codec, kOpusCodecName)) {
1947 GetOpusConfig(codec, &send_codec, &enable_codec_fec,
Minyue Li7100dcd2015-03-27 05:05:59 +01001948 &opus_max_playback_rate, &enable_opus_dtx);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001949 }
Brave Yao5225dd82015-03-26 07:39:19 +08001950
1951 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1952 int ptime_ms = 0;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02001953 if (codec.GetParam(kCodecParamPTime, &ptime_ms)) {
Brave Yao5225dd82015-03-26 07:39:19 +08001954 if (!SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
1955 LOG(LS_WARNING) << "Failed to set packet size for codec "
1956 << send_codec.plname;
1957 return false;
1958 }
1959 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001960 }
1961 found_send_codec = true;
1962 break;
1963 }
1964
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001965 if (nack_enabled_ != nack_enabled) {
1966 SetNack(channel, nack_enabled);
1967 nack_enabled_ = nack_enabled;
1968 }
1969
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001970 if (!found_send_codec) {
1971 LOG(LS_WARNING) << "Received empty list of codecs.";
1972 return false;
1973 }
1974
1975 // Set the codec immediately, since SetVADStatus() depends on whether
1976 // the current codec is mono or stereo.
1977 if (!SetSendCodec(channel, send_codec))
1978 return false;
1979
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001980 // FEC should be enabled after SetSendCodec.
1981 if (enable_codec_fec) {
1982 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
1983 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001984 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
1985 // Enable codec internal FEC. Treat any failure as fatal internal error.
1986 LOG_RTCERR2(SetFECStatus, channel, true);
1987 return false;
1988 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001989 }
1990
Minyue Li7100dcd2015-03-27 05:05:59 +01001991 if (IsCodec(send_codec, kOpusCodecName)) {
1992 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
1993 // send codec has to be Opus.
1994
1995 // Set Opus internal DTX.
1996 LOG(LS_INFO) << "Attempt to "
1997 << GetEnableString(enable_opus_dtx)
1998 << " Opus DTX on channel "
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001999 << channel;
Minyue Li7100dcd2015-03-27 05:05:59 +01002000 if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) {
2001 LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx);
2002 return false;
2003 }
2004
2005 // If opus_max_playback_rate <= 0, the default maximum playback rate
2006 // (48 kHz) will be used.
2007 if (opus_max_playback_rate > 0) {
2008 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
2009 << opus_max_playback_rate
2010 << " Hz on channel "
2011 << channel;
2012 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
2013 channel, opus_max_playback_rate) == -1) {
2014 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate);
2015 return false;
2016 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002017 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002018 }
2019
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002020 // Always update the |send_codec_| to the currently set send codec.
2021 send_codec_.reset(new webrtc::CodecInst(send_codec));
2022
minyue@webrtc.org26236952014-10-29 02:27:08 +00002023 if (send_bitrate_setting_) {
2024 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002025 }
2026
2027 // Loop through the codecs list again to config the telephone-event/CN codec.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002028 for (const AudioCodec& codec : codecs) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002029 // Ignore codecs we don't know about. The negotiation step should prevent
2030 // this, but double-check to be sure.
2031 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002032 if (!engine()->FindWebRtcCodec(codec, &voe_codec)) {
2033 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002034 continue;
2035 }
2036
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002037 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2038 // about it.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002039 if (IsCodec(codec, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002040 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002041 channel, codec.id) == -1) {
2042 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, codec.id);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002043 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002044 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002045 } else if (IsCodec(codec, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002046 // Turn voice activity detection/comfort noise on if supported.
2047 // Set the wideband CN payload type appropriately.
2048 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002049 webrtc::PayloadFrequencies cn_freq;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002050 switch (codec.clockrate) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002051 case 8000:
2052 cn_freq = webrtc::kFreq8000Hz;
2053 break;
2054 case 16000:
2055 cn_freq = webrtc::kFreq16000Hz;
2056 break;
2057 case 32000:
2058 cn_freq = webrtc::kFreq32000Hz;
2059 break;
2060 default:
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002061 LOG(LS_WARNING) << "CN frequency " << codec.clockrate
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002062 << " not supported.";
2063 continue;
2064 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002065 // Set the CN payloadtype and the VAD status.
2066 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2067 if (cn_freq != webrtc::kFreq8000Hz) {
2068 if (engine()->voe()->codec()->SetSendCNPayloadType(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002069 channel, codec.id, cn_freq) == -1) {
2070 LOG_RTCERR3(SetSendCNPayloadType, channel, codec.id, cn_freq);
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002071 // TODO(ajm): This failure condition will be removed from VoE.
2072 // Restore the return here when we update to a new enough webrtc.
2073 //
2074 // Not returning false because the SetSendCNPayloadType will fail if
2075 // the channel is already sending.
2076 // This can happen if the remote description is applied twice, for
2077 // example in the case of ROAP on top of JSEP, where both side will
2078 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002079 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002080 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002081 // Only turn on VAD if we have a CN payload type that matches the
2082 // clockrate for the codec we are going to use.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002083 if (codec.clockrate == send_codec.plfreq && send_codec.channels != 2) {
Minyue Li7100dcd2015-03-27 05:05:59 +01002084 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
2085 // interaction between VAD and Opus FEC.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002086 LOG(LS_INFO) << "Enabling VAD";
2087 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2088 LOG_RTCERR2(SetVADStatus, channel, true);
2089 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002090 }
2091 }
2092 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002093 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002094 return true;
2095}
2096
2097bool WebRtcVoiceMediaChannel::SetSendCodecs(
2098 const std::vector<AudioCodec>& codecs) {
2099 dtmf_allowed_ = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002100 for (const AudioCodec& codec : codecs) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002101 // Find the DTMF telephone event "codec".
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002102 if (IsCodec(codec, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002103 dtmf_allowed_ = true;
2104 }
2105 }
2106
2107 // Cache the codecs in order to configure the channel created later.
2108 send_codecs_ = codecs;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002109 for (const auto& ch : send_channels_) {
2110 if (!SetSendCodecs(ch.second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002111 return false;
2112 }
2113 }
2114
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002115 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002116 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002117 return true;
2118}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002119
2120void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2121 bool nack_enabled) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002122 for (const auto& ch : channels) {
2123 SetNack(ch.second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002124 }
2125}
2126
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002127void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002128 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002129 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002130 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2131 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002132 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002133 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2134 }
2135}
2136
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002137bool WebRtcVoiceMediaChannel::SetSendCodec(
2138 const webrtc::CodecInst& send_codec) {
2139 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2140 << ", bitrate=" << send_codec.rate;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002141 for (const auto& ch : send_channels_) {
2142 if (!SetSendCodec(ch.second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002143 return false;
2144 }
2145
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002146 return true;
2147}
2148
2149bool WebRtcVoiceMediaChannel::SetSendCodec(
2150 int channel, const webrtc::CodecInst& send_codec) {
2151 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2152 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2153
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002154 webrtc::CodecInst current_codec;
2155 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2156 (send_codec == current_codec)) {
2157 // Codec is already configured, we can return without setting it again.
2158 return true;
2159 }
2160
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002161 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2162 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002163 return false;
2164 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002165 return true;
2166}
2167
2168bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2169 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002170 if (receive_extensions_ == extensions) {
2171 return true;
2172 }
2173
2174 // The default channel may or may not be in |receive_channels_|. Set the rtp
2175 // header extensions for default channel regardless.
2176 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2177 return false;
2178 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002179
2180 // Loop through all receive channels and enable/disable the extensions.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002181 for (const auto& ch : receive_channels_) {
2182 if (!SetChannelRecvRtpHeaderExtensions(ch.second->channel(), extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002183 return false;
2184 }
2185 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002186
2187 receive_extensions_ = extensions;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002188
2189 // Recreate AudioReceiveStream:s.
2190 {
2191 std::vector<webrtc::RtpExtension> exts;
2192
2193 const RtpHeaderExtension* audio_level_extension =
2194 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2195 if (audio_level_extension) {
2196 exts.push_back({
2197 kRtpAudioLevelHeaderExtension, audio_level_extension->id});
2198 }
2199
2200 const RtpHeaderExtension* send_time_extension =
2201 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2202 if (send_time_extension) {
2203 exts.push_back({
2204 kRtpAbsoluteSenderTimeHeaderExtension, send_time_extension->id});
2205 }
2206
2207 recv_rtp_extensions_.swap(exts);
2208 SetCall(call_);
2209 }
2210
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002211 return true;
2212}
2213
2214bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2215 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002216 const RtpHeaderExtension* audio_level_extension =
2217 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2218 if (!SetHeaderExtension(
2219 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2220 audio_level_extension)) {
2221 return false;
2222 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002223
2224 const RtpHeaderExtension* send_time_extension =
2225 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2226 if (!SetHeaderExtension(
2227 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2228 send_time_extension)) {
2229 return false;
2230 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002231
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002232 return true;
2233}
2234
2235bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2236 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002237 if (send_extensions_ == extensions) {
2238 return true;
2239 }
2240
2241 // The default channel may or may not be in |send_channels_|. Set the rtp
2242 // header extensions for default channel regardless.
2243
2244 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2245 return false;
2246 }
2247
2248 // Loop through all send channels and enable/disable the extensions.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002249 for (const auto& ch : send_channels_) {
2250 if (!SetChannelSendRtpHeaderExtensions(ch.second->channel(), extensions)) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002251 return false;
2252 }
2253 }
2254
2255 send_extensions_ = extensions;
2256 return true;
2257}
2258
2259bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2260 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002261 const RtpHeaderExtension* audio_level_extension =
2262 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002263
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002264 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002265 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002266 audio_level_extension)) {
2267 return false;
2268 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002269
2270 const RtpHeaderExtension* send_time_extension =
2271 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002272 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002273 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002274 send_time_extension)) {
2275 return false;
2276 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002277
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002278 return true;
2279}
2280
2281bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2282 desired_playout_ = playout;
2283 return ChangePlayout(desired_playout_);
2284}
2285
2286bool WebRtcVoiceMediaChannel::PausePlayout() {
2287 return ChangePlayout(false);
2288}
2289
2290bool WebRtcVoiceMediaChannel::ResumePlayout() {
2291 return ChangePlayout(desired_playout_);
2292}
2293
2294bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2295 if (playout_ == playout) {
2296 return true;
2297 }
2298
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002299 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002300 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002301 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002302 // Only toggle the default channel if we don't have any other channels.
2303 result = SetPlayout(voe_channel(), playout);
2304 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002305 for (const auto& ch : receive_channels_) {
2306 if (!SetPlayout(ch.second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002307 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002308 << ch.second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002309 result = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002310 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002311 }
2312 }
2313
2314 if (result) {
2315 playout_ = playout;
2316 }
2317 return result;
2318}
2319
2320bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2321 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002322 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002323 return ChangeSend(desired_send_);
2324 return true;
2325}
2326
2327bool WebRtcVoiceMediaChannel::PauseSend() {
2328 return ChangeSend(SEND_NOTHING);
2329}
2330
2331bool WebRtcVoiceMediaChannel::ResumeSend() {
2332 return ChangeSend(desired_send_);
2333}
2334
2335bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2336 if (send_ == send) {
2337 return true;
2338 }
2339
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002340 // Change the settings on each send channel.
2341 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002342 engine()->SetOptionOverrides(options_);
2343
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002344 // Change the settings on each send channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002345 for (const auto& ch : send_channels_) {
2346 if (!ChangeSend(ch.second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002347 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002348 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002349
2350 // Clear up the options after stopping sending.
2351 if (send == SEND_NOTHING)
2352 engine()->ClearOptionOverrides();
2353
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002354 send_ = send;
2355 return true;
2356}
2357
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002358bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2359 if (send == SEND_MICROPHONE) {
2360 if (engine()->voe()->base()->StartSend(channel) == -1) {
2361 LOG_RTCERR1(StartSend, channel);
2362 return false;
2363 }
2364 if (engine()->voe()->file() &&
2365 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2366 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2367 return false;
2368 }
2369 } else { // SEND_NOTHING
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002370 DCHECK(send == SEND_NOTHING);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002371 if (engine()->voe()->base()->StopSend(channel) == -1) {
2372 LOG_RTCERR1(StopSend, channel);
2373 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002374 }
2375 }
2376
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002377 return true;
2378}
2379
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002380// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002381void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2382 if (engine()->voe()->network()->RegisterExternalTransport(
2383 channel, *this) == -1) {
2384 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2385 }
2386
2387 // Enable RTCP (for quality stats and feedback messages)
2388 EnableRtcp(channel);
2389
2390 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2391 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002392
2393 // Set RTP header extension for the new channel.
2394 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002395}
2396
2397bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2398 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2399 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2400 }
2401
2402 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2403 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002404 return false;
2405 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002406
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002407 return true;
2408}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002409
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002410bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2411 // If the default channel is already used for sending create a new channel
2412 // otherwise use the default channel for sending.
2413 int channel = GetSendChannelNum(sp.first_ssrc());
2414 if (channel != -1) {
2415 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2416 return false;
2417 }
2418
2419 bool default_channel_is_available = true;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002420 for (const auto& ch : send_channels_) {
2421 if (IsDefaultChannel(ch.second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002422 default_channel_is_available = false;
2423 break;
2424 }
2425 }
2426 if (default_channel_is_available) {
2427 channel = voe_channel();
2428 } else {
2429 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002430 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002431 if (channel == -1) {
2432 LOG_RTCERR0(CreateChannel);
2433 return false;
2434 }
2435
2436 ConfigureSendChannel(channel);
2437 }
2438
2439 // Save the channel to send_channels_, so that RemoveSendStream() can still
2440 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002441 webrtc::AudioTransport* audio_transport =
2442 engine()->voe()->base()->audio_transport();
pbos8fc7fa72015-07-15 08:02:58 -07002443 send_channels_.insert(
2444 std::make_pair(sp.first_ssrc(),
2445 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002446
2447 // Set the send (local) SSRC.
2448 // If there are multiple send SSRCs, we can only set the first one here, and
2449 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2450 // (with a codec requires multiple SSRC(s)).
2451 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2452 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2453 return false;
2454 }
2455
2456 // At this point the channel's local SSRC has been updated. If the channel is
2457 // the default channel make sure that all the receive channels are updated as
2458 // well. Receive channels have to have the same SSRC as the default channel in
2459 // order to send receiver reports with this SSRC.
2460 if (IsDefaultChannel(channel)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002461 for (const auto& ch : receive_channels_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002462 // Only update the SSRC for non-default channels.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002463 if (!IsDefaultChannel(ch.second->channel())) {
2464 if (engine()->voe()->rtp()->SetLocalSSRC(ch.second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002465 sp.first_ssrc()) != 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002466 LOG_RTCERR2(SetLocalSSRC, ch.second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002467 return false;
2468 }
2469 }
2470 }
2471 }
2472
2473 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002474 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2475 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002476 }
2477
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002478 // Set the current codecs to be used for the new channel.
2479 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002480 return false;
2481
2482 return ChangeSend(channel, desired_send_);
2483}
2484
2485bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2486 ChannelMap::iterator it = send_channels_.find(ssrc);
2487 if (it == send_channels_.end()) {
2488 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2489 << " which doesn't exist.";
2490 return false;
2491 }
2492
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002493 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002494 ChangeSend(channel, SEND_NOTHING);
2495
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002496 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2497 // this will disconnect the audio renderer with the send channel.
2498 delete it->second;
2499 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002500
2501 if (IsDefaultChannel(channel)) {
2502 // Do not delete the default channel since the receive channels depend on
2503 // the default channel, recycle it instead.
2504 ChangeSend(channel, SEND_NOTHING);
2505 } else {
2506 // Clean up and delete the send channel.
2507 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2508 << " with VoiceEngine channel #" << channel << ".";
2509 if (!DeleteChannel(channel))
2510 return false;
2511 }
2512
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002513 if (send_channels_.empty())
2514 ChangeSend(SEND_NOTHING);
2515
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002516 return true;
2517}
2518
2519bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002520 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002521 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002522
2523 if (!VERIFY(sp.ssrcs.size() == 1))
2524 return false;
2525 uint32 ssrc = sp.first_ssrc();
2526
wu@webrtc.org78187522013-10-07 23:32:02 +00002527 if (ssrc == 0) {
2528 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2529 return false;
2530 }
2531
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002532 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2533 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002534 return false;
2535 }
2536
pbos8fc7fa72015-07-15 08:02:58 -07002537 DCHECK(receive_stream_params_.find(ssrc) == receive_stream_params_.end());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002538
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002539 // Reuse default channel for recv stream in non-conference mode call
2540 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002541 webrtc::AudioTransport* audio_transport =
2542 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002543 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002544 LOG(LS_INFO) << "Recv stream " << ssrc << " reuse default channel";
2545 default_receive_ssrc_ = ssrc;
pbos8fc7fa72015-07-15 08:02:58 -07002546 WebRtcVoiceChannelRenderer* channel_renderer =
2547 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport);
2548 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2549 receive_stream_params_[ssrc] = sp;
2550 TryAddAudioRecvStream(ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002551 return SetPlayout(voe_channel(), playout_);
2552 }
2553
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002554 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002555 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002556 if (channel == -1) {
2557 LOG_RTCERR0(CreateChannel);
2558 return false;
2559 }
2560
wu@webrtc.org78187522013-10-07 23:32:02 +00002561 if (!ConfigureRecvChannel(channel)) {
2562 DeleteChannel(channel);
2563 return false;
2564 }
2565
pbos8fc7fa72015-07-15 08:02:58 -07002566 WebRtcVoiceChannelRenderer* channel_renderer =
2567 new WebRtcVoiceChannelRenderer(channel, audio_transport);
2568 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2569 receive_stream_params_[ssrc] = sp;
2570 TryAddAudioRecvStream(ssrc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002571
2572 LOG(LS_INFO) << "New audio stream " << ssrc
2573 << " registered to VoiceEngine channel #"
2574 << channel << ".";
2575 return true;
2576}
2577
2578bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002579 // Configure to use external transport, like our default channel.
2580 if (engine()->voe()->network()->RegisterExternalTransport(
2581 channel, *this) == -1) {
2582 LOG_RTCERR2(SetExternalTransport, channel, this);
2583 return false;
2584 }
2585
2586 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002587 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002588 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2589 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002590 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002591 return false;
2592 }
2593 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002594 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002595 return false;
2596 }
2597
Minyue2013aec2015-05-13 14:14:42 +02002598 // Associate receive channel to default channel (so the receive channel can
2599 // obtain RTT from the send channel)
2600 engine()->voe()->base()->AssociateSendChannel(channel, voe_channel());
2601 LOG(LS_INFO) << "VoiceEngine channel #"
2602 << channel << " is associated with channel #"
2603 << voe_channel() << ".";
2604
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002605 // Use the same recv payload types as our default channel.
2606 ResetRecvCodecs(channel);
2607 if (!recv_codecs_.empty()) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002608 for (const auto& codec : recv_codecs_) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002609 webrtc::CodecInst voe_codec;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002610 if (engine()->FindWebRtcCodec(codec, &voe_codec)) {
2611 voe_codec.pltype = codec.id;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002612 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2613 if (engine()->voe()->codec()->GetRecPayloadType(
2614 voe_channel(), voe_codec) != -1) {
2615 if (engine()->voe()->codec()->SetRecPayloadType(
2616 channel, voe_codec) == -1) {
2617 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2618 return false;
2619 }
2620 }
2621 }
2622 }
2623 }
2624
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002625 if (InConferenceMode()) {
2626 // To be in par with the video, voe_channel() is not used for receiving in
2627 // a conference call.
2628 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2629 // This is the first stream in a multi user meeting. We can now
2630 // disable playback of the default stream. This since the default
2631 // stream will probably have received some initial packets before
2632 // the new stream was added. This will mean that the CN state from
2633 // the default channel will be mixed in with the other streams
2634 // throughout the whole meeting, which might be disturbing.
2635 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2636 SetPlayout(voe_channel(), false);
2637 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002638 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002639 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002640
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002641 // Set RTP header extension for the new channel.
2642 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2643 return false;
2644 }
2645
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002646 return SetPlayout(channel, playout_);
2647}
2648
2649bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002650 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002651 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002652 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002653 if (it == receive_channels_.end()) {
2654 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2655 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002656 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002657 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002658
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002659 TryRemoveAudioRecvStream(ssrc);
pbos8fc7fa72015-07-15 08:02:58 -07002660 receive_stream_params_.erase(ssrc);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002661
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002662 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2663 // will disconnect the audio renderer with the receive channel.
2664 // Cache the channel before the deletion.
2665 const int channel = it->second->channel();
2666 delete it->second;
2667 receive_channels_.erase(it);
2668
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002669 if (ssrc == default_receive_ssrc_) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002670 DCHECK(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002671 // Recycle the default channel is for recv stream.
2672 if (playout_)
2673 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002674
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002675 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002676 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002677 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002678
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002679 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002680 << " with VoiceEngine channel #" << channel << ".";
2681 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002682 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002683
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002684 bool enable_default_channel_playout = false;
2685 if (receive_channels_.empty()) {
2686 // The last stream was removed. We can now enable the default
2687 // channel for new channels to be played out immediately without
2688 // waiting for AddStream messages.
2689 // We do this for both conference mode and non-conference mode.
2690 // TODO(oja): Does the default channel still have it's CN state?
2691 enable_default_channel_playout = true;
2692 }
2693 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2694 default_receive_ssrc_ != 0) {
2695 // Only the default channel is active, enable the playout on default
2696 // channel.
2697 enable_default_channel_playout = true;
2698 }
2699 if (enable_default_channel_playout && playout_) {
2700 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2701 SetPlayout(voe_channel(), true);
2702 }
2703
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002704 return true;
2705}
2706
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002707bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2708 AudioRenderer* renderer) {
2709 ChannelMap::iterator it = receive_channels_.find(ssrc);
2710 if (it == receive_channels_.end()) {
2711 if (renderer) {
2712 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002713 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002714 return false;
2715 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002716
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002717 // The channel likely has gone away, do nothing.
2718 return true;
2719 }
2720
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002721 if (renderer)
2722 it->second->Start(renderer);
2723 else
2724 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002725
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002726 return true;
2727}
2728
2729bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2730 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002731 ChannelMap::iterator it = send_channels_.find(ssrc);
2732 if (it == send_channels_.end()) {
2733 if (renderer) {
2734 // Return an error if trying to set a valid renderer with an invalid ssrc.
2735 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2736 return false;
2737 }
2738
2739 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002740 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002741 }
2742
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002743 if (renderer)
2744 it->second->Start(renderer);
2745 else
2746 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002747
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002748 return true;
2749}
2750
2751bool WebRtcVoiceMediaChannel::GetActiveStreams(
2752 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002753 // In conference mode, the default channel should not be in
2754 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002755 actives->clear();
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002756 for (const auto& ch : receive_channels_) {
2757 int level = GetOutputLevel(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002758 if (level > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002759 actives->push_back(std::make_pair(ch.first, level));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002760 }
2761 }
2762 return true;
2763}
2764
2765int WebRtcVoiceMediaChannel::GetOutputLevel() {
2766 // return the highest output level of all streams
2767 int highest = GetOutputLevel(voe_channel());
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002768 for (const auto& ch : receive_channels_) {
2769 int level = GetOutputLevel(ch.second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002770 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002771 }
2772 return highest;
2773}
2774
2775int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2776 int ret;
2777 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2778 // In case of error, log the info and continue
2779 LOG_RTCERR0(TimeSinceLastTyping);
2780 ret = -1;
2781 } else {
2782 ret *= 1000; // We return ms, webrtc returns seconds.
2783 }
2784 return ret;
2785}
2786
2787void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2788 int cost_per_typing, int reporting_threshold, int penalty_decay,
2789 int type_event_delay) {
2790 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2791 time_window, cost_per_typing,
2792 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2793 // In case of error, log the info and continue
2794 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2795 cost_per_typing, reporting_threshold, penalty_decay,
2796 type_event_delay);
2797 }
2798}
2799
2800bool WebRtcVoiceMediaChannel::SetOutputScaling(
2801 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002802 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002803 // Collect the channels to scale the output volume.
2804 std::vector<int> channels;
2805 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002806 // Default channel is not in receive_channels_ if it is not being used for
2807 // playout.
2808 if (default_receive_ssrc_ == 0)
2809 channels.push_back(voe_channel());
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002810 for (const auto& ch : receive_channels_) {
2811 channels.push_back(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002812 }
2813 } else { // Collect only the channel of the specified ssrc.
2814 int channel = GetReceiveChannelNum(ssrc);
2815 if (-1 == channel) {
2816 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2817 return false;
2818 }
2819 channels.push_back(channel);
2820 }
2821
2822 // Scale the output volume for the collected channels. We first normalize to
2823 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002824 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002825 if (scale > 0.0001f) {
2826 left /= scale;
2827 right /= scale;
2828 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002829 for (int ch_id : channels) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002830 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002831 ch_id, scale)) {
2832 LOG_RTCERR2(SetChannelOutputVolumeScaling, ch_id, scale);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002833 return false;
2834 }
2835 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002836 ch_id, static_cast<float>(left), static_cast<float>(right))) {
2837 LOG_RTCERR3(SetOutputVolumePan, ch_id, left, right);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002838 // Do not return if fails. SetOutputVolumePan is not available for all
2839 // pltforms.
2840 }
2841 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2842 << " right=" << right * scale
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002843 << " for channel " << ch_id << " and ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002844 }
2845 return true;
2846}
2847
2848bool WebRtcVoiceMediaChannel::GetOutputScaling(
2849 uint32 ssrc, double* left, double* right) {
2850 if (!left || !right) return false;
2851
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002852 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002853 // Determine which channel based on ssrc.
2854 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2855 if (channel == -1) {
2856 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2857 return false;
2858 }
2859
2860 float scaling;
2861 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2862 channel, scaling)) {
2863 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2864 return false;
2865 }
2866
2867 float left_pan;
2868 float right_pan;
2869 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2870 channel, left_pan, right_pan)) {
2871 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2872 // If GetOutputVolumePan fails, we use the default left and right pan.
2873 left_pan = 1.0f;
2874 right_pan = 1.0f;
2875 }
2876
2877 *left = scaling * left_pan;
2878 *right = scaling * right_pan;
2879 return true;
2880}
2881
2882bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2883 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2884 return true;
2885}
2886
2887bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2888 bool play, bool loop) {
2889 if (!ringback_tone_) {
2890 return false;
2891 }
2892
2893 // The voe file api is not available in chrome.
2894 if (!engine()->voe()->file()) {
2895 return false;
2896 }
2897
2898 // Determine which VoiceEngine channel to play on.
2899 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2900 if (channel == -1) {
2901 return false;
2902 }
2903
2904 // Make sure the ringtone is cued properly, and play it out.
2905 if (play) {
2906 ringback_tone_->set_loop(loop);
2907 ringback_tone_->Rewind();
2908 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2909 ringback_tone_.get()) == -1) {
2910 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2911 LOG(LS_ERROR) << "Unable to start ringback tone";
2912 return false;
2913 }
2914 ringback_channels_.insert(channel);
2915 LOG(LS_INFO) << "Started ringback on channel " << channel;
2916 } else {
2917 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2918 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2919 LOG_RTCERR1(StopPlayingFileLocally, channel);
2920 return false;
2921 }
2922 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2923 ringback_channels_.erase(channel);
2924 }
2925
2926 return true;
2927}
2928
2929bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2930 return dtmf_allowed_;
2931}
2932
2933bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2934 int duration, int flags) {
2935 if (!dtmf_allowed_) {
2936 return false;
2937 }
2938
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002939 // Send the event.
2940 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002941 int channel = -1;
2942 if (ssrc == 0) {
2943 bool default_channel_is_inuse = false;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02002944 for (const auto& ch : send_channels_) {
2945 if (IsDefaultChannel(ch.second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002946 default_channel_is_inuse = true;
2947 break;
2948 }
2949 }
2950 if (default_channel_is_inuse) {
2951 channel = voe_channel();
2952 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002953 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002954 }
2955 } else {
2956 channel = GetSendChannelNum(ssrc);
2957 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002958 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002959 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2960 << ssrc << " is not in use.";
2961 return false;
2962 }
2963 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002964 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2965 channel, event, true, duration) == -1) {
2966 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002967 return false;
2968 }
2969 }
2970
2971 // Play the event.
2972 if (flags & cricket::DF_PLAY) {
2973 // Play DTMF tone locally.
2974 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
2975 LOG_RTCERR2(PlayDtmfTone, event, duration);
2976 return false;
2977 }
2978 }
2979
2980 return true;
2981}
2982
wu@webrtc.orga9890802013-12-13 00:21:03 +00002983void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002984 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002985 DCHECK(thread_checker_.CalledOnValidThread());
2986
2987 // If hooked up to a "Call", forward packet there too.
2988 if (call_) {
2989 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
2990 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
2991 }
2992
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002993 // Pick which channel to send this packet to. If this packet doesn't match
2994 // any multiplexed streams, just send it to the default channel. Otherwise,
2995 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00002996 int which_channel =
2997 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002998 if (which_channel == -1) {
2999 which_channel = voe_channel();
3000 }
3001
3002 // Stop any ringback that might be playing on the channel.
3003 // It's possible the ringback has already stopped, ih which case we'll just
3004 // use the opportunity to remove the channel from ringback_channels_.
3005 if (engine()->voe()->file()) {
3006 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3007 if (it != ringback_channels_.end()) {
3008 if (engine()->voe()->file()->IsPlayingFileLocally(
3009 which_channel) == 1) {
3010 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3011 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3012 << " due to incoming media";
3013 }
3014 ringback_channels_.erase(which_channel);
3015 }
3016 }
3017
3018 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003019 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003020 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003021 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003022}
3023
wu@webrtc.orga9890802013-12-13 00:21:03 +00003024void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003025 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003026 DCHECK(thread_checker_.CalledOnValidThread());
3027
3028 // If hooked up to a "Call", forward packet there too.
3029 if (call_) {
3030 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3031 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3032 }
3033
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003034 // Sending channels need all RTCP packets with feedback information.
3035 // Even sender reports can contain attached report blocks.
3036 // Receiving channels need sender reports in order to create
3037 // correct receiver reports.
3038 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003039 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003040 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3041 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003042 }
3043
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003044 // If it is a sender report, find the channel that is listening.
3045 bool has_sent_to_default_channel = false;
3046 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003047 int which_channel =
3048 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003049 if (which_channel != -1) {
3050 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003051 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003052
3053 if (IsDefaultChannel(which_channel))
3054 has_sent_to_default_channel = true;
3055 }
3056 }
3057
3058 // SR may continue RR and any RR entry may correspond to any one of the send
3059 // channels. So all RTCP packets must be forwarded all send channels. VoE
3060 // will filter out RR internally.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003061 for (const auto& ch : send_channels_) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003062 // Make sure not sending the same packet to default channel more than once.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003063 if (IsDefaultChannel(ch.second->channel()) &&
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003064 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003065 continue;
3066
3067 engine()->voe()->network()->ReceivedRTCPPacket(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003068 ch.second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003069 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003070}
3071
3072bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003073 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3074 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003075 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3076 return false;
3077 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003078 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3079 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003080 return false;
3081 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003082 // We set the AGC to mute state only when all the channels are muted.
3083 // This implementation is not ideal, instead we should signal the AGC when
3084 // the mic channel is muted/unmuted. We can't do it today because there
3085 // is no good way to know which stream is mapping to the mic channel.
3086 bool all_muted = muted;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003087 for (const auto& ch : send_channels_) {
3088 if (!all_muted) {
3089 break;
3090 }
3091 if (engine()->voe()->volume()->GetInputMute(ch.second->channel(),
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003092 all_muted)) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003093 LOG_RTCERR1(GetInputMute, ch.second->channel());
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003094 return false;
3095 }
3096 }
3097
3098 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3099 if (ap)
3100 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003101 return true;
3102}
3103
minyue@webrtc.org26236952014-10-29 02:27:08 +00003104// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3105// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003106bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003107 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003108
minyue@webrtc.org26236952014-10-29 02:27:08 +00003109 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003110}
3111
minyue@webrtc.org26236952014-10-29 02:27:08 +00003112bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3113 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003114
minyue@webrtc.org26236952014-10-29 02:27:08 +00003115 send_bitrate_setting_ = true;
3116 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003117
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003118 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003119 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003120 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003121 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003122 }
3123
minyue@webrtc.org26236952014-10-29 02:27:08 +00003124 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003125 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3126 // SetMaxSendBandwith(0), the second call removes the previous limit.
3127 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003128 return true;
3129
3130 webrtc::CodecInst codec = *send_codec_;
3131 bool is_multi_rate = IsCodecMultiRate(codec);
3132
3133 if (is_multi_rate) {
3134 // If codec is multi-rate then just set the bitrate.
3135 codec.rate = bps;
3136 if (!SetSendCodec(codec)) {
3137 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3138 << " to bitrate " << bps << " bps.";
3139 return false;
3140 }
3141 return true;
3142 } else {
3143 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3144 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3145 // fixed bitrate then ignore.
3146 if (bps < codec.rate) {
3147 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3148 << " to bitrate " << bps << " bps"
3149 << ", requires at least " << codec.rate << " bps.";
3150 return false;
3151 }
3152 return true;
3153 }
3154}
3155
3156bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003157 bool echo_metrics_on = false;
3158 // These can take on valid negative values, so use the lowest possible level
3159 // as default rather than -1.
3160 int echo_return_loss = -100;
3161 int echo_return_loss_enhancement = -100;
3162 // These can also be negative, but in practice -1 is only used to signal
3163 // insufficient data, since the resolution is limited to multiples of 4 ms.
3164 int echo_delay_median_ms = -1;
3165 int echo_delay_std_ms = -1;
3166 if (engine()->voe()->processing()->GetEcMetricsStatus(
3167 echo_metrics_on) != -1 && echo_metrics_on) {
3168 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3169 // here, but it appears to be unsuitable currently. Revisit after this is
3170 // investigated: http://b/issue?id=5666755
3171 int erl, erle, rerl, anlp;
3172 if (engine()->voe()->processing()->GetEchoMetrics(
3173 erl, erle, rerl, anlp) != -1) {
3174 echo_return_loss = erl;
3175 echo_return_loss_enhancement = erle;
3176 }
3177
3178 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003179 float dummy;
3180 if (engine()->voe()->processing()->GetEcDelayMetrics(
3181 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003182 echo_delay_median_ms = median;
3183 echo_delay_std_ms = std;
3184 }
3185 }
3186
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003187 webrtc::CallStatistics cs;
3188 unsigned int ssrc;
3189 webrtc::CodecInst codec;
3190 unsigned int level;
3191
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003192 for (const auto& ch : send_channels_) {
3193 const int channel = ch.second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003194
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003195 // Fill in the sender info, based on what we know, and what the
3196 // remote side told us it got from its RTCP report.
3197 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003198
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003199 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3200 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3201 continue;
3202 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003203
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003204 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003205 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3206 sinfo.bytes_sent = cs.bytesSent;
3207 sinfo.packets_sent = cs.packetsSent;
3208 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3209 // returns 0 to indicate an error value.
3210 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3211
3212 // Get data from the last remote RTCP report. Use default values if no data
3213 // available.
3214 sinfo.fraction_lost = -1.0;
3215 sinfo.jitter_ms = -1;
3216 sinfo.packets_lost = -1;
3217 sinfo.ext_seqnum = -1;
3218 std::vector<webrtc::ReportBlock> receive_blocks;
3219 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3220 channel, &receive_blocks) != -1 &&
3221 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003222 for (const webrtc::ReportBlock& block : receive_blocks) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003223 // Lookup report for send ssrc only.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003224 if (block.source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003225 // Convert Q8 to floating point.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003226 sinfo.fraction_lost = static_cast<float>(block.fraction_lost) / 256;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003227 // Convert samples to milliseconds.
3228 if (codec.plfreq / 1000 > 0) {
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003229 sinfo.jitter_ms = block.interarrival_jitter / (codec.plfreq / 1000);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003230 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003231 sinfo.packets_lost = block.cumulative_num_packets_lost;
3232 sinfo.ext_seqnum = block.extended_highest_sequence_number;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003233 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003234 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003235 }
3236 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003237
3238 // Local speech level.
3239 sinfo.audio_level = (engine()->voe()->volume()->
3240 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3241
3242 // TODO(xians): We are injecting the same APM logging to all the send
3243 // channels here because there is no good way to know which send channel
3244 // is using the APM. The correct fix is to allow the send channels to have
3245 // their own APM so that we can feed the correct APM logging to different
3246 // send channels. See issue crbug/264611 .
3247 sinfo.echo_return_loss = echo_return_loss;
3248 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3249 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3250 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003251 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3252 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003253 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003254
3255 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003256 }
3257
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003258 // Build the list of receivers, one for each receiving channel, or 1 in
3259 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003260 std::vector<int> channels;
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003261 for (const auto& ch : receive_channels_) {
3262 channels.push_back(ch.second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003263 }
3264 if (channels.empty()) {
3265 channels.push_back(voe_channel());
3266 }
3267
3268 // Get the SSRC and stats for each receiver, based on our own calculations.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003269 for (int ch_id : channels) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003270 memset(&cs, 0, sizeof(cs));
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003271 if (engine()->voe()->rtp()->GetRemoteSSRC(ch_id, ssrc) != -1 &&
3272 engine()->voe()->rtp()->GetRTCPStatistics(ch_id, cs) != -1 &&
3273 engine()->voe()->codec()->GetRecCodec(ch_id, codec) != -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003274 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003275 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003276 rinfo.bytes_rcvd = cs.bytesReceived;
3277 rinfo.packets_rcvd = cs.packetsReceived;
3278 // The next four fields are from the most recently sent RTCP report.
3279 // Convert Q8 to floating point.
3280 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3281 rinfo.packets_lost = cs.cumulativeLost;
3282 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003283 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003284 if (codec.pltype != -1) {
3285 rinfo.codec_name = codec.plname;
3286 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003287 // Convert samples to milliseconds.
3288 if (codec.plfreq / 1000 > 0) {
3289 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3290 }
3291
3292 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3293 webrtc::NetworkStatistics ns;
3294 if (engine()->voe()->neteq() &&
3295 engine()->voe()->neteq()->GetNetworkStatistics(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003296 ch_id, ns) != -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003297 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3298 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3299 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003300 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003301 rinfo.speech_expand_rate =
3302 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3303 rinfo.secondary_decoded_rate =
3304 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
Henrik Lundin8e6fd462015-06-02 09:24:52 +02003305 rinfo.accelerate_rate =
3306 static_cast<float>(ns.currentAccelerateRate) / (1 << 14);
3307 rinfo.preemptive_expand_rate =
3308 static_cast<float>(ns.currentPreemptiveRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003309 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003310
3311 webrtc::AudioDecodingCallStats ds;
3312 if (engine()->voe()->neteq() &&
3313 engine()->voe()->neteq()->GetDecodingCallStatistics(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003314 ch_id, &ds) != -1) {
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003315 rinfo.decoding_calls_to_silence_generator =
3316 ds.calls_to_silence_generator;
3317 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3318 rinfo.decoding_normal = ds.decoded_normal;
3319 rinfo.decoding_plc = ds.decoded_plc;
3320 rinfo.decoding_cng = ds.decoded_cng;
3321 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3322 }
3323
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003324 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003325 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003326 int playout_buffer_delay_ms = 0;
3327 engine()->voe()->sync()->GetDelayEstimate(
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003328 ch_id, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003329 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3330 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003331 }
3332
3333 // Get speech level.
3334 rinfo.audio_level = (engine()->voe()->volume()->
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003335 GetSpeechOutputLevelFullRange(ch_id, level) != -1) ? level : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003336 info->receivers.push_back(rinfo);
3337 }
3338 }
3339
3340 return true;
3341}
3342
3343void WebRtcVoiceMediaChannel::GetLastMediaError(
3344 uint32* ssrc, VoiceMediaChannel::Error* error) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003345 DCHECK(ssrc != NULL);
3346 DCHECK(error != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003347 FindSsrc(voe_channel(), ssrc);
3348 *error = WebRtcErrorToChannelError(GetLastEngineError());
3349}
3350
3351bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003352 rtc::CritScope lock(&receive_channels_cs_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003353 DCHECK(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003354 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003355 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3356 // This means the error is not limited to a specific channel. Signal the
3357 // message using ssrc=0. If the current channel is sending, use this
3358 // channel for sending the message.
3359 *ssrc = 0;
3360 return true;
3361 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003362 // Check whether this is a sending channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003363 for (const auto& ch : send_channels_) {
3364 if (ch.second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003365 // This is a sending channel.
3366 uint32 local_ssrc = 0;
3367 if (engine()->voe()->rtp()->GetLocalSSRC(
3368 channel_num, local_ssrc) != -1) {
3369 *ssrc = local_ssrc;
3370 }
3371 return true;
3372 }
3373 }
3374
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003375 // Check whether this is a receiving channel.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003376 for (const auto& ch : receive_channels_) {
3377 if (ch.second->channel() == channel_num) {
3378 *ssrc = ch.first;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003379 return true;
3380 }
3381 }
3382 }
3383 return false;
3384}
3385
3386void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003387 if (error == VE_TYPING_NOISE_WARNING) {
3388 typing_noise_detected_ = true;
3389 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3390 typing_noise_detected_ = false;
3391 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003392 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3393}
3394
3395int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3396 unsigned int ulevel;
3397 int ret =
3398 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3399 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3400}
3401
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003402int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) const {
3403 ChannelMap::const_iterator it = receive_channels_.find(ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003404 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003405 return it->second->channel();
pbos8fc7fa72015-07-15 08:02:58 -07003406 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003407}
3408
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003409int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) const {
3410 ChannelMap::const_iterator it = send_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003411 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003412 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003413
3414 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003415}
3416
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003417void WebRtcVoiceMediaChannel::SetCall(webrtc::Call* call) {
3418 DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003419 for (const auto& it : receive_channels_) {
3420 TryRemoveAudioRecvStream(it.first);
3421 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003422 call_ = call;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003423 for (const auto& it : receive_channels_) {
3424 TryAddAudioRecvStream(it.first);
3425 }
3426}
3427
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003428bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3429 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3430 // Get the RED encodings from the parameter with no name. This may
3431 // change based on what is discussed on the Jingle list.
3432 // The encoding parameter is of the form "a/b"; we only support where
3433 // a == b. Verify this and parse out the value into red_pt.
3434 // If the parameter value is absent (as it will be until we wire up the
3435 // signaling of this message), use the second codec specified (i.e. the
3436 // one after "red") as the encoding parameter.
3437 int red_pt = -1;
3438 std::string red_params;
3439 CodecParameterMap::const_iterator it = red_codec.params.find("");
3440 if (it != red_codec.params.end()) {
3441 red_params = it->second;
3442 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003443 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003444 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003445 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003446 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3447 return false;
3448 }
3449 } else if (red_codec.params.empty()) {
3450 LOG(LS_WARNING) << "RED params not present, using defaults";
3451 if (all_codecs.size() > 1) {
3452 red_pt = all_codecs[1].id;
3453 }
3454 }
3455
3456 // Try to find red_pt in |codecs|.
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003457 for (const AudioCodec& codec : all_codecs) {
3458 if (codec.id == red_pt) {
3459 // If we find the right codec, that will be the codec we pass to
3460 // SetSendCodec, with the desired payload type.
3461 if (engine()->FindWebRtcCodec(codec, send_codec)) {
3462 return true;
3463 } else {
3464 break;
3465 }
3466 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003467 }
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003468 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3469 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003470}
3471
3472bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3473 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003474 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003475 return false;
3476 }
3477 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3478 // what we want to do with them.
3479 // engine()->voe().EnableVQMon(voe_channel(), true);
3480 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3481 return true;
3482}
3483
3484bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3485 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3486 for (int i = 0; i < ncodecs; ++i) {
3487 webrtc::CodecInst voe_codec;
3488 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3489 voe_codec.pltype = -1;
3490 if (engine()->voe()->codec()->SetRecPayloadType(
3491 channel, voe_codec) == -1) {
3492 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3493 return false;
3494 }
3495 }
3496 }
3497 return true;
3498}
3499
3500bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3501 if (playout) {
3502 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3503 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3504 LOG_RTCERR1(StartPlayout, channel);
3505 return false;
3506 }
3507 } else {
3508 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3509 engine()->voe()->base()->StopPlayout(channel);
3510 }
3511 return true;
3512}
3513
3514uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3515 bool rtcp) {
3516 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3517 uint32 ssrc = 0;
3518 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003519 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003520 }
3521 return ssrc;
3522}
3523
3524// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3525VoiceMediaChannel::Error
3526 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3527 switch (err_code) {
3528 case 0:
3529 return ERROR_NONE;
3530 case VE_CANNOT_START_RECORDING:
3531 case VE_MIC_VOL_ERROR:
3532 case VE_GET_MIC_VOL_ERROR:
3533 case VE_CANNOT_ACCESS_MIC_VOL:
3534 return ERROR_REC_DEVICE_OPEN_FAILED;
3535 case VE_SATURATION_WARNING:
3536 return ERROR_REC_DEVICE_SATURATION;
3537 case VE_REC_DEVICE_REMOVED:
3538 return ERROR_REC_DEVICE_REMOVED;
3539 case VE_RUNTIME_REC_WARNING:
3540 case VE_RUNTIME_REC_ERROR:
3541 return ERROR_REC_RUNTIME_ERROR;
3542 case VE_CANNOT_START_PLAYOUT:
3543 case VE_SPEAKER_VOL_ERROR:
3544 case VE_GET_SPEAKER_VOL_ERROR:
3545 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3546 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3547 case VE_RUNTIME_PLAY_WARNING:
3548 case VE_RUNTIME_PLAY_ERROR:
3549 return ERROR_PLAY_RUNTIME_ERROR;
3550 case VE_TYPING_NOISE_WARNING:
3551 return ERROR_REC_TYPING_NOISE_DETECTED;
3552 default:
3553 return VoiceMediaChannel::ERROR_OTHER;
3554 }
3555}
3556
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003557bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3558 int channel_id, const RtpHeaderExtension* extension) {
3559 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003560 int id = 0;
3561 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003562 if (extension) {
3563 enable = true;
3564 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003565 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003566 }
3567 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003568 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003569 return false;
3570 }
3571 return true;
3572}
3573
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003574void WebRtcVoiceMediaChannel::TryAddAudioRecvStream(uint32 ssrc) {
3575 DCHECK(thread_checker_.CalledOnValidThread());
pbos8fc7fa72015-07-15 08:02:58 -07003576 WebRtcVoiceChannelRenderer* channel = receive_channels_[ssrc];
3577 DCHECK(channel != nullptr);
3578 DCHECK(receive_streams_.find(ssrc) == receive_streams_.end());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003579 // If we are hooked up to a webrtc::Call, create an AudioReceiveStream too.
pbos8fc7fa72015-07-15 08:02:58 -07003580 if (!call_) {
3581 return;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003582 }
pbos8fc7fa72015-07-15 08:02:58 -07003583 webrtc::AudioReceiveStream::Config config;
3584 config.rtp.remote_ssrc = ssrc;
3585 // Only add RTP extensions if we support combined A/V BWE.
pbos6bb1b6e2015-07-24 07:10:18 -07003586 config.rtp.extensions = recv_rtp_extensions_;
3587 config.combined_audio_video_bwe =
3588 options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false);
pbos8fc7fa72015-07-15 08:02:58 -07003589 config.voe_channel_id = channel->channel();
3590 config.sync_group = receive_stream_params_[ssrc].sync_label;
3591 webrtc::AudioReceiveStream* s = call_->CreateAudioReceiveStream(config);
3592 receive_streams_.insert(std::make_pair(ssrc, s));
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003593}
3594
3595void WebRtcVoiceMediaChannel::TryRemoveAudioRecvStream(uint32 ssrc) {
3596 DCHECK(thread_checker_.CalledOnValidThread());
3597 // If we are hooked up to a webrtc::Call, assume there is an
3598 // AudioReceiveStream to destroy too.
3599 if (call_) {
3600 auto stream_it = receive_streams_.find(ssrc);
3601 if (stream_it != receive_streams_.end()) {
3602 call_->DestroyAudioReceiveStream(stream_it->second);
3603 receive_streams_.erase(stream_it);
3604 }
3605 }
3606}
3607
Fredrik Solenbergaf9fb212015-08-26 10:45:53 +02003608bool WebRtcVoiceMediaChannel::SetRecvCodecsInternal(
3609 const std::vector<AudioCodec>& new_codecs) {
3610 for (const AudioCodec& codec : new_codecs) {
3611 webrtc::CodecInst voe_codec;
3612 if (engine()->FindWebRtcCodec(codec, &voe_codec)) {
3613 LOG(LS_INFO) << ToString(codec);
3614 voe_codec.pltype = codec.id;
3615 if (default_receive_ssrc_ == 0) {
3616 // Set the receive codecs on the default channel explicitly if the
3617 // default channel is not used by |receive_channels_|, this happens in
3618 // conference mode or in non-conference mode when there is no playout
3619 // channel.
3620 // TODO(xians): Figure out how we use the default channel in conference
3621 // mode.
3622 if (engine()->voe()->codec()->SetRecPayloadType(
3623 voe_channel(), voe_codec) == -1) {
3624 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
3625 return false;
3626 }
3627 }
3628
3629 // Set the receive codecs on all receiving channels.
3630 for (const auto& ch : receive_channels_) {
3631 if (engine()->voe()->codec()->SetRecPayloadType(
3632 ch.second->channel(), voe_codec) == -1) {
3633 LOG_RTCERR2(SetRecPayloadType, ch.second->channel(),
3634 ToString(voe_codec));
3635 return false;
3636 }
3637 }
3638 } else {
3639 LOG(LS_WARNING) << "Unknown codec " << ToString(codec);
3640 return false;
3641 }
3642 }
3643 return true;
3644}
3645
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003646int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003647 size_t res = 0;
3648 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003649 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003650}
3651
3652int WebRtcSoundclipStream::Rewind() {
3653 mem_.Rewind();
3654 // Return -1 to keep VoiceEngine from looping.
3655 return (loop_) ? 0 : -1;
3656}
3657
3658} // namespace cricket
3659
3660#endif // HAVE_WEBRTC_VOICE