blob: 6a448c83116a8229ad21cd13b6ac2ff04276b050 [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) {
217 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
218 it != codecs.end(); ++it) {
219 if (it->Matches(codec)) {
220 if (found_codec != NULL) {
221 *found_codec = *it;
222 }
223 return true;
224 }
225 }
226 return false;
227}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000228
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000229static bool IsNackEnabled(const AudioCodec& codec) {
230 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
231 kParamValueEmpty));
232}
233
Brave Yao5225dd82015-03-26 07:39:19 +0800234static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
235 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
236 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
237 if (packet_size_ms && packet_size_ms <= ptime_ms) {
238 selected_packet_size_ms = packet_size_ms;
239 }
240 }
241 return selected_packet_size_ms;
242}
243
244// If the AudioCodec param kCodecParamPTime is set, then we will set it to codec
245// pacsize if it's valid, or we will pick the next smallest value we support.
246// TODO(Brave): Query supported packet sizes from ACM when the API is ready.
247static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
248 for (const CodecPref& codec_pref : kCodecPrefs) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100249 if ((IsCodec(*codec, codec_pref.name) &&
Brave Yao5225dd82015-03-26 07:39:19 +0800250 codec_pref.clockrate == codec->plfreq) ||
Minyue Li7100dcd2015-03-27 05:05:59 +0100251 IsCodec(*codec, kG722CodecName)) {
Brave Yao5225dd82015-03-26 07:39:19 +0800252 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
253 if (packet_size_ms) {
254 // Convert unit from milli-seconds to samples.
255 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
256 return true;
257 }
258 }
259 }
260 return false;
261}
262
Minyue Li7100dcd2015-03-27 05:05:59 +0100263// Return true if codec.params[feature] == "1", false otherwise.
264static bool IsCodecFeatureEnabled(const AudioCodec& codec,
265 const char* feature) {
266 int value;
267 return codec.GetParam(feature, &value) && value == 1;
268}
269
270// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
271// otherwise. If the value (either from params or codec.bitrate) <=0, use the
272// default configuration. If the value is beyond feasible bit rate of Opus,
273// clamp it. Returns the Opus bit rate for operation.
274static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
275 int bitrate = 0;
276 bool use_param = true;
277 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
278 bitrate = codec.bitrate;
279 use_param = false;
280 }
281 if (bitrate <= 0) {
282 if (max_playback_rate <= 8000) {
283 bitrate = kOpusBitrateNb;
284 } else if (max_playback_rate <= 16000) {
285 bitrate = kOpusBitrateWb;
286 } else {
287 bitrate = kOpusBitrateFb;
288 }
289
290 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
291 bitrate *= 2;
292 }
293 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
294 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
295 std::string rate_source =
296 use_param ? "Codec parameter \"maxaveragebitrate\"" :
297 "Supplied Opus bitrate";
298 LOG(LS_WARNING) << rate_source
299 << " is invalid and is replaced by: "
300 << bitrate;
301 }
302 return bitrate;
303}
304
305// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
306// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
307static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
308 int value;
309 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
310 return value;
311 }
312 return kOpusDefaultMaxPlaybackRate;
313}
314
315static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
316 bool* enable_codec_fec, int* max_playback_rate,
317 bool* enable_codec_dtx) {
318 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
319 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
320 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
321
322 // If OPUS, change what we send according to the "stereo" codec
323 // parameter, and not the "channels" parameter. We set
324 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
325 // the bitrate is not specified, i.e. is <= zero, we set it to the
326 // appropriate default value for mono or stereo Opus.
327
328 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
329 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
330}
331
332// Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
333// which says that G722 should be advertised as 8 kHz although it is a 16 kHz
334// codec.
335static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
336 if (IsCodec(*voe_codec, kG722CodecName)) {
337 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
338 // has changed, and this special case is no longer needed.
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200339 DCHECK(voe_codec->plfreq != new_plfreq);
Minyue Li7100dcd2015-03-27 05:05:59 +0100340 voe_codec->plfreq = new_plfreq;
341 }
342}
343
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000344// Gets the default set of options applied to the engine. Historically, these
345// were supplied as a combination of flags from the channel manager (ec, agc,
346// ns, and highpass) and the rest hardcoded in InitInternal.
347static AudioOptions GetDefaultEngineOptions() {
348 AudioOptions options;
349 options.echo_cancellation.Set(true);
350 options.auto_gain_control.Set(true);
351 options.noise_suppression.Set(true);
352 options.highpass_filter.Set(true);
353 options.stereo_swapping.Set(false);
Henrik Lundin64dad832015-05-11 12:44:23 +0200354 options.audio_jitter_buffer_max_packets.Set(50);
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200355 options.audio_jitter_buffer_fast_accelerate.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000356 options.typing_detection.Set(true);
357 options.conference_mode.Set(false);
358 options.adjust_agc_delta.Set(0);
359 options.experimental_agc.Set(false);
Henrik Lundin441f6342015-06-09 16:03:13 +0200360 options.extended_filter_aec.Set(false);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100361 options.delay_agnostic_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000362 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000363 options.aec_dump.Set(false);
364 return options;
365}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000366
Minyue Li7100dcd2015-03-27 05:05:59 +0100367static std::string GetEnableString(bool enable) {
368 return enable ? "enable" : "disable";
Brave Yao5225dd82015-03-26 07:39:19 +0800369}
370
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000371WebRtcVoiceEngine::WebRtcVoiceEngine()
372 : voe_wrapper_(new VoEWrapper()),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000373 tracing_(new VoETraceWrapper()),
374 adm_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000375 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
376 is_dumping_aec_(false),
377 desired_local_monitor_enable_(false),
378 tx_processor_ssrc_(0),
379 rx_processor_ssrc_(0) {
380 Construct();
381}
382
383WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000384 VoETraceWrapper* tracing)
385 : voe_wrapper_(voe_wrapper),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000386 tracing_(tracing),
387 adm_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000388 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
389 is_dumping_aec_(false),
390 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000391 tx_processor_ssrc_(0),
392 rx_processor_ssrc_(0) {
393 Construct();
394}
395
396void WebRtcVoiceEngine::Construct() {
397 SetTraceFilter(log_filter_);
398 initialized_ = false;
399 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
400 SetTraceOptions("");
401 if (tracing_->SetTraceCallback(this) == -1) {
402 LOG_RTCERR0(SetTraceCallback);
403 }
404 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
405 LOG_RTCERR0(RegisterVoiceEngineObserver);
406 }
407 // Clear the default agc state.
408 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
409
410 // Load our audio codec list.
411 ConstructCodecs();
412
413 // Load our RTP Header extensions.
414 rtp_header_extensions_.push_back(
415 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
416 kRtpAudioLevelHeaderExtensionDefaultId));
417 rtp_header_extensions_.push_back(
418 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
419 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
420 options_ = GetDefaultEngineOptions();
421}
422
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000423void WebRtcVoiceEngine::ConstructCodecs() {
424 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
425 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
426 for (int i = 0; i < ncodecs; ++i) {
427 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000428 if (GetVoeCodec(i, &voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000429 // Skip uncompressed formats.
Minyue Li7100dcd2015-03-27 05:05:59 +0100430 if (IsCodec(voe_codec, kL16CodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000431 continue;
432 }
433
434 const CodecPref* pref = NULL;
435 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100436 if (IsCodec(voe_codec, kCodecPrefs[j].name) &&
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000437 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
438 kCodecPrefs[j].channels == voe_codec.channels) {
439 pref = &kCodecPrefs[j];
440 break;
441 }
442 }
443
444 if (pref) {
445 // Use the payload type that we've configured in our pref table;
446 // use the offset in our pref table to determine the sort order.
447 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
448 voe_codec.rate, voe_codec.channels,
449 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
450 LOG(LS_INFO) << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100451 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000452 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000453 codec.bitrate = 0;
454 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100455 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000456 // Only add fmtp parameters that differ from the spec.
457 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
458 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000459 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000460 }
461 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
462 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000463 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000464 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000465 codec.SetParam(kCodecParamUseInbandFec, 1);
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000466
467 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000468 // when they can be set to values other than the default.
469 }
470 codecs_.push_back(codec);
471 } else {
472 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
473 }
474 }
475 }
476 // Make sure they are in local preference order.
477 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
478}
479
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000480bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst* codec) {
481 if (voe_wrapper_->codec()->GetCodec(index, *codec) == -1) {
482 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000483 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000484 // Change the sample rate of G722 to 8000 to match SDP.
485 MaybeFixupG722(codec, 8000);
486 return true;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000487}
488
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000489WebRtcVoiceEngine::~WebRtcVoiceEngine() {
490 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
491 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
492 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
493 }
494 if (adm_) {
495 voe_wrapper_.reset();
496 adm_->Release();
497 adm_ = NULL;
498 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000499
500 // Test to see if the media processor was deregistered properly
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200501 DCHECK(SignalRxMediaFrame.is_empty());
502 DCHECK(SignalTxMediaFrame.is_empty());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000503
504 tracing_->SetTraceCallback(NULL);
505}
506
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000507bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200508 DCHECK(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000509 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
510 bool res = InitInternal();
511 if (res) {
512 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
513 } else {
514 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
515 Terminate();
516 }
517 return res;
518}
519
520bool WebRtcVoiceEngine::InitInternal() {
521 // Temporarily turn logging level up for the Init call
522 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000523 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000524 SetTraceFilter(extended_filter);
525 SetTraceOptions("");
526
527 // Init WebRtc VoiceEngine.
528 if (voe_wrapper_->base()->Init(adm_) == -1) {
529 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
530 SetTraceFilter(old_filter);
531 return false;
532 }
533
534 SetTraceFilter(old_filter);
535 SetTraceOptions(log_options_);
536
537 // Log the VoiceEngine version info
538 char buffer[1024] = "";
539 voe_wrapper_->base()->GetVersion(buffer);
540 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000541 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000542
543 // Save the default AGC configuration settings. This must happen before
544 // calling SetOptions or the default will be overwritten.
545 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
546 LOG_RTCERR0(GetAgcConfig);
547 return false;
548 }
549
550 // Set defaults for options, so that ApplyOptions applies them explicitly
551 // when we clear option (channel) overrides. External clients can still
552 // modify the defaults via SetOptions (on the media engine).
553 if (!SetOptions(GetDefaultEngineOptions())) {
554 return false;
555 }
556
557 // Print our codec list again for the call diagnostic log
558 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
559 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
560 it != codecs_.end(); ++it) {
561 LOG(LS_INFO) << ToString(*it);
562 }
563
564 // Disable the DTMF playout when a tone is sent.
565 // PlayDtmfTone will be used if local playout is needed.
566 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
567 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
568 }
569
570 initialized_ = true;
571 return true;
572}
573
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000574void WebRtcVoiceEngine::Terminate() {
575 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
576 initialized_ = false;
577
578 StopAecDump();
579
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000580 voe_wrapper_->base()->Terminate();
581 desired_local_monitor_enable_ = false;
582}
583
584int WebRtcVoiceEngine::GetCapabilities() {
585 return AUDIO_SEND | AUDIO_RECV;
586}
587
Jelena Marusicc28a8962015-05-29 15:05:44 +0200588VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel(
589 const AudioOptions& options) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000590 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
591 if (!ch->valid()) {
592 delete ch;
Jelena Marusicc28a8962015-05-29 15:05:44 +0200593 return nullptr;
594 }
595 if (!ch->SetOptions(options)) {
596 LOG(LS_WARNING) << "Failed to set options while creating channel.";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000597 }
598 return ch;
599}
600
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000601bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
602 if (!ApplyOptions(options)) {
603 return false;
604 }
605 options_ = options;
606 return true;
607}
608
609bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
610 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
611 if (!ApplyOptions(overrides)) {
612 return false;
613 }
614 option_overrides_ = overrides;
615 return true;
616}
617
618bool WebRtcVoiceEngine::ClearOptionOverrides() {
619 LOG(LS_INFO) << "Clearing option overrides.";
620 AudioOptions options = options_;
621 // Only call ApplyOptions if |options_overrides_| contains overrided options.
622 // ApplyOptions affects NS, AGC other options that is shared between
623 // all WebRtcVoiceEngineChannels.
624 if (option_overrides_ == AudioOptions()) {
625 return true;
626 }
627
628 if (!ApplyOptions(options)) {
629 return false;
630 }
631 option_overrides_ = AudioOptions();
632 return true;
633}
634
635// AudioOptions defaults are set in InitInternal (for options with corresponding
636// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
637bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
638 AudioOptions options = options_in; // The options are modified below.
639 // kEcConference is AEC with high suppression.
640 webrtc::EcModes ec_mode = webrtc::kEcConference;
641 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
642 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
643 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
644 bool aecm_comfort_noise = false;
645 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
646 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
647 << aecm_comfort_noise << " (default is false).";
648 }
649
650#if defined(IOS)
651 // On iOS, VPIO provides built-in EC and AGC.
652 options.echo_cancellation.Set(false);
653 options.auto_gain_control.Set(false);
654#elif defined(ANDROID)
655 ec_mode = webrtc::kEcAecm;
656#endif
657
658#if defined(IOS) || defined(ANDROID)
659 // Set the AGC mode for iOS as well despite disabling it above, to avoid
660 // unsupported configuration errors from webrtc.
661 agc_mode = webrtc::kAgcFixedDigital;
662 options.typing_detection.Set(false);
663 options.experimental_agc.Set(false);
Henrik Lundin441f6342015-06-09 16:03:13 +0200664 options.extended_filter_aec.Set(false);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000665 options.experimental_ns.Set(false);
666#endif
667
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100668 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
669 // where the feature is not supported.
670 bool use_delay_agnostic_aec = false;
671#if !defined(IOS)
672 if (options.delay_agnostic_aec.Get(&use_delay_agnostic_aec)) {
673 if (use_delay_agnostic_aec) {
674 options.echo_cancellation.Set(true);
Henrik Lundin441f6342015-06-09 16:03:13 +0200675 options.extended_filter_aec.Set(true);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100676 ec_mode = webrtc::kEcConference;
677 }
678 }
679#endif
680
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000681 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
682
683 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
684
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000685 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000686 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000687 // Check if platform supports built-in EC. Currently only supported on
688 // Android and in combination with Java based audio layer.
689 // TODO(henrika): investigate possibility to support built-in EC also
690 // in combination with Open SL ES audio.
691 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
Bjorn Volcker73f72102015-06-03 14:50:15 +0200692 if (built_in_aec) {
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200693 // Built-in EC exists on this device and use_delay_agnostic_aec is not
694 // overriding it. Enable/Disable it according to the echo_cancellation
695 // audio option.
Bjorn Volcker73f72102015-06-03 14:50:15 +0200696 const bool enable_built_in_aec =
697 echo_cancellation && !use_delay_agnostic_aec;
698 if (voe_wrapper_->hw()->EnableBuiltInAEC(enable_built_in_aec) == 0 &&
699 enable_built_in_aec) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100700 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000701 // i.e., replace the software EC with the built-in EC.
702 options.echo_cancellation.Set(false);
bjornv@webrtc.org3f118232015-03-16 14:22:03 +0000703 echo_cancellation = false;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000704 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
705 }
706 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000707 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
708 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
709 return false;
710 } else {
711 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
712 << " with mode " << ec_mode;
713 }
714#if !defined(ANDROID)
715 // TODO(ajm): Remove the error return on Android from webrtc.
716 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
717 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
718 return false;
719 }
720#endif
721 if (ec_mode == webrtc::kEcAecm) {
722 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
723 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
724 return false;
725 }
726 }
727 }
728
729 bool auto_gain_control;
730 if (options.auto_gain_control.Get(&auto_gain_control)) {
731 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
732 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
733 return false;
734 } else {
735 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
736 << " with mode " << agc_mode;
737 }
738 }
739
740 if (options.tx_agc_target_dbov.IsSet() ||
741 options.tx_agc_digital_compression_gain.IsSet() ||
742 options.tx_agc_limiter.IsSet()) {
743 // Override default_agc_config_. Generally, an unset option means "leave
744 // the VoE bits alone" in this function, so we want whatever is set to be
745 // stored as the new "default". If we didn't, then setting e.g.
746 // tx_agc_target_dbov would reset digital compression gain and limiter
747 // settings.
748 // Also, if we don't update default_agc_config_, then adjust_agc_delta
749 // would be an offset from the original values, and not whatever was set
750 // explicitly.
751 default_agc_config_.targetLeveldBOv =
752 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
753 default_agc_config_.targetLeveldBOv);
754 default_agc_config_.digitalCompressionGaindB =
755 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
756 default_agc_config_.digitalCompressionGaindB);
757 default_agc_config_.limiterEnable =
758 options.tx_agc_limiter.GetWithDefaultIfUnset(
759 default_agc_config_.limiterEnable);
760 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
761 LOG_RTCERR3(SetAgcConfig,
762 default_agc_config_.targetLeveldBOv,
763 default_agc_config_.digitalCompressionGaindB,
764 default_agc_config_.limiterEnable);
765 return false;
766 }
767 }
768
769 bool noise_suppression;
770 if (options.noise_suppression.Get(&noise_suppression)) {
771 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
772 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
773 return false;
774 } else {
775 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
776 << " with mode " << ns_mode;
777 }
778 }
779
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000780 bool highpass_filter;
781 if (options.highpass_filter.Get(&highpass_filter)) {
782 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
783 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
784 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
785 return false;
786 }
787 }
788
789 bool stereo_swapping;
790 if (options.stereo_swapping.Get(&stereo_swapping)) {
791 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
792 voep->EnableStereoChannelSwapping(stereo_swapping);
793 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
794 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
795 return false;
796 }
797 }
798
Henrik Lundin64dad832015-05-11 12:44:23 +0200799 int audio_jitter_buffer_max_packets;
800 if (options.audio_jitter_buffer_max_packets.Get(
801 &audio_jitter_buffer_max_packets)) {
802 LOG(LS_INFO) << "NetEq capacity is " << audio_jitter_buffer_max_packets;
803 voe_config_.Set<webrtc::NetEqCapacityConfig>(
804 new webrtc::NetEqCapacityConfig(audio_jitter_buffer_max_packets));
805 }
806
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200807 bool audio_jitter_buffer_fast_accelerate;
808 if (options.audio_jitter_buffer_fast_accelerate.Get(
809 &audio_jitter_buffer_fast_accelerate)) {
810 LOG(LS_INFO) << "NetEq fast mode? " << audio_jitter_buffer_fast_accelerate;
811 voe_config_.Set<webrtc::NetEqFastAccelerate>(
812 new webrtc::NetEqFastAccelerate(audio_jitter_buffer_fast_accelerate));
813 }
814
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000815 bool typing_detection;
816 if (options.typing_detection.Get(&typing_detection)) {
817 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
818 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
819 // In case of error, log the info and continue
820 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
821 }
822 }
823
824 int adjust_agc_delta;
825 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
826 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
827 if (!AdjustAgcLevel(adjust_agc_delta)) {
828 return false;
829 }
830 }
831
832 bool aec_dump;
833 if (options.aec_dump.Get(&aec_dump)) {
834 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
835 if (aec_dump)
836 StartAecDump(kAecDumpByAudioOptionFilename);
837 else
838 StopAecDump();
839 }
840
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000841 webrtc::Config config;
842
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100843 delay_agnostic_aec_.SetFrom(options.delay_agnostic_aec);
844 bool delay_agnostic_aec;
845 if (delay_agnostic_aec_.Get(&delay_agnostic_aec)) {
846 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << delay_agnostic_aec;
henrik.lundin0f133b92015-07-02 00:17:55 -0700847 config.Set<webrtc::DelayAgnostic>(
848 new webrtc::DelayAgnostic(delay_agnostic_aec));
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100849 }
850
Henrik Lundin441f6342015-06-09 16:03:13 +0200851 extended_filter_aec_.SetFrom(options.extended_filter_aec);
852 bool extended_filter;
853 if (extended_filter_aec_.Get(&extended_filter)) {
854 LOG(LS_INFO) << "Extended filter aec is enabled? " << extended_filter;
855 config.Set<webrtc::ExtendedFilter>(
856 new webrtc::ExtendedFilter(extended_filter));
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000857 }
858
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000859 experimental_ns_.SetFrom(options.experimental_ns);
860 bool experimental_ns;
861 if (experimental_ns_.Get(&experimental_ns)) {
862 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
863 config.Set<webrtc::ExperimentalNs>(
864 new webrtc::ExperimentalNs(experimental_ns));
865 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000866
867 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
868 // returns NULL on audio_processing().
869 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
870 if (audioproc) {
871 audioproc->SetExtraOptions(config);
872 }
873
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000874 uint32 recording_sample_rate;
875 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
876 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
877 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
878 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
879 }
880 }
881
882 uint32 playout_sample_rate;
883 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
884 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
885 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
886 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
887 }
888 }
889
890 return true;
891}
892
893bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
894 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
895 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
896 LOG_RTCERR1(SetDelayOffsetMs, offset);
897 return false;
898 }
899
900 return true;
901}
902
903struct ResumeEntry {
904 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
905 : channel(c),
906 playout(p),
907 send(s) {
908 }
909
910 WebRtcVoiceMediaChannel *channel;
911 bool playout;
912 SendFlags send;
913};
914
915// TODO(juberti): Refactor this so that the core logic can be used to set the
916// soundclip device. At that time, reinstate the soundclip pause/resume code.
917bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
918 const Device* out_device) {
919#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000920 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000921 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000922 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000923 kDefaultAudioDeviceId;
924 // The device manager uses -1 as the default device, which was the case for
925 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
926#ifndef WIN32
927 if (-1 == in_id) {
928 in_id = kDefaultAudioDeviceId;
929 }
930 if (-1 == out_id) {
931 out_id = kDefaultAudioDeviceId;
932 }
933#endif
934
935 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
936 in_device->name : "Default device";
937 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
938 out_device->name : "Default device";
939 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
940 << ") and speaker to (id=" << out_id << ", name=" << out_name
941 << ")";
942
943 // If we're running the local monitor, we need to stop it first.
944 bool ret = true;
945 if (!PauseLocalMonitor()) {
946 LOG(LS_WARNING) << "Failed to pause local monitor";
947 ret = false;
948 }
949
950 // Must also pause all audio playback and capture.
951 for (ChannelList::const_iterator i = channels_.begin();
952 i != channels_.end(); ++i) {
953 WebRtcVoiceMediaChannel *channel = *i;
954 if (!channel->PausePlayout()) {
955 LOG(LS_WARNING) << "Failed to pause playout";
956 ret = false;
957 }
958 if (!channel->PauseSend()) {
959 LOG(LS_WARNING) << "Failed to pause send";
960 ret = false;
961 }
962 }
963
964 // Find the recording device id in VoiceEngine and set recording device.
965 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
966 ret = false;
967 }
968 if (ret) {
969 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
970 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
971 ret = false;
972 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +0000973 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
974 if (ap)
975 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000976 }
977
978 // Find the playout device id in VoiceEngine and set playout device.
979 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
980 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
981 ret = false;
982 }
983 if (ret) {
984 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000985 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000986 ret = false;
987 }
988 }
989
990 // Resume all audio playback and capture.
991 for (ChannelList::const_iterator i = channels_.begin();
992 i != channels_.end(); ++i) {
993 WebRtcVoiceMediaChannel *channel = *i;
994 if (!channel->ResumePlayout()) {
995 LOG(LS_WARNING) << "Failed to resume playout";
996 ret = false;
997 }
998 if (!channel->ResumeSend()) {
999 LOG(LS_WARNING) << "Failed to resume send";
1000 ret = false;
1001 }
1002 }
1003
1004 // Resume local monitor.
1005 if (!ResumeLocalMonitor()) {
1006 LOG(LS_WARNING) << "Failed to resume local monitor";
1007 ret = false;
1008 }
1009
1010 if (ret) {
1011 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1012 << ") and speaker to (id="<< out_id << " name=" << out_name
1013 << ")";
1014 }
1015
1016 return ret;
1017#else
1018 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001019#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001020}
1021
1022bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1023 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1024 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001025#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001026 *rtc_id = dev_id;
1027 return true;
1028#else
1029 // In Windows and Mac, we need to find the VoiceEngine device id by name
1030 // unless the input dev_id is the default device id.
1031 if (kDefaultAudioDeviceId == dev_id) {
1032 *rtc_id = dev_id;
1033 return true;
1034 }
1035
1036 // Get the number of VoiceEngine audio devices.
1037 int count = 0;
1038 if (is_input) {
1039 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1040 LOG_RTCERR0(GetNumOfRecordingDevices);
1041 return false;
1042 }
1043 } else {
1044 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1045 LOG_RTCERR0(GetNumOfPlayoutDevices);
1046 return false;
1047 }
1048 }
1049
1050 for (int i = 0; i < count; ++i) {
1051 char name[128];
1052 char guid[128];
1053 if (is_input) {
1054 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1055 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1056 } else {
1057 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1058 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1059 }
1060
1061 std::string webrtc_name(name);
1062 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1063 *rtc_id = i;
1064 return true;
1065 }
1066 }
1067 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1068 return false;
1069#endif
1070}
1071
1072bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1073 unsigned int ulevel;
1074 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1075 LOG_RTCERR1(GetSpeakerVolume, level);
1076 return false;
1077 }
1078 *level = ulevel;
1079 return true;
1080}
1081
1082bool WebRtcVoiceEngine::SetOutputVolume(int level) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001083 DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001084 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1085 LOG_RTCERR1(SetSpeakerVolume, level);
1086 return false;
1087 }
1088 return true;
1089}
1090
1091int WebRtcVoiceEngine::GetInputLevel() {
1092 unsigned int ulevel;
1093 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1094 static_cast<int>(ulevel) : -1;
1095}
1096
1097bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1098 desired_local_monitor_enable_ = enable;
1099 return ChangeLocalMonitor(desired_local_monitor_enable_);
1100}
1101
1102bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1103 // The voe file api is not available in chrome.
1104 if (!voe_wrapper_->file()) {
1105 return false;
1106 }
1107 if (enable && !monitor_) {
1108 monitor_.reset(new WebRtcMonitorStream);
1109 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1110 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1111 // Must call Stop() because there are some cases where Start will report
1112 // failure but still change the state, and if we leave VE in the on state
1113 // then it could crash later when trying to invoke methods on our monitor.
1114 voe_wrapper_->file()->StopRecordingMicrophone();
1115 monitor_.reset();
1116 return false;
1117 }
1118 } else if (!enable && monitor_) {
1119 voe_wrapper_->file()->StopRecordingMicrophone();
1120 monitor_.reset();
1121 }
1122 return true;
1123}
1124
1125bool WebRtcVoiceEngine::PauseLocalMonitor() {
1126 return ChangeLocalMonitor(false);
1127}
1128
1129bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1130 return ChangeLocalMonitor(desired_local_monitor_enable_);
1131}
1132
1133const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1134 return codecs_;
1135}
1136
1137bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1138 return FindWebRtcCodec(in, NULL);
1139}
1140
1141// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1142bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1143 webrtc::CodecInst* out) {
1144 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1145 for (int i = 0; i < ncodecs; ++i) {
1146 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001147 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001148 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1149 voe_codec.rate, voe_codec.channels, 0);
1150 bool multi_rate = IsCodecMultiRate(voe_codec);
1151 // Allow arbitrary rates for ISAC to be specified.
1152 if (multi_rate) {
1153 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1154 codec.bitrate = 0;
1155 }
1156 if (codec.Matches(in)) {
1157 if (out) {
1158 // Fixup the payload type.
1159 voe_codec.pltype = in.id;
1160
1161 // Set bitrate if specified.
1162 if (multi_rate && in.bitrate != 0) {
1163 voe_codec.rate = in.bitrate;
1164 }
1165
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001166 // Reset G722 sample rate to 16000 to match WebRTC.
1167 MaybeFixupG722(&voe_codec, 16000);
1168
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001169 // Apply codec-specific settings.
Minyue Li7100dcd2015-03-27 05:05:59 +01001170 if (IsCodec(codec, kIsacCodecName)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001171 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001172 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001173 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1174 }
1175 *out = voe_codec;
1176 }
1177 return true;
1178 }
1179 }
1180 }
1181 return false;
1182}
1183const std::vector<RtpHeaderExtension>&
1184WebRtcVoiceEngine::rtp_header_extensions() const {
1185 return rtp_header_extensions_;
1186}
1187
1188void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1189 // if min_sev == -1, we keep the current log level.
1190 if (min_sev >= 0) {
1191 SetTraceFilter(SeverityToFilter(min_sev));
1192 }
1193 log_options_ = filter;
1194 SetTraceOptions(initialized_ ? log_options_ : "");
1195}
1196
1197int WebRtcVoiceEngine::GetLastEngineError() {
1198 return voe_wrapper_->error();
1199}
1200
1201void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1202 log_filter_ = filter;
1203 tracing_->SetTraceFilter(filter);
1204}
1205
1206// We suppport three different logging settings for VoiceEngine:
1207// 1. Observer callback that goes into talk diagnostic logfile.
1208// Use --logfile and --loglevel
1209//
1210// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1211// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1212//
1213// 3. EC log and dump for debugging QualityEngine.
1214// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1215//
1216// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1217// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1218void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1219 // Set encrypted trace file.
1220 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001221 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001222 std::vector<std::string>::iterator tracefile =
1223 std::find(opts.begin(), opts.end(), "tracefile");
1224 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1225 // Write encrypted debug output (at same loglevel) to file
1226 // EncryptedTraceFile no longer supported.
1227 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1228 LOG_RTCERR1(SetTraceFile, *tracefile);
1229 }
1230 }
1231
wu@webrtc.org97077a32013-10-25 21:18:33 +00001232 // Allow trace options to override the trace filter. We default
1233 // it to log_filter_ (as a translation of libjingle log levels)
1234 // elsewhere, but this allows clients to explicitly set webrtc
1235 // log levels.
1236 std::vector<std::string>::iterator tracefilter =
1237 std::find(opts.begin(), opts.end(), "tracefilter");
1238 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001239 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001240 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1241 }
1242 }
1243
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001244 // Set AEC dump file
1245 std::vector<std::string>::iterator recordEC =
1246 std::find(opts.begin(), opts.end(), "recordEC");
1247 if (recordEC != opts.end()) {
1248 ++recordEC;
1249 if (recordEC != opts.end())
1250 StartAecDump(recordEC->c_str());
1251 else
1252 StopAecDump();
1253 }
1254}
1255
1256// Ignore spammy trace messages, mostly from the stats API when we haven't
1257// gotten RTCP info yet from the remote side.
1258bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1259 static const char* kTracesToIgnore[] = {
1260 "\tfailed to GetReportBlockInformation",
1261 "GetRecCodec() failed to get received codec",
1262 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1263 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1264 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1265 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1266 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1267 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1268 "SenderInfoReceived No received SR",
1269 "StatisticsRTP() no statistics available",
1270 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1271 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1272 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1273 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1274 NULL
1275 };
1276 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1277 if (trace.find(*p) != std::string::npos) {
1278 return true;
1279 }
1280 }
1281 return false;
1282}
1283
1284void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1285 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001286 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001287 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001288 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001289 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001290 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001291 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001292 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001294 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001295
1296 // Skip past boilerplate prefix text
1297 if (length < 72) {
1298 std::string msg(trace, length);
1299 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1300 LOG_V(sev) << msg;
1301 } else {
1302 std::string msg(trace + 71, length - 72);
1303 if (!ShouldIgnoreTrace(msg)) {
1304 LOG_V(sev) << "webrtc: " << msg;
1305 }
1306 }
1307}
1308
1309void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001310 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311 WebRtcVoiceMediaChannel* channel = NULL;
1312 uint32 ssrc = 0;
1313 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1314 << channel_num << ".";
1315 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001316 DCHECK(channel != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001317 channel->OnError(ssrc, err_code);
1318 } else {
1319 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1320 << " could not be found in channel list when error reported.";
1321 }
1322}
1323
1324bool WebRtcVoiceEngine::FindChannelAndSsrc(
1325 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001326 DCHECK(channel != NULL && ssrc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001327
1328 *channel = NULL;
1329 *ssrc = 0;
1330 // Find corresponding channel and ssrc
1331 for (ChannelList::const_iterator it = channels_.begin();
1332 it != channels_.end(); ++it) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001333 DCHECK(*it != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001334 if ((*it)->FindSsrc(channel_num, ssrc)) {
1335 *channel = *it;
1336 return true;
1337 }
1338 }
1339
1340 return false;
1341}
1342
1343// This method will search through the WebRtcVoiceMediaChannels and
1344// obtain the voice engine's channel number.
1345bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1346 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001347 DCHECK(channel_num != NULL);
1348 DCHECK(direction == MPD_RX || direction == MPD_TX);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349
1350 *channel_num = -1;
1351 // Find corresponding channel for ssrc.
1352 for (ChannelList::const_iterator it = channels_.begin();
1353 it != channels_.end(); ++it) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001354 DCHECK(*it != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001355 if (direction & MPD_RX) {
1356 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1357 }
1358 if (*channel_num == -1 && (direction & MPD_TX)) {
1359 *channel_num = (*it)->GetSendChannelNum(ssrc);
1360 }
1361 if (*channel_num != -1) {
1362 return true;
1363 }
1364 }
1365 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1366 return false;
1367}
1368
1369void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001370 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001371 channels_.push_back(channel);
1372}
1373
1374void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001375 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001376 ChannelList::iterator i = std::find(channels_.begin(),
1377 channels_.end(),
1378 channel);
1379 if (i != channels_.end()) {
1380 channels_.erase(i);
1381 }
1382}
1383
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001384// Adjusts the default AGC target level by the specified delta.
1385// NB: If we start messing with other config fields, we'll want
1386// to save the current webrtc::AgcConfig as well.
1387bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1388 webrtc::AgcConfig config = default_agc_config_;
1389 config.targetLeveldBOv -= delta;
1390
1391 LOG(LS_INFO) << "Adjusting AGC level from default -"
1392 << default_agc_config_.targetLeveldBOv << "dB to -"
1393 << config.targetLeveldBOv << "dB";
1394
1395 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1396 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1397 return false;
1398 }
1399 return true;
1400}
1401
Fredrik Solenbergccb49e72015-05-19 11:37:56 +02001402bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001403 if (initialized_) {
1404 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1405 return false;
1406 }
1407 if (adm_) {
1408 adm_->Release();
1409 adm_ = NULL;
1410 }
1411 if (adm) {
1412 adm_ = adm;
1413 adm_->AddRef();
1414 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001415 return true;
1416}
1417
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001418bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1419 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001420 if (!aec_dump_file_stream) {
1421 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001422 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001423 LOG(LS_WARNING) << "Could not close file.";
1424 return false;
1425 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001426 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001427 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001428 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001429 LOG_RTCERR0(StartDebugRecording);
1430 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001431 return false;
1432 }
1433 is_dumping_aec_ = true;
1434 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001435}
1436
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001437bool WebRtcVoiceEngine::RegisterProcessor(
1438 uint32 ssrc,
1439 VoiceProcessor* voice_processor,
1440 MediaProcessorDirection direction) {
1441 bool register_with_webrtc = false;
1442 int channel_id = -1;
1443 bool success = false;
1444 uint32* processor_ssrc = NULL;
1445 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1446 if (voice_processor == NULL || !found_channel) {
1447 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1448 << " foundChannel: " << found_channel;
1449 return false;
1450 }
1451
1452 webrtc::ProcessingTypes processing_type;
1453 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001454 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001455 if (direction == MPD_RX) {
1456 processing_type = webrtc::kPlaybackAllChannelsMixed;
1457 if (SignalRxMediaFrame.is_empty()) {
1458 register_with_webrtc = true;
1459 processor_ssrc = &rx_processor_ssrc_;
1460 }
1461 SignalRxMediaFrame.connect(voice_processor,
1462 &VoiceProcessor::OnFrame);
1463 } else {
1464 processing_type = webrtc::kRecordingPerChannel;
1465 if (SignalTxMediaFrame.is_empty()) {
1466 register_with_webrtc = true;
1467 processor_ssrc = &tx_processor_ssrc_;
1468 }
1469 SignalTxMediaFrame.connect(voice_processor,
1470 &VoiceProcessor::OnFrame);
1471 }
1472 }
1473 if (register_with_webrtc) {
1474 // TODO(janahan): when registering consider instantiating a
1475 // a VoeMediaProcess object and not make the engine extend the interface.
1476 if (voe()->media() && voe()->media()->
1477 RegisterExternalMediaProcessing(channel_id,
1478 processing_type,
1479 *this) != -1) {
1480 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1481 << channel_id;
1482 *processor_ssrc = ssrc;
1483 success = true;
1484 } else {
1485 LOG_RTCERR2(RegisterExternalMediaProcessing,
1486 channel_id,
1487 processing_type);
1488 success = false;
1489 }
1490 } else {
1491 // If we don't have to register with the engine, we just needed to
1492 // connect a new processor, set success to true;
1493 success = true;
1494 }
1495 return success;
1496}
1497
1498bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1499 MediaProcessorDirection channel_direction,
1500 uint32 ssrc,
1501 VoiceProcessor* voice_processor,
1502 MediaProcessorDirection processor_direction) {
1503 bool success = true;
1504 FrameSignal* signal;
1505 webrtc::ProcessingTypes processing_type;
1506 uint32* processor_ssrc = NULL;
1507 if (channel_direction == MPD_RX) {
1508 signal = &SignalRxMediaFrame;
1509 processing_type = webrtc::kPlaybackAllChannelsMixed;
1510 processor_ssrc = &rx_processor_ssrc_;
1511 } else {
1512 signal = &SignalTxMediaFrame;
1513 processing_type = webrtc::kRecordingPerChannel;
1514 processor_ssrc = &tx_processor_ssrc_;
1515 }
1516
1517 int deregister_id = -1;
1518 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001519 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001520 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1521 signal->disconnect(voice_processor);
1522 int channel_id = -1;
1523 bool found_channel = FindChannelNumFromSsrc(ssrc,
1524 channel_direction,
1525 &channel_id);
1526 if (signal->is_empty() && found_channel) {
1527 deregister_id = channel_id;
1528 }
1529 }
1530 }
1531 if (deregister_id != -1) {
1532 if (voe()->media() &&
1533 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1534 processing_type) != -1) {
1535 *processor_ssrc = 0;
1536 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1537 << deregister_id;
1538 } else {
1539 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1540 deregister_id,
1541 processing_type);
1542 success = false;
1543 }
1544 }
1545 return success;
1546}
1547
1548bool WebRtcVoiceEngine::UnregisterProcessor(
1549 uint32 ssrc,
1550 VoiceProcessor* voice_processor,
1551 MediaProcessorDirection direction) {
1552 bool success = true;
1553 if (voice_processor == NULL) {
1554 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1555 << ssrc;
1556 return false;
1557 }
1558 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1559 success = false;
1560 }
1561 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1562 success = false;
1563 }
1564 return success;
1565}
1566
1567// Implementing method from WebRtc VoEMediaProcess interface
1568// Do not lock mux_channel_cs_ in this callback.
1569void WebRtcVoiceEngine::Process(int channel,
1570 webrtc::ProcessingTypes type,
1571 int16_t audio10ms[],
1572 int length,
1573 int sampling_freq,
1574 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001575 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001576 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1577 if (type == webrtc::kPlaybackAllChannelsMixed) {
1578 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1579 } else if (type == webrtc::kRecordingPerChannel) {
1580 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1581 } else {
1582 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1583 << " channel: " << channel << " type: " << type
1584 << " tx_ssrc: " << tx_processor_ssrc_
1585 << " rx_ssrc: " << rx_processor_ssrc_;
1586 }
1587}
1588
1589void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1590 if (!is_dumping_aec_) {
1591 // Start dumping AEC when we are not dumping.
1592 if (voe_wrapper_->processing()->StartDebugRecording(
1593 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001594 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001595 } else {
1596 is_dumping_aec_ = true;
1597 }
1598 }
1599}
1600
1601void WebRtcVoiceEngine::StopAecDump() {
1602 if (is_dumping_aec_) {
1603 // Stop dumping AEC when we are dumping.
1604 if (voe_wrapper_->processing()->StopDebugRecording() !=
1605 webrtc::AudioProcessing::kNoError) {
1606 LOG_RTCERR0(StopDebugRecording);
1607 }
1608 is_dumping_aec_ = false;
1609 }
1610}
1611
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001612int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001613 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001614}
1615
1616int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1617 return CreateVoiceChannel(voe_wrapper_.get());
1618}
1619
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001620class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1621 : public AudioRenderer::Sink {
1622 public:
1623 WebRtcVoiceChannelRenderer(int ch,
1624 webrtc::AudioTransport* voe_audio_transport)
1625 : channel_(ch),
1626 voe_audio_transport_(voe_audio_transport),
pbos8fc7fa72015-07-15 08:02:58 -07001627 renderer_(NULL) {}
Fredrik Solenbergaaf8ff22015-05-07 16:05:53 +02001628 ~WebRtcVoiceChannelRenderer() override { Stop(); }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001629
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001630 // Starts the rendering by setting a sink to the renderer to get data
1631 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001632 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001633 // TODO(xians): Make sure Start() is called only once.
1634 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001635 rtc::CritScope lock(&lock_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001636 DCHECK(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001637 if (renderer_ != NULL) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001638 DCHECK(renderer_ == renderer);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001639 return;
1640 }
1641
1642 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1643 // in getUserMedia by default.
1644 renderer->AddChannel(channel_);
1645 renderer->SetSink(this);
1646 renderer_ = renderer;
1647 }
1648
1649 // Stops rendering by setting the sink of the renderer to NULL. No data
1650 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001651 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001652 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001653 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001654 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001655 return;
1656
1657 renderer_->RemoveChannel(channel_);
1658 renderer_->SetSink(NULL);
1659 renderer_ = NULL;
1660 }
1661
1662 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001663 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001664 void OnData(const void* audio_data,
1665 int bits_per_sample,
1666 int sample_rate,
1667 int number_of_channels,
1668 int number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001669 voe_audio_transport_->OnData(channel_,
1670 audio_data,
1671 bits_per_sample,
1672 sample_rate,
1673 number_of_channels,
1674 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001675 }
1676
1677 // Callback from the |renderer_| when it is going away. In case Start() has
1678 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001679 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001680 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001681 // Set |renderer_| to NULL to make sure no more callback will get into
1682 // the renderer.
1683 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001684 }
1685
1686 // Accessor to the VoE channel ID.
1687 int channel() const { return channel_; }
1688
1689 private:
1690 const int channel_;
1691 webrtc::AudioTransport* const voe_audio_transport_;
1692
1693 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1694 // PeerConnection will make sure invalidating the pointer before the object
1695 // goes away.
1696 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001697
1698 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001699 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001700};
1701
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001702// WebRtcVoiceMediaChannel
Fredrik Solenberge444a3d2015-05-07 16:42:08 +02001703WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine)
1704 : engine_(engine),
1705 voe_channel_(engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001706 send_bitrate_setting_(false),
1707 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001708 options_(),
1709 dtmf_allowed_(false),
1710 desired_playout_(false),
1711 nack_enabled_(false),
1712 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001713 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001714 desired_send_(SEND_NOTHING),
1715 send_(SEND_NOTHING),
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001716 call_(nullptr),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001717 default_receive_ssrc_(0) {
1718 engine->RegisterChannel(this);
1719 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1720 << voe_channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001721 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001722}
1723
1724WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1725 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1726 << voe_channel();
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001727 DCHECK(receive_streams_.empty() || call_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001728
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001729 // Remove any remaining send streams, the default channel will be deleted
1730 // later.
1731 while (!send_channels_.empty())
1732 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001733
1734 // Unregister ourselves from the engine.
1735 engine()->UnregisterChannel(this);
1736 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001737 while (!receive_channels_.empty()) {
1738 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001739 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001740 DCHECK(receive_streams_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001741
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001742 // Delete the default channel.
1743 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001744}
1745
1746bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1747 LOG(LS_INFO) << "Setting voice channel options: "
1748 << options.ToString();
1749
wu@webrtc.orgde305012013-10-31 15:40:38 +00001750 // Check if DSCP value is changed from previous.
1751 bool dscp_option_changed = (options_.dscp != options.dscp);
1752
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001753 // TODO(xians): Add support to set different options for different send
1754 // streams after we support multiple APMs.
1755
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001756 // We retain all of the existing options, and apply the given ones
1757 // on top. This means there is no way to "clear" options such that
1758 // they go back to the engine default.
1759 options_.SetAll(options);
1760
1761 if (send_ != SEND_NOTHING) {
1762 if (!engine()->SetOptionOverrides(options_)) {
1763 LOG(LS_WARNING) <<
1764 "Failed to engine SetOptionOverrides during channel SetOptions.";
1765 return false;
1766 }
1767 } else {
1768 // Will be interpreted when appropriate.
1769 }
1770
wu@webrtc.org97077a32013-10-25 21:18:33 +00001771 // Receiver-side auto gain control happens per channel, so set it here from
1772 // options. Note that, like conference mode, setting it on the engine won't
1773 // have the desired effect, since voice channels don't inherit options from
1774 // the media engine when those options are applied per-channel.
1775 bool rx_auto_gain_control;
1776 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1777 if (engine()->voe()->processing()->SetRxAgcStatus(
1778 voe_channel(), rx_auto_gain_control,
1779 webrtc::kAgcFixedDigital) == -1) {
1780 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1781 return false;
1782 } else {
1783 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1784 << " with mode " << webrtc::kAgcFixedDigital;
1785 }
1786 }
1787 if (options.rx_agc_target_dbov.IsSet() ||
1788 options.rx_agc_digital_compression_gain.IsSet() ||
1789 options.rx_agc_limiter.IsSet()) {
1790 webrtc::AgcConfig config;
1791 // If only some of the options are being overridden, get the current
1792 // settings for the channel and bail if they aren't available.
1793 if (!options.rx_agc_target_dbov.IsSet() ||
1794 !options.rx_agc_digital_compression_gain.IsSet() ||
1795 !options.rx_agc_limiter.IsSet()) {
1796 if (engine()->voe()->processing()->GetRxAgcConfig(
1797 voe_channel(), config) != 0) {
1798 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1799 << "channel " << voe_channel() << ". Since not all rx "
1800 << "agc options are specified, unable to safely set rx "
1801 << "agc options.";
1802 return false;
1803 }
1804 }
1805 config.targetLeveldBOv =
1806 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1807 config.targetLeveldBOv);
1808 config.digitalCompressionGaindB =
1809 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1810 config.digitalCompressionGaindB);
1811 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1812 config.limiterEnable);
1813 if (engine()->voe()->processing()->SetRxAgcConfig(
1814 voe_channel(), config) == -1) {
1815 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1816 config.digitalCompressionGaindB, config.limiterEnable);
1817 return false;
1818 }
1819 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001820 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001821 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001822 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001823 dscp = kAudioDscpValue;
1824 if (MediaChannel::SetDscp(dscp) != 0) {
1825 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1826 }
1827 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001828
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001829 SetCall(call_);
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001830
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001831 LOG(LS_INFO) << "Set voice channel options. Current options: "
1832 << options_.ToString();
1833 return true;
1834}
1835
1836bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1837 const std::vector<AudioCodec>& codecs) {
1838 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001839 LOG(LS_INFO) << "Setting receive voice codecs:";
1840
1841 std::vector<AudioCodec> new_codecs;
1842 // Find all new codecs. We allow adding new codecs but don't allow changing
1843 // the payload type of codecs that is already configured since we might
1844 // already be receiving packets with that payload type.
1845 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001846 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001847 AudioCodec old_codec;
1848 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1849 if (old_codec.id != it->id) {
1850 LOG(LS_ERROR) << it->name << " payload type changed.";
1851 return false;
1852 }
1853 } else {
1854 new_codecs.push_back(*it);
1855 }
1856 }
1857 if (new_codecs.empty()) {
1858 // There are no new codecs to configure. Already configured codecs are
1859 // never removed.
1860 return true;
1861 }
1862
1863 if (playout_) {
1864 // Receive codecs can not be changed while playing. So we temporarily
1865 // pause playout.
1866 PausePlayout();
1867 }
1868
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001869 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001870 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1871 it != new_codecs.end() && ret; ++it) {
1872 webrtc::CodecInst voe_codec;
1873 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1874 LOG(LS_INFO) << ToString(*it);
1875 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001876 if (default_receive_ssrc_ == 0) {
1877 // Set the receive codecs on the default channel explicitly if the
1878 // default channel is not used by |receive_channels_|, this happens in
1879 // conference mode or in non-conference mode when there is no playout
1880 // channel.
1881 // TODO(xians): Figure out how we use the default channel in conference
1882 // mode.
1883 if (engine()->voe()->codec()->SetRecPayloadType(
1884 voe_channel(), voe_codec) == -1) {
1885 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1886 ret = false;
1887 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001888 }
1889
1890 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001891 for (ChannelMap::iterator it = receive_channels_.begin();
1892 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001893 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001894 it->second->channel(), voe_codec) == -1) {
1895 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001896 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001897 ret = false;
1898 }
1899 }
1900 } else {
1901 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1902 ret = false;
1903 }
1904 }
1905 if (ret) {
1906 recv_codecs_ = codecs;
1907 }
1908
1909 if (desired_playout_ && !playout_) {
1910 ResumePlayout();
1911 }
1912 return ret;
1913}
1914
1915bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001916 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001917 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001918 engine()->voe()->codec()->SetVADStatus(channel, false);
1919 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001920 engine()->voe()->rtp()->SetREDStatus(channel, false);
1921 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001922
1923 // Scan through the list to figure out the codec to use for sending, along
1924 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001925 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001926 webrtc::CodecInst send_codec;
1927 memset(&send_codec, 0, sizeof(send_codec));
1928
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001929 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001930 bool enable_codec_fec = false;
Minyue Li7100dcd2015-03-27 05:05:59 +01001931 bool enable_opus_dtx = false;
minyue@webrtc.org26236952014-10-29 02:27:08 +00001932 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001933
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001934 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001935 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1936 it != codecs.end(); ++it) {
1937 // Ignore codecs we don't know about. The negotiation step should prevent
1938 // this, but double-check to be sure.
1939 webrtc::CodecInst voe_codec;
1940 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001941 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001942 continue;
1943 }
1944
Minyue Li7100dcd2015-03-27 05:05:59 +01001945 if (IsCodec(*it, kDtmfCodecName) || IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001946 // Skip telephone-event/CN codec, which will be handled later.
1947 continue;
1948 }
1949
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001950 // We'll use the first codec in the list to actually send audio data.
1951 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001952 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001953 // used is specified in params.
Minyue Li7100dcd2015-03-27 05:05:59 +01001954 if (IsCodec(*it, kRedCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001955 // Parse out the RED parameters. If we fail, just ignore RED;
1956 // we don't support all possible params/usage scenarios.
1957 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
1958 continue;
1959 }
1960
1961 // Enable redundant encoding of the specified codec. Treat any
1962 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001963 LOG(LS_INFO) << "Enabling RED on channel " << channel;
1964 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
1965 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001966 return false;
1967 }
1968 } else {
1969 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001970 nack_enabled = IsNackEnabled(*it);
Minyue Li7100dcd2015-03-27 05:05:59 +01001971 // For Opus as the send codec, we are to determine inband FEC, maximum
1972 // playback rate, and opus internal dtx.
1973 if (IsCodec(*it, kOpusCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00001974 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
Minyue Li7100dcd2015-03-27 05:05:59 +01001975 &opus_max_playback_rate, &enable_opus_dtx);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001976 }
Brave Yao5225dd82015-03-26 07:39:19 +08001977
1978 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1979 int ptime_ms = 0;
1980 if (it->GetParam(kCodecParamPTime, &ptime_ms)) {
1981 if (!SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
1982 LOG(LS_WARNING) << "Failed to set packet size for codec "
1983 << send_codec.plname;
1984 return false;
1985 }
1986 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001987 }
1988 found_send_codec = true;
1989 break;
1990 }
1991
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001992 if (nack_enabled_ != nack_enabled) {
1993 SetNack(channel, nack_enabled);
1994 nack_enabled_ = nack_enabled;
1995 }
1996
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001997 if (!found_send_codec) {
1998 LOG(LS_WARNING) << "Received empty list of codecs.";
1999 return false;
2000 }
2001
2002 // Set the codec immediately, since SetVADStatus() depends on whether
2003 // the current codec is mono or stereo.
2004 if (!SetSendCodec(channel, send_codec))
2005 return false;
2006
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002007 // FEC should be enabled after SetSendCodec.
2008 if (enable_codec_fec) {
2009 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2010 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002011 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2012 // Enable codec internal FEC. Treat any failure as fatal internal error.
2013 LOG_RTCERR2(SetFECStatus, channel, true);
2014 return false;
2015 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002016 }
2017
Minyue Li7100dcd2015-03-27 05:05:59 +01002018 if (IsCodec(send_codec, kOpusCodecName)) {
2019 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
2020 // send codec has to be Opus.
2021
2022 // Set Opus internal DTX.
2023 LOG(LS_INFO) << "Attempt to "
2024 << GetEnableString(enable_opus_dtx)
2025 << " Opus DTX on channel "
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002026 << channel;
Minyue Li7100dcd2015-03-27 05:05:59 +01002027 if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) {
2028 LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx);
2029 return false;
2030 }
2031
2032 // If opus_max_playback_rate <= 0, the default maximum playback rate
2033 // (48 kHz) will be used.
2034 if (opus_max_playback_rate > 0) {
2035 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
2036 << opus_max_playback_rate
2037 << " Hz on channel "
2038 << channel;
2039 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
2040 channel, opus_max_playback_rate) == -1) {
2041 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate);
2042 return false;
2043 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002044 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002045 }
2046
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002047 // Always update the |send_codec_| to the currently set send codec.
2048 send_codec_.reset(new webrtc::CodecInst(send_codec));
2049
minyue@webrtc.org26236952014-10-29 02:27:08 +00002050 if (send_bitrate_setting_) {
2051 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002052 }
2053
2054 // Loop through the codecs list again to config the telephone-event/CN codec.
2055 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2056 it != codecs.end(); ++it) {
2057 // Ignore codecs we don't know about. The negotiation step should prevent
2058 // this, but double-check to be sure.
2059 webrtc::CodecInst voe_codec;
2060 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2061 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2062 continue;
2063 }
2064
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002065 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2066 // about it.
Minyue Li7100dcd2015-03-27 05:05:59 +01002067 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002068 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2069 channel, it->id) == -1) {
2070 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2071 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002072 }
Minyue Li7100dcd2015-03-27 05:05:59 +01002073 } else if (IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002074 // Turn voice activity detection/comfort noise on if supported.
2075 // Set the wideband CN payload type appropriately.
2076 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002077 webrtc::PayloadFrequencies cn_freq;
2078 switch (it->clockrate) {
2079 case 8000:
2080 cn_freq = webrtc::kFreq8000Hz;
2081 break;
2082 case 16000:
2083 cn_freq = webrtc::kFreq16000Hz;
2084 break;
2085 case 32000:
2086 cn_freq = webrtc::kFreq32000Hz;
2087 break;
2088 default:
2089 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2090 << " not supported.";
2091 continue;
2092 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002093 // Set the CN payloadtype and the VAD status.
2094 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2095 if (cn_freq != webrtc::kFreq8000Hz) {
2096 if (engine()->voe()->codec()->SetSendCNPayloadType(
2097 channel, it->id, cn_freq) == -1) {
2098 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2099 // TODO(ajm): This failure condition will be removed from VoE.
2100 // Restore the return here when we update to a new enough webrtc.
2101 //
2102 // Not returning false because the SetSendCNPayloadType will fail if
2103 // the channel is already sending.
2104 // This can happen if the remote description is applied twice, for
2105 // example in the case of ROAP on top of JSEP, where both side will
2106 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002107 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002108 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002109 // Only turn on VAD if we have a CN payload type that matches the
2110 // clockrate for the codec we are going to use.
Minyue Li7100dcd2015-03-27 05:05:59 +01002111 if (it->clockrate == send_codec.plfreq && send_codec.channels != 2) {
2112 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
2113 // interaction between VAD and Opus FEC.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002114 LOG(LS_INFO) << "Enabling VAD";
2115 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2116 LOG_RTCERR2(SetVADStatus, channel, true);
2117 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002118 }
2119 }
2120 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002121 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002122 return true;
2123}
2124
2125bool WebRtcVoiceMediaChannel::SetSendCodecs(
2126 const std::vector<AudioCodec>& codecs) {
2127 dtmf_allowed_ = false;
2128 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2129 it != codecs.end(); ++it) {
2130 // Find the DTMF telephone event "codec".
Minyue Li7100dcd2015-03-27 05:05:59 +01002131 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002132 dtmf_allowed_ = true;
2133 }
2134 }
2135
2136 // Cache the codecs in order to configure the channel created later.
2137 send_codecs_ = codecs;
2138 for (ChannelMap::iterator iter = send_channels_.begin();
2139 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002140 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002141 return false;
2142 }
2143 }
2144
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002145 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002146 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002147 return true;
2148}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002149
2150void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2151 bool nack_enabled) {
2152 for (ChannelMap::const_iterator it = channels.begin();
2153 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002154 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002155 }
2156}
2157
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002158void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002159 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002160 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002161 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2162 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002163 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002164 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2165 }
2166}
2167
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002168bool WebRtcVoiceMediaChannel::SetSendCodec(
2169 const webrtc::CodecInst& send_codec) {
2170 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2171 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002172 for (ChannelMap::iterator iter = send_channels_.begin();
2173 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002174 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002175 return false;
2176 }
2177
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002178 return true;
2179}
2180
2181bool WebRtcVoiceMediaChannel::SetSendCodec(
2182 int channel, const webrtc::CodecInst& send_codec) {
2183 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2184 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2185
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002186 webrtc::CodecInst current_codec;
2187 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2188 (send_codec == current_codec)) {
2189 // Codec is already configured, we can return without setting it again.
2190 return true;
2191 }
2192
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002193 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2194 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002195 return false;
2196 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002197 return true;
2198}
2199
2200bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2201 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002202 if (receive_extensions_ == extensions) {
2203 return true;
2204 }
2205
2206 // The default channel may or may not be in |receive_channels_|. Set the rtp
2207 // header extensions for default channel regardless.
2208 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2209 return false;
2210 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002211
2212 // Loop through all receive channels and enable/disable the extensions.
2213 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2214 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002215 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2216 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002217 return false;
2218 }
2219 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002220
2221 receive_extensions_ = extensions;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002222
2223 // Recreate AudioReceiveStream:s.
2224 {
2225 std::vector<webrtc::RtpExtension> exts;
2226
2227 const RtpHeaderExtension* audio_level_extension =
2228 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2229 if (audio_level_extension) {
2230 exts.push_back({
2231 kRtpAudioLevelHeaderExtension, audio_level_extension->id});
2232 }
2233
2234 const RtpHeaderExtension* send_time_extension =
2235 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2236 if (send_time_extension) {
2237 exts.push_back({
2238 kRtpAbsoluteSenderTimeHeaderExtension, send_time_extension->id});
2239 }
2240
2241 recv_rtp_extensions_.swap(exts);
2242 SetCall(call_);
2243 }
2244
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002245 return true;
2246}
2247
2248bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2249 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002250 const RtpHeaderExtension* audio_level_extension =
2251 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2252 if (!SetHeaderExtension(
2253 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2254 audio_level_extension)) {
2255 return false;
2256 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002257
2258 const RtpHeaderExtension* send_time_extension =
2259 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2260 if (!SetHeaderExtension(
2261 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2262 send_time_extension)) {
2263 return false;
2264 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002265
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002266 return true;
2267}
2268
2269bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2270 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002271 if (send_extensions_ == extensions) {
2272 return true;
2273 }
2274
2275 // The default channel may or may not be in |send_channels_|. Set the rtp
2276 // header extensions for default channel regardless.
2277
2278 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2279 return false;
2280 }
2281
2282 // Loop through all send channels and enable/disable the extensions.
2283 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2284 channel_it != send_channels_.end(); ++channel_it) {
2285 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2286 extensions)) {
2287 return false;
2288 }
2289 }
2290
2291 send_extensions_ = extensions;
2292 return true;
2293}
2294
2295bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2296 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002297 const RtpHeaderExtension* audio_level_extension =
2298 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002299
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002300 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002301 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002302 audio_level_extension)) {
2303 return false;
2304 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002305
2306 const RtpHeaderExtension* send_time_extension =
2307 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002308 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002309 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002310 send_time_extension)) {
2311 return false;
2312 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002313
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002314 return true;
2315}
2316
2317bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2318 desired_playout_ = playout;
2319 return ChangePlayout(desired_playout_);
2320}
2321
2322bool WebRtcVoiceMediaChannel::PausePlayout() {
2323 return ChangePlayout(false);
2324}
2325
2326bool WebRtcVoiceMediaChannel::ResumePlayout() {
2327 return ChangePlayout(desired_playout_);
2328}
2329
2330bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2331 if (playout_ == playout) {
2332 return true;
2333 }
2334
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002335 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002336 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002337 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002338 // Only toggle the default channel if we don't have any other channels.
2339 result = SetPlayout(voe_channel(), playout);
2340 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002341 for (ChannelMap::iterator it = receive_channels_.begin();
2342 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002343 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002344 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002345 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002346 result = false;
2347 }
2348 }
2349
2350 if (result) {
2351 playout_ = playout;
2352 }
2353 return result;
2354}
2355
2356bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2357 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002358 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002359 return ChangeSend(desired_send_);
2360 return true;
2361}
2362
2363bool WebRtcVoiceMediaChannel::PauseSend() {
2364 return ChangeSend(SEND_NOTHING);
2365}
2366
2367bool WebRtcVoiceMediaChannel::ResumeSend() {
2368 return ChangeSend(desired_send_);
2369}
2370
2371bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2372 if (send_ == send) {
2373 return true;
2374 }
2375
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002376 // Change the settings on each send channel.
2377 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002378 engine()->SetOptionOverrides(options_);
2379
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002380 // Change the settings on each send channel.
2381 for (ChannelMap::iterator iter = send_channels_.begin();
2382 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002383 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002384 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002385 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002386
2387 // Clear up the options after stopping sending.
2388 if (send == SEND_NOTHING)
2389 engine()->ClearOptionOverrides();
2390
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002391 send_ = send;
2392 return true;
2393}
2394
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002395bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2396 if (send == SEND_MICROPHONE) {
2397 if (engine()->voe()->base()->StartSend(channel) == -1) {
2398 LOG_RTCERR1(StartSend, channel);
2399 return false;
2400 }
2401 if (engine()->voe()->file() &&
2402 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2403 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2404 return false;
2405 }
2406 } else { // SEND_NOTHING
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002407 DCHECK(send == SEND_NOTHING);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002408 if (engine()->voe()->base()->StopSend(channel) == -1) {
2409 LOG_RTCERR1(StopSend, channel);
2410 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002411 }
2412 }
2413
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002414 return true;
2415}
2416
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002417// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002418void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2419 if (engine()->voe()->network()->RegisterExternalTransport(
2420 channel, *this) == -1) {
2421 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2422 }
2423
2424 // Enable RTCP (for quality stats and feedback messages)
2425 EnableRtcp(channel);
2426
2427 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2428 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002429
2430 // Set RTP header extension for the new channel.
2431 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002432}
2433
2434bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2435 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2436 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2437 }
2438
2439 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2440 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002441 return false;
2442 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002443
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002444 return true;
2445}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002446
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002447bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2448 // If the default channel is already used for sending create a new channel
2449 // otherwise use the default channel for sending.
2450 int channel = GetSendChannelNum(sp.first_ssrc());
2451 if (channel != -1) {
2452 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2453 return false;
2454 }
2455
2456 bool default_channel_is_available = true;
2457 for (ChannelMap::const_iterator iter = send_channels_.begin();
2458 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002459 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002460 default_channel_is_available = false;
2461 break;
2462 }
2463 }
2464 if (default_channel_is_available) {
2465 channel = voe_channel();
2466 } else {
2467 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002468 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002469 if (channel == -1) {
2470 LOG_RTCERR0(CreateChannel);
2471 return false;
2472 }
2473
2474 ConfigureSendChannel(channel);
2475 }
2476
2477 // Save the channel to send_channels_, so that RemoveSendStream() can still
2478 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002479 webrtc::AudioTransport* audio_transport =
2480 engine()->voe()->base()->audio_transport();
pbos8fc7fa72015-07-15 08:02:58 -07002481 send_channels_.insert(
2482 std::make_pair(sp.first_ssrc(),
2483 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002484
2485 // Set the send (local) SSRC.
2486 // If there are multiple send SSRCs, we can only set the first one here, and
2487 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2488 // (with a codec requires multiple SSRC(s)).
2489 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2490 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2491 return false;
2492 }
2493
2494 // At this point the channel's local SSRC has been updated. If the channel is
2495 // the default channel make sure that all the receive channels are updated as
2496 // well. Receive channels have to have the same SSRC as the default channel in
2497 // order to send receiver reports with this SSRC.
2498 if (IsDefaultChannel(channel)) {
2499 for (ChannelMap::const_iterator it = receive_channels_.begin();
2500 it != receive_channels_.end(); ++it) {
2501 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002502 if (!IsDefaultChannel(it->second->channel())) {
2503 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002504 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002505 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002506 return false;
2507 }
2508 }
2509 }
2510 }
2511
2512 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002513 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2514 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002515 }
2516
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002517 // Set the current codecs to be used for the new channel.
2518 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002519 return false;
2520
2521 return ChangeSend(channel, desired_send_);
2522}
2523
2524bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2525 ChannelMap::iterator it = send_channels_.find(ssrc);
2526 if (it == send_channels_.end()) {
2527 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2528 << " which doesn't exist.";
2529 return false;
2530 }
2531
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002532 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002533 ChangeSend(channel, SEND_NOTHING);
2534
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002535 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2536 // this will disconnect the audio renderer with the send channel.
2537 delete it->second;
2538 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002539
2540 if (IsDefaultChannel(channel)) {
2541 // Do not delete the default channel since the receive channels depend on
2542 // the default channel, recycle it instead.
2543 ChangeSend(channel, SEND_NOTHING);
2544 } else {
2545 // Clean up and delete the send channel.
2546 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2547 << " with VoiceEngine channel #" << channel << ".";
2548 if (!DeleteChannel(channel))
2549 return false;
2550 }
2551
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002552 if (send_channels_.empty())
2553 ChangeSend(SEND_NOTHING);
2554
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002555 return true;
2556}
2557
2558bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002559 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002560 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002561
2562 if (!VERIFY(sp.ssrcs.size() == 1))
2563 return false;
2564 uint32 ssrc = sp.first_ssrc();
2565
wu@webrtc.org78187522013-10-07 23:32:02 +00002566 if (ssrc == 0) {
2567 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2568 return false;
2569 }
2570
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002571 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2572 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002573 return false;
2574 }
2575
pbos8fc7fa72015-07-15 08:02:58 -07002576 DCHECK(receive_stream_params_.find(ssrc) == receive_stream_params_.end());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002577
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002578 // Reuse default channel for recv stream in non-conference mode call
2579 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002580 webrtc::AudioTransport* audio_transport =
2581 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002582 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002583 LOG(LS_INFO) << "Recv stream " << ssrc << " reuse default channel";
2584 default_receive_ssrc_ = ssrc;
pbos8fc7fa72015-07-15 08:02:58 -07002585 WebRtcVoiceChannelRenderer* channel_renderer =
2586 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport);
2587 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2588 receive_stream_params_[ssrc] = sp;
2589 TryAddAudioRecvStream(ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002590 return SetPlayout(voe_channel(), playout_);
2591 }
2592
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002593 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002594 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002595 if (channel == -1) {
2596 LOG_RTCERR0(CreateChannel);
2597 return false;
2598 }
2599
wu@webrtc.org78187522013-10-07 23:32:02 +00002600 if (!ConfigureRecvChannel(channel)) {
2601 DeleteChannel(channel);
2602 return false;
2603 }
2604
pbos8fc7fa72015-07-15 08:02:58 -07002605 WebRtcVoiceChannelRenderer* channel_renderer =
2606 new WebRtcVoiceChannelRenderer(channel, audio_transport);
2607 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2608 receive_stream_params_[ssrc] = sp;
2609 TryAddAudioRecvStream(ssrc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002610
2611 LOG(LS_INFO) << "New audio stream " << ssrc
2612 << " registered to VoiceEngine channel #"
2613 << channel << ".";
2614 return true;
2615}
2616
2617bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002618 // Configure to use external transport, like our default channel.
2619 if (engine()->voe()->network()->RegisterExternalTransport(
2620 channel, *this) == -1) {
2621 LOG_RTCERR2(SetExternalTransport, channel, this);
2622 return false;
2623 }
2624
2625 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002626 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002627 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2628 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002629 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002630 return false;
2631 }
2632 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002633 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002634 return false;
2635 }
2636
Minyue2013aec2015-05-13 14:14:42 +02002637 // Associate receive channel to default channel (so the receive channel can
2638 // obtain RTT from the send channel)
2639 engine()->voe()->base()->AssociateSendChannel(channel, voe_channel());
2640 LOG(LS_INFO) << "VoiceEngine channel #"
2641 << channel << " is associated with channel #"
2642 << voe_channel() << ".";
2643
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002644 // Use the same recv payload types as our default channel.
2645 ResetRecvCodecs(channel);
2646 if (!recv_codecs_.empty()) {
2647 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2648 it != recv_codecs_.end(); ++it) {
2649 webrtc::CodecInst voe_codec;
2650 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2651 voe_codec.pltype = it->id;
2652 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2653 if (engine()->voe()->codec()->GetRecPayloadType(
2654 voe_channel(), voe_codec) != -1) {
2655 if (engine()->voe()->codec()->SetRecPayloadType(
2656 channel, voe_codec) == -1) {
2657 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2658 return false;
2659 }
2660 }
2661 }
2662 }
2663 }
2664
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002665 if (InConferenceMode()) {
2666 // To be in par with the video, voe_channel() is not used for receiving in
2667 // a conference call.
2668 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2669 // This is the first stream in a multi user meeting. We can now
2670 // disable playback of the default stream. This since the default
2671 // stream will probably have received some initial packets before
2672 // the new stream was added. This will mean that the CN state from
2673 // the default channel will be mixed in with the other streams
2674 // throughout the whole meeting, which might be disturbing.
2675 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2676 SetPlayout(voe_channel(), false);
2677 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002678 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002679 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002680
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002681 // Set RTP header extension for the new channel.
2682 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2683 return false;
2684 }
2685
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002686 return SetPlayout(channel, playout_);
2687}
2688
2689bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002690 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002691 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002692 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002693 if (it == receive_channels_.end()) {
2694 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2695 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002696 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002697 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002698
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002699 TryRemoveAudioRecvStream(ssrc);
pbos8fc7fa72015-07-15 08:02:58 -07002700 receive_stream_params_.erase(ssrc);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002701
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002702 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2703 // will disconnect the audio renderer with the receive channel.
2704 // Cache the channel before the deletion.
2705 const int channel = it->second->channel();
2706 delete it->second;
2707 receive_channels_.erase(it);
2708
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002709 if (ssrc == default_receive_ssrc_) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002710 DCHECK(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002711 // Recycle the default channel is for recv stream.
2712 if (playout_)
2713 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002714
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002715 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002716 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002717 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002718
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002719 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002720 << " with VoiceEngine channel #" << channel << ".";
2721 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002722 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002723
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002724 bool enable_default_channel_playout = false;
2725 if (receive_channels_.empty()) {
2726 // The last stream was removed. We can now enable the default
2727 // channel for new channels to be played out immediately without
2728 // waiting for AddStream messages.
2729 // We do this for both conference mode and non-conference mode.
2730 // TODO(oja): Does the default channel still have it's CN state?
2731 enable_default_channel_playout = true;
2732 }
2733 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2734 default_receive_ssrc_ != 0) {
2735 // Only the default channel is active, enable the playout on default
2736 // channel.
2737 enable_default_channel_playout = true;
2738 }
2739 if (enable_default_channel_playout && playout_) {
2740 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2741 SetPlayout(voe_channel(), true);
2742 }
2743
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002744 return true;
2745}
2746
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002747bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2748 AudioRenderer* renderer) {
2749 ChannelMap::iterator it = receive_channels_.find(ssrc);
2750 if (it == receive_channels_.end()) {
2751 if (renderer) {
2752 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002753 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002754 return false;
2755 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002756
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002757 // The channel likely has gone away, do nothing.
2758 return true;
2759 }
2760
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002761 if (renderer)
2762 it->second->Start(renderer);
2763 else
2764 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002765
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002766 return true;
2767}
2768
2769bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2770 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002771 ChannelMap::iterator it = send_channels_.find(ssrc);
2772 if (it == send_channels_.end()) {
2773 if (renderer) {
2774 // Return an error if trying to set a valid renderer with an invalid ssrc.
2775 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2776 return false;
2777 }
2778
2779 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002780 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002781 }
2782
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002783 if (renderer)
2784 it->second->Start(renderer);
2785 else
2786 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002787
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002788 return true;
2789}
2790
2791bool WebRtcVoiceMediaChannel::GetActiveStreams(
2792 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002793 // In conference mode, the default channel should not be in
2794 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002795 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002796 for (ChannelMap::iterator it = receive_channels_.begin();
2797 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002798 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002799 if (level > 0) {
2800 actives->push_back(std::make_pair(it->first, level));
2801 }
2802 }
2803 return true;
2804}
2805
2806int WebRtcVoiceMediaChannel::GetOutputLevel() {
2807 // return the highest output level of all streams
2808 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002809 for (ChannelMap::iterator it = receive_channels_.begin();
2810 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002811 int level = GetOutputLevel(it->second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002812 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002813 }
2814 return highest;
2815}
2816
2817int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2818 int ret;
2819 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2820 // In case of error, log the info and continue
2821 LOG_RTCERR0(TimeSinceLastTyping);
2822 ret = -1;
2823 } else {
2824 ret *= 1000; // We return ms, webrtc returns seconds.
2825 }
2826 return ret;
2827}
2828
2829void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2830 int cost_per_typing, int reporting_threshold, int penalty_decay,
2831 int type_event_delay) {
2832 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2833 time_window, cost_per_typing,
2834 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2835 // In case of error, log the info and continue
2836 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2837 cost_per_typing, reporting_threshold, penalty_decay,
2838 type_event_delay);
2839 }
2840}
2841
2842bool WebRtcVoiceMediaChannel::SetOutputScaling(
2843 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002844 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002845 // Collect the channels to scale the output volume.
2846 std::vector<int> channels;
2847 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002848 // Default channel is not in receive_channels_ if it is not being used for
2849 // playout.
2850 if (default_receive_ssrc_ == 0)
2851 channels.push_back(voe_channel());
2852 for (ChannelMap::const_iterator it = receive_channels_.begin();
2853 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002854 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002855 }
2856 } else { // Collect only the channel of the specified ssrc.
2857 int channel = GetReceiveChannelNum(ssrc);
2858 if (-1 == channel) {
2859 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2860 return false;
2861 }
2862 channels.push_back(channel);
2863 }
2864
2865 // Scale the output volume for the collected channels. We first normalize to
2866 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002867 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002868 if (scale > 0.0001f) {
2869 left /= scale;
2870 right /= scale;
2871 }
2872 for (std::vector<int>::const_iterator it = channels.begin();
2873 it != channels.end(); ++it) {
2874 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2875 *it, scale)) {
2876 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2877 return false;
2878 }
2879 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2880 *it, static_cast<float>(left), static_cast<float>(right))) {
2881 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2882 // Do not return if fails. SetOutputVolumePan is not available for all
2883 // pltforms.
2884 }
2885 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2886 << " right=" << right * scale
2887 << " for channel " << *it << " and ssrc " << ssrc;
2888 }
2889 return true;
2890}
2891
2892bool WebRtcVoiceMediaChannel::GetOutputScaling(
2893 uint32 ssrc, double* left, double* right) {
2894 if (!left || !right) return false;
2895
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002896 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002897 // Determine which channel based on ssrc.
2898 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2899 if (channel == -1) {
2900 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2901 return false;
2902 }
2903
2904 float scaling;
2905 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2906 channel, scaling)) {
2907 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2908 return false;
2909 }
2910
2911 float left_pan;
2912 float right_pan;
2913 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2914 channel, left_pan, right_pan)) {
2915 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2916 // If GetOutputVolumePan fails, we use the default left and right pan.
2917 left_pan = 1.0f;
2918 right_pan = 1.0f;
2919 }
2920
2921 *left = scaling * left_pan;
2922 *right = scaling * right_pan;
2923 return true;
2924}
2925
2926bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2927 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2928 return true;
2929}
2930
2931bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2932 bool play, bool loop) {
2933 if (!ringback_tone_) {
2934 return false;
2935 }
2936
2937 // The voe file api is not available in chrome.
2938 if (!engine()->voe()->file()) {
2939 return false;
2940 }
2941
2942 // Determine which VoiceEngine channel to play on.
2943 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2944 if (channel == -1) {
2945 return false;
2946 }
2947
2948 // Make sure the ringtone is cued properly, and play it out.
2949 if (play) {
2950 ringback_tone_->set_loop(loop);
2951 ringback_tone_->Rewind();
2952 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2953 ringback_tone_.get()) == -1) {
2954 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2955 LOG(LS_ERROR) << "Unable to start ringback tone";
2956 return false;
2957 }
2958 ringback_channels_.insert(channel);
2959 LOG(LS_INFO) << "Started ringback on channel " << channel;
2960 } else {
2961 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2962 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2963 LOG_RTCERR1(StopPlayingFileLocally, channel);
2964 return false;
2965 }
2966 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2967 ringback_channels_.erase(channel);
2968 }
2969
2970 return true;
2971}
2972
2973bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2974 return dtmf_allowed_;
2975}
2976
2977bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2978 int duration, int flags) {
2979 if (!dtmf_allowed_) {
2980 return false;
2981 }
2982
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002983 // Send the event.
2984 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002985 int channel = -1;
2986 if (ssrc == 0) {
2987 bool default_channel_is_inuse = false;
2988 for (ChannelMap::const_iterator iter = send_channels_.begin();
2989 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002990 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002991 default_channel_is_inuse = true;
2992 break;
2993 }
2994 }
2995 if (default_channel_is_inuse) {
2996 channel = voe_channel();
2997 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002998 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002999 }
3000 } else {
3001 channel = GetSendChannelNum(ssrc);
3002 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003003 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003004 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3005 << ssrc << " is not in use.";
3006 return false;
3007 }
3008 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003009 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3010 channel, event, true, duration) == -1) {
3011 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003012 return false;
3013 }
3014 }
3015
3016 // Play the event.
3017 if (flags & cricket::DF_PLAY) {
3018 // Play DTMF tone locally.
3019 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3020 LOG_RTCERR2(PlayDtmfTone, event, duration);
3021 return false;
3022 }
3023 }
3024
3025 return true;
3026}
3027
wu@webrtc.orga9890802013-12-13 00:21:03 +00003028void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003029 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003030 DCHECK(thread_checker_.CalledOnValidThread());
3031
3032 // If hooked up to a "Call", forward packet there too.
3033 if (call_) {
3034 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3035 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3036 }
3037
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003038 // Pick which channel to send this packet to. If this packet doesn't match
3039 // any multiplexed streams, just send it to the default channel. Otherwise,
3040 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003041 int which_channel =
3042 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003043 if (which_channel == -1) {
3044 which_channel = voe_channel();
3045 }
3046
3047 // Stop any ringback that might be playing on the channel.
3048 // It's possible the ringback has already stopped, ih which case we'll just
3049 // use the opportunity to remove the channel from ringback_channels_.
3050 if (engine()->voe()->file()) {
3051 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3052 if (it != ringback_channels_.end()) {
3053 if (engine()->voe()->file()->IsPlayingFileLocally(
3054 which_channel) == 1) {
3055 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3056 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3057 << " due to incoming media";
3058 }
3059 ringback_channels_.erase(which_channel);
3060 }
3061 }
3062
3063 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003064 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003065 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003066 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003067}
3068
wu@webrtc.orga9890802013-12-13 00:21:03 +00003069void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003070 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003071 DCHECK(thread_checker_.CalledOnValidThread());
3072
3073 // If hooked up to a "Call", forward packet there too.
3074 if (call_) {
3075 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3076 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3077 }
3078
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003079 // Sending channels need all RTCP packets with feedback information.
3080 // Even sender reports can contain attached report blocks.
3081 // Receiving channels need sender reports in order to create
3082 // correct receiver reports.
3083 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003084 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003085 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3086 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003087 }
3088
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003089 // If it is a sender report, find the channel that is listening.
3090 bool has_sent_to_default_channel = false;
3091 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003092 int which_channel =
3093 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003094 if (which_channel != -1) {
3095 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003096 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003097
3098 if (IsDefaultChannel(which_channel))
3099 has_sent_to_default_channel = true;
3100 }
3101 }
3102
3103 // SR may continue RR and any RR entry may correspond to any one of the send
3104 // channels. So all RTCP packets must be forwarded all send channels. VoE
3105 // will filter out RR internally.
3106 for (ChannelMap::iterator iter = send_channels_.begin();
3107 iter != send_channels_.end(); ++iter) {
3108 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003109 if (IsDefaultChannel(iter->second->channel()) &&
3110 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003111 continue;
3112
3113 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003114 iter->second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003115 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003116}
3117
3118bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003119 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3120 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003121 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3122 return false;
3123 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003124 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3125 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003126 return false;
3127 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003128 // We set the AGC to mute state only when all the channels are muted.
3129 // This implementation is not ideal, instead we should signal the AGC when
3130 // the mic channel is muted/unmuted. We can't do it today because there
3131 // is no good way to know which stream is mapping to the mic channel.
3132 bool all_muted = muted;
3133 for (ChannelMap::const_iterator iter = send_channels_.begin();
3134 iter != send_channels_.end() && all_muted; ++iter) {
3135 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3136 all_muted)) {
3137 LOG_RTCERR1(GetInputMute, iter->second->channel());
3138 return false;
3139 }
3140 }
3141
3142 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3143 if (ap)
3144 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003145 return true;
3146}
3147
minyue@webrtc.org26236952014-10-29 02:27:08 +00003148// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3149// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003150bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003151 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003152
minyue@webrtc.org26236952014-10-29 02:27:08 +00003153 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003154}
3155
minyue@webrtc.org26236952014-10-29 02:27:08 +00003156bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3157 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003158
minyue@webrtc.org26236952014-10-29 02:27:08 +00003159 send_bitrate_setting_ = true;
3160 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003161
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003162 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003163 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003164 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003165 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003166 }
3167
minyue@webrtc.org26236952014-10-29 02:27:08 +00003168 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003169 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3170 // SetMaxSendBandwith(0), the second call removes the previous limit.
3171 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003172 return true;
3173
3174 webrtc::CodecInst codec = *send_codec_;
3175 bool is_multi_rate = IsCodecMultiRate(codec);
3176
3177 if (is_multi_rate) {
3178 // If codec is multi-rate then just set the bitrate.
3179 codec.rate = bps;
3180 if (!SetSendCodec(codec)) {
3181 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3182 << " to bitrate " << bps << " bps.";
3183 return false;
3184 }
3185 return true;
3186 } else {
3187 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3188 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3189 // fixed bitrate then ignore.
3190 if (bps < codec.rate) {
3191 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3192 << " to bitrate " << bps << " bps"
3193 << ", requires at least " << codec.rate << " bps.";
3194 return false;
3195 }
3196 return true;
3197 }
3198}
3199
3200bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003201 bool echo_metrics_on = false;
3202 // These can take on valid negative values, so use the lowest possible level
3203 // as default rather than -1.
3204 int echo_return_loss = -100;
3205 int echo_return_loss_enhancement = -100;
3206 // These can also be negative, but in practice -1 is only used to signal
3207 // insufficient data, since the resolution is limited to multiples of 4 ms.
3208 int echo_delay_median_ms = -1;
3209 int echo_delay_std_ms = -1;
3210 if (engine()->voe()->processing()->GetEcMetricsStatus(
3211 echo_metrics_on) != -1 && echo_metrics_on) {
3212 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3213 // here, but it appears to be unsuitable currently. Revisit after this is
3214 // investigated: http://b/issue?id=5666755
3215 int erl, erle, rerl, anlp;
3216 if (engine()->voe()->processing()->GetEchoMetrics(
3217 erl, erle, rerl, anlp) != -1) {
3218 echo_return_loss = erl;
3219 echo_return_loss_enhancement = erle;
3220 }
3221
3222 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003223 float dummy;
3224 if (engine()->voe()->processing()->GetEcDelayMetrics(
3225 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003226 echo_delay_median_ms = median;
3227 echo_delay_std_ms = std;
3228 }
3229 }
3230
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003231 webrtc::CallStatistics cs;
3232 unsigned int ssrc;
3233 webrtc::CodecInst codec;
3234 unsigned int level;
3235
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003236 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3237 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003238 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003239
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003240 // Fill in the sender info, based on what we know, and what the
3241 // remote side told us it got from its RTCP report.
3242 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003243
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003244 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3245 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3246 continue;
3247 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003248
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003249 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003250 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3251 sinfo.bytes_sent = cs.bytesSent;
3252 sinfo.packets_sent = cs.packetsSent;
3253 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3254 // returns 0 to indicate an error value.
3255 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3256
3257 // Get data from the last remote RTCP report. Use default values if no data
3258 // available.
3259 sinfo.fraction_lost = -1.0;
3260 sinfo.jitter_ms = -1;
3261 sinfo.packets_lost = -1;
3262 sinfo.ext_seqnum = -1;
3263 std::vector<webrtc::ReportBlock> receive_blocks;
3264 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3265 channel, &receive_blocks) != -1 &&
3266 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3267 std::vector<webrtc::ReportBlock>::iterator iter;
3268 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3269 ++iter) {
3270 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003271 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003272 // Convert Q8 to floating point.
3273 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3274 // Convert samples to milliseconds.
3275 if (codec.plfreq / 1000 > 0) {
3276 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3277 }
3278 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3279 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3280 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003281 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003282 }
3283 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003284
3285 // Local speech level.
3286 sinfo.audio_level = (engine()->voe()->volume()->
3287 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3288
3289 // TODO(xians): We are injecting the same APM logging to all the send
3290 // channels here because there is no good way to know which send channel
3291 // is using the APM. The correct fix is to allow the send channels to have
3292 // their own APM so that we can feed the correct APM logging to different
3293 // send channels. See issue crbug/264611 .
3294 sinfo.echo_return_loss = echo_return_loss;
3295 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3296 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3297 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003298 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3299 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003300 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003301
3302 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003303 }
3304
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003305 // Build the list of receivers, one for each receiving channel, or 1 in
3306 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003307 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003308 for (ChannelMap::const_iterator it = receive_channels_.begin();
3309 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003310 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003311 }
3312 if (channels.empty()) {
3313 channels.push_back(voe_channel());
3314 }
3315
3316 // Get the SSRC and stats for each receiver, based on our own calculations.
3317 for (std::vector<int>::const_iterator it = channels.begin();
3318 it != channels.end(); ++it) {
3319 memset(&cs, 0, sizeof(cs));
3320 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3321 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3322 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3323 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003324 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003325 rinfo.bytes_rcvd = cs.bytesReceived;
3326 rinfo.packets_rcvd = cs.packetsReceived;
3327 // The next four fields are from the most recently sent RTCP report.
3328 // Convert Q8 to floating point.
3329 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3330 rinfo.packets_lost = cs.cumulativeLost;
3331 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003332 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003333 if (codec.pltype != -1) {
3334 rinfo.codec_name = codec.plname;
3335 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003336 // Convert samples to milliseconds.
3337 if (codec.plfreq / 1000 > 0) {
3338 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3339 }
3340
3341 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3342 webrtc::NetworkStatistics ns;
3343 if (engine()->voe()->neteq() &&
3344 engine()->voe()->neteq()->GetNetworkStatistics(
3345 *it, ns) != -1) {
3346 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3347 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3348 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003349 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003350 rinfo.speech_expand_rate =
3351 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3352 rinfo.secondary_decoded_rate =
3353 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
Henrik Lundin8e6fd462015-06-02 09:24:52 +02003354 rinfo.accelerate_rate =
3355 static_cast<float>(ns.currentAccelerateRate) / (1 << 14);
3356 rinfo.preemptive_expand_rate =
3357 static_cast<float>(ns.currentPreemptiveRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003358 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003359
3360 webrtc::AudioDecodingCallStats ds;
3361 if (engine()->voe()->neteq() &&
3362 engine()->voe()->neteq()->GetDecodingCallStatistics(
3363 *it, &ds) != -1) {
3364 rinfo.decoding_calls_to_silence_generator =
3365 ds.calls_to_silence_generator;
3366 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3367 rinfo.decoding_normal = ds.decoded_normal;
3368 rinfo.decoding_plc = ds.decoded_plc;
3369 rinfo.decoding_cng = ds.decoded_cng;
3370 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3371 }
3372
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003373 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003374 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003375 int playout_buffer_delay_ms = 0;
3376 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003377 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3378 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3379 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003380 }
3381
3382 // Get speech level.
3383 rinfo.audio_level = (engine()->voe()->volume()->
3384 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3385 info->receivers.push_back(rinfo);
3386 }
3387 }
3388
3389 return true;
3390}
3391
3392void WebRtcVoiceMediaChannel::GetLastMediaError(
3393 uint32* ssrc, VoiceMediaChannel::Error* error) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003394 DCHECK(ssrc != NULL);
3395 DCHECK(error != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003396 FindSsrc(voe_channel(), ssrc);
3397 *error = WebRtcErrorToChannelError(GetLastEngineError());
3398}
3399
3400bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003401 rtc::CritScope lock(&receive_channels_cs_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003402 DCHECK(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003403 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003404 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3405 // This means the error is not limited to a specific channel. Signal the
3406 // message using ssrc=0. If the current channel is sending, use this
3407 // channel for sending the message.
3408 *ssrc = 0;
3409 return true;
3410 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003411 // Check whether this is a sending channel.
3412 for (ChannelMap::const_iterator it = send_channels_.begin();
3413 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003414 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003415 // This is a sending channel.
3416 uint32 local_ssrc = 0;
3417 if (engine()->voe()->rtp()->GetLocalSSRC(
3418 channel_num, local_ssrc) != -1) {
3419 *ssrc = local_ssrc;
3420 }
3421 return true;
3422 }
3423 }
3424
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003425 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003426 for (ChannelMap::const_iterator it = receive_channels_.begin();
3427 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003428 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003429 *ssrc = it->first;
3430 return true;
3431 }
3432 }
3433 }
3434 return false;
3435}
3436
3437void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003438 if (error == VE_TYPING_NOISE_WARNING) {
3439 typing_noise_detected_ = true;
3440 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3441 typing_noise_detected_ = false;
3442 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003443 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3444}
3445
3446int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3447 unsigned int ulevel;
3448 int ret =
3449 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3450 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3451}
3452
3453int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003454 ChannelMap::iterator it = receive_channels_.find(ssrc);
3455 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003456 return it->second->channel();
pbos8fc7fa72015-07-15 08:02:58 -07003457 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003458}
3459
3460int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003461 ChannelMap::iterator it = send_channels_.find(ssrc);
3462 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003463 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003464
3465 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003466}
3467
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003468void WebRtcVoiceMediaChannel::SetCall(webrtc::Call* call) {
3469 DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003470 for (const auto& it : receive_channels_) {
3471 TryRemoveAudioRecvStream(it.first);
3472 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003473 call_ = call;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003474 for (const auto& it : receive_channels_) {
3475 TryAddAudioRecvStream(it.first);
3476 }
3477}
3478
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003479bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3480 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3481 // Get the RED encodings from the parameter with no name. This may
3482 // change based on what is discussed on the Jingle list.
3483 // The encoding parameter is of the form "a/b"; we only support where
3484 // a == b. Verify this and parse out the value into red_pt.
3485 // If the parameter value is absent (as it will be until we wire up the
3486 // signaling of this message), use the second codec specified (i.e. the
3487 // one after "red") as the encoding parameter.
3488 int red_pt = -1;
3489 std::string red_params;
3490 CodecParameterMap::const_iterator it = red_codec.params.find("");
3491 if (it != red_codec.params.end()) {
3492 red_params = it->second;
3493 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003494 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003495 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003496 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003497 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3498 return false;
3499 }
3500 } else if (red_codec.params.empty()) {
3501 LOG(LS_WARNING) << "RED params not present, using defaults";
3502 if (all_codecs.size() > 1) {
3503 red_pt = all_codecs[1].id;
3504 }
3505 }
3506
3507 // Try to find red_pt in |codecs|.
3508 std::vector<AudioCodec>::const_iterator codec;
3509 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3510 if (codec->id == red_pt)
3511 break;
3512 }
3513
3514 // If we find the right codec, that will be the codec we pass to
3515 // SetSendCodec, with the desired payload type.
3516 if (codec != all_codecs.end() &&
3517 engine()->FindWebRtcCodec(*codec, send_codec)) {
3518 } else {
3519 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3520 return false;
3521 }
3522
3523 return true;
3524}
3525
3526bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3527 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003528 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003529 return false;
3530 }
3531 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3532 // what we want to do with them.
3533 // engine()->voe().EnableVQMon(voe_channel(), true);
3534 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3535 return true;
3536}
3537
3538bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3539 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3540 for (int i = 0; i < ncodecs; ++i) {
3541 webrtc::CodecInst voe_codec;
3542 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3543 voe_codec.pltype = -1;
3544 if (engine()->voe()->codec()->SetRecPayloadType(
3545 channel, voe_codec) == -1) {
3546 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3547 return false;
3548 }
3549 }
3550 }
3551 return true;
3552}
3553
3554bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3555 if (playout) {
3556 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3557 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3558 LOG_RTCERR1(StartPlayout, channel);
3559 return false;
3560 }
3561 } else {
3562 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3563 engine()->voe()->base()->StopPlayout(channel);
3564 }
3565 return true;
3566}
3567
3568uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3569 bool rtcp) {
3570 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3571 uint32 ssrc = 0;
3572 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003573 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003574 }
3575 return ssrc;
3576}
3577
3578// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3579VoiceMediaChannel::Error
3580 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3581 switch (err_code) {
3582 case 0:
3583 return ERROR_NONE;
3584 case VE_CANNOT_START_RECORDING:
3585 case VE_MIC_VOL_ERROR:
3586 case VE_GET_MIC_VOL_ERROR:
3587 case VE_CANNOT_ACCESS_MIC_VOL:
3588 return ERROR_REC_DEVICE_OPEN_FAILED;
3589 case VE_SATURATION_WARNING:
3590 return ERROR_REC_DEVICE_SATURATION;
3591 case VE_REC_DEVICE_REMOVED:
3592 return ERROR_REC_DEVICE_REMOVED;
3593 case VE_RUNTIME_REC_WARNING:
3594 case VE_RUNTIME_REC_ERROR:
3595 return ERROR_REC_RUNTIME_ERROR;
3596 case VE_CANNOT_START_PLAYOUT:
3597 case VE_SPEAKER_VOL_ERROR:
3598 case VE_GET_SPEAKER_VOL_ERROR:
3599 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3600 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3601 case VE_RUNTIME_PLAY_WARNING:
3602 case VE_RUNTIME_PLAY_ERROR:
3603 return ERROR_PLAY_RUNTIME_ERROR;
3604 case VE_TYPING_NOISE_WARNING:
3605 return ERROR_REC_TYPING_NOISE_DETECTED;
3606 default:
3607 return VoiceMediaChannel::ERROR_OTHER;
3608 }
3609}
3610
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003611bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3612 int channel_id, const RtpHeaderExtension* extension) {
3613 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003614 int id = 0;
3615 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003616 if (extension) {
3617 enable = true;
3618 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003619 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003620 }
3621 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003622 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003623 return false;
3624 }
3625 return true;
3626}
3627
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003628void WebRtcVoiceMediaChannel::TryAddAudioRecvStream(uint32 ssrc) {
3629 DCHECK(thread_checker_.CalledOnValidThread());
pbos8fc7fa72015-07-15 08:02:58 -07003630 WebRtcVoiceChannelRenderer* channel = receive_channels_[ssrc];
3631 DCHECK(channel != nullptr);
3632 DCHECK(receive_streams_.find(ssrc) == receive_streams_.end());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003633 // If we are hooked up to a webrtc::Call, create an AudioReceiveStream too.
pbos8fc7fa72015-07-15 08:02:58 -07003634 if (!call_) {
3635 return;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003636 }
pbos8fc7fa72015-07-15 08:02:58 -07003637 webrtc::AudioReceiveStream::Config config;
3638 config.rtp.remote_ssrc = ssrc;
3639 // Only add RTP extensions if we support combined A/V BWE.
pbos6bb1b6e2015-07-24 07:10:18 -07003640 config.rtp.extensions = recv_rtp_extensions_;
3641 config.combined_audio_video_bwe =
3642 options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false);
pbos8fc7fa72015-07-15 08:02:58 -07003643 config.voe_channel_id = channel->channel();
3644 config.sync_group = receive_stream_params_[ssrc].sync_label;
3645 webrtc::AudioReceiveStream* s = call_->CreateAudioReceiveStream(config);
3646 receive_streams_.insert(std::make_pair(ssrc, s));
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003647}
3648
3649void WebRtcVoiceMediaChannel::TryRemoveAudioRecvStream(uint32 ssrc) {
3650 DCHECK(thread_checker_.CalledOnValidThread());
3651 // If we are hooked up to a webrtc::Call, assume there is an
3652 // AudioReceiveStream to destroy too.
3653 if (call_) {
3654 auto stream_it = receive_streams_.find(ssrc);
3655 if (stream_it != receive_streams_.end()) {
3656 call_->DestroyAudioReceiveStream(stream_it->second);
3657 receive_streams_.erase(stream_it);
3658 }
3659 }
3660}
3661
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003662int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003663 size_t res = 0;
3664 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003665 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003666}
3667
3668int WebRtcSoundclipStream::Rewind() {
3669 mem_.Rewind();
3670 // Return -1 to keep VoiceEngine from looping.
3671 return (loop_) ? 0 : -1;
3672}
3673
3674} // namespace cricket
3675
3676#endif // HAVE_WEBRTC_VOICE