blob: 284afed4d119e8b11dce8aa8d0cd0153d5d4e0e2 [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),
1627 renderer_(NULL) {
1628 }
Fredrik Solenbergaaf8ff22015-05-07 16:05:53 +02001629 ~WebRtcVoiceChannelRenderer() override { Stop(); }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001630
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001631 // Starts the rendering by setting a sink to the renderer to get data
1632 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001633 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001634 // TODO(xians): Make sure Start() is called only once.
1635 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001636 rtc::CritScope lock(&lock_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001637 DCHECK(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001638 if (renderer_ != NULL) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001639 DCHECK(renderer_ == renderer);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001640 return;
1641 }
1642
1643 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1644 // in getUserMedia by default.
1645 renderer->AddChannel(channel_);
1646 renderer->SetSink(this);
1647 renderer_ = renderer;
1648 }
1649
1650 // Stops rendering by setting the sink of the renderer to NULL. No data
1651 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001652 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001653 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001654 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001655 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001656 return;
1657
1658 renderer_->RemoveChannel(channel_);
1659 renderer_->SetSink(NULL);
1660 renderer_ = NULL;
1661 }
1662
1663 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001664 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001665 void OnData(const void* audio_data,
1666 int bits_per_sample,
1667 int sample_rate,
1668 int number_of_channels,
1669 int number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001670 voe_audio_transport_->OnData(channel_,
1671 audio_data,
1672 bits_per_sample,
1673 sample_rate,
1674 number_of_channels,
1675 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001676 }
1677
1678 // Callback from the |renderer_| when it is going away. In case Start() has
1679 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001680 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001681 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001682 // Set |renderer_| to NULL to make sure no more callback will get into
1683 // the renderer.
1684 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001685 }
1686
1687 // Accessor to the VoE channel ID.
1688 int channel() const { return channel_; }
1689
1690 private:
1691 const int channel_;
1692 webrtc::AudioTransport* const voe_audio_transport_;
1693
1694 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1695 // PeerConnection will make sure invalidating the pointer before the object
1696 // goes away.
1697 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001698
1699 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001700 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001701};
1702
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001703// WebRtcVoiceMediaChannel
Fredrik Solenberge444a3d2015-05-07 16:42:08 +02001704WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine)
1705 : engine_(engine),
1706 voe_channel_(engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001707 send_bitrate_setting_(false),
1708 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001709 options_(),
1710 dtmf_allowed_(false),
1711 desired_playout_(false),
1712 nack_enabled_(false),
1713 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001714 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001715 desired_send_(SEND_NOTHING),
1716 send_(SEND_NOTHING),
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001717 call_(nullptr),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001718 default_receive_ssrc_(0) {
1719 engine->RegisterChannel(this);
1720 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1721 << voe_channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001722 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001723}
1724
1725WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1726 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1727 << voe_channel();
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001728 DCHECK(receive_streams_.empty() || call_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001729
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001730 // Remove any remaining send streams, the default channel will be deleted
1731 // later.
1732 while (!send_channels_.empty())
1733 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001734
1735 // Unregister ourselves from the engine.
1736 engine()->UnregisterChannel(this);
1737 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001738 while (!receive_channels_.empty()) {
1739 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001740 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001741 DCHECK(receive_streams_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001742
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001743 // Delete the default channel.
1744 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001745}
1746
1747bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1748 LOG(LS_INFO) << "Setting voice channel options: "
1749 << options.ToString();
1750
wu@webrtc.orgde305012013-10-31 15:40:38 +00001751 // Check if DSCP value is changed from previous.
1752 bool dscp_option_changed = (options_.dscp != options.dscp);
1753
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001754 // TODO(xians): Add support to set different options for different send
1755 // streams after we support multiple APMs.
1756
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001757 // We retain all of the existing options, and apply the given ones
1758 // on top. This means there is no way to "clear" options such that
1759 // they go back to the engine default.
1760 options_.SetAll(options);
1761
1762 if (send_ != SEND_NOTHING) {
1763 if (!engine()->SetOptionOverrides(options_)) {
1764 LOG(LS_WARNING) <<
1765 "Failed to engine SetOptionOverrides during channel SetOptions.";
1766 return false;
1767 }
1768 } else {
1769 // Will be interpreted when appropriate.
1770 }
1771
wu@webrtc.org97077a32013-10-25 21:18:33 +00001772 // Receiver-side auto gain control happens per channel, so set it here from
1773 // options. Note that, like conference mode, setting it on the engine won't
1774 // have the desired effect, since voice channels don't inherit options from
1775 // the media engine when those options are applied per-channel.
1776 bool rx_auto_gain_control;
1777 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1778 if (engine()->voe()->processing()->SetRxAgcStatus(
1779 voe_channel(), rx_auto_gain_control,
1780 webrtc::kAgcFixedDigital) == -1) {
1781 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1782 return false;
1783 } else {
1784 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1785 << " with mode " << webrtc::kAgcFixedDigital;
1786 }
1787 }
1788 if (options.rx_agc_target_dbov.IsSet() ||
1789 options.rx_agc_digital_compression_gain.IsSet() ||
1790 options.rx_agc_limiter.IsSet()) {
1791 webrtc::AgcConfig config;
1792 // If only some of the options are being overridden, get the current
1793 // settings for the channel and bail if they aren't available.
1794 if (!options.rx_agc_target_dbov.IsSet() ||
1795 !options.rx_agc_digital_compression_gain.IsSet() ||
1796 !options.rx_agc_limiter.IsSet()) {
1797 if (engine()->voe()->processing()->GetRxAgcConfig(
1798 voe_channel(), config) != 0) {
1799 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1800 << "channel " << voe_channel() << ". Since not all rx "
1801 << "agc options are specified, unable to safely set rx "
1802 << "agc options.";
1803 return false;
1804 }
1805 }
1806 config.targetLeveldBOv =
1807 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1808 config.targetLeveldBOv);
1809 config.digitalCompressionGaindB =
1810 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1811 config.digitalCompressionGaindB);
1812 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1813 config.limiterEnable);
1814 if (engine()->voe()->processing()->SetRxAgcConfig(
1815 voe_channel(), config) == -1) {
1816 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1817 config.digitalCompressionGaindB, config.limiterEnable);
1818 return false;
1819 }
1820 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001821 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001822 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001823 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001824 dscp = kAudioDscpValue;
1825 if (MediaChannel::SetDscp(dscp) != 0) {
1826 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1827 }
1828 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001829
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001830 SetCall(call_);
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001831
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001832 LOG(LS_INFO) << "Set voice channel options. Current options: "
1833 << options_.ToString();
1834 return true;
1835}
1836
1837bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1838 const std::vector<AudioCodec>& codecs) {
1839 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001840 LOG(LS_INFO) << "Setting receive voice codecs:";
1841
1842 std::vector<AudioCodec> new_codecs;
1843 // Find all new codecs. We allow adding new codecs but don't allow changing
1844 // the payload type of codecs that is already configured since we might
1845 // already be receiving packets with that payload type.
1846 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001847 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001848 AudioCodec old_codec;
1849 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1850 if (old_codec.id != it->id) {
1851 LOG(LS_ERROR) << it->name << " payload type changed.";
1852 return false;
1853 }
1854 } else {
1855 new_codecs.push_back(*it);
1856 }
1857 }
1858 if (new_codecs.empty()) {
1859 // There are no new codecs to configure. Already configured codecs are
1860 // never removed.
1861 return true;
1862 }
1863
1864 if (playout_) {
1865 // Receive codecs can not be changed while playing. So we temporarily
1866 // pause playout.
1867 PausePlayout();
1868 }
1869
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001870 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001871 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1872 it != new_codecs.end() && ret; ++it) {
1873 webrtc::CodecInst voe_codec;
1874 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1875 LOG(LS_INFO) << ToString(*it);
1876 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001877 if (default_receive_ssrc_ == 0) {
1878 // Set the receive codecs on the default channel explicitly if the
1879 // default channel is not used by |receive_channels_|, this happens in
1880 // conference mode or in non-conference mode when there is no playout
1881 // channel.
1882 // TODO(xians): Figure out how we use the default channel in conference
1883 // mode.
1884 if (engine()->voe()->codec()->SetRecPayloadType(
1885 voe_channel(), voe_codec) == -1) {
1886 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1887 ret = false;
1888 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001889 }
1890
1891 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001892 for (ChannelMap::iterator it = receive_channels_.begin();
1893 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001894 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001895 it->second->channel(), voe_codec) == -1) {
1896 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001897 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001898 ret = false;
1899 }
1900 }
1901 } else {
1902 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1903 ret = false;
1904 }
1905 }
1906 if (ret) {
1907 recv_codecs_ = codecs;
1908 }
1909
1910 if (desired_playout_ && !playout_) {
1911 ResumePlayout();
1912 }
1913 return ret;
1914}
1915
1916bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001917 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001918 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001919 engine()->voe()->codec()->SetVADStatus(channel, false);
1920 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001921 engine()->voe()->rtp()->SetREDStatus(channel, false);
1922 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001923
1924 // Scan through the list to figure out the codec to use for sending, along
1925 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001926 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001927 webrtc::CodecInst send_codec;
1928 memset(&send_codec, 0, sizeof(send_codec));
1929
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001930 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001931 bool enable_codec_fec = false;
Minyue Li7100dcd2015-03-27 05:05:59 +01001932 bool enable_opus_dtx = false;
minyue@webrtc.org26236952014-10-29 02:27:08 +00001933 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001934
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001935 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001936 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1937 it != codecs.end(); ++it) {
1938 // Ignore codecs we don't know about. The negotiation step should prevent
1939 // this, but double-check to be sure.
1940 webrtc::CodecInst voe_codec;
1941 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001942 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001943 continue;
1944 }
1945
Minyue Li7100dcd2015-03-27 05:05:59 +01001946 if (IsCodec(*it, kDtmfCodecName) || IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001947 // Skip telephone-event/CN codec, which will be handled later.
1948 continue;
1949 }
1950
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001951 // We'll use the first codec in the list to actually send audio data.
1952 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001953 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001954 // used is specified in params.
Minyue Li7100dcd2015-03-27 05:05:59 +01001955 if (IsCodec(*it, kRedCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001956 // Parse out the RED parameters. If we fail, just ignore RED;
1957 // we don't support all possible params/usage scenarios.
1958 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
1959 continue;
1960 }
1961
1962 // Enable redundant encoding of the specified codec. Treat any
1963 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001964 LOG(LS_INFO) << "Enabling RED on channel " << channel;
1965 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
1966 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001967 return false;
1968 }
1969 } else {
1970 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001971 nack_enabled = IsNackEnabled(*it);
Minyue Li7100dcd2015-03-27 05:05:59 +01001972 // For Opus as the send codec, we are to determine inband FEC, maximum
1973 // playback rate, and opus internal dtx.
1974 if (IsCodec(*it, kOpusCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00001975 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
Minyue Li7100dcd2015-03-27 05:05:59 +01001976 &opus_max_playback_rate, &enable_opus_dtx);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001977 }
Brave Yao5225dd82015-03-26 07:39:19 +08001978
1979 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1980 int ptime_ms = 0;
1981 if (it->GetParam(kCodecParamPTime, &ptime_ms)) {
1982 if (!SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
1983 LOG(LS_WARNING) << "Failed to set packet size for codec "
1984 << send_codec.plname;
1985 return false;
1986 }
1987 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001988 }
1989 found_send_codec = true;
1990 break;
1991 }
1992
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001993 if (nack_enabled_ != nack_enabled) {
1994 SetNack(channel, nack_enabled);
1995 nack_enabled_ = nack_enabled;
1996 }
1997
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001998 if (!found_send_codec) {
1999 LOG(LS_WARNING) << "Received empty list of codecs.";
2000 return false;
2001 }
2002
2003 // Set the codec immediately, since SetVADStatus() depends on whether
2004 // the current codec is mono or stereo.
2005 if (!SetSendCodec(channel, send_codec))
2006 return false;
2007
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002008 // FEC should be enabled after SetSendCodec.
2009 if (enable_codec_fec) {
2010 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2011 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002012 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2013 // Enable codec internal FEC. Treat any failure as fatal internal error.
2014 LOG_RTCERR2(SetFECStatus, channel, true);
2015 return false;
2016 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002017 }
2018
Minyue Li7100dcd2015-03-27 05:05:59 +01002019 if (IsCodec(send_codec, kOpusCodecName)) {
2020 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
2021 // send codec has to be Opus.
2022
2023 // Set Opus internal DTX.
2024 LOG(LS_INFO) << "Attempt to "
2025 << GetEnableString(enable_opus_dtx)
2026 << " Opus DTX on channel "
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002027 << channel;
Minyue Li7100dcd2015-03-27 05:05:59 +01002028 if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) {
2029 LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx);
2030 return false;
2031 }
2032
2033 // If opus_max_playback_rate <= 0, the default maximum playback rate
2034 // (48 kHz) will be used.
2035 if (opus_max_playback_rate > 0) {
2036 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
2037 << opus_max_playback_rate
2038 << " Hz on channel "
2039 << channel;
2040 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
2041 channel, opus_max_playback_rate) == -1) {
2042 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate);
2043 return false;
2044 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002045 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002046 }
2047
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002048 // Always update the |send_codec_| to the currently set send codec.
2049 send_codec_.reset(new webrtc::CodecInst(send_codec));
2050
minyue@webrtc.org26236952014-10-29 02:27:08 +00002051 if (send_bitrate_setting_) {
2052 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002053 }
2054
2055 // Loop through the codecs list again to config the telephone-event/CN codec.
2056 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2057 it != codecs.end(); ++it) {
2058 // Ignore codecs we don't know about. The negotiation step should prevent
2059 // this, but double-check to be sure.
2060 webrtc::CodecInst voe_codec;
2061 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2062 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2063 continue;
2064 }
2065
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002066 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2067 // about it.
Minyue Li7100dcd2015-03-27 05:05:59 +01002068 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002069 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2070 channel, it->id) == -1) {
2071 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2072 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002073 }
Minyue Li7100dcd2015-03-27 05:05:59 +01002074 } else if (IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002075 // Turn voice activity detection/comfort noise on if supported.
2076 // Set the wideband CN payload type appropriately.
2077 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002078 webrtc::PayloadFrequencies cn_freq;
2079 switch (it->clockrate) {
2080 case 8000:
2081 cn_freq = webrtc::kFreq8000Hz;
2082 break;
2083 case 16000:
2084 cn_freq = webrtc::kFreq16000Hz;
2085 break;
2086 case 32000:
2087 cn_freq = webrtc::kFreq32000Hz;
2088 break;
2089 default:
2090 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2091 << " not supported.";
2092 continue;
2093 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002094 // Set the CN payloadtype and the VAD status.
2095 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2096 if (cn_freq != webrtc::kFreq8000Hz) {
2097 if (engine()->voe()->codec()->SetSendCNPayloadType(
2098 channel, it->id, cn_freq) == -1) {
2099 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2100 // TODO(ajm): This failure condition will be removed from VoE.
2101 // Restore the return here when we update to a new enough webrtc.
2102 //
2103 // Not returning false because the SetSendCNPayloadType will fail if
2104 // the channel is already sending.
2105 // This can happen if the remote description is applied twice, for
2106 // example in the case of ROAP on top of JSEP, where both side will
2107 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002108 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002109 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002110 // Only turn on VAD if we have a CN payload type that matches the
2111 // clockrate for the codec we are going to use.
Minyue Li7100dcd2015-03-27 05:05:59 +01002112 if (it->clockrate == send_codec.plfreq && send_codec.channels != 2) {
2113 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
2114 // interaction between VAD and Opus FEC.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002115 LOG(LS_INFO) << "Enabling VAD";
2116 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2117 LOG_RTCERR2(SetVADStatus, channel, true);
2118 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002119 }
2120 }
2121 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002122 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002123 return true;
2124}
2125
2126bool WebRtcVoiceMediaChannel::SetSendCodecs(
2127 const std::vector<AudioCodec>& codecs) {
2128 dtmf_allowed_ = false;
2129 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2130 it != codecs.end(); ++it) {
2131 // Find the DTMF telephone event "codec".
Minyue Li7100dcd2015-03-27 05:05:59 +01002132 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002133 dtmf_allowed_ = true;
2134 }
2135 }
2136
2137 // Cache the codecs in order to configure the channel created later.
2138 send_codecs_ = codecs;
2139 for (ChannelMap::iterator iter = send_channels_.begin();
2140 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002141 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002142 return false;
2143 }
2144 }
2145
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002146 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002147 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002148 return true;
2149}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002150
2151void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2152 bool nack_enabled) {
2153 for (ChannelMap::const_iterator it = channels.begin();
2154 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002155 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002156 }
2157}
2158
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002159void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002160 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002161 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002162 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2163 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002164 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002165 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2166 }
2167}
2168
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002169bool WebRtcVoiceMediaChannel::SetSendCodec(
2170 const webrtc::CodecInst& send_codec) {
2171 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2172 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002173 for (ChannelMap::iterator iter = send_channels_.begin();
2174 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002175 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002176 return false;
2177 }
2178
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002179 return true;
2180}
2181
2182bool WebRtcVoiceMediaChannel::SetSendCodec(
2183 int channel, const webrtc::CodecInst& send_codec) {
2184 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2185 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2186
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002187 webrtc::CodecInst current_codec;
2188 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2189 (send_codec == current_codec)) {
2190 // Codec is already configured, we can return without setting it again.
2191 return true;
2192 }
2193
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002194 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2195 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002196 return false;
2197 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002198 return true;
2199}
2200
2201bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2202 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002203 if (receive_extensions_ == extensions) {
2204 return true;
2205 }
2206
2207 // The default channel may or may not be in |receive_channels_|. Set the rtp
2208 // header extensions for default channel regardless.
2209 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2210 return false;
2211 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002212
2213 // Loop through all receive channels and enable/disable the extensions.
2214 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2215 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002216 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2217 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002218 return false;
2219 }
2220 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002221
2222 receive_extensions_ = extensions;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002223
2224 // Recreate AudioReceiveStream:s.
2225 {
2226 std::vector<webrtc::RtpExtension> exts;
2227
2228 const RtpHeaderExtension* audio_level_extension =
2229 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2230 if (audio_level_extension) {
2231 exts.push_back({
2232 kRtpAudioLevelHeaderExtension, audio_level_extension->id});
2233 }
2234
2235 const RtpHeaderExtension* send_time_extension =
2236 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2237 if (send_time_extension) {
2238 exts.push_back({
2239 kRtpAbsoluteSenderTimeHeaderExtension, send_time_extension->id});
2240 }
2241
2242 recv_rtp_extensions_.swap(exts);
2243 SetCall(call_);
2244 }
2245
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002246 return true;
2247}
2248
2249bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2250 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002251 const RtpHeaderExtension* audio_level_extension =
2252 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2253 if (!SetHeaderExtension(
2254 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2255 audio_level_extension)) {
2256 return false;
2257 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002258
2259 const RtpHeaderExtension* send_time_extension =
2260 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2261 if (!SetHeaderExtension(
2262 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2263 send_time_extension)) {
2264 return false;
2265 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002266
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002267 return true;
2268}
2269
2270bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2271 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002272 if (send_extensions_ == extensions) {
2273 return true;
2274 }
2275
2276 // The default channel may or may not be in |send_channels_|. Set the rtp
2277 // header extensions for default channel regardless.
2278
2279 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2280 return false;
2281 }
2282
2283 // Loop through all send channels and enable/disable the extensions.
2284 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2285 channel_it != send_channels_.end(); ++channel_it) {
2286 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2287 extensions)) {
2288 return false;
2289 }
2290 }
2291
2292 send_extensions_ = extensions;
2293 return true;
2294}
2295
2296bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2297 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002298 const RtpHeaderExtension* audio_level_extension =
2299 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002300
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002301 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002302 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002303 audio_level_extension)) {
2304 return false;
2305 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002306
2307 const RtpHeaderExtension* send_time_extension =
2308 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002309 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002310 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002311 send_time_extension)) {
2312 return false;
2313 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002314
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002315 return true;
2316}
2317
2318bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2319 desired_playout_ = playout;
2320 return ChangePlayout(desired_playout_);
2321}
2322
2323bool WebRtcVoiceMediaChannel::PausePlayout() {
2324 return ChangePlayout(false);
2325}
2326
2327bool WebRtcVoiceMediaChannel::ResumePlayout() {
2328 return ChangePlayout(desired_playout_);
2329}
2330
2331bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2332 if (playout_ == playout) {
2333 return true;
2334 }
2335
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002336 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002337 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002338 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002339 // Only toggle the default channel if we don't have any other channels.
2340 result = SetPlayout(voe_channel(), playout);
2341 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002342 for (ChannelMap::iterator it = receive_channels_.begin();
2343 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002344 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002345 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002346 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002347 result = false;
2348 }
2349 }
2350
2351 if (result) {
2352 playout_ = playout;
2353 }
2354 return result;
2355}
2356
2357bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2358 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002359 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002360 return ChangeSend(desired_send_);
2361 return true;
2362}
2363
2364bool WebRtcVoiceMediaChannel::PauseSend() {
2365 return ChangeSend(SEND_NOTHING);
2366}
2367
2368bool WebRtcVoiceMediaChannel::ResumeSend() {
2369 return ChangeSend(desired_send_);
2370}
2371
2372bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2373 if (send_ == send) {
2374 return true;
2375 }
2376
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002377 // Change the settings on each send channel.
2378 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002379 engine()->SetOptionOverrides(options_);
2380
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002381 // Change the settings on each send channel.
2382 for (ChannelMap::iterator iter = send_channels_.begin();
2383 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002384 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002385 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002386 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002387
2388 // Clear up the options after stopping sending.
2389 if (send == SEND_NOTHING)
2390 engine()->ClearOptionOverrides();
2391
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002392 send_ = send;
2393 return true;
2394}
2395
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002396bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2397 if (send == SEND_MICROPHONE) {
2398 if (engine()->voe()->base()->StartSend(channel) == -1) {
2399 LOG_RTCERR1(StartSend, channel);
2400 return false;
2401 }
2402 if (engine()->voe()->file() &&
2403 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2404 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2405 return false;
2406 }
2407 } else { // SEND_NOTHING
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002408 DCHECK(send == SEND_NOTHING);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002409 if (engine()->voe()->base()->StopSend(channel) == -1) {
2410 LOG_RTCERR1(StopSend, channel);
2411 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002412 }
2413 }
2414
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002415 return true;
2416}
2417
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002418// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002419void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2420 if (engine()->voe()->network()->RegisterExternalTransport(
2421 channel, *this) == -1) {
2422 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2423 }
2424
2425 // Enable RTCP (for quality stats and feedback messages)
2426 EnableRtcp(channel);
2427
2428 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2429 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002430
2431 // Set RTP header extension for the new channel.
2432 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002433}
2434
2435bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2436 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2437 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2438 }
2439
2440 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2441 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002442 return false;
2443 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002444
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002445 return true;
2446}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002447
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002448bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2449 // If the default channel is already used for sending create a new channel
2450 // otherwise use the default channel for sending.
2451 int channel = GetSendChannelNum(sp.first_ssrc());
2452 if (channel != -1) {
2453 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2454 return false;
2455 }
2456
2457 bool default_channel_is_available = true;
2458 for (ChannelMap::const_iterator iter = send_channels_.begin();
2459 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002460 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002461 default_channel_is_available = false;
2462 break;
2463 }
2464 }
2465 if (default_channel_is_available) {
2466 channel = voe_channel();
2467 } else {
2468 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002469 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002470 if (channel == -1) {
2471 LOG_RTCERR0(CreateChannel);
2472 return false;
2473 }
2474
2475 ConfigureSendChannel(channel);
2476 }
2477
2478 // Save the channel to send_channels_, so that RemoveSendStream() can still
2479 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002480 webrtc::AudioTransport* audio_transport =
2481 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002482 send_channels_.insert(std::make_pair(
2483 sp.first_ssrc(),
2484 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002485
2486 // Set the send (local) SSRC.
2487 // If there are multiple send SSRCs, we can only set the first one here, and
2488 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2489 // (with a codec requires multiple SSRC(s)).
2490 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2491 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2492 return false;
2493 }
2494
2495 // At this point the channel's local SSRC has been updated. If the channel is
2496 // the default channel make sure that all the receive channels are updated as
2497 // well. Receive channels have to have the same SSRC as the default channel in
2498 // order to send receiver reports with this SSRC.
2499 if (IsDefaultChannel(channel)) {
2500 for (ChannelMap::const_iterator it = receive_channels_.begin();
2501 it != receive_channels_.end(); ++it) {
2502 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002503 if (!IsDefaultChannel(it->second->channel())) {
2504 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002505 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002506 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002507 return false;
2508 }
2509 }
2510 }
2511 }
2512
2513 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002514 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2515 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002516 }
2517
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002518 // Set the current codecs to be used for the new channel.
2519 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002520 return false;
2521
2522 return ChangeSend(channel, desired_send_);
2523}
2524
2525bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2526 ChannelMap::iterator it = send_channels_.find(ssrc);
2527 if (it == send_channels_.end()) {
2528 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2529 << " which doesn't exist.";
2530 return false;
2531 }
2532
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002533 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002534 ChangeSend(channel, SEND_NOTHING);
2535
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002536 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2537 // this will disconnect the audio renderer with the send channel.
2538 delete it->second;
2539 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002540
2541 if (IsDefaultChannel(channel)) {
2542 // Do not delete the default channel since the receive channels depend on
2543 // the default channel, recycle it instead.
2544 ChangeSend(channel, SEND_NOTHING);
2545 } else {
2546 // Clean up and delete the send channel.
2547 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2548 << " with VoiceEngine channel #" << channel << ".";
2549 if (!DeleteChannel(channel))
2550 return false;
2551 }
2552
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002553 if (send_channels_.empty())
2554 ChangeSend(SEND_NOTHING);
2555
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002556 return true;
2557}
2558
2559bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002560 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002561 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002562
2563 if (!VERIFY(sp.ssrcs.size() == 1))
2564 return false;
2565 uint32 ssrc = sp.first_ssrc();
2566
wu@webrtc.org78187522013-10-07 23:32:02 +00002567 if (ssrc == 0) {
2568 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2569 return false;
2570 }
2571
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002572 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2573 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002574 return false;
2575 }
2576
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002577 TryAddAudioRecvStream(ssrc);
2578
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002579 // Reuse default channel for recv stream in non-conference mode call
2580 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002581 webrtc::AudioTransport* audio_transport =
2582 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002583 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002584 LOG(LS_INFO) << "Recv stream " << ssrc << " reuse default channel";
2585 default_receive_ssrc_ = ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002586 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002587 default_receive_ssrc_,
2588 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002589 return SetPlayout(voe_channel(), playout_);
2590 }
2591
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002592 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002593 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002594 if (channel == -1) {
2595 LOG_RTCERR0(CreateChannel);
2596 return false;
2597 }
2598
wu@webrtc.org78187522013-10-07 23:32:02 +00002599 if (!ConfigureRecvChannel(channel)) {
2600 DeleteChannel(channel);
2601 return false;
2602 }
2603
2604 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002605 std::make_pair(
2606 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002607
2608 LOG(LS_INFO) << "New audio stream " << ssrc
2609 << " registered to VoiceEngine channel #"
2610 << channel << ".";
2611 return true;
2612}
2613
2614bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002615 // Configure to use external transport, like our default channel.
2616 if (engine()->voe()->network()->RegisterExternalTransport(
2617 channel, *this) == -1) {
2618 LOG_RTCERR2(SetExternalTransport, channel, this);
2619 return false;
2620 }
2621
2622 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002623 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002624 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2625 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002626 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002627 return false;
2628 }
2629 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002630 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002631 return false;
2632 }
2633
Minyue2013aec2015-05-13 14:14:42 +02002634 // Associate receive channel to default channel (so the receive channel can
2635 // obtain RTT from the send channel)
2636 engine()->voe()->base()->AssociateSendChannel(channel, voe_channel());
2637 LOG(LS_INFO) << "VoiceEngine channel #"
2638 << channel << " is associated with channel #"
2639 << voe_channel() << ".";
2640
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002641 // Use the same recv payload types as our default channel.
2642 ResetRecvCodecs(channel);
2643 if (!recv_codecs_.empty()) {
2644 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2645 it != recv_codecs_.end(); ++it) {
2646 webrtc::CodecInst voe_codec;
2647 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2648 voe_codec.pltype = it->id;
2649 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2650 if (engine()->voe()->codec()->GetRecPayloadType(
2651 voe_channel(), voe_codec) != -1) {
2652 if (engine()->voe()->codec()->SetRecPayloadType(
2653 channel, voe_codec) == -1) {
2654 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2655 return false;
2656 }
2657 }
2658 }
2659 }
2660 }
2661
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002662 if (InConferenceMode()) {
2663 // To be in par with the video, voe_channel() is not used for receiving in
2664 // a conference call.
2665 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2666 // This is the first stream in a multi user meeting. We can now
2667 // disable playback of the default stream. This since the default
2668 // stream will probably have received some initial packets before
2669 // the new stream was added. This will mean that the CN state from
2670 // the default channel will be mixed in with the other streams
2671 // throughout the whole meeting, which might be disturbing.
2672 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2673 SetPlayout(voe_channel(), false);
2674 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002675 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002676 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002677
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002678 // Set RTP header extension for the new channel.
2679 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2680 return false;
2681 }
2682
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002683 return SetPlayout(channel, playout_);
2684}
2685
2686bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002687 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002688 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002689 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002690 if (it == receive_channels_.end()) {
2691 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2692 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002693 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002694 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002695
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002696 TryRemoveAudioRecvStream(ssrc);
2697
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002698 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2699 // will disconnect the audio renderer with the receive channel.
2700 // Cache the channel before the deletion.
2701 const int channel = it->second->channel();
2702 delete it->second;
2703 receive_channels_.erase(it);
2704
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002705 if (ssrc == default_receive_ssrc_) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002706 DCHECK(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002707 // Recycle the default channel is for recv stream.
2708 if (playout_)
2709 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002710
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002711 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002712 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002713 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002714
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002715 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002716 << " with VoiceEngine channel #" << channel << ".";
2717 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002718 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002719
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002720 bool enable_default_channel_playout = false;
2721 if (receive_channels_.empty()) {
2722 // The last stream was removed. We can now enable the default
2723 // channel for new channels to be played out immediately without
2724 // waiting for AddStream messages.
2725 // We do this for both conference mode and non-conference mode.
2726 // TODO(oja): Does the default channel still have it's CN state?
2727 enable_default_channel_playout = true;
2728 }
2729 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2730 default_receive_ssrc_ != 0) {
2731 // Only the default channel is active, enable the playout on default
2732 // channel.
2733 enable_default_channel_playout = true;
2734 }
2735 if (enable_default_channel_playout && playout_) {
2736 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2737 SetPlayout(voe_channel(), true);
2738 }
2739
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002740 return true;
2741}
2742
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002743bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2744 AudioRenderer* renderer) {
2745 ChannelMap::iterator it = receive_channels_.find(ssrc);
2746 if (it == receive_channels_.end()) {
2747 if (renderer) {
2748 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002749 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002750 return false;
2751 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002752
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002753 // The channel likely has gone away, do nothing.
2754 return true;
2755 }
2756
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002757 if (renderer)
2758 it->second->Start(renderer);
2759 else
2760 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002761
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002762 return true;
2763}
2764
2765bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2766 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002767 ChannelMap::iterator it = send_channels_.find(ssrc);
2768 if (it == send_channels_.end()) {
2769 if (renderer) {
2770 // Return an error if trying to set a valid renderer with an invalid ssrc.
2771 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2772 return false;
2773 }
2774
2775 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002776 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002777 }
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.org28e20752013-07-10 00:45:36 +00002784 return true;
2785}
2786
2787bool WebRtcVoiceMediaChannel::GetActiveStreams(
2788 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002789 // In conference mode, the default channel should not be in
2790 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002791 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002792 for (ChannelMap::iterator it = receive_channels_.begin();
2793 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002794 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002795 if (level > 0) {
2796 actives->push_back(std::make_pair(it->first, level));
2797 }
2798 }
2799 return true;
2800}
2801
2802int WebRtcVoiceMediaChannel::GetOutputLevel() {
2803 // return the highest output level of all streams
2804 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002805 for (ChannelMap::iterator it = receive_channels_.begin();
2806 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002807 int level = GetOutputLevel(it->second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002808 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002809 }
2810 return highest;
2811}
2812
2813int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2814 int ret;
2815 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2816 // In case of error, log the info and continue
2817 LOG_RTCERR0(TimeSinceLastTyping);
2818 ret = -1;
2819 } else {
2820 ret *= 1000; // We return ms, webrtc returns seconds.
2821 }
2822 return ret;
2823}
2824
2825void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2826 int cost_per_typing, int reporting_threshold, int penalty_decay,
2827 int type_event_delay) {
2828 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2829 time_window, cost_per_typing,
2830 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2831 // In case of error, log the info and continue
2832 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2833 cost_per_typing, reporting_threshold, penalty_decay,
2834 type_event_delay);
2835 }
2836}
2837
2838bool WebRtcVoiceMediaChannel::SetOutputScaling(
2839 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002840 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002841 // Collect the channels to scale the output volume.
2842 std::vector<int> channels;
2843 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002844 // Default channel is not in receive_channels_ if it is not being used for
2845 // playout.
2846 if (default_receive_ssrc_ == 0)
2847 channels.push_back(voe_channel());
2848 for (ChannelMap::const_iterator it = receive_channels_.begin();
2849 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002850 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002851 }
2852 } else { // Collect only the channel of the specified ssrc.
2853 int channel = GetReceiveChannelNum(ssrc);
2854 if (-1 == channel) {
2855 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2856 return false;
2857 }
2858 channels.push_back(channel);
2859 }
2860
2861 // Scale the output volume for the collected channels. We first normalize to
2862 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002863 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002864 if (scale > 0.0001f) {
2865 left /= scale;
2866 right /= scale;
2867 }
2868 for (std::vector<int>::const_iterator it = channels.begin();
2869 it != channels.end(); ++it) {
2870 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2871 *it, scale)) {
2872 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2873 return false;
2874 }
2875 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2876 *it, static_cast<float>(left), static_cast<float>(right))) {
2877 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2878 // Do not return if fails. SetOutputVolumePan is not available for all
2879 // pltforms.
2880 }
2881 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2882 << " right=" << right * scale
2883 << " for channel " << *it << " and ssrc " << ssrc;
2884 }
2885 return true;
2886}
2887
2888bool WebRtcVoiceMediaChannel::GetOutputScaling(
2889 uint32 ssrc, double* left, double* right) {
2890 if (!left || !right) return false;
2891
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002892 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002893 // Determine which channel based on ssrc.
2894 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2895 if (channel == -1) {
2896 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2897 return false;
2898 }
2899
2900 float scaling;
2901 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2902 channel, scaling)) {
2903 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2904 return false;
2905 }
2906
2907 float left_pan;
2908 float right_pan;
2909 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2910 channel, left_pan, right_pan)) {
2911 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2912 // If GetOutputVolumePan fails, we use the default left and right pan.
2913 left_pan = 1.0f;
2914 right_pan = 1.0f;
2915 }
2916
2917 *left = scaling * left_pan;
2918 *right = scaling * right_pan;
2919 return true;
2920}
2921
2922bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2923 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2924 return true;
2925}
2926
2927bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2928 bool play, bool loop) {
2929 if (!ringback_tone_) {
2930 return false;
2931 }
2932
2933 // The voe file api is not available in chrome.
2934 if (!engine()->voe()->file()) {
2935 return false;
2936 }
2937
2938 // Determine which VoiceEngine channel to play on.
2939 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2940 if (channel == -1) {
2941 return false;
2942 }
2943
2944 // Make sure the ringtone is cued properly, and play it out.
2945 if (play) {
2946 ringback_tone_->set_loop(loop);
2947 ringback_tone_->Rewind();
2948 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2949 ringback_tone_.get()) == -1) {
2950 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2951 LOG(LS_ERROR) << "Unable to start ringback tone";
2952 return false;
2953 }
2954 ringback_channels_.insert(channel);
2955 LOG(LS_INFO) << "Started ringback on channel " << channel;
2956 } else {
2957 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2958 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2959 LOG_RTCERR1(StopPlayingFileLocally, channel);
2960 return false;
2961 }
2962 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2963 ringback_channels_.erase(channel);
2964 }
2965
2966 return true;
2967}
2968
2969bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2970 return dtmf_allowed_;
2971}
2972
2973bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2974 int duration, int flags) {
2975 if (!dtmf_allowed_) {
2976 return false;
2977 }
2978
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002979 // Send the event.
2980 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002981 int channel = -1;
2982 if (ssrc == 0) {
2983 bool default_channel_is_inuse = false;
2984 for (ChannelMap::const_iterator iter = send_channels_.begin();
2985 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002986 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002987 default_channel_is_inuse = true;
2988 break;
2989 }
2990 }
2991 if (default_channel_is_inuse) {
2992 channel = voe_channel();
2993 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002994 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002995 }
2996 } else {
2997 channel = GetSendChannelNum(ssrc);
2998 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002999 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003000 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3001 << ssrc << " is not in use.";
3002 return false;
3003 }
3004 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003005 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3006 channel, event, true, duration) == -1) {
3007 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003008 return false;
3009 }
3010 }
3011
3012 // Play the event.
3013 if (flags & cricket::DF_PLAY) {
3014 // Play DTMF tone locally.
3015 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3016 LOG_RTCERR2(PlayDtmfTone, event, duration);
3017 return false;
3018 }
3019 }
3020
3021 return true;
3022}
3023
wu@webrtc.orga9890802013-12-13 00:21:03 +00003024void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003025 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003026 DCHECK(thread_checker_.CalledOnValidThread());
3027
3028 // If hooked up to a "Call", forward packet there too.
3029 if (call_) {
3030 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3031 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3032 }
3033
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003034 // Pick which channel to send this packet to. If this packet doesn't match
3035 // any multiplexed streams, just send it to the default channel. Otherwise,
3036 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003037 int which_channel =
3038 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003039 if (which_channel == -1) {
3040 which_channel = voe_channel();
3041 }
3042
3043 // Stop any ringback that might be playing on the channel.
3044 // It's possible the ringback has already stopped, ih which case we'll just
3045 // use the opportunity to remove the channel from ringback_channels_.
3046 if (engine()->voe()->file()) {
3047 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3048 if (it != ringback_channels_.end()) {
3049 if (engine()->voe()->file()->IsPlayingFileLocally(
3050 which_channel) == 1) {
3051 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3052 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3053 << " due to incoming media";
3054 }
3055 ringback_channels_.erase(which_channel);
3056 }
3057 }
3058
3059 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003060 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003061 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003062 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003063}
3064
wu@webrtc.orga9890802013-12-13 00:21:03 +00003065void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003066 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003067 DCHECK(thread_checker_.CalledOnValidThread());
3068
3069 // If hooked up to a "Call", forward packet there too.
3070 if (call_) {
3071 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3072 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3073 }
3074
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003075 // Sending channels need all RTCP packets with feedback information.
3076 // Even sender reports can contain attached report blocks.
3077 // Receiving channels need sender reports in order to create
3078 // correct receiver reports.
3079 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003080 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003081 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3082 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003083 }
3084
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003085 // If it is a sender report, find the channel that is listening.
3086 bool has_sent_to_default_channel = false;
3087 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003088 int which_channel =
3089 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003090 if (which_channel != -1) {
3091 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003092 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003093
3094 if (IsDefaultChannel(which_channel))
3095 has_sent_to_default_channel = true;
3096 }
3097 }
3098
3099 // SR may continue RR and any RR entry may correspond to any one of the send
3100 // channels. So all RTCP packets must be forwarded all send channels. VoE
3101 // will filter out RR internally.
3102 for (ChannelMap::iterator iter = send_channels_.begin();
3103 iter != send_channels_.end(); ++iter) {
3104 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003105 if (IsDefaultChannel(iter->second->channel()) &&
3106 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003107 continue;
3108
3109 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003110 iter->second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003111 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003112}
3113
3114bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003115 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3116 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003117 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3118 return false;
3119 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003120 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3121 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003122 return false;
3123 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003124 // We set the AGC to mute state only when all the channels are muted.
3125 // This implementation is not ideal, instead we should signal the AGC when
3126 // the mic channel is muted/unmuted. We can't do it today because there
3127 // is no good way to know which stream is mapping to the mic channel.
3128 bool all_muted = muted;
3129 for (ChannelMap::const_iterator iter = send_channels_.begin();
3130 iter != send_channels_.end() && all_muted; ++iter) {
3131 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3132 all_muted)) {
3133 LOG_RTCERR1(GetInputMute, iter->second->channel());
3134 return false;
3135 }
3136 }
3137
3138 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3139 if (ap)
3140 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003141 return true;
3142}
3143
minyue@webrtc.org26236952014-10-29 02:27:08 +00003144// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3145// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003146bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003147 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003148
minyue@webrtc.org26236952014-10-29 02:27:08 +00003149 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003150}
3151
minyue@webrtc.org26236952014-10-29 02:27:08 +00003152bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3153 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003154
minyue@webrtc.org26236952014-10-29 02:27:08 +00003155 send_bitrate_setting_ = true;
3156 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003157
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003158 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003159 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003160 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003161 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003162 }
3163
minyue@webrtc.org26236952014-10-29 02:27:08 +00003164 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003165 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3166 // SetMaxSendBandwith(0), the second call removes the previous limit.
3167 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003168 return true;
3169
3170 webrtc::CodecInst codec = *send_codec_;
3171 bool is_multi_rate = IsCodecMultiRate(codec);
3172
3173 if (is_multi_rate) {
3174 // If codec is multi-rate then just set the bitrate.
3175 codec.rate = bps;
3176 if (!SetSendCodec(codec)) {
3177 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3178 << " to bitrate " << bps << " bps.";
3179 return false;
3180 }
3181 return true;
3182 } else {
3183 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3184 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3185 // fixed bitrate then ignore.
3186 if (bps < codec.rate) {
3187 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3188 << " to bitrate " << bps << " bps"
3189 << ", requires at least " << codec.rate << " bps.";
3190 return false;
3191 }
3192 return true;
3193 }
3194}
3195
3196bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003197 bool echo_metrics_on = false;
3198 // These can take on valid negative values, so use the lowest possible level
3199 // as default rather than -1.
3200 int echo_return_loss = -100;
3201 int echo_return_loss_enhancement = -100;
3202 // These can also be negative, but in practice -1 is only used to signal
3203 // insufficient data, since the resolution is limited to multiples of 4 ms.
3204 int echo_delay_median_ms = -1;
3205 int echo_delay_std_ms = -1;
3206 if (engine()->voe()->processing()->GetEcMetricsStatus(
3207 echo_metrics_on) != -1 && echo_metrics_on) {
3208 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3209 // here, but it appears to be unsuitable currently. Revisit after this is
3210 // investigated: http://b/issue?id=5666755
3211 int erl, erle, rerl, anlp;
3212 if (engine()->voe()->processing()->GetEchoMetrics(
3213 erl, erle, rerl, anlp) != -1) {
3214 echo_return_loss = erl;
3215 echo_return_loss_enhancement = erle;
3216 }
3217
3218 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003219 float dummy;
3220 if (engine()->voe()->processing()->GetEcDelayMetrics(
3221 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003222 echo_delay_median_ms = median;
3223 echo_delay_std_ms = std;
3224 }
3225 }
3226
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003227 webrtc::CallStatistics cs;
3228 unsigned int ssrc;
3229 webrtc::CodecInst codec;
3230 unsigned int level;
3231
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003232 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3233 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003234 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003235
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003236 // Fill in the sender info, based on what we know, and what the
3237 // remote side told us it got from its RTCP report.
3238 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003239
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003240 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3241 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3242 continue;
3243 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003244
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003245 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003246 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3247 sinfo.bytes_sent = cs.bytesSent;
3248 sinfo.packets_sent = cs.packetsSent;
3249 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3250 // returns 0 to indicate an error value.
3251 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3252
3253 // Get data from the last remote RTCP report. Use default values if no data
3254 // available.
3255 sinfo.fraction_lost = -1.0;
3256 sinfo.jitter_ms = -1;
3257 sinfo.packets_lost = -1;
3258 sinfo.ext_seqnum = -1;
3259 std::vector<webrtc::ReportBlock> receive_blocks;
3260 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3261 channel, &receive_blocks) != -1 &&
3262 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3263 std::vector<webrtc::ReportBlock>::iterator iter;
3264 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3265 ++iter) {
3266 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003267 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003268 // Convert Q8 to floating point.
3269 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3270 // Convert samples to milliseconds.
3271 if (codec.plfreq / 1000 > 0) {
3272 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3273 }
3274 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3275 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3276 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003277 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003278 }
3279 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003280
3281 // Local speech level.
3282 sinfo.audio_level = (engine()->voe()->volume()->
3283 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3284
3285 // TODO(xians): We are injecting the same APM logging to all the send
3286 // channels here because there is no good way to know which send channel
3287 // is using the APM. The correct fix is to allow the send channels to have
3288 // their own APM so that we can feed the correct APM logging to different
3289 // send channels. See issue crbug/264611 .
3290 sinfo.echo_return_loss = echo_return_loss;
3291 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3292 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3293 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003294 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3295 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003296 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003297
3298 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003299 }
3300
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003301 // Build the list of receivers, one for each receiving channel, or 1 in
3302 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003303 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003304 for (ChannelMap::const_iterator it = receive_channels_.begin();
3305 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003306 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003307 }
3308 if (channels.empty()) {
3309 channels.push_back(voe_channel());
3310 }
3311
3312 // Get the SSRC and stats for each receiver, based on our own calculations.
3313 for (std::vector<int>::const_iterator it = channels.begin();
3314 it != channels.end(); ++it) {
3315 memset(&cs, 0, sizeof(cs));
3316 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3317 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3318 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3319 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003320 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003321 rinfo.bytes_rcvd = cs.bytesReceived;
3322 rinfo.packets_rcvd = cs.packetsReceived;
3323 // The next four fields are from the most recently sent RTCP report.
3324 // Convert Q8 to floating point.
3325 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3326 rinfo.packets_lost = cs.cumulativeLost;
3327 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003328 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003329 if (codec.pltype != -1) {
3330 rinfo.codec_name = codec.plname;
3331 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003332 // Convert samples to milliseconds.
3333 if (codec.plfreq / 1000 > 0) {
3334 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3335 }
3336
3337 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3338 webrtc::NetworkStatistics ns;
3339 if (engine()->voe()->neteq() &&
3340 engine()->voe()->neteq()->GetNetworkStatistics(
3341 *it, ns) != -1) {
3342 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3343 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3344 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003345 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003346 rinfo.speech_expand_rate =
3347 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3348 rinfo.secondary_decoded_rate =
3349 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
Henrik Lundin8e6fd462015-06-02 09:24:52 +02003350 rinfo.accelerate_rate =
3351 static_cast<float>(ns.currentAccelerateRate) / (1 << 14);
3352 rinfo.preemptive_expand_rate =
3353 static_cast<float>(ns.currentPreemptiveRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003354 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003355
3356 webrtc::AudioDecodingCallStats ds;
3357 if (engine()->voe()->neteq() &&
3358 engine()->voe()->neteq()->GetDecodingCallStatistics(
3359 *it, &ds) != -1) {
3360 rinfo.decoding_calls_to_silence_generator =
3361 ds.calls_to_silence_generator;
3362 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3363 rinfo.decoding_normal = ds.decoded_normal;
3364 rinfo.decoding_plc = ds.decoded_plc;
3365 rinfo.decoding_cng = ds.decoded_cng;
3366 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3367 }
3368
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003369 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003370 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003371 int playout_buffer_delay_ms = 0;
3372 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003373 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3374 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3375 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003376 }
3377
3378 // Get speech level.
3379 rinfo.audio_level = (engine()->voe()->volume()->
3380 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3381 info->receivers.push_back(rinfo);
3382 }
3383 }
3384
3385 return true;
3386}
3387
3388void WebRtcVoiceMediaChannel::GetLastMediaError(
3389 uint32* ssrc, VoiceMediaChannel::Error* error) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003390 DCHECK(ssrc != NULL);
3391 DCHECK(error != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003392 FindSsrc(voe_channel(), ssrc);
3393 *error = WebRtcErrorToChannelError(GetLastEngineError());
3394}
3395
3396bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003397 rtc::CritScope lock(&receive_channels_cs_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003398 DCHECK(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003399 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003400 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3401 // This means the error is not limited to a specific channel. Signal the
3402 // message using ssrc=0. If the current channel is sending, use this
3403 // channel for sending the message.
3404 *ssrc = 0;
3405 return true;
3406 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003407 // Check whether this is a sending channel.
3408 for (ChannelMap::const_iterator it = send_channels_.begin();
3409 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003410 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003411 // This is a sending channel.
3412 uint32 local_ssrc = 0;
3413 if (engine()->voe()->rtp()->GetLocalSSRC(
3414 channel_num, local_ssrc) != -1) {
3415 *ssrc = local_ssrc;
3416 }
3417 return true;
3418 }
3419 }
3420
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003421 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003422 for (ChannelMap::const_iterator it = receive_channels_.begin();
3423 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003424 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003425 *ssrc = it->first;
3426 return true;
3427 }
3428 }
3429 }
3430 return false;
3431}
3432
3433void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003434 if (error == VE_TYPING_NOISE_WARNING) {
3435 typing_noise_detected_ = true;
3436 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3437 typing_noise_detected_ = false;
3438 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003439 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3440}
3441
3442int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3443 unsigned int ulevel;
3444 int ret =
3445 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3446 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3447}
3448
3449int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003450 ChannelMap::iterator it = receive_channels_.find(ssrc);
3451 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003452 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003453 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3454}
3455
3456int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003457 ChannelMap::iterator it = send_channels_.find(ssrc);
3458 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003459 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003460
3461 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003462}
3463
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003464void WebRtcVoiceMediaChannel::SetCall(webrtc::Call* call) {
3465 DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003466 for (const auto& it : receive_channels_) {
3467 TryRemoveAudioRecvStream(it.first);
3468 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003469 call_ = call;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003470 for (const auto& it : receive_channels_) {
3471 TryAddAudioRecvStream(it.first);
3472 }
3473}
3474
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003475bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3476 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3477 // Get the RED encodings from the parameter with no name. This may
3478 // change based on what is discussed on the Jingle list.
3479 // The encoding parameter is of the form "a/b"; we only support where
3480 // a == b. Verify this and parse out the value into red_pt.
3481 // If the parameter value is absent (as it will be until we wire up the
3482 // signaling of this message), use the second codec specified (i.e. the
3483 // one after "red") as the encoding parameter.
3484 int red_pt = -1;
3485 std::string red_params;
3486 CodecParameterMap::const_iterator it = red_codec.params.find("");
3487 if (it != red_codec.params.end()) {
3488 red_params = it->second;
3489 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003490 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003491 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003492 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003493 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3494 return false;
3495 }
3496 } else if (red_codec.params.empty()) {
3497 LOG(LS_WARNING) << "RED params not present, using defaults";
3498 if (all_codecs.size() > 1) {
3499 red_pt = all_codecs[1].id;
3500 }
3501 }
3502
3503 // Try to find red_pt in |codecs|.
3504 std::vector<AudioCodec>::const_iterator codec;
3505 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3506 if (codec->id == red_pt)
3507 break;
3508 }
3509
3510 // If we find the right codec, that will be the codec we pass to
3511 // SetSendCodec, with the desired payload type.
3512 if (codec != all_codecs.end() &&
3513 engine()->FindWebRtcCodec(*codec, send_codec)) {
3514 } else {
3515 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3516 return false;
3517 }
3518
3519 return true;
3520}
3521
3522bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3523 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003524 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003525 return false;
3526 }
3527 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3528 // what we want to do with them.
3529 // engine()->voe().EnableVQMon(voe_channel(), true);
3530 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3531 return true;
3532}
3533
3534bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3535 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3536 for (int i = 0; i < ncodecs; ++i) {
3537 webrtc::CodecInst voe_codec;
3538 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3539 voe_codec.pltype = -1;
3540 if (engine()->voe()->codec()->SetRecPayloadType(
3541 channel, voe_codec) == -1) {
3542 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3543 return false;
3544 }
3545 }
3546 }
3547 return true;
3548}
3549
3550bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3551 if (playout) {
3552 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3553 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3554 LOG_RTCERR1(StartPlayout, channel);
3555 return false;
3556 }
3557 } else {
3558 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3559 engine()->voe()->base()->StopPlayout(channel);
3560 }
3561 return true;
3562}
3563
3564uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3565 bool rtcp) {
3566 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3567 uint32 ssrc = 0;
3568 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003569 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003570 }
3571 return ssrc;
3572}
3573
3574// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3575VoiceMediaChannel::Error
3576 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3577 switch (err_code) {
3578 case 0:
3579 return ERROR_NONE;
3580 case VE_CANNOT_START_RECORDING:
3581 case VE_MIC_VOL_ERROR:
3582 case VE_GET_MIC_VOL_ERROR:
3583 case VE_CANNOT_ACCESS_MIC_VOL:
3584 return ERROR_REC_DEVICE_OPEN_FAILED;
3585 case VE_SATURATION_WARNING:
3586 return ERROR_REC_DEVICE_SATURATION;
3587 case VE_REC_DEVICE_REMOVED:
3588 return ERROR_REC_DEVICE_REMOVED;
3589 case VE_RUNTIME_REC_WARNING:
3590 case VE_RUNTIME_REC_ERROR:
3591 return ERROR_REC_RUNTIME_ERROR;
3592 case VE_CANNOT_START_PLAYOUT:
3593 case VE_SPEAKER_VOL_ERROR:
3594 case VE_GET_SPEAKER_VOL_ERROR:
3595 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3596 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3597 case VE_RUNTIME_PLAY_WARNING:
3598 case VE_RUNTIME_PLAY_ERROR:
3599 return ERROR_PLAY_RUNTIME_ERROR;
3600 case VE_TYPING_NOISE_WARNING:
3601 return ERROR_REC_TYPING_NOISE_DETECTED;
3602 default:
3603 return VoiceMediaChannel::ERROR_OTHER;
3604 }
3605}
3606
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003607bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3608 int channel_id, const RtpHeaderExtension* extension) {
3609 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003610 int id = 0;
3611 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003612 if (extension) {
3613 enable = true;
3614 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003615 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003616 }
3617 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003618 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003619 return false;
3620 }
3621 return true;
3622}
3623
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003624void WebRtcVoiceMediaChannel::TryAddAudioRecvStream(uint32 ssrc) {
3625 DCHECK(thread_checker_.CalledOnValidThread());
3626 // If we are hooked up to a webrtc::Call, create an AudioReceiveStream too.
3627 if (call_ && options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false)) {
3628 DCHECK(receive_streams_.find(ssrc) == receive_streams_.end());
3629 webrtc::AudioReceiveStream::Config config;
3630 config.rtp.remote_ssrc = ssrc;
3631 config.rtp.extensions = recv_rtp_extensions_;
3632 webrtc::AudioReceiveStream* s = call_->CreateAudioReceiveStream(config);
3633 receive_streams_.insert(std::make_pair(ssrc, s));
3634 }
3635}
3636
3637void WebRtcVoiceMediaChannel::TryRemoveAudioRecvStream(uint32 ssrc) {
3638 DCHECK(thread_checker_.CalledOnValidThread());
3639 // If we are hooked up to a webrtc::Call, assume there is an
3640 // AudioReceiveStream to destroy too.
3641 if (call_) {
3642 auto stream_it = receive_streams_.find(ssrc);
3643 if (stream_it != receive_streams_.end()) {
3644 call_->DestroyAudioReceiveStream(stream_it->second);
3645 receive_streams_.erase(stream_it);
3646 }
3647 }
3648}
3649
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003650int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003651 size_t res = 0;
3652 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003653 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003654}
3655
3656int WebRtcSoundclipStream::Rewind() {
3657 mem_.Rewind();
3658 // Return -1 to keep VoiceEngine from looping.
3659 return (loop_) ? 0 : -1;
3660}
3661
3662} // namespace cricket
3663
3664#endif // HAVE_WEBRTC_VOICE