blob: 230953e88b0a734e0f48ced0a0bc6dc3f60be5cf [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);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000355 options.typing_detection.Set(true);
356 options.conference_mode.Set(false);
357 options.adjust_agc_delta.Set(0);
358 options.experimental_agc.Set(false);
359 options.experimental_aec.Set(false);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100360 options.delay_agnostic_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000361 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000362 options.aec_dump.Set(false);
363 return options;
364}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000365
Minyue Li7100dcd2015-03-27 05:05:59 +0100366static std::string GetEnableString(bool enable) {
367 return enable ? "enable" : "disable";
Brave Yao5225dd82015-03-26 07:39:19 +0800368}
369
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000370WebRtcVoiceEngine::WebRtcVoiceEngine()
371 : voe_wrapper_(new VoEWrapper()),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000372 tracing_(new VoETraceWrapper()),
373 adm_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000374 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
375 is_dumping_aec_(false),
376 desired_local_monitor_enable_(false),
377 tx_processor_ssrc_(0),
378 rx_processor_ssrc_(0) {
379 Construct();
380}
381
382WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000383 VoETraceWrapper* tracing)
384 : voe_wrapper_(voe_wrapper),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000385 tracing_(tracing),
386 adm_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000387 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
388 is_dumping_aec_(false),
389 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000390 tx_processor_ssrc_(0),
391 rx_processor_ssrc_(0) {
392 Construct();
393}
394
395void WebRtcVoiceEngine::Construct() {
396 SetTraceFilter(log_filter_);
397 initialized_ = false;
398 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
399 SetTraceOptions("");
400 if (tracing_->SetTraceCallback(this) == -1) {
401 LOG_RTCERR0(SetTraceCallback);
402 }
403 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
404 LOG_RTCERR0(RegisterVoiceEngineObserver);
405 }
406 // Clear the default agc state.
407 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
408
409 // Load our audio codec list.
410 ConstructCodecs();
411
412 // Load our RTP Header extensions.
413 rtp_header_extensions_.push_back(
414 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
415 kRtpAudioLevelHeaderExtensionDefaultId));
416 rtp_header_extensions_.push_back(
417 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
418 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
419 options_ = GetDefaultEngineOptions();
420}
421
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000422void WebRtcVoiceEngine::ConstructCodecs() {
423 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
424 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
425 for (int i = 0; i < ncodecs; ++i) {
426 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000427 if (GetVoeCodec(i, &voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000428 // Skip uncompressed formats.
Minyue Li7100dcd2015-03-27 05:05:59 +0100429 if (IsCodec(voe_codec, kL16CodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000430 continue;
431 }
432
433 const CodecPref* pref = NULL;
434 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100435 if (IsCodec(voe_codec, kCodecPrefs[j].name) &&
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000436 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
437 kCodecPrefs[j].channels == voe_codec.channels) {
438 pref = &kCodecPrefs[j];
439 break;
440 }
441 }
442
443 if (pref) {
444 // Use the payload type that we've configured in our pref table;
445 // use the offset in our pref table to determine the sort order.
446 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
447 voe_codec.rate, voe_codec.channels,
448 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
449 LOG(LS_INFO) << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100450 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000451 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000452 codec.bitrate = 0;
453 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100454 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000455 // Only add fmtp parameters that differ from the spec.
456 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
457 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000458 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000459 }
460 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
461 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000462 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000463 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000464 codec.SetParam(kCodecParamUseInbandFec, 1);
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000465
466 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000467 // when they can be set to values other than the default.
468 }
469 codecs_.push_back(codec);
470 } else {
471 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
472 }
473 }
474 }
475 // Make sure they are in local preference order.
476 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
477}
478
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000479bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst* codec) {
480 if (voe_wrapper_->codec()->GetCodec(index, *codec) == -1) {
481 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000482 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000483 // Change the sample rate of G722 to 8000 to match SDP.
484 MaybeFixupG722(codec, 8000);
485 return true;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000486}
487
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000488WebRtcVoiceEngine::~WebRtcVoiceEngine() {
489 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
490 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
491 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
492 }
493 if (adm_) {
494 voe_wrapper_.reset();
495 adm_->Release();
496 adm_ = NULL;
497 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000498
499 // Test to see if the media processor was deregistered properly
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200500 DCHECK(SignalRxMediaFrame.is_empty());
501 DCHECK(SignalTxMediaFrame.is_empty());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000502
503 tracing_->SetTraceCallback(NULL);
504}
505
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000506bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200507 DCHECK(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000508 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
509 bool res = InitInternal();
510 if (res) {
511 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
512 } else {
513 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
514 Terminate();
515 }
516 return res;
517}
518
519bool WebRtcVoiceEngine::InitInternal() {
520 // Temporarily turn logging level up for the Init call
521 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000522 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000523 SetTraceFilter(extended_filter);
524 SetTraceOptions("");
525
526 // Init WebRtc VoiceEngine.
527 if (voe_wrapper_->base()->Init(adm_) == -1) {
528 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
529 SetTraceFilter(old_filter);
530 return false;
531 }
532
533 SetTraceFilter(old_filter);
534 SetTraceOptions(log_options_);
535
536 // Log the VoiceEngine version info
537 char buffer[1024] = "";
538 voe_wrapper_->base()->GetVersion(buffer);
539 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000540 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000541
542 // Save the default AGC configuration settings. This must happen before
543 // calling SetOptions or the default will be overwritten.
544 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
545 LOG_RTCERR0(GetAgcConfig);
546 return false;
547 }
548
549 // Set defaults for options, so that ApplyOptions applies them explicitly
550 // when we clear option (channel) overrides. External clients can still
551 // modify the defaults via SetOptions (on the media engine).
552 if (!SetOptions(GetDefaultEngineOptions())) {
553 return false;
554 }
555
556 // Print our codec list again for the call diagnostic log
557 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
558 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
559 it != codecs_.end(); ++it) {
560 LOG(LS_INFO) << ToString(*it);
561 }
562
563 // Disable the DTMF playout when a tone is sent.
564 // PlayDtmfTone will be used if local playout is needed.
565 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
566 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
567 }
568
569 initialized_ = true;
570 return true;
571}
572
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000573void WebRtcVoiceEngine::Terminate() {
574 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
575 initialized_ = false;
576
577 StopAecDump();
578
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000579 voe_wrapper_->base()->Terminate();
580 desired_local_monitor_enable_ = false;
581}
582
583int WebRtcVoiceEngine::GetCapabilities() {
584 return AUDIO_SEND | AUDIO_RECV;
585}
586
Jelena Marusicc28a8962015-05-29 15:05:44 +0200587VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel(
588 const AudioOptions& options) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000589 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
590 if (!ch->valid()) {
591 delete ch;
Jelena Marusicc28a8962015-05-29 15:05:44 +0200592 return nullptr;
593 }
594 if (!ch->SetOptions(options)) {
595 LOG(LS_WARNING) << "Failed to set options while creating channel.";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000596 }
597 return ch;
598}
599
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000600bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
601 if (!ApplyOptions(options)) {
602 return false;
603 }
604 options_ = options;
605 return true;
606}
607
608bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
609 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
610 if (!ApplyOptions(overrides)) {
611 return false;
612 }
613 option_overrides_ = overrides;
614 return true;
615}
616
617bool WebRtcVoiceEngine::ClearOptionOverrides() {
618 LOG(LS_INFO) << "Clearing option overrides.";
619 AudioOptions options = options_;
620 // Only call ApplyOptions if |options_overrides_| contains overrided options.
621 // ApplyOptions affects NS, AGC other options that is shared between
622 // all WebRtcVoiceEngineChannels.
623 if (option_overrides_ == AudioOptions()) {
624 return true;
625 }
626
627 if (!ApplyOptions(options)) {
628 return false;
629 }
630 option_overrides_ = AudioOptions();
631 return true;
632}
633
634// AudioOptions defaults are set in InitInternal (for options with corresponding
635// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
636bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
637 AudioOptions options = options_in; // The options are modified below.
638 // kEcConference is AEC with high suppression.
639 webrtc::EcModes ec_mode = webrtc::kEcConference;
640 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
641 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
642 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
643 bool aecm_comfort_noise = false;
644 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
645 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
646 << aecm_comfort_noise << " (default is false).";
647 }
648
649#if defined(IOS)
650 // On iOS, VPIO provides built-in EC and AGC.
651 options.echo_cancellation.Set(false);
652 options.auto_gain_control.Set(false);
653#elif defined(ANDROID)
654 ec_mode = webrtc::kEcAecm;
655#endif
656
657#if defined(IOS) || defined(ANDROID)
658 // Set the AGC mode for iOS as well despite disabling it above, to avoid
659 // unsupported configuration errors from webrtc.
660 agc_mode = webrtc::kAgcFixedDigital;
661 options.typing_detection.Set(false);
662 options.experimental_agc.Set(false);
663 options.experimental_aec.Set(false);
664 options.experimental_ns.Set(false);
665#endif
666
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100667 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
668 // where the feature is not supported.
669 bool use_delay_agnostic_aec = false;
670#if !defined(IOS)
671 if (options.delay_agnostic_aec.Get(&use_delay_agnostic_aec)) {
672 if (use_delay_agnostic_aec) {
673 options.echo_cancellation.Set(true);
674 options.experimental_aec.Set(true);
675 ec_mode = webrtc::kEcConference;
676 }
677 }
678#endif
679
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000680 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
681
682 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
683
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000684 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000685 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000686 // Check if platform supports built-in EC. Currently only supported on
687 // Android and in combination with Java based audio layer.
688 // TODO(henrika): investigate possibility to support built-in EC also
689 // in combination with Open SL ES audio.
690 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200691 if (built_in_aec && !use_delay_agnostic_aec) {
692 // Built-in EC exists on this device and use_delay_agnostic_aec is not
693 // overriding it. Enable/Disable it according to the echo_cancellation
694 // audio option.
Bjorn Volcker1d83f1e2015-04-07 15:25:39 +0200695 if (voe_wrapper_->hw()->EnableBuiltInAEC(echo_cancellation) == 0 &&
696 echo_cancellation) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100697 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000698 // i.e., replace the software EC with the built-in EC.
699 options.echo_cancellation.Set(false);
bjornv@webrtc.org3f118232015-03-16 14:22:03 +0000700 echo_cancellation = false;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000701 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
702 }
703 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000704 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
705 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
706 return false;
707 } else {
708 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
709 << " with mode " << ec_mode;
710 }
711#if !defined(ANDROID)
712 // TODO(ajm): Remove the error return on Android from webrtc.
713 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
714 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
715 return false;
716 }
717#endif
718 if (ec_mode == webrtc::kEcAecm) {
719 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
720 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
721 return false;
722 }
723 }
724 }
725
726 bool auto_gain_control;
727 if (options.auto_gain_control.Get(&auto_gain_control)) {
728 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
729 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
730 return false;
731 } else {
732 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
733 << " with mode " << agc_mode;
734 }
735 }
736
737 if (options.tx_agc_target_dbov.IsSet() ||
738 options.tx_agc_digital_compression_gain.IsSet() ||
739 options.tx_agc_limiter.IsSet()) {
740 // Override default_agc_config_. Generally, an unset option means "leave
741 // the VoE bits alone" in this function, so we want whatever is set to be
742 // stored as the new "default". If we didn't, then setting e.g.
743 // tx_agc_target_dbov would reset digital compression gain and limiter
744 // settings.
745 // Also, if we don't update default_agc_config_, then adjust_agc_delta
746 // would be an offset from the original values, and not whatever was set
747 // explicitly.
748 default_agc_config_.targetLeveldBOv =
749 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
750 default_agc_config_.targetLeveldBOv);
751 default_agc_config_.digitalCompressionGaindB =
752 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
753 default_agc_config_.digitalCompressionGaindB);
754 default_agc_config_.limiterEnable =
755 options.tx_agc_limiter.GetWithDefaultIfUnset(
756 default_agc_config_.limiterEnable);
757 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
758 LOG_RTCERR3(SetAgcConfig,
759 default_agc_config_.targetLeveldBOv,
760 default_agc_config_.digitalCompressionGaindB,
761 default_agc_config_.limiterEnable);
762 return false;
763 }
764 }
765
766 bool noise_suppression;
767 if (options.noise_suppression.Get(&noise_suppression)) {
768 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
769 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
770 return false;
771 } else {
772 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
773 << " with mode " << ns_mode;
774 }
775 }
776
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000777 bool highpass_filter;
778 if (options.highpass_filter.Get(&highpass_filter)) {
779 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
780 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
781 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
782 return false;
783 }
784 }
785
786 bool stereo_swapping;
787 if (options.stereo_swapping.Get(&stereo_swapping)) {
788 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
789 voep->EnableStereoChannelSwapping(stereo_swapping);
790 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
791 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
792 return false;
793 }
794 }
795
Henrik Lundin64dad832015-05-11 12:44:23 +0200796 int audio_jitter_buffer_max_packets;
797 if (options.audio_jitter_buffer_max_packets.Get(
798 &audio_jitter_buffer_max_packets)) {
799 LOG(LS_INFO) << "NetEq capacity is " << audio_jitter_buffer_max_packets;
800 voe_config_.Set<webrtc::NetEqCapacityConfig>(
801 new webrtc::NetEqCapacityConfig(audio_jitter_buffer_max_packets));
802 }
803
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000804 bool typing_detection;
805 if (options.typing_detection.Get(&typing_detection)) {
806 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
807 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
808 // In case of error, log the info and continue
809 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
810 }
811 }
812
813 int adjust_agc_delta;
814 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
815 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
816 if (!AdjustAgcLevel(adjust_agc_delta)) {
817 return false;
818 }
819 }
820
821 bool aec_dump;
822 if (options.aec_dump.Get(&aec_dump)) {
823 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
824 if (aec_dump)
825 StartAecDump(kAecDumpByAudioOptionFilename);
826 else
827 StopAecDump();
828 }
829
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000830 webrtc::Config config;
831
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100832 delay_agnostic_aec_.SetFrom(options.delay_agnostic_aec);
833 bool delay_agnostic_aec;
834 if (delay_agnostic_aec_.Get(&delay_agnostic_aec)) {
835 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << delay_agnostic_aec;
836 config.Set<webrtc::ReportedDelay>(
837 new webrtc::ReportedDelay(!delay_agnostic_aec));
838 }
839
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000840 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000841 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000842 if (experimental_aec_.Get(&experimental_aec)) {
843 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
844 config.Set<webrtc::DelayCorrection>(
845 new webrtc::DelayCorrection(experimental_aec));
846 }
847
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000848 experimental_ns_.SetFrom(options.experimental_ns);
849 bool experimental_ns;
850 if (experimental_ns_.Get(&experimental_ns)) {
851 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
852 config.Set<webrtc::ExperimentalNs>(
853 new webrtc::ExperimentalNs(experimental_ns));
854 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000855
856 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
857 // returns NULL on audio_processing().
858 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
859 if (audioproc) {
860 audioproc->SetExtraOptions(config);
861 }
862
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000863 uint32 recording_sample_rate;
864 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
865 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
866 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
867 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
868 }
869 }
870
871 uint32 playout_sample_rate;
872 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
873 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
874 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
875 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
876 }
877 }
878
879 return true;
880}
881
882bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
883 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
884 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
885 LOG_RTCERR1(SetDelayOffsetMs, offset);
886 return false;
887 }
888
889 return true;
890}
891
892struct ResumeEntry {
893 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
894 : channel(c),
895 playout(p),
896 send(s) {
897 }
898
899 WebRtcVoiceMediaChannel *channel;
900 bool playout;
901 SendFlags send;
902};
903
904// TODO(juberti): Refactor this so that the core logic can be used to set the
905// soundclip device. At that time, reinstate the soundclip pause/resume code.
906bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
907 const Device* out_device) {
908#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000909 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000910 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000911 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000912 kDefaultAudioDeviceId;
913 // The device manager uses -1 as the default device, which was the case for
914 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
915#ifndef WIN32
916 if (-1 == in_id) {
917 in_id = kDefaultAudioDeviceId;
918 }
919 if (-1 == out_id) {
920 out_id = kDefaultAudioDeviceId;
921 }
922#endif
923
924 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
925 in_device->name : "Default device";
926 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
927 out_device->name : "Default device";
928 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
929 << ") and speaker to (id=" << out_id << ", name=" << out_name
930 << ")";
931
932 // If we're running the local monitor, we need to stop it first.
933 bool ret = true;
934 if (!PauseLocalMonitor()) {
935 LOG(LS_WARNING) << "Failed to pause local monitor";
936 ret = false;
937 }
938
939 // Must also pause all audio playback and capture.
940 for (ChannelList::const_iterator i = channels_.begin();
941 i != channels_.end(); ++i) {
942 WebRtcVoiceMediaChannel *channel = *i;
943 if (!channel->PausePlayout()) {
944 LOG(LS_WARNING) << "Failed to pause playout";
945 ret = false;
946 }
947 if (!channel->PauseSend()) {
948 LOG(LS_WARNING) << "Failed to pause send";
949 ret = false;
950 }
951 }
952
953 // Find the recording device id in VoiceEngine and set recording device.
954 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
955 ret = false;
956 }
957 if (ret) {
958 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
959 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
960 ret = false;
961 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +0000962 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
963 if (ap)
964 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000965 }
966
967 // Find the playout device id in VoiceEngine and set playout device.
968 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
969 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
970 ret = false;
971 }
972 if (ret) {
973 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000974 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000975 ret = false;
976 }
977 }
978
979 // Resume all audio playback and capture.
980 for (ChannelList::const_iterator i = channels_.begin();
981 i != channels_.end(); ++i) {
982 WebRtcVoiceMediaChannel *channel = *i;
983 if (!channel->ResumePlayout()) {
984 LOG(LS_WARNING) << "Failed to resume playout";
985 ret = false;
986 }
987 if (!channel->ResumeSend()) {
988 LOG(LS_WARNING) << "Failed to resume send";
989 ret = false;
990 }
991 }
992
993 // Resume local monitor.
994 if (!ResumeLocalMonitor()) {
995 LOG(LS_WARNING) << "Failed to resume local monitor";
996 ret = false;
997 }
998
999 if (ret) {
1000 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1001 << ") and speaker to (id="<< out_id << " name=" << out_name
1002 << ")";
1003 }
1004
1005 return ret;
1006#else
1007 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001008#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001009}
1010
1011bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1012 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1013 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001014#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001015 *rtc_id = dev_id;
1016 return true;
1017#else
1018 // In Windows and Mac, we need to find the VoiceEngine device id by name
1019 // unless the input dev_id is the default device id.
1020 if (kDefaultAudioDeviceId == dev_id) {
1021 *rtc_id = dev_id;
1022 return true;
1023 }
1024
1025 // Get the number of VoiceEngine audio devices.
1026 int count = 0;
1027 if (is_input) {
1028 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1029 LOG_RTCERR0(GetNumOfRecordingDevices);
1030 return false;
1031 }
1032 } else {
1033 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1034 LOG_RTCERR0(GetNumOfPlayoutDevices);
1035 return false;
1036 }
1037 }
1038
1039 for (int i = 0; i < count; ++i) {
1040 char name[128];
1041 char guid[128];
1042 if (is_input) {
1043 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1044 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1045 } else {
1046 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1047 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1048 }
1049
1050 std::string webrtc_name(name);
1051 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1052 *rtc_id = i;
1053 return true;
1054 }
1055 }
1056 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1057 return false;
1058#endif
1059}
1060
1061bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1062 unsigned int ulevel;
1063 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1064 LOG_RTCERR1(GetSpeakerVolume, level);
1065 return false;
1066 }
1067 *level = ulevel;
1068 return true;
1069}
1070
1071bool WebRtcVoiceEngine::SetOutputVolume(int level) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001072 DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001073 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1074 LOG_RTCERR1(SetSpeakerVolume, level);
1075 return false;
1076 }
1077 return true;
1078}
1079
1080int WebRtcVoiceEngine::GetInputLevel() {
1081 unsigned int ulevel;
1082 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1083 static_cast<int>(ulevel) : -1;
1084}
1085
1086bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1087 desired_local_monitor_enable_ = enable;
1088 return ChangeLocalMonitor(desired_local_monitor_enable_);
1089}
1090
1091bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1092 // The voe file api is not available in chrome.
1093 if (!voe_wrapper_->file()) {
1094 return false;
1095 }
1096 if (enable && !monitor_) {
1097 monitor_.reset(new WebRtcMonitorStream);
1098 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1099 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1100 // Must call Stop() because there are some cases where Start will report
1101 // failure but still change the state, and if we leave VE in the on state
1102 // then it could crash later when trying to invoke methods on our monitor.
1103 voe_wrapper_->file()->StopRecordingMicrophone();
1104 monitor_.reset();
1105 return false;
1106 }
1107 } else if (!enable && monitor_) {
1108 voe_wrapper_->file()->StopRecordingMicrophone();
1109 monitor_.reset();
1110 }
1111 return true;
1112}
1113
1114bool WebRtcVoiceEngine::PauseLocalMonitor() {
1115 return ChangeLocalMonitor(false);
1116}
1117
1118bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1119 return ChangeLocalMonitor(desired_local_monitor_enable_);
1120}
1121
1122const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1123 return codecs_;
1124}
1125
1126bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1127 return FindWebRtcCodec(in, NULL);
1128}
1129
1130// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1131bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1132 webrtc::CodecInst* out) {
1133 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1134 for (int i = 0; i < ncodecs; ++i) {
1135 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001136 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001137 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1138 voe_codec.rate, voe_codec.channels, 0);
1139 bool multi_rate = IsCodecMultiRate(voe_codec);
1140 // Allow arbitrary rates for ISAC to be specified.
1141 if (multi_rate) {
1142 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1143 codec.bitrate = 0;
1144 }
1145 if (codec.Matches(in)) {
1146 if (out) {
1147 // Fixup the payload type.
1148 voe_codec.pltype = in.id;
1149
1150 // Set bitrate if specified.
1151 if (multi_rate && in.bitrate != 0) {
1152 voe_codec.rate = in.bitrate;
1153 }
1154
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001155 // Reset G722 sample rate to 16000 to match WebRTC.
1156 MaybeFixupG722(&voe_codec, 16000);
1157
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001158 // Apply codec-specific settings.
Minyue Li7100dcd2015-03-27 05:05:59 +01001159 if (IsCodec(codec, kIsacCodecName)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001160 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001161 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001162 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1163 }
1164 *out = voe_codec;
1165 }
1166 return true;
1167 }
1168 }
1169 }
1170 return false;
1171}
1172const std::vector<RtpHeaderExtension>&
1173WebRtcVoiceEngine::rtp_header_extensions() const {
1174 return rtp_header_extensions_;
1175}
1176
1177void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1178 // if min_sev == -1, we keep the current log level.
1179 if (min_sev >= 0) {
1180 SetTraceFilter(SeverityToFilter(min_sev));
1181 }
1182 log_options_ = filter;
1183 SetTraceOptions(initialized_ ? log_options_ : "");
1184}
1185
1186int WebRtcVoiceEngine::GetLastEngineError() {
1187 return voe_wrapper_->error();
1188}
1189
1190void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1191 log_filter_ = filter;
1192 tracing_->SetTraceFilter(filter);
1193}
1194
1195// We suppport three different logging settings for VoiceEngine:
1196// 1. Observer callback that goes into talk diagnostic logfile.
1197// Use --logfile and --loglevel
1198//
1199// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1200// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1201//
1202// 3. EC log and dump for debugging QualityEngine.
1203// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1204//
1205// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1206// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1207void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1208 // Set encrypted trace file.
1209 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001210 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001211 std::vector<std::string>::iterator tracefile =
1212 std::find(opts.begin(), opts.end(), "tracefile");
1213 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1214 // Write encrypted debug output (at same loglevel) to file
1215 // EncryptedTraceFile no longer supported.
1216 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1217 LOG_RTCERR1(SetTraceFile, *tracefile);
1218 }
1219 }
1220
wu@webrtc.org97077a32013-10-25 21:18:33 +00001221 // Allow trace options to override the trace filter. We default
1222 // it to log_filter_ (as a translation of libjingle log levels)
1223 // elsewhere, but this allows clients to explicitly set webrtc
1224 // log levels.
1225 std::vector<std::string>::iterator tracefilter =
1226 std::find(opts.begin(), opts.end(), "tracefilter");
1227 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001228 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001229 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1230 }
1231 }
1232
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001233 // Set AEC dump file
1234 std::vector<std::string>::iterator recordEC =
1235 std::find(opts.begin(), opts.end(), "recordEC");
1236 if (recordEC != opts.end()) {
1237 ++recordEC;
1238 if (recordEC != opts.end())
1239 StartAecDump(recordEC->c_str());
1240 else
1241 StopAecDump();
1242 }
1243}
1244
1245// Ignore spammy trace messages, mostly from the stats API when we haven't
1246// gotten RTCP info yet from the remote side.
1247bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1248 static const char* kTracesToIgnore[] = {
1249 "\tfailed to GetReportBlockInformation",
1250 "GetRecCodec() failed to get received codec",
1251 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1252 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1253 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1254 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1255 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1256 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1257 "SenderInfoReceived No received SR",
1258 "StatisticsRTP() no statistics available",
1259 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1260 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1261 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1262 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1263 NULL
1264 };
1265 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1266 if (trace.find(*p) != std::string::npos) {
1267 return true;
1268 }
1269 }
1270 return false;
1271}
1272
1273void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1274 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001275 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001276 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001277 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001278 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001279 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001281 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001282 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001283 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001284
1285 // Skip past boilerplate prefix text
1286 if (length < 72) {
1287 std::string msg(trace, length);
1288 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1289 LOG_V(sev) << msg;
1290 } else {
1291 std::string msg(trace + 71, length - 72);
1292 if (!ShouldIgnoreTrace(msg)) {
1293 LOG_V(sev) << "webrtc: " << msg;
1294 }
1295 }
1296}
1297
1298void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001299 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001300 WebRtcVoiceMediaChannel* channel = NULL;
1301 uint32 ssrc = 0;
1302 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1303 << channel_num << ".";
1304 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001305 DCHECK(channel != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001306 channel->OnError(ssrc, err_code);
1307 } else {
1308 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1309 << " could not be found in channel list when error reported.";
1310 }
1311}
1312
1313bool WebRtcVoiceEngine::FindChannelAndSsrc(
1314 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001315 DCHECK(channel != NULL && ssrc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001316
1317 *channel = NULL;
1318 *ssrc = 0;
1319 // Find corresponding channel and ssrc
1320 for (ChannelList::const_iterator it = channels_.begin();
1321 it != channels_.end(); ++it) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001322 DCHECK(*it != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001323 if ((*it)->FindSsrc(channel_num, ssrc)) {
1324 *channel = *it;
1325 return true;
1326 }
1327 }
1328
1329 return false;
1330}
1331
1332// This method will search through the WebRtcVoiceMediaChannels and
1333// obtain the voice engine's channel number.
1334bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1335 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001336 DCHECK(channel_num != NULL);
1337 DCHECK(direction == MPD_RX || direction == MPD_TX);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001338
1339 *channel_num = -1;
1340 // Find corresponding channel for ssrc.
1341 for (ChannelList::const_iterator it = channels_.begin();
1342 it != channels_.end(); ++it) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001343 DCHECK(*it != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001344 if (direction & MPD_RX) {
1345 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1346 }
1347 if (*channel_num == -1 && (direction & MPD_TX)) {
1348 *channel_num = (*it)->GetSendChannelNum(ssrc);
1349 }
1350 if (*channel_num != -1) {
1351 return true;
1352 }
1353 }
1354 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1355 return false;
1356}
1357
1358void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001359 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001360 channels_.push_back(channel);
1361}
1362
1363void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001364 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001365 ChannelList::iterator i = std::find(channels_.begin(),
1366 channels_.end(),
1367 channel);
1368 if (i != channels_.end()) {
1369 channels_.erase(i);
1370 }
1371}
1372
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001373// Adjusts the default AGC target level by the specified delta.
1374// NB: If we start messing with other config fields, we'll want
1375// to save the current webrtc::AgcConfig as well.
1376bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1377 webrtc::AgcConfig config = default_agc_config_;
1378 config.targetLeveldBOv -= delta;
1379
1380 LOG(LS_INFO) << "Adjusting AGC level from default -"
1381 << default_agc_config_.targetLeveldBOv << "dB to -"
1382 << config.targetLeveldBOv << "dB";
1383
1384 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1385 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1386 return false;
1387 }
1388 return true;
1389}
1390
Fredrik Solenbergccb49e72015-05-19 11:37:56 +02001391bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392 if (initialized_) {
1393 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1394 return false;
1395 }
1396 if (adm_) {
1397 adm_->Release();
1398 adm_ = NULL;
1399 }
1400 if (adm) {
1401 adm_ = adm;
1402 adm_->AddRef();
1403 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001404 return true;
1405}
1406
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001407bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1408 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001409 if (!aec_dump_file_stream) {
1410 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001411 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001412 LOG(LS_WARNING) << "Could not close file.";
1413 return false;
1414 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001415 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001416 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001417 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001418 LOG_RTCERR0(StartDebugRecording);
1419 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001420 return false;
1421 }
1422 is_dumping_aec_ = true;
1423 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001424}
1425
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001426bool WebRtcVoiceEngine::RegisterProcessor(
1427 uint32 ssrc,
1428 VoiceProcessor* voice_processor,
1429 MediaProcessorDirection direction) {
1430 bool register_with_webrtc = false;
1431 int channel_id = -1;
1432 bool success = false;
1433 uint32* processor_ssrc = NULL;
1434 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1435 if (voice_processor == NULL || !found_channel) {
1436 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1437 << " foundChannel: " << found_channel;
1438 return false;
1439 }
1440
1441 webrtc::ProcessingTypes processing_type;
1442 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001443 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001444 if (direction == MPD_RX) {
1445 processing_type = webrtc::kPlaybackAllChannelsMixed;
1446 if (SignalRxMediaFrame.is_empty()) {
1447 register_with_webrtc = true;
1448 processor_ssrc = &rx_processor_ssrc_;
1449 }
1450 SignalRxMediaFrame.connect(voice_processor,
1451 &VoiceProcessor::OnFrame);
1452 } else {
1453 processing_type = webrtc::kRecordingPerChannel;
1454 if (SignalTxMediaFrame.is_empty()) {
1455 register_with_webrtc = true;
1456 processor_ssrc = &tx_processor_ssrc_;
1457 }
1458 SignalTxMediaFrame.connect(voice_processor,
1459 &VoiceProcessor::OnFrame);
1460 }
1461 }
1462 if (register_with_webrtc) {
1463 // TODO(janahan): when registering consider instantiating a
1464 // a VoeMediaProcess object and not make the engine extend the interface.
1465 if (voe()->media() && voe()->media()->
1466 RegisterExternalMediaProcessing(channel_id,
1467 processing_type,
1468 *this) != -1) {
1469 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1470 << channel_id;
1471 *processor_ssrc = ssrc;
1472 success = true;
1473 } else {
1474 LOG_RTCERR2(RegisterExternalMediaProcessing,
1475 channel_id,
1476 processing_type);
1477 success = false;
1478 }
1479 } else {
1480 // If we don't have to register with the engine, we just needed to
1481 // connect a new processor, set success to true;
1482 success = true;
1483 }
1484 return success;
1485}
1486
1487bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1488 MediaProcessorDirection channel_direction,
1489 uint32 ssrc,
1490 VoiceProcessor* voice_processor,
1491 MediaProcessorDirection processor_direction) {
1492 bool success = true;
1493 FrameSignal* signal;
1494 webrtc::ProcessingTypes processing_type;
1495 uint32* processor_ssrc = NULL;
1496 if (channel_direction == MPD_RX) {
1497 signal = &SignalRxMediaFrame;
1498 processing_type = webrtc::kPlaybackAllChannelsMixed;
1499 processor_ssrc = &rx_processor_ssrc_;
1500 } else {
1501 signal = &SignalTxMediaFrame;
1502 processing_type = webrtc::kRecordingPerChannel;
1503 processor_ssrc = &tx_processor_ssrc_;
1504 }
1505
1506 int deregister_id = -1;
1507 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001508 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001509 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1510 signal->disconnect(voice_processor);
1511 int channel_id = -1;
1512 bool found_channel = FindChannelNumFromSsrc(ssrc,
1513 channel_direction,
1514 &channel_id);
1515 if (signal->is_empty() && found_channel) {
1516 deregister_id = channel_id;
1517 }
1518 }
1519 }
1520 if (deregister_id != -1) {
1521 if (voe()->media() &&
1522 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1523 processing_type) != -1) {
1524 *processor_ssrc = 0;
1525 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1526 << deregister_id;
1527 } else {
1528 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1529 deregister_id,
1530 processing_type);
1531 success = false;
1532 }
1533 }
1534 return success;
1535}
1536
1537bool WebRtcVoiceEngine::UnregisterProcessor(
1538 uint32 ssrc,
1539 VoiceProcessor* voice_processor,
1540 MediaProcessorDirection direction) {
1541 bool success = true;
1542 if (voice_processor == NULL) {
1543 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1544 << ssrc;
1545 return false;
1546 }
1547 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1548 success = false;
1549 }
1550 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1551 success = false;
1552 }
1553 return success;
1554}
1555
1556// Implementing method from WebRtc VoEMediaProcess interface
1557// Do not lock mux_channel_cs_ in this callback.
1558void WebRtcVoiceEngine::Process(int channel,
1559 webrtc::ProcessingTypes type,
1560 int16_t audio10ms[],
1561 int length,
1562 int sampling_freq,
1563 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001564 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001565 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1566 if (type == webrtc::kPlaybackAllChannelsMixed) {
1567 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1568 } else if (type == webrtc::kRecordingPerChannel) {
1569 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1570 } else {
1571 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1572 << " channel: " << channel << " type: " << type
1573 << " tx_ssrc: " << tx_processor_ssrc_
1574 << " rx_ssrc: " << rx_processor_ssrc_;
1575 }
1576}
1577
1578void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1579 if (!is_dumping_aec_) {
1580 // Start dumping AEC when we are not dumping.
1581 if (voe_wrapper_->processing()->StartDebugRecording(
1582 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001583 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001584 } else {
1585 is_dumping_aec_ = true;
1586 }
1587 }
1588}
1589
1590void WebRtcVoiceEngine::StopAecDump() {
1591 if (is_dumping_aec_) {
1592 // Stop dumping AEC when we are dumping.
1593 if (voe_wrapper_->processing()->StopDebugRecording() !=
1594 webrtc::AudioProcessing::kNoError) {
1595 LOG_RTCERR0(StopDebugRecording);
1596 }
1597 is_dumping_aec_ = false;
1598 }
1599}
1600
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001601int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001602 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001603}
1604
1605int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1606 return CreateVoiceChannel(voe_wrapper_.get());
1607}
1608
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001609class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1610 : public AudioRenderer::Sink {
1611 public:
1612 WebRtcVoiceChannelRenderer(int ch,
1613 webrtc::AudioTransport* voe_audio_transport)
1614 : channel_(ch),
1615 voe_audio_transport_(voe_audio_transport),
1616 renderer_(NULL) {
1617 }
Fredrik Solenbergaaf8ff22015-05-07 16:05:53 +02001618 ~WebRtcVoiceChannelRenderer() override { Stop(); }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001619
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001620 // Starts the rendering by setting a sink to the renderer to get data
1621 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001622 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001623 // TODO(xians): Make sure Start() is called only once.
1624 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001625 rtc::CritScope lock(&lock_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001626 DCHECK(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001627 if (renderer_ != NULL) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001628 DCHECK(renderer_ == renderer);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001629 return;
1630 }
1631
1632 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1633 // in getUserMedia by default.
1634 renderer->AddChannel(channel_);
1635 renderer->SetSink(this);
1636 renderer_ = renderer;
1637 }
1638
1639 // Stops rendering by setting the sink of the renderer to NULL. No data
1640 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001641 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001642 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001643 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001644 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001645 return;
1646
1647 renderer_->RemoveChannel(channel_);
1648 renderer_->SetSink(NULL);
1649 renderer_ = NULL;
1650 }
1651
1652 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001653 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001654 void OnData(const void* audio_data,
1655 int bits_per_sample,
1656 int sample_rate,
1657 int number_of_channels,
1658 int number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001659 voe_audio_transport_->OnData(channel_,
1660 audio_data,
1661 bits_per_sample,
1662 sample_rate,
1663 number_of_channels,
1664 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001665 }
1666
1667 // Callback from the |renderer_| when it is going away. In case Start() has
1668 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001669 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001670 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001671 // Set |renderer_| to NULL to make sure no more callback will get into
1672 // the renderer.
1673 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001674 }
1675
1676 // Accessor to the VoE channel ID.
1677 int channel() const { return channel_; }
1678
1679 private:
1680 const int channel_;
1681 webrtc::AudioTransport* const voe_audio_transport_;
1682
1683 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1684 // PeerConnection will make sure invalidating the pointer before the object
1685 // goes away.
1686 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001687
1688 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001689 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001690};
1691
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001692// WebRtcVoiceMediaChannel
Fredrik Solenberge444a3d2015-05-07 16:42:08 +02001693WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine)
1694 : engine_(engine),
1695 voe_channel_(engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001696 send_bitrate_setting_(false),
1697 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001698 options_(),
1699 dtmf_allowed_(false),
1700 desired_playout_(false),
1701 nack_enabled_(false),
1702 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001703 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001704 desired_send_(SEND_NOTHING),
1705 send_(SEND_NOTHING),
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001706 call_(nullptr),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001707 default_receive_ssrc_(0) {
1708 engine->RegisterChannel(this);
1709 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1710 << voe_channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001711 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001712}
1713
1714WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1715 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1716 << voe_channel();
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001717 DCHECK(receive_streams_.empty() || call_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001718
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001719 // Remove any remaining send streams, the default channel will be deleted
1720 // later.
1721 while (!send_channels_.empty())
1722 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001723
1724 // Unregister ourselves from the engine.
1725 engine()->UnregisterChannel(this);
1726 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001727 while (!receive_channels_.empty()) {
1728 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001729 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001730 DCHECK(receive_streams_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001731
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001732 // Delete the default channel.
1733 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001734}
1735
1736bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1737 LOG(LS_INFO) << "Setting voice channel options: "
1738 << options.ToString();
1739
wu@webrtc.orgde305012013-10-31 15:40:38 +00001740 // Check if DSCP value is changed from previous.
1741 bool dscp_option_changed = (options_.dscp != options.dscp);
1742
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001743 // TODO(xians): Add support to set different options for different send
1744 // streams after we support multiple APMs.
1745
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001746 // We retain all of the existing options, and apply the given ones
1747 // on top. This means there is no way to "clear" options such that
1748 // they go back to the engine default.
1749 options_.SetAll(options);
1750
1751 if (send_ != SEND_NOTHING) {
1752 if (!engine()->SetOptionOverrides(options_)) {
1753 LOG(LS_WARNING) <<
1754 "Failed to engine SetOptionOverrides during channel SetOptions.";
1755 return false;
1756 }
1757 } else {
1758 // Will be interpreted when appropriate.
1759 }
1760
wu@webrtc.org97077a32013-10-25 21:18:33 +00001761 // Receiver-side auto gain control happens per channel, so set it here from
1762 // options. Note that, like conference mode, setting it on the engine won't
1763 // have the desired effect, since voice channels don't inherit options from
1764 // the media engine when those options are applied per-channel.
1765 bool rx_auto_gain_control;
1766 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1767 if (engine()->voe()->processing()->SetRxAgcStatus(
1768 voe_channel(), rx_auto_gain_control,
1769 webrtc::kAgcFixedDigital) == -1) {
1770 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1771 return false;
1772 } else {
1773 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1774 << " with mode " << webrtc::kAgcFixedDigital;
1775 }
1776 }
1777 if (options.rx_agc_target_dbov.IsSet() ||
1778 options.rx_agc_digital_compression_gain.IsSet() ||
1779 options.rx_agc_limiter.IsSet()) {
1780 webrtc::AgcConfig config;
1781 // If only some of the options are being overridden, get the current
1782 // settings for the channel and bail if they aren't available.
1783 if (!options.rx_agc_target_dbov.IsSet() ||
1784 !options.rx_agc_digital_compression_gain.IsSet() ||
1785 !options.rx_agc_limiter.IsSet()) {
1786 if (engine()->voe()->processing()->GetRxAgcConfig(
1787 voe_channel(), config) != 0) {
1788 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1789 << "channel " << voe_channel() << ". Since not all rx "
1790 << "agc options are specified, unable to safely set rx "
1791 << "agc options.";
1792 return false;
1793 }
1794 }
1795 config.targetLeveldBOv =
1796 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1797 config.targetLeveldBOv);
1798 config.digitalCompressionGaindB =
1799 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1800 config.digitalCompressionGaindB);
1801 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1802 config.limiterEnable);
1803 if (engine()->voe()->processing()->SetRxAgcConfig(
1804 voe_channel(), config) == -1) {
1805 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1806 config.digitalCompressionGaindB, config.limiterEnable);
1807 return false;
1808 }
1809 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001810 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001811 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001812 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001813 dscp = kAudioDscpValue;
1814 if (MediaChannel::SetDscp(dscp) != 0) {
1815 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1816 }
1817 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001818
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001819 SetCall(call_);
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001820
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001821 LOG(LS_INFO) << "Set voice channel options. Current options: "
1822 << options_.ToString();
1823 return true;
1824}
1825
1826bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1827 const std::vector<AudioCodec>& codecs) {
1828 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001829 LOG(LS_INFO) << "Setting receive voice codecs:";
1830
1831 std::vector<AudioCodec> new_codecs;
1832 // Find all new codecs. We allow adding new codecs but don't allow changing
1833 // the payload type of codecs that is already configured since we might
1834 // already be receiving packets with that payload type.
1835 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001836 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001837 AudioCodec old_codec;
1838 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1839 if (old_codec.id != it->id) {
1840 LOG(LS_ERROR) << it->name << " payload type changed.";
1841 return false;
1842 }
1843 } else {
1844 new_codecs.push_back(*it);
1845 }
1846 }
1847 if (new_codecs.empty()) {
1848 // There are no new codecs to configure. Already configured codecs are
1849 // never removed.
1850 return true;
1851 }
1852
1853 if (playout_) {
1854 // Receive codecs can not be changed while playing. So we temporarily
1855 // pause playout.
1856 PausePlayout();
1857 }
1858
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001859 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001860 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1861 it != new_codecs.end() && ret; ++it) {
1862 webrtc::CodecInst voe_codec;
1863 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1864 LOG(LS_INFO) << ToString(*it);
1865 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001866 if (default_receive_ssrc_ == 0) {
1867 // Set the receive codecs on the default channel explicitly if the
1868 // default channel is not used by |receive_channels_|, this happens in
1869 // conference mode or in non-conference mode when there is no playout
1870 // channel.
1871 // TODO(xians): Figure out how we use the default channel in conference
1872 // mode.
1873 if (engine()->voe()->codec()->SetRecPayloadType(
1874 voe_channel(), voe_codec) == -1) {
1875 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1876 ret = false;
1877 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001878 }
1879
1880 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001881 for (ChannelMap::iterator it = receive_channels_.begin();
1882 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001883 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001884 it->second->channel(), voe_codec) == -1) {
1885 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001886 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001887 ret = false;
1888 }
1889 }
1890 } else {
1891 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1892 ret = false;
1893 }
1894 }
1895 if (ret) {
1896 recv_codecs_ = codecs;
1897 }
1898
1899 if (desired_playout_ && !playout_) {
1900 ResumePlayout();
1901 }
1902 return ret;
1903}
1904
1905bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001906 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001907 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001908 engine()->voe()->codec()->SetVADStatus(channel, false);
1909 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001910 engine()->voe()->rtp()->SetREDStatus(channel, false);
1911 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001912
1913 // Scan through the list to figure out the codec to use for sending, along
1914 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001915 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001916 webrtc::CodecInst send_codec;
1917 memset(&send_codec, 0, sizeof(send_codec));
1918
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001919 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001920 bool enable_codec_fec = false;
Minyue Li7100dcd2015-03-27 05:05:59 +01001921 bool enable_opus_dtx = false;
minyue@webrtc.org26236952014-10-29 02:27:08 +00001922 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001923
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001924 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001925 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1926 it != codecs.end(); ++it) {
1927 // Ignore codecs we don't know about. The negotiation step should prevent
1928 // this, but double-check to be sure.
1929 webrtc::CodecInst voe_codec;
1930 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001931 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001932 continue;
1933 }
1934
Minyue Li7100dcd2015-03-27 05:05:59 +01001935 if (IsCodec(*it, kDtmfCodecName) || IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001936 // Skip telephone-event/CN codec, which will be handled later.
1937 continue;
1938 }
1939
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001940 // We'll use the first codec in the list to actually send audio data.
1941 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001942 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001943 // used is specified in params.
Minyue Li7100dcd2015-03-27 05:05:59 +01001944 if (IsCodec(*it, kRedCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001945 // Parse out the RED parameters. If we fail, just ignore RED;
1946 // we don't support all possible params/usage scenarios.
1947 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
1948 continue;
1949 }
1950
1951 // Enable redundant encoding of the specified codec. Treat any
1952 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001953 LOG(LS_INFO) << "Enabling RED on channel " << channel;
1954 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
1955 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001956 return false;
1957 }
1958 } else {
1959 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001960 nack_enabled = IsNackEnabled(*it);
Minyue Li7100dcd2015-03-27 05:05:59 +01001961 // For Opus as the send codec, we are to determine inband FEC, maximum
1962 // playback rate, and opus internal dtx.
1963 if (IsCodec(*it, kOpusCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00001964 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
Minyue Li7100dcd2015-03-27 05:05:59 +01001965 &opus_max_playback_rate, &enable_opus_dtx);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001966 }
Brave Yao5225dd82015-03-26 07:39:19 +08001967
1968 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1969 int ptime_ms = 0;
1970 if (it->GetParam(kCodecParamPTime, &ptime_ms)) {
1971 if (!SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
1972 LOG(LS_WARNING) << "Failed to set packet size for codec "
1973 << send_codec.plname;
1974 return false;
1975 }
1976 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001977 }
1978 found_send_codec = true;
1979 break;
1980 }
1981
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001982 if (nack_enabled_ != nack_enabled) {
1983 SetNack(channel, nack_enabled);
1984 nack_enabled_ = nack_enabled;
1985 }
1986
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001987 if (!found_send_codec) {
1988 LOG(LS_WARNING) << "Received empty list of codecs.";
1989 return false;
1990 }
1991
1992 // Set the codec immediately, since SetVADStatus() depends on whether
1993 // the current codec is mono or stereo.
1994 if (!SetSendCodec(channel, send_codec))
1995 return false;
1996
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001997 // FEC should be enabled after SetSendCodec.
1998 if (enable_codec_fec) {
1999 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2000 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002001 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2002 // Enable codec internal FEC. Treat any failure as fatal internal error.
2003 LOG_RTCERR2(SetFECStatus, channel, true);
2004 return false;
2005 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002006 }
2007
Minyue Li7100dcd2015-03-27 05:05:59 +01002008 if (IsCodec(send_codec, kOpusCodecName)) {
2009 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
2010 // send codec has to be Opus.
2011
2012 // Set Opus internal DTX.
2013 LOG(LS_INFO) << "Attempt to "
2014 << GetEnableString(enable_opus_dtx)
2015 << " Opus DTX on channel "
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002016 << channel;
Minyue Li7100dcd2015-03-27 05:05:59 +01002017 if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) {
2018 LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx);
2019 return false;
2020 }
2021
2022 // If opus_max_playback_rate <= 0, the default maximum playback rate
2023 // (48 kHz) will be used.
2024 if (opus_max_playback_rate > 0) {
2025 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
2026 << opus_max_playback_rate
2027 << " Hz on channel "
2028 << channel;
2029 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
2030 channel, opus_max_playback_rate) == -1) {
2031 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate);
2032 return false;
2033 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002034 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002035 }
2036
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002037 // Always update the |send_codec_| to the currently set send codec.
2038 send_codec_.reset(new webrtc::CodecInst(send_codec));
2039
minyue@webrtc.org26236952014-10-29 02:27:08 +00002040 if (send_bitrate_setting_) {
2041 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002042 }
2043
2044 // Loop through the codecs list again to config the telephone-event/CN codec.
2045 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2046 it != codecs.end(); ++it) {
2047 // Ignore codecs we don't know about. The negotiation step should prevent
2048 // this, but double-check to be sure.
2049 webrtc::CodecInst voe_codec;
2050 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2051 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2052 continue;
2053 }
2054
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002055 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2056 // about it.
Minyue Li7100dcd2015-03-27 05:05:59 +01002057 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002058 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2059 channel, it->id) == -1) {
2060 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2061 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002062 }
Minyue Li7100dcd2015-03-27 05:05:59 +01002063 } else if (IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002064 // Turn voice activity detection/comfort noise on if supported.
2065 // Set the wideband CN payload type appropriately.
2066 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002067 webrtc::PayloadFrequencies cn_freq;
2068 switch (it->clockrate) {
2069 case 8000:
2070 cn_freq = webrtc::kFreq8000Hz;
2071 break;
2072 case 16000:
2073 cn_freq = webrtc::kFreq16000Hz;
2074 break;
2075 case 32000:
2076 cn_freq = webrtc::kFreq32000Hz;
2077 break;
2078 default:
2079 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2080 << " not supported.";
2081 continue;
2082 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002083 // Set the CN payloadtype and the VAD status.
2084 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2085 if (cn_freq != webrtc::kFreq8000Hz) {
2086 if (engine()->voe()->codec()->SetSendCNPayloadType(
2087 channel, it->id, cn_freq) == -1) {
2088 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2089 // TODO(ajm): This failure condition will be removed from VoE.
2090 // Restore the return here when we update to a new enough webrtc.
2091 //
2092 // Not returning false because the SetSendCNPayloadType will fail if
2093 // the channel is already sending.
2094 // This can happen if the remote description is applied twice, for
2095 // example in the case of ROAP on top of JSEP, where both side will
2096 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002097 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002098 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002099 // Only turn on VAD if we have a CN payload type that matches the
2100 // clockrate for the codec we are going to use.
Minyue Li7100dcd2015-03-27 05:05:59 +01002101 if (it->clockrate == send_codec.plfreq && send_codec.channels != 2) {
2102 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
2103 // interaction between VAD and Opus FEC.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002104 LOG(LS_INFO) << "Enabling VAD";
2105 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2106 LOG_RTCERR2(SetVADStatus, channel, true);
2107 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002108 }
2109 }
2110 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002111 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002112 return true;
2113}
2114
2115bool WebRtcVoiceMediaChannel::SetSendCodecs(
2116 const std::vector<AudioCodec>& codecs) {
2117 dtmf_allowed_ = false;
2118 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2119 it != codecs.end(); ++it) {
2120 // Find the DTMF telephone event "codec".
Minyue Li7100dcd2015-03-27 05:05:59 +01002121 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002122 dtmf_allowed_ = true;
2123 }
2124 }
2125
2126 // Cache the codecs in order to configure the channel created later.
2127 send_codecs_ = codecs;
2128 for (ChannelMap::iterator iter = send_channels_.begin();
2129 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002130 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002131 return false;
2132 }
2133 }
2134
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002135 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002136 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002137 return true;
2138}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002139
2140void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2141 bool nack_enabled) {
2142 for (ChannelMap::const_iterator it = channels.begin();
2143 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002144 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002145 }
2146}
2147
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002148void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002149 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002150 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002151 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2152 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002153 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002154 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2155 }
2156}
2157
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002158bool WebRtcVoiceMediaChannel::SetSendCodec(
2159 const webrtc::CodecInst& send_codec) {
2160 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2161 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002162 for (ChannelMap::iterator iter = send_channels_.begin();
2163 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002164 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002165 return false;
2166 }
2167
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002168 return true;
2169}
2170
2171bool WebRtcVoiceMediaChannel::SetSendCodec(
2172 int channel, const webrtc::CodecInst& send_codec) {
2173 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2174 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2175
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002176 webrtc::CodecInst current_codec;
2177 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2178 (send_codec == current_codec)) {
2179 // Codec is already configured, we can return without setting it again.
2180 return true;
2181 }
2182
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002183 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2184 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002185 return false;
2186 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002187 return true;
2188}
2189
2190bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2191 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002192 if (receive_extensions_ == extensions) {
2193 return true;
2194 }
2195
2196 // The default channel may or may not be in |receive_channels_|. Set the rtp
2197 // header extensions for default channel regardless.
2198 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2199 return false;
2200 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002201
2202 // Loop through all receive channels and enable/disable the extensions.
2203 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2204 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002205 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2206 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002207 return false;
2208 }
2209 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002210
2211 receive_extensions_ = extensions;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002212
2213 // Recreate AudioReceiveStream:s.
2214 {
2215 std::vector<webrtc::RtpExtension> exts;
2216
2217 const RtpHeaderExtension* audio_level_extension =
2218 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2219 if (audio_level_extension) {
2220 exts.push_back({
2221 kRtpAudioLevelHeaderExtension, audio_level_extension->id});
2222 }
2223
2224 const RtpHeaderExtension* send_time_extension =
2225 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2226 if (send_time_extension) {
2227 exts.push_back({
2228 kRtpAbsoluteSenderTimeHeaderExtension, send_time_extension->id});
2229 }
2230
2231 recv_rtp_extensions_.swap(exts);
2232 SetCall(call_);
2233 }
2234
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002235 return true;
2236}
2237
2238bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2239 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002240 const RtpHeaderExtension* audio_level_extension =
2241 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2242 if (!SetHeaderExtension(
2243 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2244 audio_level_extension)) {
2245 return false;
2246 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002247
2248 const RtpHeaderExtension* send_time_extension =
2249 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2250 if (!SetHeaderExtension(
2251 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2252 send_time_extension)) {
2253 return false;
2254 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002255
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002256 return true;
2257}
2258
2259bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2260 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002261 if (send_extensions_ == extensions) {
2262 return true;
2263 }
2264
2265 // The default channel may or may not be in |send_channels_|. Set the rtp
2266 // header extensions for default channel regardless.
2267
2268 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2269 return false;
2270 }
2271
2272 // Loop through all send channels and enable/disable the extensions.
2273 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2274 channel_it != send_channels_.end(); ++channel_it) {
2275 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2276 extensions)) {
2277 return false;
2278 }
2279 }
2280
2281 send_extensions_ = extensions;
2282 return true;
2283}
2284
2285bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2286 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002287 const RtpHeaderExtension* audio_level_extension =
2288 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002289
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002290 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002291 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002292 audio_level_extension)) {
2293 return false;
2294 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002295
2296 const RtpHeaderExtension* send_time_extension =
2297 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002298 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002299 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002300 send_time_extension)) {
2301 return false;
2302 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002303
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002304 return true;
2305}
2306
2307bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2308 desired_playout_ = playout;
2309 return ChangePlayout(desired_playout_);
2310}
2311
2312bool WebRtcVoiceMediaChannel::PausePlayout() {
2313 return ChangePlayout(false);
2314}
2315
2316bool WebRtcVoiceMediaChannel::ResumePlayout() {
2317 return ChangePlayout(desired_playout_);
2318}
2319
2320bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2321 if (playout_ == playout) {
2322 return true;
2323 }
2324
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002325 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002326 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002327 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002328 // Only toggle the default channel if we don't have any other channels.
2329 result = SetPlayout(voe_channel(), playout);
2330 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002331 for (ChannelMap::iterator it = receive_channels_.begin();
2332 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002333 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002334 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002335 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002336 result = false;
2337 }
2338 }
2339
2340 if (result) {
2341 playout_ = playout;
2342 }
2343 return result;
2344}
2345
2346bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2347 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002348 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002349 return ChangeSend(desired_send_);
2350 return true;
2351}
2352
2353bool WebRtcVoiceMediaChannel::PauseSend() {
2354 return ChangeSend(SEND_NOTHING);
2355}
2356
2357bool WebRtcVoiceMediaChannel::ResumeSend() {
2358 return ChangeSend(desired_send_);
2359}
2360
2361bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2362 if (send_ == send) {
2363 return true;
2364 }
2365
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002366 // Change the settings on each send channel.
2367 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002368 engine()->SetOptionOverrides(options_);
2369
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002370 // Change the settings on each send channel.
2371 for (ChannelMap::iterator iter = send_channels_.begin();
2372 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002373 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002374 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002375 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002376
2377 // Clear up the options after stopping sending.
2378 if (send == SEND_NOTHING)
2379 engine()->ClearOptionOverrides();
2380
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002381 send_ = send;
2382 return true;
2383}
2384
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002385bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2386 if (send == SEND_MICROPHONE) {
2387 if (engine()->voe()->base()->StartSend(channel) == -1) {
2388 LOG_RTCERR1(StartSend, channel);
2389 return false;
2390 }
2391 if (engine()->voe()->file() &&
2392 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2393 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2394 return false;
2395 }
2396 } else { // SEND_NOTHING
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002397 DCHECK(send == SEND_NOTHING);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002398 if (engine()->voe()->base()->StopSend(channel) == -1) {
2399 LOG_RTCERR1(StopSend, channel);
2400 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002401 }
2402 }
2403
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002404 return true;
2405}
2406
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002407// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002408void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2409 if (engine()->voe()->network()->RegisterExternalTransport(
2410 channel, *this) == -1) {
2411 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2412 }
2413
2414 // Enable RTCP (for quality stats and feedback messages)
2415 EnableRtcp(channel);
2416
2417 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2418 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002419
2420 // Set RTP header extension for the new channel.
2421 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002422}
2423
2424bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2425 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2426 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2427 }
2428
2429 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2430 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002431 return false;
2432 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002433
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002434 return true;
2435}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002436
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002437bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2438 // If the default channel is already used for sending create a new channel
2439 // otherwise use the default channel for sending.
2440 int channel = GetSendChannelNum(sp.first_ssrc());
2441 if (channel != -1) {
2442 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2443 return false;
2444 }
2445
2446 bool default_channel_is_available = true;
2447 for (ChannelMap::const_iterator iter = send_channels_.begin();
2448 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002449 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002450 default_channel_is_available = false;
2451 break;
2452 }
2453 }
2454 if (default_channel_is_available) {
2455 channel = voe_channel();
2456 } else {
2457 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002458 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002459 if (channel == -1) {
2460 LOG_RTCERR0(CreateChannel);
2461 return false;
2462 }
2463
2464 ConfigureSendChannel(channel);
2465 }
2466
2467 // Save the channel to send_channels_, so that RemoveSendStream() can still
2468 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002469 webrtc::AudioTransport* audio_transport =
2470 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002471 send_channels_.insert(std::make_pair(
2472 sp.first_ssrc(),
2473 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002474
2475 // Set the send (local) SSRC.
2476 // If there are multiple send SSRCs, we can only set the first one here, and
2477 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2478 // (with a codec requires multiple SSRC(s)).
2479 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2480 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2481 return false;
2482 }
2483
2484 // At this point the channel's local SSRC has been updated. If the channel is
2485 // the default channel make sure that all the receive channels are updated as
2486 // well. Receive channels have to have the same SSRC as the default channel in
2487 // order to send receiver reports with this SSRC.
2488 if (IsDefaultChannel(channel)) {
2489 for (ChannelMap::const_iterator it = receive_channels_.begin();
2490 it != receive_channels_.end(); ++it) {
2491 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002492 if (!IsDefaultChannel(it->second->channel())) {
2493 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002494 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002495 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002496 return false;
2497 }
2498 }
2499 }
2500 }
2501
2502 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002503 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2504 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002505 }
2506
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002507 // Set the current codecs to be used for the new channel.
2508 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002509 return false;
2510
2511 return ChangeSend(channel, desired_send_);
2512}
2513
2514bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2515 ChannelMap::iterator it = send_channels_.find(ssrc);
2516 if (it == send_channels_.end()) {
2517 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2518 << " which doesn't exist.";
2519 return false;
2520 }
2521
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002522 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002523 ChangeSend(channel, SEND_NOTHING);
2524
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002525 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2526 // this will disconnect the audio renderer with the send channel.
2527 delete it->second;
2528 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002529
2530 if (IsDefaultChannel(channel)) {
2531 // Do not delete the default channel since the receive channels depend on
2532 // the default channel, recycle it instead.
2533 ChangeSend(channel, SEND_NOTHING);
2534 } else {
2535 // Clean up and delete the send channel.
2536 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2537 << " with VoiceEngine channel #" << channel << ".";
2538 if (!DeleteChannel(channel))
2539 return false;
2540 }
2541
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002542 if (send_channels_.empty())
2543 ChangeSend(SEND_NOTHING);
2544
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002545 return true;
2546}
2547
2548bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002549 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002550 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002551
2552 if (!VERIFY(sp.ssrcs.size() == 1))
2553 return false;
2554 uint32 ssrc = sp.first_ssrc();
2555
wu@webrtc.org78187522013-10-07 23:32:02 +00002556 if (ssrc == 0) {
2557 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2558 return false;
2559 }
2560
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002561 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2562 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002563 return false;
2564 }
2565
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002566 TryAddAudioRecvStream(ssrc);
2567
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002568 // Reuse default channel for recv stream in non-conference mode call
2569 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002570 webrtc::AudioTransport* audio_transport =
2571 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002572 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002573 LOG(LS_INFO) << "Recv stream " << ssrc << " reuse default channel";
2574 default_receive_ssrc_ = ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002575 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002576 default_receive_ssrc_,
2577 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002578 return SetPlayout(voe_channel(), playout_);
2579 }
2580
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002581 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002582 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002583 if (channel == -1) {
2584 LOG_RTCERR0(CreateChannel);
2585 return false;
2586 }
2587
wu@webrtc.org78187522013-10-07 23:32:02 +00002588 if (!ConfigureRecvChannel(channel)) {
2589 DeleteChannel(channel);
2590 return false;
2591 }
2592
2593 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002594 std::make_pair(
2595 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002596
2597 LOG(LS_INFO) << "New audio stream " << ssrc
2598 << " registered to VoiceEngine channel #"
2599 << channel << ".";
2600 return true;
2601}
2602
2603bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002604 // Configure to use external transport, like our default channel.
2605 if (engine()->voe()->network()->RegisterExternalTransport(
2606 channel, *this) == -1) {
2607 LOG_RTCERR2(SetExternalTransport, channel, this);
2608 return false;
2609 }
2610
2611 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002612 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002613 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2614 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002615 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002616 return false;
2617 }
2618 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002619 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002620 return false;
2621 }
2622
Minyue2013aec2015-05-13 14:14:42 +02002623 // Associate receive channel to default channel (so the receive channel can
2624 // obtain RTT from the send channel)
2625 engine()->voe()->base()->AssociateSendChannel(channel, voe_channel());
2626 LOG(LS_INFO) << "VoiceEngine channel #"
2627 << channel << " is associated with channel #"
2628 << voe_channel() << ".";
2629
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002630 // Use the same recv payload types as our default channel.
2631 ResetRecvCodecs(channel);
2632 if (!recv_codecs_.empty()) {
2633 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2634 it != recv_codecs_.end(); ++it) {
2635 webrtc::CodecInst voe_codec;
2636 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2637 voe_codec.pltype = it->id;
2638 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2639 if (engine()->voe()->codec()->GetRecPayloadType(
2640 voe_channel(), voe_codec) != -1) {
2641 if (engine()->voe()->codec()->SetRecPayloadType(
2642 channel, voe_codec) == -1) {
2643 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2644 return false;
2645 }
2646 }
2647 }
2648 }
2649 }
2650
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002651 if (InConferenceMode()) {
2652 // To be in par with the video, voe_channel() is not used for receiving in
2653 // a conference call.
2654 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2655 // This is the first stream in a multi user meeting. We can now
2656 // disable playback of the default stream. This since the default
2657 // stream will probably have received some initial packets before
2658 // the new stream was added. This will mean that the CN state from
2659 // the default channel will be mixed in with the other streams
2660 // throughout the whole meeting, which might be disturbing.
2661 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2662 SetPlayout(voe_channel(), false);
2663 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002664 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002665 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002666
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002667 // Set RTP header extension for the new channel.
2668 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2669 return false;
2670 }
2671
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002672 return SetPlayout(channel, playout_);
2673}
2674
2675bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002676 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002677 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002678 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002679 if (it == receive_channels_.end()) {
2680 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2681 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002682 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002683 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002684
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002685 TryRemoveAudioRecvStream(ssrc);
2686
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002687 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2688 // will disconnect the audio renderer with the receive channel.
2689 // Cache the channel before the deletion.
2690 const int channel = it->second->channel();
2691 delete it->second;
2692 receive_channels_.erase(it);
2693
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002694 if (ssrc == default_receive_ssrc_) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002695 DCHECK(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002696 // Recycle the default channel is for recv stream.
2697 if (playout_)
2698 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002699
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002700 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002701 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002702 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002703
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002704 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002705 << " with VoiceEngine channel #" << channel << ".";
2706 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002707 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002708
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002709 bool enable_default_channel_playout = false;
2710 if (receive_channels_.empty()) {
2711 // The last stream was removed. We can now enable the default
2712 // channel for new channels to be played out immediately without
2713 // waiting for AddStream messages.
2714 // We do this for both conference mode and non-conference mode.
2715 // TODO(oja): Does the default channel still have it's CN state?
2716 enable_default_channel_playout = true;
2717 }
2718 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2719 default_receive_ssrc_ != 0) {
2720 // Only the default channel is active, enable the playout on default
2721 // channel.
2722 enable_default_channel_playout = true;
2723 }
2724 if (enable_default_channel_playout && playout_) {
2725 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2726 SetPlayout(voe_channel(), true);
2727 }
2728
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002729 return true;
2730}
2731
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002732bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2733 AudioRenderer* renderer) {
2734 ChannelMap::iterator it = receive_channels_.find(ssrc);
2735 if (it == receive_channels_.end()) {
2736 if (renderer) {
2737 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002738 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002739 return false;
2740 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002741
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002742 // The channel likely has gone away, do nothing.
2743 return true;
2744 }
2745
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002746 if (renderer)
2747 it->second->Start(renderer);
2748 else
2749 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002750
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002751 return true;
2752}
2753
2754bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2755 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002756 ChannelMap::iterator it = send_channels_.find(ssrc);
2757 if (it == send_channels_.end()) {
2758 if (renderer) {
2759 // Return an error if trying to set a valid renderer with an invalid ssrc.
2760 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2761 return false;
2762 }
2763
2764 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002765 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002766 }
2767
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002768 if (renderer)
2769 it->second->Start(renderer);
2770 else
2771 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002772
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002773 return true;
2774}
2775
2776bool WebRtcVoiceMediaChannel::GetActiveStreams(
2777 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002778 // In conference mode, the default channel should not be in
2779 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002780 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002781 for (ChannelMap::iterator it = receive_channels_.begin();
2782 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002783 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002784 if (level > 0) {
2785 actives->push_back(std::make_pair(it->first, level));
2786 }
2787 }
2788 return true;
2789}
2790
2791int WebRtcVoiceMediaChannel::GetOutputLevel() {
2792 // return the highest output level of all streams
2793 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002794 for (ChannelMap::iterator it = receive_channels_.begin();
2795 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002796 int level = GetOutputLevel(it->second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002797 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002798 }
2799 return highest;
2800}
2801
2802int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2803 int ret;
2804 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2805 // In case of error, log the info and continue
2806 LOG_RTCERR0(TimeSinceLastTyping);
2807 ret = -1;
2808 } else {
2809 ret *= 1000; // We return ms, webrtc returns seconds.
2810 }
2811 return ret;
2812}
2813
2814void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2815 int cost_per_typing, int reporting_threshold, int penalty_decay,
2816 int type_event_delay) {
2817 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2818 time_window, cost_per_typing,
2819 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2820 // In case of error, log the info and continue
2821 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2822 cost_per_typing, reporting_threshold, penalty_decay,
2823 type_event_delay);
2824 }
2825}
2826
2827bool WebRtcVoiceMediaChannel::SetOutputScaling(
2828 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002829 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002830 // Collect the channels to scale the output volume.
2831 std::vector<int> channels;
2832 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002833 // Default channel is not in receive_channels_ if it is not being used for
2834 // playout.
2835 if (default_receive_ssrc_ == 0)
2836 channels.push_back(voe_channel());
2837 for (ChannelMap::const_iterator it = receive_channels_.begin();
2838 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002839 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002840 }
2841 } else { // Collect only the channel of the specified ssrc.
2842 int channel = GetReceiveChannelNum(ssrc);
2843 if (-1 == channel) {
2844 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2845 return false;
2846 }
2847 channels.push_back(channel);
2848 }
2849
2850 // Scale the output volume for the collected channels. We first normalize to
2851 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002852 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002853 if (scale > 0.0001f) {
2854 left /= scale;
2855 right /= scale;
2856 }
2857 for (std::vector<int>::const_iterator it = channels.begin();
2858 it != channels.end(); ++it) {
2859 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2860 *it, scale)) {
2861 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2862 return false;
2863 }
2864 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2865 *it, static_cast<float>(left), static_cast<float>(right))) {
2866 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2867 // Do not return if fails. SetOutputVolumePan is not available for all
2868 // pltforms.
2869 }
2870 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2871 << " right=" << right * scale
2872 << " for channel " << *it << " and ssrc " << ssrc;
2873 }
2874 return true;
2875}
2876
2877bool WebRtcVoiceMediaChannel::GetOutputScaling(
2878 uint32 ssrc, double* left, double* right) {
2879 if (!left || !right) return false;
2880
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002881 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002882 // Determine which channel based on ssrc.
2883 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2884 if (channel == -1) {
2885 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2886 return false;
2887 }
2888
2889 float scaling;
2890 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2891 channel, scaling)) {
2892 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2893 return false;
2894 }
2895
2896 float left_pan;
2897 float right_pan;
2898 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2899 channel, left_pan, right_pan)) {
2900 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2901 // If GetOutputVolumePan fails, we use the default left and right pan.
2902 left_pan = 1.0f;
2903 right_pan = 1.0f;
2904 }
2905
2906 *left = scaling * left_pan;
2907 *right = scaling * right_pan;
2908 return true;
2909}
2910
2911bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2912 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2913 return true;
2914}
2915
2916bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2917 bool play, bool loop) {
2918 if (!ringback_tone_) {
2919 return false;
2920 }
2921
2922 // The voe file api is not available in chrome.
2923 if (!engine()->voe()->file()) {
2924 return false;
2925 }
2926
2927 // Determine which VoiceEngine channel to play on.
2928 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2929 if (channel == -1) {
2930 return false;
2931 }
2932
2933 // Make sure the ringtone is cued properly, and play it out.
2934 if (play) {
2935 ringback_tone_->set_loop(loop);
2936 ringback_tone_->Rewind();
2937 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2938 ringback_tone_.get()) == -1) {
2939 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2940 LOG(LS_ERROR) << "Unable to start ringback tone";
2941 return false;
2942 }
2943 ringback_channels_.insert(channel);
2944 LOG(LS_INFO) << "Started ringback on channel " << channel;
2945 } else {
2946 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2947 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2948 LOG_RTCERR1(StopPlayingFileLocally, channel);
2949 return false;
2950 }
2951 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2952 ringback_channels_.erase(channel);
2953 }
2954
2955 return true;
2956}
2957
2958bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2959 return dtmf_allowed_;
2960}
2961
2962bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2963 int duration, int flags) {
2964 if (!dtmf_allowed_) {
2965 return false;
2966 }
2967
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002968 // Send the event.
2969 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002970 int channel = -1;
2971 if (ssrc == 0) {
2972 bool default_channel_is_inuse = false;
2973 for (ChannelMap::const_iterator iter = send_channels_.begin();
2974 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002975 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002976 default_channel_is_inuse = true;
2977 break;
2978 }
2979 }
2980 if (default_channel_is_inuse) {
2981 channel = voe_channel();
2982 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002983 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002984 }
2985 } else {
2986 channel = GetSendChannelNum(ssrc);
2987 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002988 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002989 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2990 << ssrc << " is not in use.";
2991 return false;
2992 }
2993 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002994 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2995 channel, event, true, duration) == -1) {
2996 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002997 return false;
2998 }
2999 }
3000
3001 // Play the event.
3002 if (flags & cricket::DF_PLAY) {
3003 // Play DTMF tone locally.
3004 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3005 LOG_RTCERR2(PlayDtmfTone, event, duration);
3006 return false;
3007 }
3008 }
3009
3010 return true;
3011}
3012
wu@webrtc.orga9890802013-12-13 00:21:03 +00003013void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003014 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003015 DCHECK(thread_checker_.CalledOnValidThread());
3016
3017 // If hooked up to a "Call", forward packet there too.
3018 if (call_) {
3019 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3020 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3021 }
3022
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003023 // Pick which channel to send this packet to. If this packet doesn't match
3024 // any multiplexed streams, just send it to the default channel. Otherwise,
3025 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003026 int which_channel =
3027 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003028 if (which_channel == -1) {
3029 which_channel = voe_channel();
3030 }
3031
3032 // Stop any ringback that might be playing on the channel.
3033 // It's possible the ringback has already stopped, ih which case we'll just
3034 // use the opportunity to remove the channel from ringback_channels_.
3035 if (engine()->voe()->file()) {
3036 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3037 if (it != ringback_channels_.end()) {
3038 if (engine()->voe()->file()->IsPlayingFileLocally(
3039 which_channel) == 1) {
3040 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3041 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3042 << " due to incoming media";
3043 }
3044 ringback_channels_.erase(which_channel);
3045 }
3046 }
3047
3048 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003049 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003050 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003051 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003052}
3053
wu@webrtc.orga9890802013-12-13 00:21:03 +00003054void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003055 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003056 DCHECK(thread_checker_.CalledOnValidThread());
3057
3058 // If hooked up to a "Call", forward packet there too.
3059 if (call_) {
3060 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3061 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3062 }
3063
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003064 // Sending channels need all RTCP packets with feedback information.
3065 // Even sender reports can contain attached report blocks.
3066 // Receiving channels need sender reports in order to create
3067 // correct receiver reports.
3068 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003069 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003070 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3071 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003072 }
3073
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003074 // If it is a sender report, find the channel that is listening.
3075 bool has_sent_to_default_channel = false;
3076 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003077 int which_channel =
3078 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003079 if (which_channel != -1) {
3080 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003081 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003082
3083 if (IsDefaultChannel(which_channel))
3084 has_sent_to_default_channel = true;
3085 }
3086 }
3087
3088 // SR may continue RR and any RR entry may correspond to any one of the send
3089 // channels. So all RTCP packets must be forwarded all send channels. VoE
3090 // will filter out RR internally.
3091 for (ChannelMap::iterator iter = send_channels_.begin();
3092 iter != send_channels_.end(); ++iter) {
3093 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003094 if (IsDefaultChannel(iter->second->channel()) &&
3095 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003096 continue;
3097
3098 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003099 iter->second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003100 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003101}
3102
3103bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003104 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3105 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003106 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3107 return false;
3108 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003109 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3110 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003111 return false;
3112 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003113 // We set the AGC to mute state only when all the channels are muted.
3114 // This implementation is not ideal, instead we should signal the AGC when
3115 // the mic channel is muted/unmuted. We can't do it today because there
3116 // is no good way to know which stream is mapping to the mic channel.
3117 bool all_muted = muted;
3118 for (ChannelMap::const_iterator iter = send_channels_.begin();
3119 iter != send_channels_.end() && all_muted; ++iter) {
3120 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3121 all_muted)) {
3122 LOG_RTCERR1(GetInputMute, iter->second->channel());
3123 return false;
3124 }
3125 }
3126
3127 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3128 if (ap)
3129 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003130 return true;
3131}
3132
minyue@webrtc.org26236952014-10-29 02:27:08 +00003133// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3134// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003135bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003136 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003137
minyue@webrtc.org26236952014-10-29 02:27:08 +00003138 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003139}
3140
minyue@webrtc.org26236952014-10-29 02:27:08 +00003141bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3142 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003143
minyue@webrtc.org26236952014-10-29 02:27:08 +00003144 send_bitrate_setting_ = true;
3145 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003146
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003147 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003148 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003149 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003150 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003151 }
3152
minyue@webrtc.org26236952014-10-29 02:27:08 +00003153 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003154 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3155 // SetMaxSendBandwith(0), the second call removes the previous limit.
3156 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003157 return true;
3158
3159 webrtc::CodecInst codec = *send_codec_;
3160 bool is_multi_rate = IsCodecMultiRate(codec);
3161
3162 if (is_multi_rate) {
3163 // If codec is multi-rate then just set the bitrate.
3164 codec.rate = bps;
3165 if (!SetSendCodec(codec)) {
3166 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3167 << " to bitrate " << bps << " bps.";
3168 return false;
3169 }
3170 return true;
3171 } else {
3172 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3173 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3174 // fixed bitrate then ignore.
3175 if (bps < codec.rate) {
3176 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3177 << " to bitrate " << bps << " bps"
3178 << ", requires at least " << codec.rate << " bps.";
3179 return false;
3180 }
3181 return true;
3182 }
3183}
3184
3185bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003186 bool echo_metrics_on = false;
3187 // These can take on valid negative values, so use the lowest possible level
3188 // as default rather than -1.
3189 int echo_return_loss = -100;
3190 int echo_return_loss_enhancement = -100;
3191 // These can also be negative, but in practice -1 is only used to signal
3192 // insufficient data, since the resolution is limited to multiples of 4 ms.
3193 int echo_delay_median_ms = -1;
3194 int echo_delay_std_ms = -1;
3195 if (engine()->voe()->processing()->GetEcMetricsStatus(
3196 echo_metrics_on) != -1 && echo_metrics_on) {
3197 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3198 // here, but it appears to be unsuitable currently. Revisit after this is
3199 // investigated: http://b/issue?id=5666755
3200 int erl, erle, rerl, anlp;
3201 if (engine()->voe()->processing()->GetEchoMetrics(
3202 erl, erle, rerl, anlp) != -1) {
3203 echo_return_loss = erl;
3204 echo_return_loss_enhancement = erle;
3205 }
3206
3207 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003208 float dummy;
3209 if (engine()->voe()->processing()->GetEcDelayMetrics(
3210 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003211 echo_delay_median_ms = median;
3212 echo_delay_std_ms = std;
3213 }
3214 }
3215
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003216 webrtc::CallStatistics cs;
3217 unsigned int ssrc;
3218 webrtc::CodecInst codec;
3219 unsigned int level;
3220
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003221 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3222 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003223 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003224
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003225 // Fill in the sender info, based on what we know, and what the
3226 // remote side told us it got from its RTCP report.
3227 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003228
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003229 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3230 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3231 continue;
3232 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003233
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003234 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003235 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3236 sinfo.bytes_sent = cs.bytesSent;
3237 sinfo.packets_sent = cs.packetsSent;
3238 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3239 // returns 0 to indicate an error value.
3240 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3241
3242 // Get data from the last remote RTCP report. Use default values if no data
3243 // available.
3244 sinfo.fraction_lost = -1.0;
3245 sinfo.jitter_ms = -1;
3246 sinfo.packets_lost = -1;
3247 sinfo.ext_seqnum = -1;
3248 std::vector<webrtc::ReportBlock> receive_blocks;
3249 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3250 channel, &receive_blocks) != -1 &&
3251 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3252 std::vector<webrtc::ReportBlock>::iterator iter;
3253 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3254 ++iter) {
3255 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003256 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003257 // Convert Q8 to floating point.
3258 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3259 // Convert samples to milliseconds.
3260 if (codec.plfreq / 1000 > 0) {
3261 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3262 }
3263 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3264 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3265 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003266 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003267 }
3268 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003269
3270 // Local speech level.
3271 sinfo.audio_level = (engine()->voe()->volume()->
3272 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3273
3274 // TODO(xians): We are injecting the same APM logging to all the send
3275 // channels here because there is no good way to know which send channel
3276 // is using the APM. The correct fix is to allow the send channels to have
3277 // their own APM so that we can feed the correct APM logging to different
3278 // send channels. See issue crbug/264611 .
3279 sinfo.echo_return_loss = echo_return_loss;
3280 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3281 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3282 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003283 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3284 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003285 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003286
3287 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003288 }
3289
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003290 // Build the list of receivers, one for each receiving channel, or 1 in
3291 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003292 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003293 for (ChannelMap::const_iterator it = receive_channels_.begin();
3294 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003295 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003296 }
3297 if (channels.empty()) {
3298 channels.push_back(voe_channel());
3299 }
3300
3301 // Get the SSRC and stats for each receiver, based on our own calculations.
3302 for (std::vector<int>::const_iterator it = channels.begin();
3303 it != channels.end(); ++it) {
3304 memset(&cs, 0, sizeof(cs));
3305 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3306 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3307 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3308 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003309 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003310 rinfo.bytes_rcvd = cs.bytesReceived;
3311 rinfo.packets_rcvd = cs.packetsReceived;
3312 // The next four fields are from the most recently sent RTCP report.
3313 // Convert Q8 to floating point.
3314 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3315 rinfo.packets_lost = cs.cumulativeLost;
3316 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003317 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003318 if (codec.pltype != -1) {
3319 rinfo.codec_name = codec.plname;
3320 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003321 // Convert samples to milliseconds.
3322 if (codec.plfreq / 1000 > 0) {
3323 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3324 }
3325
3326 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3327 webrtc::NetworkStatistics ns;
3328 if (engine()->voe()->neteq() &&
3329 engine()->voe()->neteq()->GetNetworkStatistics(
3330 *it, ns) != -1) {
3331 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3332 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3333 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003334 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003335 rinfo.speech_expand_rate =
3336 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3337 rinfo.secondary_decoded_rate =
3338 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003339 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003340
3341 webrtc::AudioDecodingCallStats ds;
3342 if (engine()->voe()->neteq() &&
3343 engine()->voe()->neteq()->GetDecodingCallStatistics(
3344 *it, &ds) != -1) {
3345 rinfo.decoding_calls_to_silence_generator =
3346 ds.calls_to_silence_generator;
3347 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3348 rinfo.decoding_normal = ds.decoded_normal;
3349 rinfo.decoding_plc = ds.decoded_plc;
3350 rinfo.decoding_cng = ds.decoded_cng;
3351 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3352 }
3353
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003354 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003355 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003356 int playout_buffer_delay_ms = 0;
3357 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003358 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3359 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3360 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003361 }
3362
3363 // Get speech level.
3364 rinfo.audio_level = (engine()->voe()->volume()->
3365 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3366 info->receivers.push_back(rinfo);
3367 }
3368 }
3369
3370 return true;
3371}
3372
3373void WebRtcVoiceMediaChannel::GetLastMediaError(
3374 uint32* ssrc, VoiceMediaChannel::Error* error) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003375 DCHECK(ssrc != NULL);
3376 DCHECK(error != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003377 FindSsrc(voe_channel(), ssrc);
3378 *error = WebRtcErrorToChannelError(GetLastEngineError());
3379}
3380
3381bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003382 rtc::CritScope lock(&receive_channels_cs_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003383 DCHECK(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003384 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003385 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3386 // This means the error is not limited to a specific channel. Signal the
3387 // message using ssrc=0. If the current channel is sending, use this
3388 // channel for sending the message.
3389 *ssrc = 0;
3390 return true;
3391 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003392 // Check whether this is a sending channel.
3393 for (ChannelMap::const_iterator it = send_channels_.begin();
3394 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003395 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003396 // This is a sending channel.
3397 uint32 local_ssrc = 0;
3398 if (engine()->voe()->rtp()->GetLocalSSRC(
3399 channel_num, local_ssrc) != -1) {
3400 *ssrc = local_ssrc;
3401 }
3402 return true;
3403 }
3404 }
3405
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003406 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003407 for (ChannelMap::const_iterator it = receive_channels_.begin();
3408 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003409 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003410 *ssrc = it->first;
3411 return true;
3412 }
3413 }
3414 }
3415 return false;
3416}
3417
3418void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003419 if (error == VE_TYPING_NOISE_WARNING) {
3420 typing_noise_detected_ = true;
3421 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3422 typing_noise_detected_ = false;
3423 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003424 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3425}
3426
3427int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3428 unsigned int ulevel;
3429 int ret =
3430 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3431 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3432}
3433
3434int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003435 ChannelMap::iterator it = receive_channels_.find(ssrc);
3436 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003437 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003438 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3439}
3440
3441int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003442 ChannelMap::iterator it = send_channels_.find(ssrc);
3443 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003444 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003445
3446 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003447}
3448
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003449void WebRtcVoiceMediaChannel::SetCall(webrtc::Call* call) {
3450 DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003451 for (const auto& it : receive_channels_) {
3452 TryRemoveAudioRecvStream(it.first);
3453 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003454 call_ = call;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003455 for (const auto& it : receive_channels_) {
3456 TryAddAudioRecvStream(it.first);
3457 }
3458}
3459
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003460bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3461 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3462 // Get the RED encodings from the parameter with no name. This may
3463 // change based on what is discussed on the Jingle list.
3464 // The encoding parameter is of the form "a/b"; we only support where
3465 // a == b. Verify this and parse out the value into red_pt.
3466 // If the parameter value is absent (as it will be until we wire up the
3467 // signaling of this message), use the second codec specified (i.e. the
3468 // one after "red") as the encoding parameter.
3469 int red_pt = -1;
3470 std::string red_params;
3471 CodecParameterMap::const_iterator it = red_codec.params.find("");
3472 if (it != red_codec.params.end()) {
3473 red_params = it->second;
3474 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003475 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003476 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003477 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003478 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3479 return false;
3480 }
3481 } else if (red_codec.params.empty()) {
3482 LOG(LS_WARNING) << "RED params not present, using defaults";
3483 if (all_codecs.size() > 1) {
3484 red_pt = all_codecs[1].id;
3485 }
3486 }
3487
3488 // Try to find red_pt in |codecs|.
3489 std::vector<AudioCodec>::const_iterator codec;
3490 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3491 if (codec->id == red_pt)
3492 break;
3493 }
3494
3495 // If we find the right codec, that will be the codec we pass to
3496 // SetSendCodec, with the desired payload type.
3497 if (codec != all_codecs.end() &&
3498 engine()->FindWebRtcCodec(*codec, send_codec)) {
3499 } else {
3500 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3501 return false;
3502 }
3503
3504 return true;
3505}
3506
3507bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3508 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003509 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003510 return false;
3511 }
3512 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3513 // what we want to do with them.
3514 // engine()->voe().EnableVQMon(voe_channel(), true);
3515 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3516 return true;
3517}
3518
3519bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3520 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3521 for (int i = 0; i < ncodecs; ++i) {
3522 webrtc::CodecInst voe_codec;
3523 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3524 voe_codec.pltype = -1;
3525 if (engine()->voe()->codec()->SetRecPayloadType(
3526 channel, voe_codec) == -1) {
3527 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3528 return false;
3529 }
3530 }
3531 }
3532 return true;
3533}
3534
3535bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3536 if (playout) {
3537 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3538 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3539 LOG_RTCERR1(StartPlayout, channel);
3540 return false;
3541 }
3542 } else {
3543 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3544 engine()->voe()->base()->StopPlayout(channel);
3545 }
3546 return true;
3547}
3548
3549uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3550 bool rtcp) {
3551 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3552 uint32 ssrc = 0;
3553 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003554 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003555 }
3556 return ssrc;
3557}
3558
3559// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3560VoiceMediaChannel::Error
3561 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3562 switch (err_code) {
3563 case 0:
3564 return ERROR_NONE;
3565 case VE_CANNOT_START_RECORDING:
3566 case VE_MIC_VOL_ERROR:
3567 case VE_GET_MIC_VOL_ERROR:
3568 case VE_CANNOT_ACCESS_MIC_VOL:
3569 return ERROR_REC_DEVICE_OPEN_FAILED;
3570 case VE_SATURATION_WARNING:
3571 return ERROR_REC_DEVICE_SATURATION;
3572 case VE_REC_DEVICE_REMOVED:
3573 return ERROR_REC_DEVICE_REMOVED;
3574 case VE_RUNTIME_REC_WARNING:
3575 case VE_RUNTIME_REC_ERROR:
3576 return ERROR_REC_RUNTIME_ERROR;
3577 case VE_CANNOT_START_PLAYOUT:
3578 case VE_SPEAKER_VOL_ERROR:
3579 case VE_GET_SPEAKER_VOL_ERROR:
3580 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3581 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3582 case VE_RUNTIME_PLAY_WARNING:
3583 case VE_RUNTIME_PLAY_ERROR:
3584 return ERROR_PLAY_RUNTIME_ERROR;
3585 case VE_TYPING_NOISE_WARNING:
3586 return ERROR_REC_TYPING_NOISE_DETECTED;
3587 default:
3588 return VoiceMediaChannel::ERROR_OTHER;
3589 }
3590}
3591
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003592bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3593 int channel_id, const RtpHeaderExtension* extension) {
3594 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003595 int id = 0;
3596 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003597 if (extension) {
3598 enable = true;
3599 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003600 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003601 }
3602 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003603 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003604 return false;
3605 }
3606 return true;
3607}
3608
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003609void WebRtcVoiceMediaChannel::TryAddAudioRecvStream(uint32 ssrc) {
3610 DCHECK(thread_checker_.CalledOnValidThread());
3611 // If we are hooked up to a webrtc::Call, create an AudioReceiveStream too.
3612 if (call_ && options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false)) {
3613 DCHECK(receive_streams_.find(ssrc) == receive_streams_.end());
3614 webrtc::AudioReceiveStream::Config config;
3615 config.rtp.remote_ssrc = ssrc;
3616 config.rtp.extensions = recv_rtp_extensions_;
3617 webrtc::AudioReceiveStream* s = call_->CreateAudioReceiveStream(config);
3618 receive_streams_.insert(std::make_pair(ssrc, s));
3619 }
3620}
3621
3622void WebRtcVoiceMediaChannel::TryRemoveAudioRecvStream(uint32 ssrc) {
3623 DCHECK(thread_checker_.CalledOnValidThread());
3624 // If we are hooked up to a webrtc::Call, assume there is an
3625 // AudioReceiveStream to destroy too.
3626 if (call_) {
3627 auto stream_it = receive_streams_.find(ssrc);
3628 if (stream_it != receive_streams_.end()) {
3629 call_->DestroyAudioReceiveStream(stream_it->second);
3630 receive_streams_.erase(stream_it);
3631 }
3632 }
3633}
3634
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003635int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003636 size_t res = 0;
3637 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003638 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003639}
3640
3641int WebRtcSoundclipStream::Rewind() {
3642 mem_.Rewind();
3643 // Return -1 to keep VoiceEngine from looping.
3644 return (loop_) ? 0 : -1;
3645}
3646
3647} // namespace cricket
3648
3649#endif // HAVE_WEBRTC_VOICE