blob: e288e7040fac5b450d307986c37c389b2d279c5b [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
Peter Thatcherc2ee2c82015-08-07 16:05:34 -07001746bool WebRtcVoiceMediaChannel::SetSendParameters(
1747 const AudioSendParameters& params) {
1748 // TODO(pthatcher): Refactor this to be more clean now that we have
1749 // all the information at once.
1750 return (SetSendCodecs(params.codecs) &&
1751 SetSendRtpHeaderExtensions(params.extensions) &&
1752 SetMaxSendBandwidth(params.max_bandwidth_bps) &&
1753 SetOptions(params.options));
1754}
1755
1756bool WebRtcVoiceMediaChannel::SetRecvParameters(
1757 const AudioRecvParameters& params) {
1758 // TODO(pthatcher): Refactor this to be more clean now that we have
1759 // all the information at once.
1760 return (SetRecvCodecs(params.codecs) &&
1761 SetRecvRtpHeaderExtensions(params.extensions));
1762}
1763
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001764bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1765 LOG(LS_INFO) << "Setting voice channel options: "
1766 << options.ToString();
1767
wu@webrtc.orgde305012013-10-31 15:40:38 +00001768 // Check if DSCP value is changed from previous.
1769 bool dscp_option_changed = (options_.dscp != options.dscp);
1770
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001771 // TODO(xians): Add support to set different options for different send
1772 // streams after we support multiple APMs.
1773
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001774 // We retain all of the existing options, and apply the given ones
1775 // on top. This means there is no way to "clear" options such that
1776 // they go back to the engine default.
1777 options_.SetAll(options);
1778
1779 if (send_ != SEND_NOTHING) {
1780 if (!engine()->SetOptionOverrides(options_)) {
1781 LOG(LS_WARNING) <<
1782 "Failed to engine SetOptionOverrides during channel SetOptions.";
1783 return false;
1784 }
1785 } else {
1786 // Will be interpreted when appropriate.
1787 }
1788
wu@webrtc.org97077a32013-10-25 21:18:33 +00001789 // Receiver-side auto gain control happens per channel, so set it here from
1790 // options. Note that, like conference mode, setting it on the engine won't
1791 // have the desired effect, since voice channels don't inherit options from
1792 // the media engine when those options are applied per-channel.
1793 bool rx_auto_gain_control;
1794 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1795 if (engine()->voe()->processing()->SetRxAgcStatus(
1796 voe_channel(), rx_auto_gain_control,
1797 webrtc::kAgcFixedDigital) == -1) {
1798 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1799 return false;
1800 } else {
1801 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1802 << " with mode " << webrtc::kAgcFixedDigital;
1803 }
1804 }
1805 if (options.rx_agc_target_dbov.IsSet() ||
1806 options.rx_agc_digital_compression_gain.IsSet() ||
1807 options.rx_agc_limiter.IsSet()) {
1808 webrtc::AgcConfig config;
1809 // If only some of the options are being overridden, get the current
1810 // settings for the channel and bail if they aren't available.
1811 if (!options.rx_agc_target_dbov.IsSet() ||
1812 !options.rx_agc_digital_compression_gain.IsSet() ||
1813 !options.rx_agc_limiter.IsSet()) {
1814 if (engine()->voe()->processing()->GetRxAgcConfig(
1815 voe_channel(), config) != 0) {
1816 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1817 << "channel " << voe_channel() << ". Since not all rx "
1818 << "agc options are specified, unable to safely set rx "
1819 << "agc options.";
1820 return false;
1821 }
1822 }
1823 config.targetLeveldBOv =
1824 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1825 config.targetLeveldBOv);
1826 config.digitalCompressionGaindB =
1827 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1828 config.digitalCompressionGaindB);
1829 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1830 config.limiterEnable);
1831 if (engine()->voe()->processing()->SetRxAgcConfig(
1832 voe_channel(), config) == -1) {
1833 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1834 config.digitalCompressionGaindB, config.limiterEnable);
1835 return false;
1836 }
1837 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001838 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001839 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001840 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001841 dscp = kAudioDscpValue;
1842 if (MediaChannel::SetDscp(dscp) != 0) {
1843 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1844 }
1845 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001846
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001847 SetCall(call_);
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001848
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001849 LOG(LS_INFO) << "Set voice channel options. Current options: "
1850 << options_.ToString();
1851 return true;
1852}
1853
1854bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1855 const std::vector<AudioCodec>& codecs) {
1856 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001857 LOG(LS_INFO) << "Setting receive voice codecs:";
1858
1859 std::vector<AudioCodec> new_codecs;
1860 // Find all new codecs. We allow adding new codecs but don't allow changing
1861 // the payload type of codecs that is already configured since we might
1862 // already be receiving packets with that payload type.
1863 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001864 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001865 AudioCodec old_codec;
1866 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1867 if (old_codec.id != it->id) {
1868 LOG(LS_ERROR) << it->name << " payload type changed.";
1869 return false;
1870 }
1871 } else {
1872 new_codecs.push_back(*it);
1873 }
1874 }
1875 if (new_codecs.empty()) {
1876 // There are no new codecs to configure. Already configured codecs are
1877 // never removed.
1878 return true;
1879 }
1880
1881 if (playout_) {
1882 // Receive codecs can not be changed while playing. So we temporarily
1883 // pause playout.
1884 PausePlayout();
1885 }
1886
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001887 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001888 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1889 it != new_codecs.end() && ret; ++it) {
1890 webrtc::CodecInst voe_codec;
1891 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1892 LOG(LS_INFO) << ToString(*it);
1893 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001894 if (default_receive_ssrc_ == 0) {
1895 // Set the receive codecs on the default channel explicitly if the
1896 // default channel is not used by |receive_channels_|, this happens in
1897 // conference mode or in non-conference mode when there is no playout
1898 // channel.
1899 // TODO(xians): Figure out how we use the default channel in conference
1900 // mode.
1901 if (engine()->voe()->codec()->SetRecPayloadType(
1902 voe_channel(), voe_codec) == -1) {
1903 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1904 ret = false;
1905 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001906 }
1907
1908 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001909 for (ChannelMap::iterator it = receive_channels_.begin();
1910 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001911 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001912 it->second->channel(), voe_codec) == -1) {
1913 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001914 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001915 ret = false;
1916 }
1917 }
1918 } else {
1919 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1920 ret = false;
1921 }
1922 }
1923 if (ret) {
1924 recv_codecs_ = codecs;
1925 }
1926
1927 if (desired_playout_ && !playout_) {
1928 ResumePlayout();
1929 }
1930 return ret;
1931}
1932
1933bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001934 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001935 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001936 engine()->voe()->codec()->SetVADStatus(channel, false);
1937 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001938 engine()->voe()->rtp()->SetREDStatus(channel, false);
1939 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001940
1941 // Scan through the list to figure out the codec to use for sending, along
1942 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001943 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001944 webrtc::CodecInst send_codec;
1945 memset(&send_codec, 0, sizeof(send_codec));
1946
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001947 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001948 bool enable_codec_fec = false;
Minyue Li7100dcd2015-03-27 05:05:59 +01001949 bool enable_opus_dtx = false;
minyue@webrtc.org26236952014-10-29 02:27:08 +00001950 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001951
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001952 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001953 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1954 it != codecs.end(); ++it) {
1955 // Ignore codecs we don't know about. The negotiation step should prevent
1956 // this, but double-check to be sure.
1957 webrtc::CodecInst voe_codec;
1958 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001959 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001960 continue;
1961 }
1962
Minyue Li7100dcd2015-03-27 05:05:59 +01001963 if (IsCodec(*it, kDtmfCodecName) || IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001964 // Skip telephone-event/CN codec, which will be handled later.
1965 continue;
1966 }
1967
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001968 // We'll use the first codec in the list to actually send audio data.
1969 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001970 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001971 // used is specified in params.
Minyue Li7100dcd2015-03-27 05:05:59 +01001972 if (IsCodec(*it, kRedCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001973 // Parse out the RED parameters. If we fail, just ignore RED;
1974 // we don't support all possible params/usage scenarios.
1975 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
1976 continue;
1977 }
1978
1979 // Enable redundant encoding of the specified codec. Treat any
1980 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001981 LOG(LS_INFO) << "Enabling RED on channel " << channel;
1982 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
1983 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001984 return false;
1985 }
1986 } else {
1987 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001988 nack_enabled = IsNackEnabled(*it);
Minyue Li7100dcd2015-03-27 05:05:59 +01001989 // For Opus as the send codec, we are to determine inband FEC, maximum
1990 // playback rate, and opus internal dtx.
1991 if (IsCodec(*it, kOpusCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00001992 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
Minyue Li7100dcd2015-03-27 05:05:59 +01001993 &opus_max_playback_rate, &enable_opus_dtx);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001994 }
Brave Yao5225dd82015-03-26 07:39:19 +08001995
1996 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1997 int ptime_ms = 0;
1998 if (it->GetParam(kCodecParamPTime, &ptime_ms)) {
1999 if (!SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
2000 LOG(LS_WARNING) << "Failed to set packet size for codec "
2001 << send_codec.plname;
2002 return false;
2003 }
2004 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002005 }
2006 found_send_codec = true;
2007 break;
2008 }
2009
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002010 if (nack_enabled_ != nack_enabled) {
2011 SetNack(channel, nack_enabled);
2012 nack_enabled_ = nack_enabled;
2013 }
2014
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002015 if (!found_send_codec) {
2016 LOG(LS_WARNING) << "Received empty list of codecs.";
2017 return false;
2018 }
2019
2020 // Set the codec immediately, since SetVADStatus() depends on whether
2021 // the current codec is mono or stereo.
2022 if (!SetSendCodec(channel, send_codec))
2023 return false;
2024
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002025 // FEC should be enabled after SetSendCodec.
2026 if (enable_codec_fec) {
2027 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2028 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002029 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2030 // Enable codec internal FEC. Treat any failure as fatal internal error.
2031 LOG_RTCERR2(SetFECStatus, channel, true);
2032 return false;
2033 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002034 }
2035
Minyue Li7100dcd2015-03-27 05:05:59 +01002036 if (IsCodec(send_codec, kOpusCodecName)) {
2037 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
2038 // send codec has to be Opus.
2039
2040 // Set Opus internal DTX.
2041 LOG(LS_INFO) << "Attempt to "
2042 << GetEnableString(enable_opus_dtx)
2043 << " Opus DTX on channel "
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002044 << channel;
Minyue Li7100dcd2015-03-27 05:05:59 +01002045 if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) {
2046 LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx);
2047 return false;
2048 }
2049
2050 // If opus_max_playback_rate <= 0, the default maximum playback rate
2051 // (48 kHz) will be used.
2052 if (opus_max_playback_rate > 0) {
2053 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
2054 << opus_max_playback_rate
2055 << " Hz on channel "
2056 << channel;
2057 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
2058 channel, opus_max_playback_rate) == -1) {
2059 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate);
2060 return false;
2061 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002062 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002063 }
2064
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002065 // Always update the |send_codec_| to the currently set send codec.
2066 send_codec_.reset(new webrtc::CodecInst(send_codec));
2067
minyue@webrtc.org26236952014-10-29 02:27:08 +00002068 if (send_bitrate_setting_) {
2069 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002070 }
2071
2072 // Loop through the codecs list again to config the telephone-event/CN codec.
2073 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2074 it != codecs.end(); ++it) {
2075 // Ignore codecs we don't know about. The negotiation step should prevent
2076 // this, but double-check to be sure.
2077 webrtc::CodecInst voe_codec;
2078 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2079 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2080 continue;
2081 }
2082
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002083 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2084 // about it.
Minyue Li7100dcd2015-03-27 05:05:59 +01002085 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002086 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2087 channel, it->id) == -1) {
2088 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2089 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002090 }
Minyue Li7100dcd2015-03-27 05:05:59 +01002091 } else if (IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002092 // Turn voice activity detection/comfort noise on if supported.
2093 // Set the wideband CN payload type appropriately.
2094 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002095 webrtc::PayloadFrequencies cn_freq;
2096 switch (it->clockrate) {
2097 case 8000:
2098 cn_freq = webrtc::kFreq8000Hz;
2099 break;
2100 case 16000:
2101 cn_freq = webrtc::kFreq16000Hz;
2102 break;
2103 case 32000:
2104 cn_freq = webrtc::kFreq32000Hz;
2105 break;
2106 default:
2107 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2108 << " not supported.";
2109 continue;
2110 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002111 // Set the CN payloadtype and the VAD status.
2112 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2113 if (cn_freq != webrtc::kFreq8000Hz) {
2114 if (engine()->voe()->codec()->SetSendCNPayloadType(
2115 channel, it->id, cn_freq) == -1) {
2116 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2117 // TODO(ajm): This failure condition will be removed from VoE.
2118 // Restore the return here when we update to a new enough webrtc.
2119 //
2120 // Not returning false because the SetSendCNPayloadType will fail if
2121 // the channel is already sending.
2122 // This can happen if the remote description is applied twice, for
2123 // example in the case of ROAP on top of JSEP, where both side will
2124 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002125 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002126 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002127 // Only turn on VAD if we have a CN payload type that matches the
2128 // clockrate for the codec we are going to use.
Minyue Li7100dcd2015-03-27 05:05:59 +01002129 if (it->clockrate == send_codec.plfreq && send_codec.channels != 2) {
2130 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
2131 // interaction between VAD and Opus FEC.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002132 LOG(LS_INFO) << "Enabling VAD";
2133 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2134 LOG_RTCERR2(SetVADStatus, channel, true);
2135 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002136 }
2137 }
2138 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002139 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002140 return true;
2141}
2142
2143bool WebRtcVoiceMediaChannel::SetSendCodecs(
2144 const std::vector<AudioCodec>& codecs) {
2145 dtmf_allowed_ = false;
2146 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2147 it != codecs.end(); ++it) {
2148 // Find the DTMF telephone event "codec".
Minyue Li7100dcd2015-03-27 05:05:59 +01002149 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002150 dtmf_allowed_ = true;
2151 }
2152 }
2153
2154 // Cache the codecs in order to configure the channel created later.
2155 send_codecs_ = codecs;
2156 for (ChannelMap::iterator iter = send_channels_.begin();
2157 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002158 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002159 return false;
2160 }
2161 }
2162
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002163 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002164 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002165 return true;
2166}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002167
2168void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2169 bool nack_enabled) {
2170 for (ChannelMap::const_iterator it = channels.begin();
2171 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002172 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002173 }
2174}
2175
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002176void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002177 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002178 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002179 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2180 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002181 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002182 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2183 }
2184}
2185
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002186bool WebRtcVoiceMediaChannel::SetSendCodec(
2187 const webrtc::CodecInst& send_codec) {
2188 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2189 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002190 for (ChannelMap::iterator iter = send_channels_.begin();
2191 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002192 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002193 return false;
2194 }
2195
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002196 return true;
2197}
2198
2199bool WebRtcVoiceMediaChannel::SetSendCodec(
2200 int channel, const webrtc::CodecInst& send_codec) {
2201 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2202 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2203
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002204 webrtc::CodecInst current_codec;
2205 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2206 (send_codec == current_codec)) {
2207 // Codec is already configured, we can return without setting it again.
2208 return true;
2209 }
2210
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002211 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2212 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002213 return false;
2214 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002215 return true;
2216}
2217
2218bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2219 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002220 if (receive_extensions_ == extensions) {
2221 return true;
2222 }
2223
2224 // The default channel may or may not be in |receive_channels_|. Set the rtp
2225 // header extensions for default channel regardless.
2226 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2227 return false;
2228 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002229
2230 // Loop through all receive channels and enable/disable the extensions.
2231 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2232 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002233 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2234 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002235 return false;
2236 }
2237 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002238
2239 receive_extensions_ = extensions;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002240
2241 // Recreate AudioReceiveStream:s.
2242 {
2243 std::vector<webrtc::RtpExtension> exts;
2244
2245 const RtpHeaderExtension* audio_level_extension =
2246 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2247 if (audio_level_extension) {
2248 exts.push_back({
2249 kRtpAudioLevelHeaderExtension, audio_level_extension->id});
2250 }
2251
2252 const RtpHeaderExtension* send_time_extension =
2253 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2254 if (send_time_extension) {
2255 exts.push_back({
2256 kRtpAbsoluteSenderTimeHeaderExtension, send_time_extension->id});
2257 }
2258
2259 recv_rtp_extensions_.swap(exts);
2260 SetCall(call_);
2261 }
2262
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002263 return true;
2264}
2265
2266bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2267 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002268 const RtpHeaderExtension* audio_level_extension =
2269 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2270 if (!SetHeaderExtension(
2271 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2272 audio_level_extension)) {
2273 return false;
2274 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002275
2276 const RtpHeaderExtension* send_time_extension =
2277 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2278 if (!SetHeaderExtension(
2279 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2280 send_time_extension)) {
2281 return false;
2282 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002283
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002284 return true;
2285}
2286
2287bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2288 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002289 if (send_extensions_ == extensions) {
2290 return true;
2291 }
2292
2293 // The default channel may or may not be in |send_channels_|. Set the rtp
2294 // header extensions for default channel regardless.
2295
2296 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2297 return false;
2298 }
2299
2300 // Loop through all send channels and enable/disable the extensions.
2301 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2302 channel_it != send_channels_.end(); ++channel_it) {
2303 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2304 extensions)) {
2305 return false;
2306 }
2307 }
2308
2309 send_extensions_ = extensions;
2310 return true;
2311}
2312
2313bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2314 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002315 const RtpHeaderExtension* audio_level_extension =
2316 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002317
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002318 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002319 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002320 audio_level_extension)) {
2321 return false;
2322 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002323
2324 const RtpHeaderExtension* send_time_extension =
2325 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002326 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002327 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002328 send_time_extension)) {
2329 return false;
2330 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002331
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002332 return true;
2333}
2334
2335bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2336 desired_playout_ = playout;
2337 return ChangePlayout(desired_playout_);
2338}
2339
2340bool WebRtcVoiceMediaChannel::PausePlayout() {
2341 return ChangePlayout(false);
2342}
2343
2344bool WebRtcVoiceMediaChannel::ResumePlayout() {
2345 return ChangePlayout(desired_playout_);
2346}
2347
2348bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2349 if (playout_ == playout) {
2350 return true;
2351 }
2352
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002353 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002354 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002355 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002356 // Only toggle the default channel if we don't have any other channels.
2357 result = SetPlayout(voe_channel(), playout);
2358 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002359 for (ChannelMap::iterator it = receive_channels_.begin();
2360 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002361 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002362 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002363 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002364 result = false;
2365 }
2366 }
2367
2368 if (result) {
2369 playout_ = playout;
2370 }
2371 return result;
2372}
2373
2374bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2375 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002376 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002377 return ChangeSend(desired_send_);
2378 return true;
2379}
2380
2381bool WebRtcVoiceMediaChannel::PauseSend() {
2382 return ChangeSend(SEND_NOTHING);
2383}
2384
2385bool WebRtcVoiceMediaChannel::ResumeSend() {
2386 return ChangeSend(desired_send_);
2387}
2388
2389bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2390 if (send_ == send) {
2391 return true;
2392 }
2393
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002394 // Change the settings on each send channel.
2395 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002396 engine()->SetOptionOverrides(options_);
2397
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002398 // Change the settings on each send channel.
2399 for (ChannelMap::iterator iter = send_channels_.begin();
2400 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002401 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002402 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002403 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002404
2405 // Clear up the options after stopping sending.
2406 if (send == SEND_NOTHING)
2407 engine()->ClearOptionOverrides();
2408
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002409 send_ = send;
2410 return true;
2411}
2412
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002413bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2414 if (send == SEND_MICROPHONE) {
2415 if (engine()->voe()->base()->StartSend(channel) == -1) {
2416 LOG_RTCERR1(StartSend, channel);
2417 return false;
2418 }
2419 if (engine()->voe()->file() &&
2420 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2421 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2422 return false;
2423 }
2424 } else { // SEND_NOTHING
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002425 DCHECK(send == SEND_NOTHING);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002426 if (engine()->voe()->base()->StopSend(channel) == -1) {
2427 LOG_RTCERR1(StopSend, channel);
2428 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002429 }
2430 }
2431
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002432 return true;
2433}
2434
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002435// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002436void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2437 if (engine()->voe()->network()->RegisterExternalTransport(
2438 channel, *this) == -1) {
2439 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2440 }
2441
2442 // Enable RTCP (for quality stats and feedback messages)
2443 EnableRtcp(channel);
2444
2445 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2446 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002447
2448 // Set RTP header extension for the new channel.
2449 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002450}
2451
2452bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2453 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2454 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2455 }
2456
2457 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2458 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002459 return false;
2460 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002461
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002462 return true;
2463}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002464
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002465bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2466 // If the default channel is already used for sending create a new channel
2467 // otherwise use the default channel for sending.
2468 int channel = GetSendChannelNum(sp.first_ssrc());
2469 if (channel != -1) {
2470 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2471 return false;
2472 }
2473
2474 bool default_channel_is_available = true;
2475 for (ChannelMap::const_iterator iter = send_channels_.begin();
2476 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002477 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002478 default_channel_is_available = false;
2479 break;
2480 }
2481 }
2482 if (default_channel_is_available) {
2483 channel = voe_channel();
2484 } else {
2485 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002486 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002487 if (channel == -1) {
2488 LOG_RTCERR0(CreateChannel);
2489 return false;
2490 }
2491
2492 ConfigureSendChannel(channel);
2493 }
2494
2495 // Save the channel to send_channels_, so that RemoveSendStream() can still
2496 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002497 webrtc::AudioTransport* audio_transport =
2498 engine()->voe()->base()->audio_transport();
pbos8fc7fa72015-07-15 08:02:58 -07002499 send_channels_.insert(
2500 std::make_pair(sp.first_ssrc(),
2501 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002502
2503 // Set the send (local) SSRC.
2504 // If there are multiple send SSRCs, we can only set the first one here, and
2505 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2506 // (with a codec requires multiple SSRC(s)).
2507 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2508 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2509 return false;
2510 }
2511
2512 // At this point the channel's local SSRC has been updated. If the channel is
2513 // the default channel make sure that all the receive channels are updated as
2514 // well. Receive channels have to have the same SSRC as the default channel in
2515 // order to send receiver reports with this SSRC.
2516 if (IsDefaultChannel(channel)) {
2517 for (ChannelMap::const_iterator it = receive_channels_.begin();
2518 it != receive_channels_.end(); ++it) {
2519 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002520 if (!IsDefaultChannel(it->second->channel())) {
2521 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002522 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002523 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002524 return false;
2525 }
2526 }
2527 }
2528 }
2529
2530 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002531 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2532 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002533 }
2534
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002535 // Set the current codecs to be used for the new channel.
2536 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002537 return false;
2538
2539 return ChangeSend(channel, desired_send_);
2540}
2541
2542bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2543 ChannelMap::iterator it = send_channels_.find(ssrc);
2544 if (it == send_channels_.end()) {
2545 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2546 << " which doesn't exist.";
2547 return false;
2548 }
2549
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002550 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002551 ChangeSend(channel, SEND_NOTHING);
2552
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002553 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2554 // this will disconnect the audio renderer with the send channel.
2555 delete it->second;
2556 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002557
2558 if (IsDefaultChannel(channel)) {
2559 // Do not delete the default channel since the receive channels depend on
2560 // the default channel, recycle it instead.
2561 ChangeSend(channel, SEND_NOTHING);
2562 } else {
2563 // Clean up and delete the send channel.
2564 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2565 << " with VoiceEngine channel #" << channel << ".";
2566 if (!DeleteChannel(channel))
2567 return false;
2568 }
2569
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002570 if (send_channels_.empty())
2571 ChangeSend(SEND_NOTHING);
2572
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002573 return true;
2574}
2575
2576bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002577 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002578 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002579
2580 if (!VERIFY(sp.ssrcs.size() == 1))
2581 return false;
2582 uint32 ssrc = sp.first_ssrc();
2583
wu@webrtc.org78187522013-10-07 23:32:02 +00002584 if (ssrc == 0) {
2585 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2586 return false;
2587 }
2588
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002589 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2590 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002591 return false;
2592 }
2593
pbos8fc7fa72015-07-15 08:02:58 -07002594 DCHECK(receive_stream_params_.find(ssrc) == receive_stream_params_.end());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002595
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002596 // Reuse default channel for recv stream in non-conference mode call
2597 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002598 webrtc::AudioTransport* audio_transport =
2599 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002600 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002601 LOG(LS_INFO) << "Recv stream " << ssrc << " reuse default channel";
2602 default_receive_ssrc_ = ssrc;
pbos8fc7fa72015-07-15 08:02:58 -07002603 WebRtcVoiceChannelRenderer* channel_renderer =
2604 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport);
2605 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2606 receive_stream_params_[ssrc] = sp;
2607 TryAddAudioRecvStream(ssrc);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002608 return SetPlayout(voe_channel(), playout_);
2609 }
2610
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002611 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002612 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002613 if (channel == -1) {
2614 LOG_RTCERR0(CreateChannel);
2615 return false;
2616 }
2617
wu@webrtc.org78187522013-10-07 23:32:02 +00002618 if (!ConfigureRecvChannel(channel)) {
2619 DeleteChannel(channel);
2620 return false;
2621 }
2622
pbos8fc7fa72015-07-15 08:02:58 -07002623 WebRtcVoiceChannelRenderer* channel_renderer =
2624 new WebRtcVoiceChannelRenderer(channel, audio_transport);
2625 receive_channels_.insert(std::make_pair(ssrc, channel_renderer));
2626 receive_stream_params_[ssrc] = sp;
2627 TryAddAudioRecvStream(ssrc);
wu@webrtc.org78187522013-10-07 23:32:02 +00002628
2629 LOG(LS_INFO) << "New audio stream " << ssrc
2630 << " registered to VoiceEngine channel #"
2631 << channel << ".";
2632 return true;
2633}
2634
2635bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002636 // Configure to use external transport, like our default channel.
2637 if (engine()->voe()->network()->RegisterExternalTransport(
2638 channel, *this) == -1) {
2639 LOG_RTCERR2(SetExternalTransport, channel, this);
2640 return false;
2641 }
2642
2643 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002644 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002645 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2646 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002647 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002648 return false;
2649 }
2650 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002651 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002652 return false;
2653 }
2654
Minyue2013aec2015-05-13 14:14:42 +02002655 // Associate receive channel to default channel (so the receive channel can
2656 // obtain RTT from the send channel)
2657 engine()->voe()->base()->AssociateSendChannel(channel, voe_channel());
2658 LOG(LS_INFO) << "VoiceEngine channel #"
2659 << channel << " is associated with channel #"
2660 << voe_channel() << ".";
2661
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002662 // Use the same recv payload types as our default channel.
2663 ResetRecvCodecs(channel);
2664 if (!recv_codecs_.empty()) {
2665 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2666 it != recv_codecs_.end(); ++it) {
2667 webrtc::CodecInst voe_codec;
2668 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2669 voe_codec.pltype = it->id;
2670 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2671 if (engine()->voe()->codec()->GetRecPayloadType(
2672 voe_channel(), voe_codec) != -1) {
2673 if (engine()->voe()->codec()->SetRecPayloadType(
2674 channel, voe_codec) == -1) {
2675 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2676 return false;
2677 }
2678 }
2679 }
2680 }
2681 }
2682
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002683 if (InConferenceMode()) {
2684 // To be in par with the video, voe_channel() is not used for receiving in
2685 // a conference call.
2686 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2687 // This is the first stream in a multi user meeting. We can now
2688 // disable playback of the default stream. This since the default
2689 // stream will probably have received some initial packets before
2690 // the new stream was added. This will mean that the CN state from
2691 // the default channel will be mixed in with the other streams
2692 // throughout the whole meeting, which might be disturbing.
2693 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2694 SetPlayout(voe_channel(), false);
2695 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002696 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002697 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002698
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002699 // Set RTP header extension for the new channel.
2700 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2701 return false;
2702 }
2703
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002704 return SetPlayout(channel, playout_);
2705}
2706
2707bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002708 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002709 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002710 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002711 if (it == receive_channels_.end()) {
2712 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2713 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002714 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002715 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002716
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002717 TryRemoveAudioRecvStream(ssrc);
pbos8fc7fa72015-07-15 08:02:58 -07002718 receive_stream_params_.erase(ssrc);
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002719
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002720 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2721 // will disconnect the audio renderer with the receive channel.
2722 // Cache the channel before the deletion.
2723 const int channel = it->second->channel();
2724 delete it->second;
2725 receive_channels_.erase(it);
2726
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002727 if (ssrc == default_receive_ssrc_) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002728 DCHECK(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002729 // Recycle the default channel is for recv stream.
2730 if (playout_)
2731 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002732
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002733 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002734 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002735 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002736
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002737 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002738 << " with VoiceEngine channel #" << channel << ".";
2739 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002740 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002741
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002742 bool enable_default_channel_playout = false;
2743 if (receive_channels_.empty()) {
2744 // The last stream was removed. We can now enable the default
2745 // channel for new channels to be played out immediately without
2746 // waiting for AddStream messages.
2747 // We do this for both conference mode and non-conference mode.
2748 // TODO(oja): Does the default channel still have it's CN state?
2749 enable_default_channel_playout = true;
2750 }
2751 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2752 default_receive_ssrc_ != 0) {
2753 // Only the default channel is active, enable the playout on default
2754 // channel.
2755 enable_default_channel_playout = true;
2756 }
2757 if (enable_default_channel_playout && playout_) {
2758 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2759 SetPlayout(voe_channel(), true);
2760 }
2761
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002762 return true;
2763}
2764
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002765bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2766 AudioRenderer* renderer) {
2767 ChannelMap::iterator it = receive_channels_.find(ssrc);
2768 if (it == receive_channels_.end()) {
2769 if (renderer) {
2770 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002771 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002772 return false;
2773 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002774
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002775 // The channel likely has gone away, do nothing.
2776 return true;
2777 }
2778
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002779 if (renderer)
2780 it->second->Start(renderer);
2781 else
2782 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002783
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002784 return true;
2785}
2786
2787bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2788 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002789 ChannelMap::iterator it = send_channels_.find(ssrc);
2790 if (it == send_channels_.end()) {
2791 if (renderer) {
2792 // Return an error if trying to set a valid renderer with an invalid ssrc.
2793 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2794 return false;
2795 }
2796
2797 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002798 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002799 }
2800
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002801 if (renderer)
2802 it->second->Start(renderer);
2803 else
2804 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002805
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002806 return true;
2807}
2808
2809bool WebRtcVoiceMediaChannel::GetActiveStreams(
2810 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002811 // In conference mode, the default channel should not be in
2812 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002813 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002814 for (ChannelMap::iterator it = receive_channels_.begin();
2815 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002816 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002817 if (level > 0) {
2818 actives->push_back(std::make_pair(it->first, level));
2819 }
2820 }
2821 return true;
2822}
2823
2824int WebRtcVoiceMediaChannel::GetOutputLevel() {
2825 // return the highest output level of all streams
2826 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002827 for (ChannelMap::iterator it = receive_channels_.begin();
2828 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002829 int level = GetOutputLevel(it->second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002830 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002831 }
2832 return highest;
2833}
2834
2835int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2836 int ret;
2837 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2838 // In case of error, log the info and continue
2839 LOG_RTCERR0(TimeSinceLastTyping);
2840 ret = -1;
2841 } else {
2842 ret *= 1000; // We return ms, webrtc returns seconds.
2843 }
2844 return ret;
2845}
2846
2847void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2848 int cost_per_typing, int reporting_threshold, int penalty_decay,
2849 int type_event_delay) {
2850 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2851 time_window, cost_per_typing,
2852 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2853 // In case of error, log the info and continue
2854 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2855 cost_per_typing, reporting_threshold, penalty_decay,
2856 type_event_delay);
2857 }
2858}
2859
2860bool WebRtcVoiceMediaChannel::SetOutputScaling(
2861 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002862 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002863 // Collect the channels to scale the output volume.
2864 std::vector<int> channels;
2865 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002866 // Default channel is not in receive_channels_ if it is not being used for
2867 // playout.
2868 if (default_receive_ssrc_ == 0)
2869 channels.push_back(voe_channel());
2870 for (ChannelMap::const_iterator it = receive_channels_.begin();
2871 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002872 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002873 }
2874 } else { // Collect only the channel of the specified ssrc.
2875 int channel = GetReceiveChannelNum(ssrc);
2876 if (-1 == channel) {
2877 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2878 return false;
2879 }
2880 channels.push_back(channel);
2881 }
2882
2883 // Scale the output volume for the collected channels. We first normalize to
2884 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002885 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002886 if (scale > 0.0001f) {
2887 left /= scale;
2888 right /= scale;
2889 }
2890 for (std::vector<int>::const_iterator it = channels.begin();
2891 it != channels.end(); ++it) {
2892 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2893 *it, scale)) {
2894 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2895 return false;
2896 }
2897 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2898 *it, static_cast<float>(left), static_cast<float>(right))) {
2899 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2900 // Do not return if fails. SetOutputVolumePan is not available for all
2901 // pltforms.
2902 }
2903 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2904 << " right=" << right * scale
2905 << " for channel " << *it << " and ssrc " << ssrc;
2906 }
2907 return true;
2908}
2909
2910bool WebRtcVoiceMediaChannel::GetOutputScaling(
2911 uint32 ssrc, double* left, double* right) {
2912 if (!left || !right) return false;
2913
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002914 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002915 // Determine which channel based on ssrc.
2916 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2917 if (channel == -1) {
2918 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2919 return false;
2920 }
2921
2922 float scaling;
2923 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2924 channel, scaling)) {
2925 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2926 return false;
2927 }
2928
2929 float left_pan;
2930 float right_pan;
2931 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2932 channel, left_pan, right_pan)) {
2933 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2934 // If GetOutputVolumePan fails, we use the default left and right pan.
2935 left_pan = 1.0f;
2936 right_pan = 1.0f;
2937 }
2938
2939 *left = scaling * left_pan;
2940 *right = scaling * right_pan;
2941 return true;
2942}
2943
2944bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2945 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2946 return true;
2947}
2948
2949bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2950 bool play, bool loop) {
2951 if (!ringback_tone_) {
2952 return false;
2953 }
2954
2955 // The voe file api is not available in chrome.
2956 if (!engine()->voe()->file()) {
2957 return false;
2958 }
2959
2960 // Determine which VoiceEngine channel to play on.
2961 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2962 if (channel == -1) {
2963 return false;
2964 }
2965
2966 // Make sure the ringtone is cued properly, and play it out.
2967 if (play) {
2968 ringback_tone_->set_loop(loop);
2969 ringback_tone_->Rewind();
2970 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2971 ringback_tone_.get()) == -1) {
2972 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2973 LOG(LS_ERROR) << "Unable to start ringback tone";
2974 return false;
2975 }
2976 ringback_channels_.insert(channel);
2977 LOG(LS_INFO) << "Started ringback on channel " << channel;
2978 } else {
2979 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2980 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2981 LOG_RTCERR1(StopPlayingFileLocally, channel);
2982 return false;
2983 }
2984 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2985 ringback_channels_.erase(channel);
2986 }
2987
2988 return true;
2989}
2990
2991bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2992 return dtmf_allowed_;
2993}
2994
2995bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2996 int duration, int flags) {
2997 if (!dtmf_allowed_) {
2998 return false;
2999 }
3000
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003001 // Send the event.
3002 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003003 int channel = -1;
3004 if (ssrc == 0) {
3005 bool default_channel_is_inuse = false;
3006 for (ChannelMap::const_iterator iter = send_channels_.begin();
3007 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003008 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003009 default_channel_is_inuse = true;
3010 break;
3011 }
3012 }
3013 if (default_channel_is_inuse) {
3014 channel = voe_channel();
3015 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003016 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003017 }
3018 } else {
3019 channel = GetSendChannelNum(ssrc);
3020 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003021 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003022 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3023 << ssrc << " is not in use.";
3024 return false;
3025 }
3026 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003027 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3028 channel, event, true, duration) == -1) {
3029 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003030 return false;
3031 }
3032 }
3033
3034 // Play the event.
3035 if (flags & cricket::DF_PLAY) {
3036 // Play DTMF tone locally.
3037 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3038 LOG_RTCERR2(PlayDtmfTone, event, duration);
3039 return false;
3040 }
3041 }
3042
3043 return true;
3044}
3045
wu@webrtc.orga9890802013-12-13 00:21:03 +00003046void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003047 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003048 DCHECK(thread_checker_.CalledOnValidThread());
3049
3050 // If hooked up to a "Call", forward packet there too.
3051 if (call_) {
3052 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3053 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3054 }
3055
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003056 // Pick which channel to send this packet to. If this packet doesn't match
3057 // any multiplexed streams, just send it to the default channel. Otherwise,
3058 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003059 int which_channel =
3060 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003061 if (which_channel == -1) {
3062 which_channel = voe_channel();
3063 }
3064
3065 // Stop any ringback that might be playing on the channel.
3066 // It's possible the ringback has already stopped, ih which case we'll just
3067 // use the opportunity to remove the channel from ringback_channels_.
3068 if (engine()->voe()->file()) {
3069 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3070 if (it != ringback_channels_.end()) {
3071 if (engine()->voe()->file()->IsPlayingFileLocally(
3072 which_channel) == 1) {
3073 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3074 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3075 << " due to incoming media";
3076 }
3077 ringback_channels_.erase(which_channel);
3078 }
3079 }
3080
3081 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003082 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003083 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003084 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003085}
3086
wu@webrtc.orga9890802013-12-13 00:21:03 +00003087void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003088 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003089 DCHECK(thread_checker_.CalledOnValidThread());
3090
3091 // If hooked up to a "Call", forward packet there too.
3092 if (call_) {
3093 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3094 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3095 }
3096
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003097 // Sending channels need all RTCP packets with feedback information.
3098 // Even sender reports can contain attached report blocks.
3099 // Receiving channels need sender reports in order to create
3100 // correct receiver reports.
3101 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003102 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003103 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3104 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003105 }
3106
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003107 // If it is a sender report, find the channel that is listening.
3108 bool has_sent_to_default_channel = false;
3109 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003110 int which_channel =
3111 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003112 if (which_channel != -1) {
3113 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003114 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003115
3116 if (IsDefaultChannel(which_channel))
3117 has_sent_to_default_channel = true;
3118 }
3119 }
3120
3121 // SR may continue RR and any RR entry may correspond to any one of the send
3122 // channels. So all RTCP packets must be forwarded all send channels. VoE
3123 // will filter out RR internally.
3124 for (ChannelMap::iterator iter = send_channels_.begin();
3125 iter != send_channels_.end(); ++iter) {
3126 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003127 if (IsDefaultChannel(iter->second->channel()) &&
3128 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003129 continue;
3130
3131 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003132 iter->second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003133 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003134}
3135
3136bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003137 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3138 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003139 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3140 return false;
3141 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003142 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3143 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003144 return false;
3145 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003146 // We set the AGC to mute state only when all the channels are muted.
3147 // This implementation is not ideal, instead we should signal the AGC when
3148 // the mic channel is muted/unmuted. We can't do it today because there
3149 // is no good way to know which stream is mapping to the mic channel.
3150 bool all_muted = muted;
3151 for (ChannelMap::const_iterator iter = send_channels_.begin();
3152 iter != send_channels_.end() && all_muted; ++iter) {
3153 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3154 all_muted)) {
3155 LOG_RTCERR1(GetInputMute, iter->second->channel());
3156 return false;
3157 }
3158 }
3159
3160 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3161 if (ap)
3162 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003163 return true;
3164}
3165
minyue@webrtc.org26236952014-10-29 02:27:08 +00003166// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3167// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003168bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003169 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003170
minyue@webrtc.org26236952014-10-29 02:27:08 +00003171 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003172}
3173
minyue@webrtc.org26236952014-10-29 02:27:08 +00003174bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3175 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003176
minyue@webrtc.org26236952014-10-29 02:27:08 +00003177 send_bitrate_setting_ = true;
3178 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003179
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003180 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003181 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003182 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003183 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003184 }
3185
minyue@webrtc.org26236952014-10-29 02:27:08 +00003186 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003187 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3188 // SetMaxSendBandwith(0), the second call removes the previous limit.
3189 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003190 return true;
3191
3192 webrtc::CodecInst codec = *send_codec_;
3193 bool is_multi_rate = IsCodecMultiRate(codec);
3194
3195 if (is_multi_rate) {
3196 // If codec is multi-rate then just set the bitrate.
3197 codec.rate = bps;
3198 if (!SetSendCodec(codec)) {
3199 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3200 << " to bitrate " << bps << " bps.";
3201 return false;
3202 }
3203 return true;
3204 } else {
3205 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3206 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3207 // fixed bitrate then ignore.
3208 if (bps < codec.rate) {
3209 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3210 << " to bitrate " << bps << " bps"
3211 << ", requires at least " << codec.rate << " bps.";
3212 return false;
3213 }
3214 return true;
3215 }
3216}
3217
3218bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003219 bool echo_metrics_on = false;
3220 // These can take on valid negative values, so use the lowest possible level
3221 // as default rather than -1.
3222 int echo_return_loss = -100;
3223 int echo_return_loss_enhancement = -100;
3224 // These can also be negative, but in practice -1 is only used to signal
3225 // insufficient data, since the resolution is limited to multiples of 4 ms.
3226 int echo_delay_median_ms = -1;
3227 int echo_delay_std_ms = -1;
3228 if (engine()->voe()->processing()->GetEcMetricsStatus(
3229 echo_metrics_on) != -1 && echo_metrics_on) {
3230 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3231 // here, but it appears to be unsuitable currently. Revisit after this is
3232 // investigated: http://b/issue?id=5666755
3233 int erl, erle, rerl, anlp;
3234 if (engine()->voe()->processing()->GetEchoMetrics(
3235 erl, erle, rerl, anlp) != -1) {
3236 echo_return_loss = erl;
3237 echo_return_loss_enhancement = erle;
3238 }
3239
3240 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003241 float dummy;
3242 if (engine()->voe()->processing()->GetEcDelayMetrics(
3243 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003244 echo_delay_median_ms = median;
3245 echo_delay_std_ms = std;
3246 }
3247 }
3248
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003249 webrtc::CallStatistics cs;
3250 unsigned int ssrc;
3251 webrtc::CodecInst codec;
3252 unsigned int level;
3253
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003254 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3255 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003256 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003257
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003258 // Fill in the sender info, based on what we know, and what the
3259 // remote side told us it got from its RTCP report.
3260 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003261
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003262 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3263 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3264 continue;
3265 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003266
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003267 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003268 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3269 sinfo.bytes_sent = cs.bytesSent;
3270 sinfo.packets_sent = cs.packetsSent;
3271 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3272 // returns 0 to indicate an error value.
3273 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3274
3275 // Get data from the last remote RTCP report. Use default values if no data
3276 // available.
3277 sinfo.fraction_lost = -1.0;
3278 sinfo.jitter_ms = -1;
3279 sinfo.packets_lost = -1;
3280 sinfo.ext_seqnum = -1;
3281 std::vector<webrtc::ReportBlock> receive_blocks;
3282 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3283 channel, &receive_blocks) != -1 &&
3284 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3285 std::vector<webrtc::ReportBlock>::iterator iter;
3286 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3287 ++iter) {
3288 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003289 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003290 // Convert Q8 to floating point.
3291 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3292 // Convert samples to milliseconds.
3293 if (codec.plfreq / 1000 > 0) {
3294 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3295 }
3296 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3297 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3298 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003299 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003300 }
3301 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003302
3303 // Local speech level.
3304 sinfo.audio_level = (engine()->voe()->volume()->
3305 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3306
3307 // TODO(xians): We are injecting the same APM logging to all the send
3308 // channels here because there is no good way to know which send channel
3309 // is using the APM. The correct fix is to allow the send channels to have
3310 // their own APM so that we can feed the correct APM logging to different
3311 // send channels. See issue crbug/264611 .
3312 sinfo.echo_return_loss = echo_return_loss;
3313 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3314 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3315 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003316 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3317 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003318 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003319
3320 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003321 }
3322
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003323 // Build the list of receivers, one for each receiving channel, or 1 in
3324 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003325 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003326 for (ChannelMap::const_iterator it = receive_channels_.begin();
3327 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003328 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003329 }
3330 if (channels.empty()) {
3331 channels.push_back(voe_channel());
3332 }
3333
3334 // Get the SSRC and stats for each receiver, based on our own calculations.
3335 for (std::vector<int>::const_iterator it = channels.begin();
3336 it != channels.end(); ++it) {
3337 memset(&cs, 0, sizeof(cs));
3338 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3339 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3340 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3341 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003342 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003343 rinfo.bytes_rcvd = cs.bytesReceived;
3344 rinfo.packets_rcvd = cs.packetsReceived;
3345 // The next four fields are from the most recently sent RTCP report.
3346 // Convert Q8 to floating point.
3347 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3348 rinfo.packets_lost = cs.cumulativeLost;
3349 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003350 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003351 if (codec.pltype != -1) {
3352 rinfo.codec_name = codec.plname;
3353 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003354 // Convert samples to milliseconds.
3355 if (codec.plfreq / 1000 > 0) {
3356 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3357 }
3358
3359 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3360 webrtc::NetworkStatistics ns;
3361 if (engine()->voe()->neteq() &&
3362 engine()->voe()->neteq()->GetNetworkStatistics(
3363 *it, ns) != -1) {
3364 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3365 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3366 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003367 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003368 rinfo.speech_expand_rate =
3369 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3370 rinfo.secondary_decoded_rate =
3371 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
Henrik Lundin8e6fd462015-06-02 09:24:52 +02003372 rinfo.accelerate_rate =
3373 static_cast<float>(ns.currentAccelerateRate) / (1 << 14);
3374 rinfo.preemptive_expand_rate =
3375 static_cast<float>(ns.currentPreemptiveRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003376 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003377
3378 webrtc::AudioDecodingCallStats ds;
3379 if (engine()->voe()->neteq() &&
3380 engine()->voe()->neteq()->GetDecodingCallStatistics(
3381 *it, &ds) != -1) {
3382 rinfo.decoding_calls_to_silence_generator =
3383 ds.calls_to_silence_generator;
3384 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3385 rinfo.decoding_normal = ds.decoded_normal;
3386 rinfo.decoding_plc = ds.decoded_plc;
3387 rinfo.decoding_cng = ds.decoded_cng;
3388 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3389 }
3390
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003391 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003392 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003393 int playout_buffer_delay_ms = 0;
3394 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003395 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3396 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3397 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003398 }
3399
3400 // Get speech level.
3401 rinfo.audio_level = (engine()->voe()->volume()->
3402 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3403 info->receivers.push_back(rinfo);
3404 }
3405 }
3406
3407 return true;
3408}
3409
3410void WebRtcVoiceMediaChannel::GetLastMediaError(
3411 uint32* ssrc, VoiceMediaChannel::Error* error) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003412 DCHECK(ssrc != NULL);
3413 DCHECK(error != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003414 FindSsrc(voe_channel(), ssrc);
3415 *error = WebRtcErrorToChannelError(GetLastEngineError());
3416}
3417
3418bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003419 rtc::CritScope lock(&receive_channels_cs_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003420 DCHECK(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003421 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003422 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3423 // This means the error is not limited to a specific channel. Signal the
3424 // message using ssrc=0. If the current channel is sending, use this
3425 // channel for sending the message.
3426 *ssrc = 0;
3427 return true;
3428 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003429 // Check whether this is a sending channel.
3430 for (ChannelMap::const_iterator it = send_channels_.begin();
3431 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003432 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003433 // This is a sending channel.
3434 uint32 local_ssrc = 0;
3435 if (engine()->voe()->rtp()->GetLocalSSRC(
3436 channel_num, local_ssrc) != -1) {
3437 *ssrc = local_ssrc;
3438 }
3439 return true;
3440 }
3441 }
3442
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003443 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003444 for (ChannelMap::const_iterator it = receive_channels_.begin();
3445 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003446 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003447 *ssrc = it->first;
3448 return true;
3449 }
3450 }
3451 }
3452 return false;
3453}
3454
3455void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003456 if (error == VE_TYPING_NOISE_WARNING) {
3457 typing_noise_detected_ = true;
3458 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3459 typing_noise_detected_ = false;
3460 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003461 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3462}
3463
3464int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3465 unsigned int ulevel;
3466 int ret =
3467 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3468 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3469}
3470
3471int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003472 ChannelMap::iterator it = receive_channels_.find(ssrc);
3473 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003474 return it->second->channel();
pbos8fc7fa72015-07-15 08:02:58 -07003475 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003476}
3477
3478int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003479 ChannelMap::iterator it = send_channels_.find(ssrc);
3480 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003481 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003482
3483 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003484}
3485
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003486void WebRtcVoiceMediaChannel::SetCall(webrtc::Call* call) {
3487 DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003488 for (const auto& it : receive_channels_) {
3489 TryRemoveAudioRecvStream(it.first);
3490 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003491 call_ = call;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003492 for (const auto& it : receive_channels_) {
3493 TryAddAudioRecvStream(it.first);
3494 }
3495}
3496
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003497bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3498 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3499 // Get the RED encodings from the parameter with no name. This may
3500 // change based on what is discussed on the Jingle list.
3501 // The encoding parameter is of the form "a/b"; we only support where
3502 // a == b. Verify this and parse out the value into red_pt.
3503 // If the parameter value is absent (as it will be until we wire up the
3504 // signaling of this message), use the second codec specified (i.e. the
3505 // one after "red") as the encoding parameter.
3506 int red_pt = -1;
3507 std::string red_params;
3508 CodecParameterMap::const_iterator it = red_codec.params.find("");
3509 if (it != red_codec.params.end()) {
3510 red_params = it->second;
3511 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003512 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003513 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003514 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003515 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3516 return false;
3517 }
3518 } else if (red_codec.params.empty()) {
3519 LOG(LS_WARNING) << "RED params not present, using defaults";
3520 if (all_codecs.size() > 1) {
3521 red_pt = all_codecs[1].id;
3522 }
3523 }
3524
3525 // Try to find red_pt in |codecs|.
3526 std::vector<AudioCodec>::const_iterator codec;
3527 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3528 if (codec->id == red_pt)
3529 break;
3530 }
3531
3532 // If we find the right codec, that will be the codec we pass to
3533 // SetSendCodec, with the desired payload type.
3534 if (codec != all_codecs.end() &&
3535 engine()->FindWebRtcCodec(*codec, send_codec)) {
3536 } else {
3537 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3538 return false;
3539 }
3540
3541 return true;
3542}
3543
3544bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3545 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003546 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003547 return false;
3548 }
3549 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3550 // what we want to do with them.
3551 // engine()->voe().EnableVQMon(voe_channel(), true);
3552 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3553 return true;
3554}
3555
3556bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3557 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3558 for (int i = 0; i < ncodecs; ++i) {
3559 webrtc::CodecInst voe_codec;
3560 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3561 voe_codec.pltype = -1;
3562 if (engine()->voe()->codec()->SetRecPayloadType(
3563 channel, voe_codec) == -1) {
3564 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3565 return false;
3566 }
3567 }
3568 }
3569 return true;
3570}
3571
3572bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3573 if (playout) {
3574 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3575 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3576 LOG_RTCERR1(StartPlayout, channel);
3577 return false;
3578 }
3579 } else {
3580 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3581 engine()->voe()->base()->StopPlayout(channel);
3582 }
3583 return true;
3584}
3585
3586uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3587 bool rtcp) {
3588 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3589 uint32 ssrc = 0;
3590 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003591 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003592 }
3593 return ssrc;
3594}
3595
3596// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3597VoiceMediaChannel::Error
3598 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3599 switch (err_code) {
3600 case 0:
3601 return ERROR_NONE;
3602 case VE_CANNOT_START_RECORDING:
3603 case VE_MIC_VOL_ERROR:
3604 case VE_GET_MIC_VOL_ERROR:
3605 case VE_CANNOT_ACCESS_MIC_VOL:
3606 return ERROR_REC_DEVICE_OPEN_FAILED;
3607 case VE_SATURATION_WARNING:
3608 return ERROR_REC_DEVICE_SATURATION;
3609 case VE_REC_DEVICE_REMOVED:
3610 return ERROR_REC_DEVICE_REMOVED;
3611 case VE_RUNTIME_REC_WARNING:
3612 case VE_RUNTIME_REC_ERROR:
3613 return ERROR_REC_RUNTIME_ERROR;
3614 case VE_CANNOT_START_PLAYOUT:
3615 case VE_SPEAKER_VOL_ERROR:
3616 case VE_GET_SPEAKER_VOL_ERROR:
3617 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3618 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3619 case VE_RUNTIME_PLAY_WARNING:
3620 case VE_RUNTIME_PLAY_ERROR:
3621 return ERROR_PLAY_RUNTIME_ERROR;
3622 case VE_TYPING_NOISE_WARNING:
3623 return ERROR_REC_TYPING_NOISE_DETECTED;
3624 default:
3625 return VoiceMediaChannel::ERROR_OTHER;
3626 }
3627}
3628
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003629bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3630 int channel_id, const RtpHeaderExtension* extension) {
3631 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003632 int id = 0;
3633 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003634 if (extension) {
3635 enable = true;
3636 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003637 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003638 }
3639 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003640 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003641 return false;
3642 }
3643 return true;
3644}
3645
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003646void WebRtcVoiceMediaChannel::TryAddAudioRecvStream(uint32 ssrc) {
3647 DCHECK(thread_checker_.CalledOnValidThread());
pbos8fc7fa72015-07-15 08:02:58 -07003648 WebRtcVoiceChannelRenderer* channel = receive_channels_[ssrc];
3649 DCHECK(channel != nullptr);
3650 DCHECK(receive_streams_.find(ssrc) == receive_streams_.end());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003651 // If we are hooked up to a webrtc::Call, create an AudioReceiveStream too.
pbos8fc7fa72015-07-15 08:02:58 -07003652 if (!call_) {
3653 return;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003654 }
pbos8fc7fa72015-07-15 08:02:58 -07003655 webrtc::AudioReceiveStream::Config config;
3656 config.rtp.remote_ssrc = ssrc;
3657 // Only add RTP extensions if we support combined A/V BWE.
pbos6bb1b6e2015-07-24 07:10:18 -07003658 config.rtp.extensions = recv_rtp_extensions_;
3659 config.combined_audio_video_bwe =
3660 options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false);
pbos8fc7fa72015-07-15 08:02:58 -07003661 config.voe_channel_id = channel->channel();
3662 config.sync_group = receive_stream_params_[ssrc].sync_label;
3663 webrtc::AudioReceiveStream* s = call_->CreateAudioReceiveStream(config);
3664 receive_streams_.insert(std::make_pair(ssrc, s));
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003665}
3666
3667void WebRtcVoiceMediaChannel::TryRemoveAudioRecvStream(uint32 ssrc) {
3668 DCHECK(thread_checker_.CalledOnValidThread());
3669 // If we are hooked up to a webrtc::Call, assume there is an
3670 // AudioReceiveStream to destroy too.
3671 if (call_) {
3672 auto stream_it = receive_streams_.find(ssrc);
3673 if (stream_it != receive_streams_.end()) {
3674 call_->DestroyAudioReceiveStream(stream_it->second);
3675 receive_streams_.erase(stream_it);
3676 }
3677 }
3678}
3679
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003680int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003681 size_t res = 0;
3682 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003683 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003684}
3685
3686int WebRtcSoundclipStream::Rewind() {
3687 mem_.Rewind();
3688 // Return -1 to keep VoiceEngine from looping.
3689 return (loop_) ? 0 : -1;
3690}
3691
3692} // namespace cricket
3693
3694#endif // HAVE_WEBRTC_VOICE