blob: 7f000ab6bbfdffdf19fdf74cec83ad72b0f26104 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#ifdef HAVE_CONFIG_H
29#include <config.h>
30#endif
31
32#ifdef HAVE_WEBRTC_VOICE
33
34#include "talk/media/webrtc/webrtcvoiceengine.h"
35
36#include <algorithm>
37#include <cstdio>
38#include <string>
39#include <vector>
40
Thiago Farinaef883092015-04-06 10:36:41 +000041#include "talk/media/base/audioframe.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000042#include "talk/media/base/audiorenderer.h"
43#include "talk/media/base/constants.h"
44#include "talk/media/base/streamparams.h"
45#include "talk/media/base/voiceprocessor.h"
46#include "talk/media/webrtc/webrtcvoe.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000047#include "webrtc/base/base64.h"
48#include "webrtc/base/byteorder.h"
49#include "webrtc/base/common.h"
50#include "webrtc/base/helpers.h"
51#include "webrtc/base/logging.h"
52#include "webrtc/base/stringencode.h"
53#include "webrtc/base/stringutils.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000054#include "webrtc/common.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055#include "webrtc/modules/audio_processing/include/audio_processing.h"
56
57#ifdef WIN32
58#include <objbase.h> // NOLINT
59#endif
60
61namespace cricket {
62
Brave Yao5225dd82015-03-26 07:39:19 +080063static const int kMaxNumPacketSize = 6;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064struct CodecPref {
65 const char* name;
66 int clockrate;
67 int channels;
68 int payload_type;
69 bool is_multi_rate;
Brave Yao5225dd82015-03-26 07:39:19 +080070 int packet_sizes_ms[kMaxNumPacketSize];
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071};
Brave Yao5225dd82015-03-26 07:39:19 +080072// Note: keep the supported packet sizes in ascending order.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073static const CodecPref kCodecPrefs[] = {
Brave Yao5225dd82015-03-26 07:39:19 +080074 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
75 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
76 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +000077 // G722 should be advertised as 8000 Hz because of the RFC "bug".
Brave Yao5225dd82015-03-26 07:39:19 +080078 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
79 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
80 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
81 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
Brave Yao5225dd82015-03-26 07:39:19 +080082 { kCnCodecName, 32000, 1, 106, false, { } },
83 { kCnCodecName, 16000, 1, 105, false, { } },
84 { kCnCodecName, 8000, 1, 13, false, { } },
85 { kRedCodecName, 8000, 1, 127, false, { } },
86 { kDtmfCodecName, 8000, 1, 126, false, { } },
henrike@webrtc.org28e20752013-07-10 00:45:36 +000087};
88
89// For Linux/Mac, using the default device is done by specifying index 0 for
90// VoE 4.0 and not -1 (which was the case for VoE 3.5).
91//
92// On Windows Vista and newer, Microsoft introduced the concept of "Default
93// Communications Device". This means that there are two types of default
94// devices (old Wave Audio style default and Default Communications Device).
95//
96// On Windows systems which only support Wave Audio style default, uses either
97// -1 or 0 to select the default device.
98//
99// On Windows systems which support both "Default Communication Device" and
100// old Wave Audio style default, use -1 for Default Communications Device and
101// -2 for Wave Audio style default, which is what we want to use for clips.
102// It's not clear yet whether the -2 index is handled properly on other OSes.
103
104#ifdef WIN32
105static const int kDefaultAudioDeviceId = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106#else
107static const int kDefaultAudioDeviceId = 0;
108#endif
109
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110// Parameter used for NACK.
111// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
112static const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000113
114// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000115// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000116
117// Recommended bitrates:
118// 8-12 kb/s for NB speech,
119// 16-20 kb/s for WB speech,
120// 28-40 kb/s for FB speech,
121// 48-64 kb/s for FB mono music, and
122// 64-128 kb/s for FB stereo music.
123// The current implementation applies the following values to mono signals,
124// and multiplies them by 2 for stereo.
125static const int kOpusBitrateNb = 12000;
126static const int kOpusBitrateWb = 20000;
127static const int kOpusBitrateFb = 32000;
128
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000129// Opus bitrate should be in the range between 6000 and 510000.
130static const int kOpusMinBitrate = 6000;
131static const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000132
wu@webrtc.orgde305012013-10-31 15:40:38 +0000133// Default audio dscp value.
134// See http://tools.ietf.org/html/rfc2474 for details.
135// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000136static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000137
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000138// Ensure we open the file in a writeable path on ChromeOS and Android. This
139// workaround can be removed when it's possible to specify a filename for audio
140// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000141//
142// TODO(grunell): Use a string in the options instead of hardcoding it here
143// and let the embedder choose the filename (crbug.com/264223).
144//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000145// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
146// below.
147#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000148static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000149#elif defined(ANDROID)
150static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000151#else
152static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
153#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000154
155// Dumps an AudioCodec in RFC 2327-ish format.
156static std::string ToString(const AudioCodec& codec) {
157 std::stringstream ss;
158 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
159 << " (" << codec.id << ")";
160 return ss.str();
161}
Minyue Li7100dcd2015-03-27 05:05:59 +0100162
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000163static std::string ToString(const webrtc::CodecInst& codec) {
164 std::stringstream ss;
165 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
166 << " (" << codec.pltype << ")";
167 return ss.str();
168}
169
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000170static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000171 const char* delim = "\r\n";
172 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
173 LOG_V(sev) << tok;
174 }
175}
176
177// Severity is an integer because it comes is assumed to be from command line.
178static int SeverityToFilter(int severity) {
179 int filter = webrtc::kTraceNone;
180 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000181 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000182 filter |= webrtc::kTraceAll;
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200183 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000184 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000185 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200186 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000187 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000188 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200189 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000190 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000191 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
192 }
193 return filter;
194}
195
Minyue Li7100dcd2015-03-27 05:05:59 +0100196static bool IsCodec(const AudioCodec& codec, const char* ref_name) {
197 return (_stricmp(codec.name.c_str(), ref_name) == 0);
198}
199
200static bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
201 return (_stricmp(codec.plname, ref_name) == 0);
202}
203
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000204static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
205 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100206 if (IsCodec(codec, kCodecPrefs[i].name) &&
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000207 kCodecPrefs[i].clockrate == codec.plfreq) {
208 return kCodecPrefs[i].is_multi_rate;
209 }
210 }
211 return false;
212}
213
214static bool FindCodec(const std::vector<AudioCodec>& codecs,
215 const AudioCodec& codec,
216 AudioCodec* found_codec) {
217 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
218 it != codecs.end(); ++it) {
219 if (it->Matches(codec)) {
220 if (found_codec != NULL) {
221 *found_codec = *it;
222 }
223 return true;
224 }
225 }
226 return false;
227}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000228
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000229static bool IsNackEnabled(const AudioCodec& codec) {
230 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
231 kParamValueEmpty));
232}
233
Brave Yao5225dd82015-03-26 07:39:19 +0800234static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
235 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
236 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
237 if (packet_size_ms && packet_size_ms <= ptime_ms) {
238 selected_packet_size_ms = packet_size_ms;
239 }
240 }
241 return selected_packet_size_ms;
242}
243
244// If the AudioCodec param kCodecParamPTime is set, then we will set it to codec
245// pacsize if it's valid, or we will pick the next smallest value we support.
246// TODO(Brave): Query supported packet sizes from ACM when the API is ready.
247static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
248 for (const CodecPref& codec_pref : kCodecPrefs) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100249 if ((IsCodec(*codec, codec_pref.name) &&
Brave Yao5225dd82015-03-26 07:39:19 +0800250 codec_pref.clockrate == codec->plfreq) ||
Minyue Li7100dcd2015-03-27 05:05:59 +0100251 IsCodec(*codec, kG722CodecName)) {
Brave Yao5225dd82015-03-26 07:39:19 +0800252 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
253 if (packet_size_ms) {
254 // Convert unit from milli-seconds to samples.
255 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
256 return true;
257 }
258 }
259 }
260 return false;
261}
262
Minyue Li7100dcd2015-03-27 05:05:59 +0100263// Return true if codec.params[feature] == "1", false otherwise.
264static bool IsCodecFeatureEnabled(const AudioCodec& codec,
265 const char* feature) {
266 int value;
267 return codec.GetParam(feature, &value) && value == 1;
268}
269
270// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
271// otherwise. If the value (either from params or codec.bitrate) <=0, use the
272// default configuration. If the value is beyond feasible bit rate of Opus,
273// clamp it. Returns the Opus bit rate for operation.
274static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
275 int bitrate = 0;
276 bool use_param = true;
277 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
278 bitrate = codec.bitrate;
279 use_param = false;
280 }
281 if (bitrate <= 0) {
282 if (max_playback_rate <= 8000) {
283 bitrate = kOpusBitrateNb;
284 } else if (max_playback_rate <= 16000) {
285 bitrate = kOpusBitrateWb;
286 } else {
287 bitrate = kOpusBitrateFb;
288 }
289
290 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
291 bitrate *= 2;
292 }
293 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
294 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
295 std::string rate_source =
296 use_param ? "Codec parameter \"maxaveragebitrate\"" :
297 "Supplied Opus bitrate";
298 LOG(LS_WARNING) << rate_source
299 << " is invalid and is replaced by: "
300 << bitrate;
301 }
302 return bitrate;
303}
304
305// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
306// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
307static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
308 int value;
309 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
310 return value;
311 }
312 return kOpusDefaultMaxPlaybackRate;
313}
314
315static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
316 bool* enable_codec_fec, int* max_playback_rate,
317 bool* enable_codec_dtx) {
318 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
319 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
320 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
321
322 // If OPUS, change what we send according to the "stereo" codec
323 // parameter, and not the "channels" parameter. We set
324 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
325 // the bitrate is not specified, i.e. is <= zero, we set it to the
326 // appropriate default value for mono or stereo Opus.
327
328 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
329 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
330}
331
332// Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
333// which says that G722 should be advertised as 8 kHz although it is a 16 kHz
334// codec.
335static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
336 if (IsCodec(*voe_codec, kG722CodecName)) {
337 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
338 // has changed, and this special case is no longer needed.
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200339 DCHECK(voe_codec->plfreq != new_plfreq);
Minyue Li7100dcd2015-03-27 05:05:59 +0100340 voe_codec->plfreq = new_plfreq;
341 }
342}
343
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000344// Gets the default set of options applied to the engine. Historically, these
345// were supplied as a combination of flags from the channel manager (ec, agc,
346// ns, and highpass) and the rest hardcoded in InitInternal.
347static AudioOptions GetDefaultEngineOptions() {
348 AudioOptions options;
349 options.echo_cancellation.Set(true);
350 options.auto_gain_control.Set(true);
351 options.noise_suppression.Set(true);
352 options.highpass_filter.Set(true);
353 options.stereo_swapping.Set(false);
Henrik Lundin64dad832015-05-11 12:44:23 +0200354 options.audio_jitter_buffer_max_packets.Set(50);
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200355 options.audio_jitter_buffer_fast_accelerate.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000356 options.typing_detection.Set(true);
357 options.conference_mode.Set(false);
358 options.adjust_agc_delta.Set(0);
359 options.experimental_agc.Set(false);
360 options.experimental_aec.Set(false);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100361 options.delay_agnostic_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000362 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000363 options.aec_dump.Set(false);
364 return options;
365}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000366
Minyue Li7100dcd2015-03-27 05:05:59 +0100367static std::string GetEnableString(bool enable) {
368 return enable ? "enable" : "disable";
Brave Yao5225dd82015-03-26 07:39:19 +0800369}
370
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000371WebRtcVoiceEngine::WebRtcVoiceEngine()
372 : voe_wrapper_(new VoEWrapper()),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000373 tracing_(new VoETraceWrapper()),
374 adm_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000375 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
376 is_dumping_aec_(false),
377 desired_local_monitor_enable_(false),
378 tx_processor_ssrc_(0),
379 rx_processor_ssrc_(0) {
380 Construct();
381}
382
383WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000384 VoETraceWrapper* tracing)
385 : voe_wrapper_(voe_wrapper),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000386 tracing_(tracing),
387 adm_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000388 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
389 is_dumping_aec_(false),
390 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000391 tx_processor_ssrc_(0),
392 rx_processor_ssrc_(0) {
393 Construct();
394}
395
396void WebRtcVoiceEngine::Construct() {
397 SetTraceFilter(log_filter_);
398 initialized_ = false;
399 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
400 SetTraceOptions("");
401 if (tracing_->SetTraceCallback(this) == -1) {
402 LOG_RTCERR0(SetTraceCallback);
403 }
404 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
405 LOG_RTCERR0(RegisterVoiceEngineObserver);
406 }
407 // Clear the default agc state.
408 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
409
410 // Load our audio codec list.
411 ConstructCodecs();
412
413 // Load our RTP Header extensions.
414 rtp_header_extensions_.push_back(
415 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
416 kRtpAudioLevelHeaderExtensionDefaultId));
417 rtp_header_extensions_.push_back(
418 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
419 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
420 options_ = GetDefaultEngineOptions();
421}
422
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000423void WebRtcVoiceEngine::ConstructCodecs() {
424 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
425 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
426 for (int i = 0; i < ncodecs; ++i) {
427 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000428 if (GetVoeCodec(i, &voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000429 // Skip uncompressed formats.
Minyue Li7100dcd2015-03-27 05:05:59 +0100430 if (IsCodec(voe_codec, kL16CodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000431 continue;
432 }
433
434 const CodecPref* pref = NULL;
435 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100436 if (IsCodec(voe_codec, kCodecPrefs[j].name) &&
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000437 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
438 kCodecPrefs[j].channels == voe_codec.channels) {
439 pref = &kCodecPrefs[j];
440 break;
441 }
442 }
443
444 if (pref) {
445 // Use the payload type that we've configured in our pref table;
446 // use the offset in our pref table to determine the sort order.
447 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
448 voe_codec.rate, voe_codec.channels,
449 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
450 LOG(LS_INFO) << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100451 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000452 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000453 codec.bitrate = 0;
454 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100455 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000456 // Only add fmtp parameters that differ from the spec.
457 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
458 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000459 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000460 }
461 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
462 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000463 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000464 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000465 codec.SetParam(kCodecParamUseInbandFec, 1);
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000466
467 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000468 // when they can be set to values other than the default.
469 }
470 codecs_.push_back(codec);
471 } else {
472 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
473 }
474 }
475 }
476 // Make sure they are in local preference order.
477 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
478}
479
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000480bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst* codec) {
481 if (voe_wrapper_->codec()->GetCodec(index, *codec) == -1) {
482 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000483 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000484 // Change the sample rate of G722 to 8000 to match SDP.
485 MaybeFixupG722(codec, 8000);
486 return true;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000487}
488
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000489WebRtcVoiceEngine::~WebRtcVoiceEngine() {
490 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
491 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
492 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
493 }
494 if (adm_) {
495 voe_wrapper_.reset();
496 adm_->Release();
497 adm_ = NULL;
498 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000499
500 // Test to see if the media processor was deregistered properly
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200501 DCHECK(SignalRxMediaFrame.is_empty());
502 DCHECK(SignalTxMediaFrame.is_empty());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000503
504 tracing_->SetTraceCallback(NULL);
505}
506
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000507bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200508 DCHECK(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000509 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
510 bool res = InitInternal();
511 if (res) {
512 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
513 } else {
514 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
515 Terminate();
516 }
517 return res;
518}
519
520bool WebRtcVoiceEngine::InitInternal() {
521 // Temporarily turn logging level up for the Init call
522 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000523 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000524 SetTraceFilter(extended_filter);
525 SetTraceOptions("");
526
527 // Init WebRtc VoiceEngine.
528 if (voe_wrapper_->base()->Init(adm_) == -1) {
529 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
530 SetTraceFilter(old_filter);
531 return false;
532 }
533
534 SetTraceFilter(old_filter);
535 SetTraceOptions(log_options_);
536
537 // Log the VoiceEngine version info
538 char buffer[1024] = "";
539 voe_wrapper_->base()->GetVersion(buffer);
540 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000541 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000542
543 // Save the default AGC configuration settings. This must happen before
544 // calling SetOptions or the default will be overwritten.
545 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
546 LOG_RTCERR0(GetAgcConfig);
547 return false;
548 }
549
550 // Set defaults for options, so that ApplyOptions applies them explicitly
551 // when we clear option (channel) overrides. External clients can still
552 // modify the defaults via SetOptions (on the media engine).
553 if (!SetOptions(GetDefaultEngineOptions())) {
554 return false;
555 }
556
557 // Print our codec list again for the call diagnostic log
558 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
559 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
560 it != codecs_.end(); ++it) {
561 LOG(LS_INFO) << ToString(*it);
562 }
563
564 // Disable the DTMF playout when a tone is sent.
565 // PlayDtmfTone will be used if local playout is needed.
566 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
567 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
568 }
569
570 initialized_ = true;
571 return true;
572}
573
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000574void WebRtcVoiceEngine::Terminate() {
575 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
576 initialized_ = false;
577
578 StopAecDump();
579
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000580 voe_wrapper_->base()->Terminate();
581 desired_local_monitor_enable_ = false;
582}
583
584int WebRtcVoiceEngine::GetCapabilities() {
585 return AUDIO_SEND | AUDIO_RECV;
586}
587
Jelena Marusicc28a8962015-05-29 15:05:44 +0200588VoiceMediaChannel* WebRtcVoiceEngine::CreateChannel(
589 const AudioOptions& options) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000590 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
591 if (!ch->valid()) {
592 delete ch;
Jelena Marusicc28a8962015-05-29 15:05:44 +0200593 return nullptr;
594 }
595 if (!ch->SetOptions(options)) {
596 LOG(LS_WARNING) << "Failed to set options while creating channel.";
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000597 }
598 return ch;
599}
600
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000601bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
602 if (!ApplyOptions(options)) {
603 return false;
604 }
605 options_ = options;
606 return true;
607}
608
609bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
610 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
611 if (!ApplyOptions(overrides)) {
612 return false;
613 }
614 option_overrides_ = overrides;
615 return true;
616}
617
618bool WebRtcVoiceEngine::ClearOptionOverrides() {
619 LOG(LS_INFO) << "Clearing option overrides.";
620 AudioOptions options = options_;
621 // Only call ApplyOptions if |options_overrides_| contains overrided options.
622 // ApplyOptions affects NS, AGC other options that is shared between
623 // all WebRtcVoiceEngineChannels.
624 if (option_overrides_ == AudioOptions()) {
625 return true;
626 }
627
628 if (!ApplyOptions(options)) {
629 return false;
630 }
631 option_overrides_ = AudioOptions();
632 return true;
633}
634
635// AudioOptions defaults are set in InitInternal (for options with corresponding
636// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
637bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
638 AudioOptions options = options_in; // The options are modified below.
639 // kEcConference is AEC with high suppression.
640 webrtc::EcModes ec_mode = webrtc::kEcConference;
641 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
642 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
643 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
644 bool aecm_comfort_noise = false;
645 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
646 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
647 << aecm_comfort_noise << " (default is false).";
648 }
649
650#if defined(IOS)
651 // On iOS, VPIO provides built-in EC and AGC.
652 options.echo_cancellation.Set(false);
653 options.auto_gain_control.Set(false);
654#elif defined(ANDROID)
655 ec_mode = webrtc::kEcAecm;
656#endif
657
658#if defined(IOS) || defined(ANDROID)
659 // Set the AGC mode for iOS as well despite disabling it above, to avoid
660 // unsupported configuration errors from webrtc.
661 agc_mode = webrtc::kAgcFixedDigital;
662 options.typing_detection.Set(false);
663 options.experimental_agc.Set(false);
664 options.experimental_aec.Set(false);
665 options.experimental_ns.Set(false);
666#endif
667
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100668 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
669 // where the feature is not supported.
670 bool use_delay_agnostic_aec = false;
671#if !defined(IOS)
672 if (options.delay_agnostic_aec.Get(&use_delay_agnostic_aec)) {
673 if (use_delay_agnostic_aec) {
674 options.echo_cancellation.Set(true);
675 options.experimental_aec.Set(true);
676 ec_mode = webrtc::kEcConference;
677 }
678 }
679#endif
680
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000681 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
682
683 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
684
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000685 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000686 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000687 // Check if platform supports built-in EC. Currently only supported on
688 // Android and in combination with Java based audio layer.
689 // TODO(henrika): investigate possibility to support built-in EC also
690 // in combination with Open SL ES audio.
691 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200692 if (built_in_aec && !use_delay_agnostic_aec) {
693 // Built-in EC exists on this device and use_delay_agnostic_aec is not
694 // overriding it. Enable/Disable it according to the echo_cancellation
695 // audio option.
Bjorn Volcker1d83f1e2015-04-07 15:25:39 +0200696 if (voe_wrapper_->hw()->EnableBuiltInAEC(echo_cancellation) == 0 &&
697 echo_cancellation) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100698 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000699 // i.e., replace the software EC with the built-in EC.
700 options.echo_cancellation.Set(false);
bjornv@webrtc.org3f118232015-03-16 14:22:03 +0000701 echo_cancellation = false;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000702 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
703 }
704 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000705 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
706 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
707 return false;
708 } else {
709 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
710 << " with mode " << ec_mode;
711 }
712#if !defined(ANDROID)
713 // TODO(ajm): Remove the error return on Android from webrtc.
714 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
715 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
716 return false;
717 }
718#endif
719 if (ec_mode == webrtc::kEcAecm) {
720 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
721 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
722 return false;
723 }
724 }
725 }
726
727 bool auto_gain_control;
728 if (options.auto_gain_control.Get(&auto_gain_control)) {
729 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
730 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
731 return false;
732 } else {
733 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
734 << " with mode " << agc_mode;
735 }
736 }
737
738 if (options.tx_agc_target_dbov.IsSet() ||
739 options.tx_agc_digital_compression_gain.IsSet() ||
740 options.tx_agc_limiter.IsSet()) {
741 // Override default_agc_config_. Generally, an unset option means "leave
742 // the VoE bits alone" in this function, so we want whatever is set to be
743 // stored as the new "default". If we didn't, then setting e.g.
744 // tx_agc_target_dbov would reset digital compression gain and limiter
745 // settings.
746 // Also, if we don't update default_agc_config_, then adjust_agc_delta
747 // would be an offset from the original values, and not whatever was set
748 // explicitly.
749 default_agc_config_.targetLeveldBOv =
750 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
751 default_agc_config_.targetLeveldBOv);
752 default_agc_config_.digitalCompressionGaindB =
753 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
754 default_agc_config_.digitalCompressionGaindB);
755 default_agc_config_.limiterEnable =
756 options.tx_agc_limiter.GetWithDefaultIfUnset(
757 default_agc_config_.limiterEnable);
758 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
759 LOG_RTCERR3(SetAgcConfig,
760 default_agc_config_.targetLeveldBOv,
761 default_agc_config_.digitalCompressionGaindB,
762 default_agc_config_.limiterEnable);
763 return false;
764 }
765 }
766
767 bool noise_suppression;
768 if (options.noise_suppression.Get(&noise_suppression)) {
769 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
770 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
771 return false;
772 } else {
773 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
774 << " with mode " << ns_mode;
775 }
776 }
777
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000778 bool highpass_filter;
779 if (options.highpass_filter.Get(&highpass_filter)) {
780 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
781 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
782 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
783 return false;
784 }
785 }
786
787 bool stereo_swapping;
788 if (options.stereo_swapping.Get(&stereo_swapping)) {
789 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
790 voep->EnableStereoChannelSwapping(stereo_swapping);
791 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
792 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
793 return false;
794 }
795 }
796
Henrik Lundin64dad832015-05-11 12:44:23 +0200797 int audio_jitter_buffer_max_packets;
798 if (options.audio_jitter_buffer_max_packets.Get(
799 &audio_jitter_buffer_max_packets)) {
800 LOG(LS_INFO) << "NetEq capacity is " << audio_jitter_buffer_max_packets;
801 voe_config_.Set<webrtc::NetEqCapacityConfig>(
802 new webrtc::NetEqCapacityConfig(audio_jitter_buffer_max_packets));
803 }
804
Henrik Lundin5263b3c2015-06-01 10:29:41 +0200805 bool audio_jitter_buffer_fast_accelerate;
806 if (options.audio_jitter_buffer_fast_accelerate.Get(
807 &audio_jitter_buffer_fast_accelerate)) {
808 LOG(LS_INFO) << "NetEq fast mode? " << audio_jitter_buffer_fast_accelerate;
809 voe_config_.Set<webrtc::NetEqFastAccelerate>(
810 new webrtc::NetEqFastAccelerate(audio_jitter_buffer_fast_accelerate));
811 }
812
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000813 bool typing_detection;
814 if (options.typing_detection.Get(&typing_detection)) {
815 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
816 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
817 // In case of error, log the info and continue
818 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
819 }
820 }
821
822 int adjust_agc_delta;
823 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
824 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
825 if (!AdjustAgcLevel(adjust_agc_delta)) {
826 return false;
827 }
828 }
829
830 bool aec_dump;
831 if (options.aec_dump.Get(&aec_dump)) {
832 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
833 if (aec_dump)
834 StartAecDump(kAecDumpByAudioOptionFilename);
835 else
836 StopAecDump();
837 }
838
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000839 webrtc::Config config;
840
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100841 delay_agnostic_aec_.SetFrom(options.delay_agnostic_aec);
842 bool delay_agnostic_aec;
843 if (delay_agnostic_aec_.Get(&delay_agnostic_aec)) {
844 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << delay_agnostic_aec;
845 config.Set<webrtc::ReportedDelay>(
846 new webrtc::ReportedDelay(!delay_agnostic_aec));
847 }
848
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000849 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000850 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000851 if (experimental_aec_.Get(&experimental_aec)) {
852 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
853 config.Set<webrtc::DelayCorrection>(
854 new webrtc::DelayCorrection(experimental_aec));
855 }
856
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000857 experimental_ns_.SetFrom(options.experimental_ns);
858 bool experimental_ns;
859 if (experimental_ns_.Get(&experimental_ns)) {
860 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
861 config.Set<webrtc::ExperimentalNs>(
862 new webrtc::ExperimentalNs(experimental_ns));
863 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000864
865 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
866 // returns NULL on audio_processing().
867 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
868 if (audioproc) {
869 audioproc->SetExtraOptions(config);
870 }
871
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000872 uint32 recording_sample_rate;
873 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
874 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
875 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
876 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
877 }
878 }
879
880 uint32 playout_sample_rate;
881 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
882 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
883 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
884 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
885 }
886 }
887
888 return true;
889}
890
891bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
892 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
893 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
894 LOG_RTCERR1(SetDelayOffsetMs, offset);
895 return false;
896 }
897
898 return true;
899}
900
901struct ResumeEntry {
902 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
903 : channel(c),
904 playout(p),
905 send(s) {
906 }
907
908 WebRtcVoiceMediaChannel *channel;
909 bool playout;
910 SendFlags send;
911};
912
913// TODO(juberti): Refactor this so that the core logic can be used to set the
914// soundclip device. At that time, reinstate the soundclip pause/resume code.
915bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
916 const Device* out_device) {
917#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000918 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000919 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000920 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000921 kDefaultAudioDeviceId;
922 // The device manager uses -1 as the default device, which was the case for
923 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
924#ifndef WIN32
925 if (-1 == in_id) {
926 in_id = kDefaultAudioDeviceId;
927 }
928 if (-1 == out_id) {
929 out_id = kDefaultAudioDeviceId;
930 }
931#endif
932
933 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
934 in_device->name : "Default device";
935 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
936 out_device->name : "Default device";
937 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
938 << ") and speaker to (id=" << out_id << ", name=" << out_name
939 << ")";
940
941 // If we're running the local monitor, we need to stop it first.
942 bool ret = true;
943 if (!PauseLocalMonitor()) {
944 LOG(LS_WARNING) << "Failed to pause local monitor";
945 ret = false;
946 }
947
948 // Must also pause all audio playback and capture.
949 for (ChannelList::const_iterator i = channels_.begin();
950 i != channels_.end(); ++i) {
951 WebRtcVoiceMediaChannel *channel = *i;
952 if (!channel->PausePlayout()) {
953 LOG(LS_WARNING) << "Failed to pause playout";
954 ret = false;
955 }
956 if (!channel->PauseSend()) {
957 LOG(LS_WARNING) << "Failed to pause send";
958 ret = false;
959 }
960 }
961
962 // Find the recording device id in VoiceEngine and set recording device.
963 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
964 ret = false;
965 }
966 if (ret) {
967 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
968 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
969 ret = false;
970 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +0000971 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
972 if (ap)
973 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000974 }
975
976 // Find the playout device id in VoiceEngine and set playout device.
977 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
978 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
979 ret = false;
980 }
981 if (ret) {
982 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000983 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000984 ret = false;
985 }
986 }
987
988 // Resume all audio playback and capture.
989 for (ChannelList::const_iterator i = channels_.begin();
990 i != channels_.end(); ++i) {
991 WebRtcVoiceMediaChannel *channel = *i;
992 if (!channel->ResumePlayout()) {
993 LOG(LS_WARNING) << "Failed to resume playout";
994 ret = false;
995 }
996 if (!channel->ResumeSend()) {
997 LOG(LS_WARNING) << "Failed to resume send";
998 ret = false;
999 }
1000 }
1001
1002 // Resume local monitor.
1003 if (!ResumeLocalMonitor()) {
1004 LOG(LS_WARNING) << "Failed to resume local monitor";
1005 ret = false;
1006 }
1007
1008 if (ret) {
1009 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1010 << ") and speaker to (id="<< out_id << " name=" << out_name
1011 << ")";
1012 }
1013
1014 return ret;
1015#else
1016 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001017#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001018}
1019
1020bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1021 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1022 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001023#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001024 *rtc_id = dev_id;
1025 return true;
1026#else
1027 // In Windows and Mac, we need to find the VoiceEngine device id by name
1028 // unless the input dev_id is the default device id.
1029 if (kDefaultAudioDeviceId == dev_id) {
1030 *rtc_id = dev_id;
1031 return true;
1032 }
1033
1034 // Get the number of VoiceEngine audio devices.
1035 int count = 0;
1036 if (is_input) {
1037 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1038 LOG_RTCERR0(GetNumOfRecordingDevices);
1039 return false;
1040 }
1041 } else {
1042 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1043 LOG_RTCERR0(GetNumOfPlayoutDevices);
1044 return false;
1045 }
1046 }
1047
1048 for (int i = 0; i < count; ++i) {
1049 char name[128];
1050 char guid[128];
1051 if (is_input) {
1052 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1053 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1054 } else {
1055 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1056 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1057 }
1058
1059 std::string webrtc_name(name);
1060 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1061 *rtc_id = i;
1062 return true;
1063 }
1064 }
1065 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1066 return false;
1067#endif
1068}
1069
1070bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1071 unsigned int ulevel;
1072 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1073 LOG_RTCERR1(GetSpeakerVolume, level);
1074 return false;
1075 }
1076 *level = ulevel;
1077 return true;
1078}
1079
1080bool WebRtcVoiceEngine::SetOutputVolume(int level) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001081 DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001082 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1083 LOG_RTCERR1(SetSpeakerVolume, level);
1084 return false;
1085 }
1086 return true;
1087}
1088
1089int WebRtcVoiceEngine::GetInputLevel() {
1090 unsigned int ulevel;
1091 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1092 static_cast<int>(ulevel) : -1;
1093}
1094
1095bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1096 desired_local_monitor_enable_ = enable;
1097 return ChangeLocalMonitor(desired_local_monitor_enable_);
1098}
1099
1100bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1101 // The voe file api is not available in chrome.
1102 if (!voe_wrapper_->file()) {
1103 return false;
1104 }
1105 if (enable && !monitor_) {
1106 monitor_.reset(new WebRtcMonitorStream);
1107 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1108 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1109 // Must call Stop() because there are some cases where Start will report
1110 // failure but still change the state, and if we leave VE in the on state
1111 // then it could crash later when trying to invoke methods on our monitor.
1112 voe_wrapper_->file()->StopRecordingMicrophone();
1113 monitor_.reset();
1114 return false;
1115 }
1116 } else if (!enable && monitor_) {
1117 voe_wrapper_->file()->StopRecordingMicrophone();
1118 monitor_.reset();
1119 }
1120 return true;
1121}
1122
1123bool WebRtcVoiceEngine::PauseLocalMonitor() {
1124 return ChangeLocalMonitor(false);
1125}
1126
1127bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1128 return ChangeLocalMonitor(desired_local_monitor_enable_);
1129}
1130
1131const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1132 return codecs_;
1133}
1134
1135bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1136 return FindWebRtcCodec(in, NULL);
1137}
1138
1139// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1140bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1141 webrtc::CodecInst* out) {
1142 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1143 for (int i = 0; i < ncodecs; ++i) {
1144 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001145 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001146 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1147 voe_codec.rate, voe_codec.channels, 0);
1148 bool multi_rate = IsCodecMultiRate(voe_codec);
1149 // Allow arbitrary rates for ISAC to be specified.
1150 if (multi_rate) {
1151 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1152 codec.bitrate = 0;
1153 }
1154 if (codec.Matches(in)) {
1155 if (out) {
1156 // Fixup the payload type.
1157 voe_codec.pltype = in.id;
1158
1159 // Set bitrate if specified.
1160 if (multi_rate && in.bitrate != 0) {
1161 voe_codec.rate = in.bitrate;
1162 }
1163
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001164 // Reset G722 sample rate to 16000 to match WebRTC.
1165 MaybeFixupG722(&voe_codec, 16000);
1166
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001167 // Apply codec-specific settings.
Minyue Li7100dcd2015-03-27 05:05:59 +01001168 if (IsCodec(codec, kIsacCodecName)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001169 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001170 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001171 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1172 }
1173 *out = voe_codec;
1174 }
1175 return true;
1176 }
1177 }
1178 }
1179 return false;
1180}
1181const std::vector<RtpHeaderExtension>&
1182WebRtcVoiceEngine::rtp_header_extensions() const {
1183 return rtp_header_extensions_;
1184}
1185
1186void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1187 // if min_sev == -1, we keep the current log level.
1188 if (min_sev >= 0) {
1189 SetTraceFilter(SeverityToFilter(min_sev));
1190 }
1191 log_options_ = filter;
1192 SetTraceOptions(initialized_ ? log_options_ : "");
1193}
1194
1195int WebRtcVoiceEngine::GetLastEngineError() {
1196 return voe_wrapper_->error();
1197}
1198
1199void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1200 log_filter_ = filter;
1201 tracing_->SetTraceFilter(filter);
1202}
1203
1204// We suppport three different logging settings for VoiceEngine:
1205// 1. Observer callback that goes into talk diagnostic logfile.
1206// Use --logfile and --loglevel
1207//
1208// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1209// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1210//
1211// 3. EC log and dump for debugging QualityEngine.
1212// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1213//
1214// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1215// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1216void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1217 // Set encrypted trace file.
1218 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001219 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001220 std::vector<std::string>::iterator tracefile =
1221 std::find(opts.begin(), opts.end(), "tracefile");
1222 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1223 // Write encrypted debug output (at same loglevel) to file
1224 // EncryptedTraceFile no longer supported.
1225 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1226 LOG_RTCERR1(SetTraceFile, *tracefile);
1227 }
1228 }
1229
wu@webrtc.org97077a32013-10-25 21:18:33 +00001230 // Allow trace options to override the trace filter. We default
1231 // it to log_filter_ (as a translation of libjingle log levels)
1232 // elsewhere, but this allows clients to explicitly set webrtc
1233 // log levels.
1234 std::vector<std::string>::iterator tracefilter =
1235 std::find(opts.begin(), opts.end(), "tracefilter");
1236 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001237 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001238 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1239 }
1240 }
1241
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001242 // Set AEC dump file
1243 std::vector<std::string>::iterator recordEC =
1244 std::find(opts.begin(), opts.end(), "recordEC");
1245 if (recordEC != opts.end()) {
1246 ++recordEC;
1247 if (recordEC != opts.end())
1248 StartAecDump(recordEC->c_str());
1249 else
1250 StopAecDump();
1251 }
1252}
1253
1254// Ignore spammy trace messages, mostly from the stats API when we haven't
1255// gotten RTCP info yet from the remote side.
1256bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1257 static const char* kTracesToIgnore[] = {
1258 "\tfailed to GetReportBlockInformation",
1259 "GetRecCodec() failed to get received codec",
1260 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1261 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1262 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1263 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1264 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1265 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1266 "SenderInfoReceived No received SR",
1267 "StatisticsRTP() no statistics available",
1268 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1269 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1270 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1271 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1272 NULL
1273 };
1274 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1275 if (trace.find(*p) != std::string::npos) {
1276 return true;
1277 }
1278 }
1279 return false;
1280}
1281
1282void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1283 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001284 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001285 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001286 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001287 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001288 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001289 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001290 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001291 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001292 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293
1294 // Skip past boilerplate prefix text
1295 if (length < 72) {
1296 std::string msg(trace, length);
1297 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1298 LOG_V(sev) << msg;
1299 } else {
1300 std::string msg(trace + 71, length - 72);
1301 if (!ShouldIgnoreTrace(msg)) {
1302 LOG_V(sev) << "webrtc: " << msg;
1303 }
1304 }
1305}
1306
1307void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001308 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001309 WebRtcVoiceMediaChannel* channel = NULL;
1310 uint32 ssrc = 0;
1311 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1312 << channel_num << ".";
1313 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001314 DCHECK(channel != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001315 channel->OnError(ssrc, err_code);
1316 } else {
1317 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1318 << " could not be found in channel list when error reported.";
1319 }
1320}
1321
1322bool WebRtcVoiceEngine::FindChannelAndSsrc(
1323 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001324 DCHECK(channel != NULL && ssrc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001325
1326 *channel = NULL;
1327 *ssrc = 0;
1328 // Find corresponding channel and ssrc
1329 for (ChannelList::const_iterator it = channels_.begin();
1330 it != channels_.end(); ++it) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001331 DCHECK(*it != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001332 if ((*it)->FindSsrc(channel_num, ssrc)) {
1333 *channel = *it;
1334 return true;
1335 }
1336 }
1337
1338 return false;
1339}
1340
1341// This method will search through the WebRtcVoiceMediaChannels and
1342// obtain the voice engine's channel number.
1343bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1344 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001345 DCHECK(channel_num != NULL);
1346 DCHECK(direction == MPD_RX || direction == MPD_TX);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001347
1348 *channel_num = -1;
1349 // Find corresponding channel for ssrc.
1350 for (ChannelList::const_iterator it = channels_.begin();
1351 it != channels_.end(); ++it) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001352 DCHECK(*it != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001353 if (direction & MPD_RX) {
1354 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1355 }
1356 if (*channel_num == -1 && (direction & MPD_TX)) {
1357 *channel_num = (*it)->GetSendChannelNum(ssrc);
1358 }
1359 if (*channel_num != -1) {
1360 return true;
1361 }
1362 }
1363 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1364 return false;
1365}
1366
1367void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001368 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369 channels_.push_back(channel);
1370}
1371
1372void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001373 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001374 ChannelList::iterator i = std::find(channels_.begin(),
1375 channels_.end(),
1376 channel);
1377 if (i != channels_.end()) {
1378 channels_.erase(i);
1379 }
1380}
1381
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001382// Adjusts the default AGC target level by the specified delta.
1383// NB: If we start messing with other config fields, we'll want
1384// to save the current webrtc::AgcConfig as well.
1385bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1386 webrtc::AgcConfig config = default_agc_config_;
1387 config.targetLeveldBOv -= delta;
1388
1389 LOG(LS_INFO) << "Adjusting AGC level from default -"
1390 << default_agc_config_.targetLeveldBOv << "dB to -"
1391 << config.targetLeveldBOv << "dB";
1392
1393 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1394 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1395 return false;
1396 }
1397 return true;
1398}
1399
Fredrik Solenbergccb49e72015-05-19 11:37:56 +02001400bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001401 if (initialized_) {
1402 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1403 return false;
1404 }
1405 if (adm_) {
1406 adm_->Release();
1407 adm_ = NULL;
1408 }
1409 if (adm) {
1410 adm_ = adm;
1411 adm_->AddRef();
1412 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001413 return true;
1414}
1415
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001416bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1417 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001418 if (!aec_dump_file_stream) {
1419 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001420 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001421 LOG(LS_WARNING) << "Could not close file.";
1422 return false;
1423 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001424 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001425 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001426 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001427 LOG_RTCERR0(StartDebugRecording);
1428 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001429 return false;
1430 }
1431 is_dumping_aec_ = true;
1432 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001433}
1434
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001435bool WebRtcVoiceEngine::RegisterProcessor(
1436 uint32 ssrc,
1437 VoiceProcessor* voice_processor,
1438 MediaProcessorDirection direction) {
1439 bool register_with_webrtc = false;
1440 int channel_id = -1;
1441 bool success = false;
1442 uint32* processor_ssrc = NULL;
1443 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1444 if (voice_processor == NULL || !found_channel) {
1445 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1446 << " foundChannel: " << found_channel;
1447 return false;
1448 }
1449
1450 webrtc::ProcessingTypes processing_type;
1451 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001452 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001453 if (direction == MPD_RX) {
1454 processing_type = webrtc::kPlaybackAllChannelsMixed;
1455 if (SignalRxMediaFrame.is_empty()) {
1456 register_with_webrtc = true;
1457 processor_ssrc = &rx_processor_ssrc_;
1458 }
1459 SignalRxMediaFrame.connect(voice_processor,
1460 &VoiceProcessor::OnFrame);
1461 } else {
1462 processing_type = webrtc::kRecordingPerChannel;
1463 if (SignalTxMediaFrame.is_empty()) {
1464 register_with_webrtc = true;
1465 processor_ssrc = &tx_processor_ssrc_;
1466 }
1467 SignalTxMediaFrame.connect(voice_processor,
1468 &VoiceProcessor::OnFrame);
1469 }
1470 }
1471 if (register_with_webrtc) {
1472 // TODO(janahan): when registering consider instantiating a
1473 // a VoeMediaProcess object and not make the engine extend the interface.
1474 if (voe()->media() && voe()->media()->
1475 RegisterExternalMediaProcessing(channel_id,
1476 processing_type,
1477 *this) != -1) {
1478 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1479 << channel_id;
1480 *processor_ssrc = ssrc;
1481 success = true;
1482 } else {
1483 LOG_RTCERR2(RegisterExternalMediaProcessing,
1484 channel_id,
1485 processing_type);
1486 success = false;
1487 }
1488 } else {
1489 // If we don't have to register with the engine, we just needed to
1490 // connect a new processor, set success to true;
1491 success = true;
1492 }
1493 return success;
1494}
1495
1496bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1497 MediaProcessorDirection channel_direction,
1498 uint32 ssrc,
1499 VoiceProcessor* voice_processor,
1500 MediaProcessorDirection processor_direction) {
1501 bool success = true;
1502 FrameSignal* signal;
1503 webrtc::ProcessingTypes processing_type;
1504 uint32* processor_ssrc = NULL;
1505 if (channel_direction == MPD_RX) {
1506 signal = &SignalRxMediaFrame;
1507 processing_type = webrtc::kPlaybackAllChannelsMixed;
1508 processor_ssrc = &rx_processor_ssrc_;
1509 } else {
1510 signal = &SignalTxMediaFrame;
1511 processing_type = webrtc::kRecordingPerChannel;
1512 processor_ssrc = &tx_processor_ssrc_;
1513 }
1514
1515 int deregister_id = -1;
1516 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001517 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001518 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1519 signal->disconnect(voice_processor);
1520 int channel_id = -1;
1521 bool found_channel = FindChannelNumFromSsrc(ssrc,
1522 channel_direction,
1523 &channel_id);
1524 if (signal->is_empty() && found_channel) {
1525 deregister_id = channel_id;
1526 }
1527 }
1528 }
1529 if (deregister_id != -1) {
1530 if (voe()->media() &&
1531 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1532 processing_type) != -1) {
1533 *processor_ssrc = 0;
1534 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1535 << deregister_id;
1536 } else {
1537 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1538 deregister_id,
1539 processing_type);
1540 success = false;
1541 }
1542 }
1543 return success;
1544}
1545
1546bool WebRtcVoiceEngine::UnregisterProcessor(
1547 uint32 ssrc,
1548 VoiceProcessor* voice_processor,
1549 MediaProcessorDirection direction) {
1550 bool success = true;
1551 if (voice_processor == NULL) {
1552 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1553 << ssrc;
1554 return false;
1555 }
1556 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1557 success = false;
1558 }
1559 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1560 success = false;
1561 }
1562 return success;
1563}
1564
1565// Implementing method from WebRtc VoEMediaProcess interface
1566// Do not lock mux_channel_cs_ in this callback.
1567void WebRtcVoiceEngine::Process(int channel,
1568 webrtc::ProcessingTypes type,
1569 int16_t audio10ms[],
1570 int length,
1571 int sampling_freq,
1572 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001573 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001574 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1575 if (type == webrtc::kPlaybackAllChannelsMixed) {
1576 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1577 } else if (type == webrtc::kRecordingPerChannel) {
1578 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1579 } else {
1580 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1581 << " channel: " << channel << " type: " << type
1582 << " tx_ssrc: " << tx_processor_ssrc_
1583 << " rx_ssrc: " << rx_processor_ssrc_;
1584 }
1585}
1586
1587void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1588 if (!is_dumping_aec_) {
1589 // Start dumping AEC when we are not dumping.
1590 if (voe_wrapper_->processing()->StartDebugRecording(
1591 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001592 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001593 } else {
1594 is_dumping_aec_ = true;
1595 }
1596 }
1597}
1598
1599void WebRtcVoiceEngine::StopAecDump() {
1600 if (is_dumping_aec_) {
1601 // Stop dumping AEC when we are dumping.
1602 if (voe_wrapper_->processing()->StopDebugRecording() !=
1603 webrtc::AudioProcessing::kNoError) {
1604 LOG_RTCERR0(StopDebugRecording);
1605 }
1606 is_dumping_aec_ = false;
1607 }
1608}
1609
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001610int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001611 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001612}
1613
1614int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1615 return CreateVoiceChannel(voe_wrapper_.get());
1616}
1617
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001618class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1619 : public AudioRenderer::Sink {
1620 public:
1621 WebRtcVoiceChannelRenderer(int ch,
1622 webrtc::AudioTransport* voe_audio_transport)
1623 : channel_(ch),
1624 voe_audio_transport_(voe_audio_transport),
1625 renderer_(NULL) {
1626 }
Fredrik Solenbergaaf8ff22015-05-07 16:05:53 +02001627 ~WebRtcVoiceChannelRenderer() override { Stop(); }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001628
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001629 // Starts the rendering by setting a sink to the renderer to get data
1630 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001631 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001632 // TODO(xians): Make sure Start() is called only once.
1633 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001634 rtc::CritScope lock(&lock_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001635 DCHECK(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001636 if (renderer_ != NULL) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001637 DCHECK(renderer_ == renderer);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001638 return;
1639 }
1640
1641 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1642 // in getUserMedia by default.
1643 renderer->AddChannel(channel_);
1644 renderer->SetSink(this);
1645 renderer_ = renderer;
1646 }
1647
1648 // Stops rendering by setting the sink of the renderer to NULL. No data
1649 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001650 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001651 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001652 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001653 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001654 return;
1655
1656 renderer_->RemoveChannel(channel_);
1657 renderer_->SetSink(NULL);
1658 renderer_ = NULL;
1659 }
1660
1661 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001662 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001663 void OnData(const void* audio_data,
1664 int bits_per_sample,
1665 int sample_rate,
1666 int number_of_channels,
1667 int number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001668 voe_audio_transport_->OnData(channel_,
1669 audio_data,
1670 bits_per_sample,
1671 sample_rate,
1672 number_of_channels,
1673 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001674 }
1675
1676 // Callback from the |renderer_| when it is going away. In case Start() has
1677 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001678 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001679 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001680 // Set |renderer_| to NULL to make sure no more callback will get into
1681 // the renderer.
1682 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001683 }
1684
1685 // Accessor to the VoE channel ID.
1686 int channel() const { return channel_; }
1687
1688 private:
1689 const int channel_;
1690 webrtc::AudioTransport* const voe_audio_transport_;
1691
1692 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1693 // PeerConnection will make sure invalidating the pointer before the object
1694 // goes away.
1695 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001696
1697 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001698 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001699};
1700
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001701// WebRtcVoiceMediaChannel
Fredrik Solenberge444a3d2015-05-07 16:42:08 +02001702WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine)
1703 : engine_(engine),
1704 voe_channel_(engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001705 send_bitrate_setting_(false),
1706 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001707 options_(),
1708 dtmf_allowed_(false),
1709 desired_playout_(false),
1710 nack_enabled_(false),
1711 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001712 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001713 desired_send_(SEND_NOTHING),
1714 send_(SEND_NOTHING),
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001715 call_(nullptr),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001716 default_receive_ssrc_(0) {
1717 engine->RegisterChannel(this);
1718 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1719 << voe_channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001720 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001721}
1722
1723WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1724 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1725 << voe_channel();
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001726 DCHECK(receive_streams_.empty() || call_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001727
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001728 // Remove any remaining send streams, the default channel will be deleted
1729 // later.
1730 while (!send_channels_.empty())
1731 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001732
1733 // Unregister ourselves from the engine.
1734 engine()->UnregisterChannel(this);
1735 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001736 while (!receive_channels_.empty()) {
1737 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001738 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001739 DCHECK(receive_streams_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001740
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001741 // Delete the default channel.
1742 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001743}
1744
1745bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1746 LOG(LS_INFO) << "Setting voice channel options: "
1747 << options.ToString();
1748
wu@webrtc.orgde305012013-10-31 15:40:38 +00001749 // Check if DSCP value is changed from previous.
1750 bool dscp_option_changed = (options_.dscp != options.dscp);
1751
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001752 // TODO(xians): Add support to set different options for different send
1753 // streams after we support multiple APMs.
1754
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001755 // We retain all of the existing options, and apply the given ones
1756 // on top. This means there is no way to "clear" options such that
1757 // they go back to the engine default.
1758 options_.SetAll(options);
1759
1760 if (send_ != SEND_NOTHING) {
1761 if (!engine()->SetOptionOverrides(options_)) {
1762 LOG(LS_WARNING) <<
1763 "Failed to engine SetOptionOverrides during channel SetOptions.";
1764 return false;
1765 }
1766 } else {
1767 // Will be interpreted when appropriate.
1768 }
1769
wu@webrtc.org97077a32013-10-25 21:18:33 +00001770 // Receiver-side auto gain control happens per channel, so set it here from
1771 // options. Note that, like conference mode, setting it on the engine won't
1772 // have the desired effect, since voice channels don't inherit options from
1773 // the media engine when those options are applied per-channel.
1774 bool rx_auto_gain_control;
1775 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1776 if (engine()->voe()->processing()->SetRxAgcStatus(
1777 voe_channel(), rx_auto_gain_control,
1778 webrtc::kAgcFixedDigital) == -1) {
1779 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1780 return false;
1781 } else {
1782 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1783 << " with mode " << webrtc::kAgcFixedDigital;
1784 }
1785 }
1786 if (options.rx_agc_target_dbov.IsSet() ||
1787 options.rx_agc_digital_compression_gain.IsSet() ||
1788 options.rx_agc_limiter.IsSet()) {
1789 webrtc::AgcConfig config;
1790 // If only some of the options are being overridden, get the current
1791 // settings for the channel and bail if they aren't available.
1792 if (!options.rx_agc_target_dbov.IsSet() ||
1793 !options.rx_agc_digital_compression_gain.IsSet() ||
1794 !options.rx_agc_limiter.IsSet()) {
1795 if (engine()->voe()->processing()->GetRxAgcConfig(
1796 voe_channel(), config) != 0) {
1797 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1798 << "channel " << voe_channel() << ". Since not all rx "
1799 << "agc options are specified, unable to safely set rx "
1800 << "agc options.";
1801 return false;
1802 }
1803 }
1804 config.targetLeveldBOv =
1805 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1806 config.targetLeveldBOv);
1807 config.digitalCompressionGaindB =
1808 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1809 config.digitalCompressionGaindB);
1810 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1811 config.limiterEnable);
1812 if (engine()->voe()->processing()->SetRxAgcConfig(
1813 voe_channel(), config) == -1) {
1814 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1815 config.digitalCompressionGaindB, config.limiterEnable);
1816 return false;
1817 }
1818 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001819 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001820 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001821 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001822 dscp = kAudioDscpValue;
1823 if (MediaChannel::SetDscp(dscp) != 0) {
1824 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1825 }
1826 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001827
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001828 SetCall(call_);
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001829
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001830 LOG(LS_INFO) << "Set voice channel options. Current options: "
1831 << options_.ToString();
1832 return true;
1833}
1834
1835bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1836 const std::vector<AudioCodec>& codecs) {
1837 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001838 LOG(LS_INFO) << "Setting receive voice codecs:";
1839
1840 std::vector<AudioCodec> new_codecs;
1841 // Find all new codecs. We allow adding new codecs but don't allow changing
1842 // the payload type of codecs that is already configured since we might
1843 // already be receiving packets with that payload type.
1844 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001845 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001846 AudioCodec old_codec;
1847 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1848 if (old_codec.id != it->id) {
1849 LOG(LS_ERROR) << it->name << " payload type changed.";
1850 return false;
1851 }
1852 } else {
1853 new_codecs.push_back(*it);
1854 }
1855 }
1856 if (new_codecs.empty()) {
1857 // There are no new codecs to configure. Already configured codecs are
1858 // never removed.
1859 return true;
1860 }
1861
1862 if (playout_) {
1863 // Receive codecs can not be changed while playing. So we temporarily
1864 // pause playout.
1865 PausePlayout();
1866 }
1867
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001868 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001869 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1870 it != new_codecs.end() && ret; ++it) {
1871 webrtc::CodecInst voe_codec;
1872 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1873 LOG(LS_INFO) << ToString(*it);
1874 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001875 if (default_receive_ssrc_ == 0) {
1876 // Set the receive codecs on the default channel explicitly if the
1877 // default channel is not used by |receive_channels_|, this happens in
1878 // conference mode or in non-conference mode when there is no playout
1879 // channel.
1880 // TODO(xians): Figure out how we use the default channel in conference
1881 // mode.
1882 if (engine()->voe()->codec()->SetRecPayloadType(
1883 voe_channel(), voe_codec) == -1) {
1884 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1885 ret = false;
1886 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001887 }
1888
1889 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001890 for (ChannelMap::iterator it = receive_channels_.begin();
1891 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001892 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001893 it->second->channel(), voe_codec) == -1) {
1894 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001895 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001896 ret = false;
1897 }
1898 }
1899 } else {
1900 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1901 ret = false;
1902 }
1903 }
1904 if (ret) {
1905 recv_codecs_ = codecs;
1906 }
1907
1908 if (desired_playout_ && !playout_) {
1909 ResumePlayout();
1910 }
1911 return ret;
1912}
1913
1914bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001915 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001916 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001917 engine()->voe()->codec()->SetVADStatus(channel, false);
1918 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001919 engine()->voe()->rtp()->SetREDStatus(channel, false);
1920 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001921
1922 // Scan through the list to figure out the codec to use for sending, along
1923 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001924 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001925 webrtc::CodecInst send_codec;
1926 memset(&send_codec, 0, sizeof(send_codec));
1927
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001928 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001929 bool enable_codec_fec = false;
Minyue Li7100dcd2015-03-27 05:05:59 +01001930 bool enable_opus_dtx = false;
minyue@webrtc.org26236952014-10-29 02:27:08 +00001931 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001932
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001933 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001934 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1935 it != codecs.end(); ++it) {
1936 // Ignore codecs we don't know about. The negotiation step should prevent
1937 // this, but double-check to be sure.
1938 webrtc::CodecInst voe_codec;
1939 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001940 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001941 continue;
1942 }
1943
Minyue Li7100dcd2015-03-27 05:05:59 +01001944 if (IsCodec(*it, kDtmfCodecName) || IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001945 // Skip telephone-event/CN codec, which will be handled later.
1946 continue;
1947 }
1948
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001949 // We'll use the first codec in the list to actually send audio data.
1950 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001951 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001952 // used is specified in params.
Minyue Li7100dcd2015-03-27 05:05:59 +01001953 if (IsCodec(*it, kRedCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001954 // Parse out the RED parameters. If we fail, just ignore RED;
1955 // we don't support all possible params/usage scenarios.
1956 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
1957 continue;
1958 }
1959
1960 // Enable redundant encoding of the specified codec. Treat any
1961 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001962 LOG(LS_INFO) << "Enabling RED on channel " << channel;
1963 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
1964 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001965 return false;
1966 }
1967 } else {
1968 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001969 nack_enabled = IsNackEnabled(*it);
Minyue Li7100dcd2015-03-27 05:05:59 +01001970 // For Opus as the send codec, we are to determine inband FEC, maximum
1971 // playback rate, and opus internal dtx.
1972 if (IsCodec(*it, kOpusCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00001973 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
Minyue Li7100dcd2015-03-27 05:05:59 +01001974 &opus_max_playback_rate, &enable_opus_dtx);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001975 }
Brave Yao5225dd82015-03-26 07:39:19 +08001976
1977 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1978 int ptime_ms = 0;
1979 if (it->GetParam(kCodecParamPTime, &ptime_ms)) {
1980 if (!SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
1981 LOG(LS_WARNING) << "Failed to set packet size for codec "
1982 << send_codec.plname;
1983 return false;
1984 }
1985 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001986 }
1987 found_send_codec = true;
1988 break;
1989 }
1990
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001991 if (nack_enabled_ != nack_enabled) {
1992 SetNack(channel, nack_enabled);
1993 nack_enabled_ = nack_enabled;
1994 }
1995
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001996 if (!found_send_codec) {
1997 LOG(LS_WARNING) << "Received empty list of codecs.";
1998 return false;
1999 }
2000
2001 // Set the codec immediately, since SetVADStatus() depends on whether
2002 // the current codec is mono or stereo.
2003 if (!SetSendCodec(channel, send_codec))
2004 return false;
2005
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002006 // FEC should be enabled after SetSendCodec.
2007 if (enable_codec_fec) {
2008 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2009 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002010 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2011 // Enable codec internal FEC. Treat any failure as fatal internal error.
2012 LOG_RTCERR2(SetFECStatus, channel, true);
2013 return false;
2014 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002015 }
2016
Minyue Li7100dcd2015-03-27 05:05:59 +01002017 if (IsCodec(send_codec, kOpusCodecName)) {
2018 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
2019 // send codec has to be Opus.
2020
2021 // Set Opus internal DTX.
2022 LOG(LS_INFO) << "Attempt to "
2023 << GetEnableString(enable_opus_dtx)
2024 << " Opus DTX on channel "
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002025 << channel;
Minyue Li7100dcd2015-03-27 05:05:59 +01002026 if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) {
2027 LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx);
2028 return false;
2029 }
2030
2031 // If opus_max_playback_rate <= 0, the default maximum playback rate
2032 // (48 kHz) will be used.
2033 if (opus_max_playback_rate > 0) {
2034 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
2035 << opus_max_playback_rate
2036 << " Hz on channel "
2037 << channel;
2038 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
2039 channel, opus_max_playback_rate) == -1) {
2040 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate);
2041 return false;
2042 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002043 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002044 }
2045
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002046 // Always update the |send_codec_| to the currently set send codec.
2047 send_codec_.reset(new webrtc::CodecInst(send_codec));
2048
minyue@webrtc.org26236952014-10-29 02:27:08 +00002049 if (send_bitrate_setting_) {
2050 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002051 }
2052
2053 // Loop through the codecs list again to config the telephone-event/CN codec.
2054 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2055 it != codecs.end(); ++it) {
2056 // Ignore codecs we don't know about. The negotiation step should prevent
2057 // this, but double-check to be sure.
2058 webrtc::CodecInst voe_codec;
2059 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2060 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2061 continue;
2062 }
2063
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002064 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2065 // about it.
Minyue Li7100dcd2015-03-27 05:05:59 +01002066 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002067 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2068 channel, it->id) == -1) {
2069 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2070 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002071 }
Minyue Li7100dcd2015-03-27 05:05:59 +01002072 } else if (IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002073 // Turn voice activity detection/comfort noise on if supported.
2074 // Set the wideband CN payload type appropriately.
2075 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002076 webrtc::PayloadFrequencies cn_freq;
2077 switch (it->clockrate) {
2078 case 8000:
2079 cn_freq = webrtc::kFreq8000Hz;
2080 break;
2081 case 16000:
2082 cn_freq = webrtc::kFreq16000Hz;
2083 break;
2084 case 32000:
2085 cn_freq = webrtc::kFreq32000Hz;
2086 break;
2087 default:
2088 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2089 << " not supported.";
2090 continue;
2091 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002092 // Set the CN payloadtype and the VAD status.
2093 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2094 if (cn_freq != webrtc::kFreq8000Hz) {
2095 if (engine()->voe()->codec()->SetSendCNPayloadType(
2096 channel, it->id, cn_freq) == -1) {
2097 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2098 // TODO(ajm): This failure condition will be removed from VoE.
2099 // Restore the return here when we update to a new enough webrtc.
2100 //
2101 // Not returning false because the SetSendCNPayloadType will fail if
2102 // the channel is already sending.
2103 // This can happen if the remote description is applied twice, for
2104 // example in the case of ROAP on top of JSEP, where both side will
2105 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002106 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002107 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002108 // Only turn on VAD if we have a CN payload type that matches the
2109 // clockrate for the codec we are going to use.
Minyue Li7100dcd2015-03-27 05:05:59 +01002110 if (it->clockrate == send_codec.plfreq && send_codec.channels != 2) {
2111 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
2112 // interaction between VAD and Opus FEC.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002113 LOG(LS_INFO) << "Enabling VAD";
2114 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2115 LOG_RTCERR2(SetVADStatus, channel, true);
2116 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002117 }
2118 }
2119 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002120 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002121 return true;
2122}
2123
2124bool WebRtcVoiceMediaChannel::SetSendCodecs(
2125 const std::vector<AudioCodec>& codecs) {
2126 dtmf_allowed_ = false;
2127 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2128 it != codecs.end(); ++it) {
2129 // Find the DTMF telephone event "codec".
Minyue Li7100dcd2015-03-27 05:05:59 +01002130 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002131 dtmf_allowed_ = true;
2132 }
2133 }
2134
2135 // Cache the codecs in order to configure the channel created later.
2136 send_codecs_ = codecs;
2137 for (ChannelMap::iterator iter = send_channels_.begin();
2138 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002139 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002140 return false;
2141 }
2142 }
2143
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002144 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002145 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002146 return true;
2147}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002148
2149void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2150 bool nack_enabled) {
2151 for (ChannelMap::const_iterator it = channels.begin();
2152 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002153 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002154 }
2155}
2156
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002157void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002158 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002159 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002160 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2161 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002162 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002163 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2164 }
2165}
2166
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002167bool WebRtcVoiceMediaChannel::SetSendCodec(
2168 const webrtc::CodecInst& send_codec) {
2169 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2170 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002171 for (ChannelMap::iterator iter = send_channels_.begin();
2172 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002173 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002174 return false;
2175 }
2176
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002177 return true;
2178}
2179
2180bool WebRtcVoiceMediaChannel::SetSendCodec(
2181 int channel, const webrtc::CodecInst& send_codec) {
2182 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2183 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2184
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002185 webrtc::CodecInst current_codec;
2186 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2187 (send_codec == current_codec)) {
2188 // Codec is already configured, we can return without setting it again.
2189 return true;
2190 }
2191
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002192 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2193 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002194 return false;
2195 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002196 return true;
2197}
2198
2199bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2200 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002201 if (receive_extensions_ == extensions) {
2202 return true;
2203 }
2204
2205 // The default channel may or may not be in |receive_channels_|. Set the rtp
2206 // header extensions for default channel regardless.
2207 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2208 return false;
2209 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002210
2211 // Loop through all receive channels and enable/disable the extensions.
2212 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2213 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002214 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2215 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002216 return false;
2217 }
2218 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002219
2220 receive_extensions_ = extensions;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002221
2222 // Recreate AudioReceiveStream:s.
2223 {
2224 std::vector<webrtc::RtpExtension> exts;
2225
2226 const RtpHeaderExtension* audio_level_extension =
2227 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2228 if (audio_level_extension) {
2229 exts.push_back({
2230 kRtpAudioLevelHeaderExtension, audio_level_extension->id});
2231 }
2232
2233 const RtpHeaderExtension* send_time_extension =
2234 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2235 if (send_time_extension) {
2236 exts.push_back({
2237 kRtpAbsoluteSenderTimeHeaderExtension, send_time_extension->id});
2238 }
2239
2240 recv_rtp_extensions_.swap(exts);
2241 SetCall(call_);
2242 }
2243
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002244 return true;
2245}
2246
2247bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2248 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002249 const RtpHeaderExtension* audio_level_extension =
2250 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2251 if (!SetHeaderExtension(
2252 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2253 audio_level_extension)) {
2254 return false;
2255 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002256
2257 const RtpHeaderExtension* send_time_extension =
2258 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2259 if (!SetHeaderExtension(
2260 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2261 send_time_extension)) {
2262 return false;
2263 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002264
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002265 return true;
2266}
2267
2268bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2269 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002270 if (send_extensions_ == extensions) {
2271 return true;
2272 }
2273
2274 // The default channel may or may not be in |send_channels_|. Set the rtp
2275 // header extensions for default channel regardless.
2276
2277 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2278 return false;
2279 }
2280
2281 // Loop through all send channels and enable/disable the extensions.
2282 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2283 channel_it != send_channels_.end(); ++channel_it) {
2284 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2285 extensions)) {
2286 return false;
2287 }
2288 }
2289
2290 send_extensions_ = extensions;
2291 return true;
2292}
2293
2294bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2295 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002296 const RtpHeaderExtension* audio_level_extension =
2297 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002298
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002299 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002300 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002301 audio_level_extension)) {
2302 return false;
2303 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002304
2305 const RtpHeaderExtension* send_time_extension =
2306 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002307 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002308 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002309 send_time_extension)) {
2310 return false;
2311 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002312
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002313 return true;
2314}
2315
2316bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2317 desired_playout_ = playout;
2318 return ChangePlayout(desired_playout_);
2319}
2320
2321bool WebRtcVoiceMediaChannel::PausePlayout() {
2322 return ChangePlayout(false);
2323}
2324
2325bool WebRtcVoiceMediaChannel::ResumePlayout() {
2326 return ChangePlayout(desired_playout_);
2327}
2328
2329bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2330 if (playout_ == playout) {
2331 return true;
2332 }
2333
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002334 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002335 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002336 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002337 // Only toggle the default channel if we don't have any other channels.
2338 result = SetPlayout(voe_channel(), playout);
2339 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002340 for (ChannelMap::iterator it = receive_channels_.begin();
2341 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002342 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002343 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002344 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002345 result = false;
2346 }
2347 }
2348
2349 if (result) {
2350 playout_ = playout;
2351 }
2352 return result;
2353}
2354
2355bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2356 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002357 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002358 return ChangeSend(desired_send_);
2359 return true;
2360}
2361
2362bool WebRtcVoiceMediaChannel::PauseSend() {
2363 return ChangeSend(SEND_NOTHING);
2364}
2365
2366bool WebRtcVoiceMediaChannel::ResumeSend() {
2367 return ChangeSend(desired_send_);
2368}
2369
2370bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2371 if (send_ == send) {
2372 return true;
2373 }
2374
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002375 // Change the settings on each send channel.
2376 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002377 engine()->SetOptionOverrides(options_);
2378
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002379 // Change the settings on each send channel.
2380 for (ChannelMap::iterator iter = send_channels_.begin();
2381 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002382 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002383 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002384 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002385
2386 // Clear up the options after stopping sending.
2387 if (send == SEND_NOTHING)
2388 engine()->ClearOptionOverrides();
2389
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002390 send_ = send;
2391 return true;
2392}
2393
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002394bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2395 if (send == SEND_MICROPHONE) {
2396 if (engine()->voe()->base()->StartSend(channel) == -1) {
2397 LOG_RTCERR1(StartSend, channel);
2398 return false;
2399 }
2400 if (engine()->voe()->file() &&
2401 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2402 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2403 return false;
2404 }
2405 } else { // SEND_NOTHING
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002406 DCHECK(send == SEND_NOTHING);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002407 if (engine()->voe()->base()->StopSend(channel) == -1) {
2408 LOG_RTCERR1(StopSend, channel);
2409 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002410 }
2411 }
2412
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002413 return true;
2414}
2415
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002416// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002417void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2418 if (engine()->voe()->network()->RegisterExternalTransport(
2419 channel, *this) == -1) {
2420 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2421 }
2422
2423 // Enable RTCP (for quality stats and feedback messages)
2424 EnableRtcp(channel);
2425
2426 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2427 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002428
2429 // Set RTP header extension for the new channel.
2430 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002431}
2432
2433bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2434 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2435 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2436 }
2437
2438 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2439 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002440 return false;
2441 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002442
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002443 return true;
2444}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002445
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002446bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2447 // If the default channel is already used for sending create a new channel
2448 // otherwise use the default channel for sending.
2449 int channel = GetSendChannelNum(sp.first_ssrc());
2450 if (channel != -1) {
2451 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2452 return false;
2453 }
2454
2455 bool default_channel_is_available = true;
2456 for (ChannelMap::const_iterator iter = send_channels_.begin();
2457 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002458 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002459 default_channel_is_available = false;
2460 break;
2461 }
2462 }
2463 if (default_channel_is_available) {
2464 channel = voe_channel();
2465 } else {
2466 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002467 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002468 if (channel == -1) {
2469 LOG_RTCERR0(CreateChannel);
2470 return false;
2471 }
2472
2473 ConfigureSendChannel(channel);
2474 }
2475
2476 // Save the channel to send_channels_, so that RemoveSendStream() can still
2477 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002478 webrtc::AudioTransport* audio_transport =
2479 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002480 send_channels_.insert(std::make_pair(
2481 sp.first_ssrc(),
2482 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002483
2484 // Set the send (local) SSRC.
2485 // If there are multiple send SSRCs, we can only set the first one here, and
2486 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2487 // (with a codec requires multiple SSRC(s)).
2488 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2489 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2490 return false;
2491 }
2492
2493 // At this point the channel's local SSRC has been updated. If the channel is
2494 // the default channel make sure that all the receive channels are updated as
2495 // well. Receive channels have to have the same SSRC as the default channel in
2496 // order to send receiver reports with this SSRC.
2497 if (IsDefaultChannel(channel)) {
2498 for (ChannelMap::const_iterator it = receive_channels_.begin();
2499 it != receive_channels_.end(); ++it) {
2500 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002501 if (!IsDefaultChannel(it->second->channel())) {
2502 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002503 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002504 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002505 return false;
2506 }
2507 }
2508 }
2509 }
2510
2511 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002512 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2513 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002514 }
2515
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002516 // Set the current codecs to be used for the new channel.
2517 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002518 return false;
2519
2520 return ChangeSend(channel, desired_send_);
2521}
2522
2523bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2524 ChannelMap::iterator it = send_channels_.find(ssrc);
2525 if (it == send_channels_.end()) {
2526 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2527 << " which doesn't exist.";
2528 return false;
2529 }
2530
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002531 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002532 ChangeSend(channel, SEND_NOTHING);
2533
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002534 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2535 // this will disconnect the audio renderer with the send channel.
2536 delete it->second;
2537 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002538
2539 if (IsDefaultChannel(channel)) {
2540 // Do not delete the default channel since the receive channels depend on
2541 // the default channel, recycle it instead.
2542 ChangeSend(channel, SEND_NOTHING);
2543 } else {
2544 // Clean up and delete the send channel.
2545 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2546 << " with VoiceEngine channel #" << channel << ".";
2547 if (!DeleteChannel(channel))
2548 return false;
2549 }
2550
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002551 if (send_channels_.empty())
2552 ChangeSend(SEND_NOTHING);
2553
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002554 return true;
2555}
2556
2557bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002558 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002559 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002560
2561 if (!VERIFY(sp.ssrcs.size() == 1))
2562 return false;
2563 uint32 ssrc = sp.first_ssrc();
2564
wu@webrtc.org78187522013-10-07 23:32:02 +00002565 if (ssrc == 0) {
2566 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2567 return false;
2568 }
2569
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002570 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2571 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002572 return false;
2573 }
2574
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002575 TryAddAudioRecvStream(ssrc);
2576
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002577 // Reuse default channel for recv stream in non-conference mode call
2578 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002579 webrtc::AudioTransport* audio_transport =
2580 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002581 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002582 LOG(LS_INFO) << "Recv stream " << ssrc << " reuse default channel";
2583 default_receive_ssrc_ = ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002584 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002585 default_receive_ssrc_,
2586 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002587 return SetPlayout(voe_channel(), playout_);
2588 }
2589
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002590 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002591 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002592 if (channel == -1) {
2593 LOG_RTCERR0(CreateChannel);
2594 return false;
2595 }
2596
wu@webrtc.org78187522013-10-07 23:32:02 +00002597 if (!ConfigureRecvChannel(channel)) {
2598 DeleteChannel(channel);
2599 return false;
2600 }
2601
2602 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002603 std::make_pair(
2604 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002605
2606 LOG(LS_INFO) << "New audio stream " << ssrc
2607 << " registered to VoiceEngine channel #"
2608 << channel << ".";
2609 return true;
2610}
2611
2612bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002613 // Configure to use external transport, like our default channel.
2614 if (engine()->voe()->network()->RegisterExternalTransport(
2615 channel, *this) == -1) {
2616 LOG_RTCERR2(SetExternalTransport, channel, this);
2617 return false;
2618 }
2619
2620 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002621 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002622 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2623 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002624 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002625 return false;
2626 }
2627 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002628 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002629 return false;
2630 }
2631
Minyue2013aec2015-05-13 14:14:42 +02002632 // Associate receive channel to default channel (so the receive channel can
2633 // obtain RTT from the send channel)
2634 engine()->voe()->base()->AssociateSendChannel(channel, voe_channel());
2635 LOG(LS_INFO) << "VoiceEngine channel #"
2636 << channel << " is associated with channel #"
2637 << voe_channel() << ".";
2638
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002639 // Use the same recv payload types as our default channel.
2640 ResetRecvCodecs(channel);
2641 if (!recv_codecs_.empty()) {
2642 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2643 it != recv_codecs_.end(); ++it) {
2644 webrtc::CodecInst voe_codec;
2645 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2646 voe_codec.pltype = it->id;
2647 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2648 if (engine()->voe()->codec()->GetRecPayloadType(
2649 voe_channel(), voe_codec) != -1) {
2650 if (engine()->voe()->codec()->SetRecPayloadType(
2651 channel, voe_codec) == -1) {
2652 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2653 return false;
2654 }
2655 }
2656 }
2657 }
2658 }
2659
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002660 if (InConferenceMode()) {
2661 // To be in par with the video, voe_channel() is not used for receiving in
2662 // a conference call.
2663 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2664 // This is the first stream in a multi user meeting. We can now
2665 // disable playback of the default stream. This since the default
2666 // stream will probably have received some initial packets before
2667 // the new stream was added. This will mean that the CN state from
2668 // the default channel will be mixed in with the other streams
2669 // throughout the whole meeting, which might be disturbing.
2670 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2671 SetPlayout(voe_channel(), false);
2672 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002673 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002674 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002675
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002676 // Set RTP header extension for the new channel.
2677 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2678 return false;
2679 }
2680
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002681 return SetPlayout(channel, playout_);
2682}
2683
2684bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002685 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002686 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002687 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002688 if (it == receive_channels_.end()) {
2689 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2690 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002691 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002692 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002693
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002694 TryRemoveAudioRecvStream(ssrc);
2695
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002696 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2697 // will disconnect the audio renderer with the receive channel.
2698 // Cache the channel before the deletion.
2699 const int channel = it->second->channel();
2700 delete it->second;
2701 receive_channels_.erase(it);
2702
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002703 if (ssrc == default_receive_ssrc_) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002704 DCHECK(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002705 // Recycle the default channel is for recv stream.
2706 if (playout_)
2707 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002708
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002709 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002710 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002711 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002712
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002713 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002714 << " with VoiceEngine channel #" << channel << ".";
2715 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002716 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002717
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002718 bool enable_default_channel_playout = false;
2719 if (receive_channels_.empty()) {
2720 // The last stream was removed. We can now enable the default
2721 // channel for new channels to be played out immediately without
2722 // waiting for AddStream messages.
2723 // We do this for both conference mode and non-conference mode.
2724 // TODO(oja): Does the default channel still have it's CN state?
2725 enable_default_channel_playout = true;
2726 }
2727 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2728 default_receive_ssrc_ != 0) {
2729 // Only the default channel is active, enable the playout on default
2730 // channel.
2731 enable_default_channel_playout = true;
2732 }
2733 if (enable_default_channel_playout && playout_) {
2734 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2735 SetPlayout(voe_channel(), true);
2736 }
2737
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002738 return true;
2739}
2740
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002741bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2742 AudioRenderer* renderer) {
2743 ChannelMap::iterator it = receive_channels_.find(ssrc);
2744 if (it == receive_channels_.end()) {
2745 if (renderer) {
2746 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002747 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002748 return false;
2749 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002750
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002751 // The channel likely has gone away, do nothing.
2752 return true;
2753 }
2754
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002755 if (renderer)
2756 it->second->Start(renderer);
2757 else
2758 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002759
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002760 return true;
2761}
2762
2763bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2764 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002765 ChannelMap::iterator it = send_channels_.find(ssrc);
2766 if (it == send_channels_.end()) {
2767 if (renderer) {
2768 // Return an error if trying to set a valid renderer with an invalid ssrc.
2769 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2770 return false;
2771 }
2772
2773 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002774 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002775 }
2776
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002777 if (renderer)
2778 it->second->Start(renderer);
2779 else
2780 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002781
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002782 return true;
2783}
2784
2785bool WebRtcVoiceMediaChannel::GetActiveStreams(
2786 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002787 // In conference mode, the default channel should not be in
2788 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002789 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002790 for (ChannelMap::iterator it = receive_channels_.begin();
2791 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002792 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002793 if (level > 0) {
2794 actives->push_back(std::make_pair(it->first, level));
2795 }
2796 }
2797 return true;
2798}
2799
2800int WebRtcVoiceMediaChannel::GetOutputLevel() {
2801 // return the highest output level of all streams
2802 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002803 for (ChannelMap::iterator it = receive_channels_.begin();
2804 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002805 int level = GetOutputLevel(it->second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002806 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002807 }
2808 return highest;
2809}
2810
2811int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2812 int ret;
2813 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2814 // In case of error, log the info and continue
2815 LOG_RTCERR0(TimeSinceLastTyping);
2816 ret = -1;
2817 } else {
2818 ret *= 1000; // We return ms, webrtc returns seconds.
2819 }
2820 return ret;
2821}
2822
2823void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2824 int cost_per_typing, int reporting_threshold, int penalty_decay,
2825 int type_event_delay) {
2826 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2827 time_window, cost_per_typing,
2828 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2829 // In case of error, log the info and continue
2830 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2831 cost_per_typing, reporting_threshold, penalty_decay,
2832 type_event_delay);
2833 }
2834}
2835
2836bool WebRtcVoiceMediaChannel::SetOutputScaling(
2837 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002838 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002839 // Collect the channels to scale the output volume.
2840 std::vector<int> channels;
2841 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002842 // Default channel is not in receive_channels_ if it is not being used for
2843 // playout.
2844 if (default_receive_ssrc_ == 0)
2845 channels.push_back(voe_channel());
2846 for (ChannelMap::const_iterator it = receive_channels_.begin();
2847 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002848 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002849 }
2850 } else { // Collect only the channel of the specified ssrc.
2851 int channel = GetReceiveChannelNum(ssrc);
2852 if (-1 == channel) {
2853 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2854 return false;
2855 }
2856 channels.push_back(channel);
2857 }
2858
2859 // Scale the output volume for the collected channels. We first normalize to
2860 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002861 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002862 if (scale > 0.0001f) {
2863 left /= scale;
2864 right /= scale;
2865 }
2866 for (std::vector<int>::const_iterator it = channels.begin();
2867 it != channels.end(); ++it) {
2868 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2869 *it, scale)) {
2870 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2871 return false;
2872 }
2873 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2874 *it, static_cast<float>(left), static_cast<float>(right))) {
2875 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2876 // Do not return if fails. SetOutputVolumePan is not available for all
2877 // pltforms.
2878 }
2879 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2880 << " right=" << right * scale
2881 << " for channel " << *it << " and ssrc " << ssrc;
2882 }
2883 return true;
2884}
2885
2886bool WebRtcVoiceMediaChannel::GetOutputScaling(
2887 uint32 ssrc, double* left, double* right) {
2888 if (!left || !right) return false;
2889
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002890 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002891 // Determine which channel based on ssrc.
2892 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2893 if (channel == -1) {
2894 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2895 return false;
2896 }
2897
2898 float scaling;
2899 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2900 channel, scaling)) {
2901 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2902 return false;
2903 }
2904
2905 float left_pan;
2906 float right_pan;
2907 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2908 channel, left_pan, right_pan)) {
2909 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2910 // If GetOutputVolumePan fails, we use the default left and right pan.
2911 left_pan = 1.0f;
2912 right_pan = 1.0f;
2913 }
2914
2915 *left = scaling * left_pan;
2916 *right = scaling * right_pan;
2917 return true;
2918}
2919
2920bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2921 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2922 return true;
2923}
2924
2925bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2926 bool play, bool loop) {
2927 if (!ringback_tone_) {
2928 return false;
2929 }
2930
2931 // The voe file api is not available in chrome.
2932 if (!engine()->voe()->file()) {
2933 return false;
2934 }
2935
2936 // Determine which VoiceEngine channel to play on.
2937 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2938 if (channel == -1) {
2939 return false;
2940 }
2941
2942 // Make sure the ringtone is cued properly, and play it out.
2943 if (play) {
2944 ringback_tone_->set_loop(loop);
2945 ringback_tone_->Rewind();
2946 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2947 ringback_tone_.get()) == -1) {
2948 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2949 LOG(LS_ERROR) << "Unable to start ringback tone";
2950 return false;
2951 }
2952 ringback_channels_.insert(channel);
2953 LOG(LS_INFO) << "Started ringback on channel " << channel;
2954 } else {
2955 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2956 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2957 LOG_RTCERR1(StopPlayingFileLocally, channel);
2958 return false;
2959 }
2960 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2961 ringback_channels_.erase(channel);
2962 }
2963
2964 return true;
2965}
2966
2967bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2968 return dtmf_allowed_;
2969}
2970
2971bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2972 int duration, int flags) {
2973 if (!dtmf_allowed_) {
2974 return false;
2975 }
2976
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002977 // Send the event.
2978 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002979 int channel = -1;
2980 if (ssrc == 0) {
2981 bool default_channel_is_inuse = false;
2982 for (ChannelMap::const_iterator iter = send_channels_.begin();
2983 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002984 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002985 default_channel_is_inuse = true;
2986 break;
2987 }
2988 }
2989 if (default_channel_is_inuse) {
2990 channel = voe_channel();
2991 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002992 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002993 }
2994 } else {
2995 channel = GetSendChannelNum(ssrc);
2996 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002997 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002998 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2999 << ssrc << " is not in use.";
3000 return false;
3001 }
3002 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003003 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3004 channel, event, true, duration) == -1) {
3005 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003006 return false;
3007 }
3008 }
3009
3010 // Play the event.
3011 if (flags & cricket::DF_PLAY) {
3012 // Play DTMF tone locally.
3013 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3014 LOG_RTCERR2(PlayDtmfTone, event, duration);
3015 return false;
3016 }
3017 }
3018
3019 return true;
3020}
3021
wu@webrtc.orga9890802013-12-13 00:21:03 +00003022void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003023 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003024 DCHECK(thread_checker_.CalledOnValidThread());
3025
3026 // If hooked up to a "Call", forward packet there too.
3027 if (call_) {
3028 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3029 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3030 }
3031
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003032 // Pick which channel to send this packet to. If this packet doesn't match
3033 // any multiplexed streams, just send it to the default channel. Otherwise,
3034 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003035 int which_channel =
3036 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003037 if (which_channel == -1) {
3038 which_channel = voe_channel();
3039 }
3040
3041 // Stop any ringback that might be playing on the channel.
3042 // It's possible the ringback has already stopped, ih which case we'll just
3043 // use the opportunity to remove the channel from ringback_channels_.
3044 if (engine()->voe()->file()) {
3045 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3046 if (it != ringback_channels_.end()) {
3047 if (engine()->voe()->file()->IsPlayingFileLocally(
3048 which_channel) == 1) {
3049 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3050 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3051 << " due to incoming media";
3052 }
3053 ringback_channels_.erase(which_channel);
3054 }
3055 }
3056
3057 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003058 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003059 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003060 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003061}
3062
wu@webrtc.orga9890802013-12-13 00:21:03 +00003063void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003064 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003065 DCHECK(thread_checker_.CalledOnValidThread());
3066
3067 // If hooked up to a "Call", forward packet there too.
3068 if (call_) {
3069 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3070 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3071 }
3072
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003073 // Sending channels need all RTCP packets with feedback information.
3074 // Even sender reports can contain attached report blocks.
3075 // Receiving channels need sender reports in order to create
3076 // correct receiver reports.
3077 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003078 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003079 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3080 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003081 }
3082
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003083 // If it is a sender report, find the channel that is listening.
3084 bool has_sent_to_default_channel = false;
3085 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003086 int which_channel =
3087 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003088 if (which_channel != -1) {
3089 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003090 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003091
3092 if (IsDefaultChannel(which_channel))
3093 has_sent_to_default_channel = true;
3094 }
3095 }
3096
3097 // SR may continue RR and any RR entry may correspond to any one of the send
3098 // channels. So all RTCP packets must be forwarded all send channels. VoE
3099 // will filter out RR internally.
3100 for (ChannelMap::iterator iter = send_channels_.begin();
3101 iter != send_channels_.end(); ++iter) {
3102 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003103 if (IsDefaultChannel(iter->second->channel()) &&
3104 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003105 continue;
3106
3107 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003108 iter->second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003109 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003110}
3111
3112bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003113 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3114 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003115 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3116 return false;
3117 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003118 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3119 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003120 return false;
3121 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003122 // We set the AGC to mute state only when all the channels are muted.
3123 // This implementation is not ideal, instead we should signal the AGC when
3124 // the mic channel is muted/unmuted. We can't do it today because there
3125 // is no good way to know which stream is mapping to the mic channel.
3126 bool all_muted = muted;
3127 for (ChannelMap::const_iterator iter = send_channels_.begin();
3128 iter != send_channels_.end() && all_muted; ++iter) {
3129 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3130 all_muted)) {
3131 LOG_RTCERR1(GetInputMute, iter->second->channel());
3132 return false;
3133 }
3134 }
3135
3136 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3137 if (ap)
3138 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003139 return true;
3140}
3141
minyue@webrtc.org26236952014-10-29 02:27:08 +00003142// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3143// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003144bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003145 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003146
minyue@webrtc.org26236952014-10-29 02:27:08 +00003147 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003148}
3149
minyue@webrtc.org26236952014-10-29 02:27:08 +00003150bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3151 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003152
minyue@webrtc.org26236952014-10-29 02:27:08 +00003153 send_bitrate_setting_ = true;
3154 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003155
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003156 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003157 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003158 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003159 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003160 }
3161
minyue@webrtc.org26236952014-10-29 02:27:08 +00003162 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003163 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3164 // SetMaxSendBandwith(0), the second call removes the previous limit.
3165 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003166 return true;
3167
3168 webrtc::CodecInst codec = *send_codec_;
3169 bool is_multi_rate = IsCodecMultiRate(codec);
3170
3171 if (is_multi_rate) {
3172 // If codec is multi-rate then just set the bitrate.
3173 codec.rate = bps;
3174 if (!SetSendCodec(codec)) {
3175 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3176 << " to bitrate " << bps << " bps.";
3177 return false;
3178 }
3179 return true;
3180 } else {
3181 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3182 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3183 // fixed bitrate then ignore.
3184 if (bps < codec.rate) {
3185 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3186 << " to bitrate " << bps << " bps"
3187 << ", requires at least " << codec.rate << " bps.";
3188 return false;
3189 }
3190 return true;
3191 }
3192}
3193
3194bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003195 bool echo_metrics_on = false;
3196 // These can take on valid negative values, so use the lowest possible level
3197 // as default rather than -1.
3198 int echo_return_loss = -100;
3199 int echo_return_loss_enhancement = -100;
3200 // These can also be negative, but in practice -1 is only used to signal
3201 // insufficient data, since the resolution is limited to multiples of 4 ms.
3202 int echo_delay_median_ms = -1;
3203 int echo_delay_std_ms = -1;
3204 if (engine()->voe()->processing()->GetEcMetricsStatus(
3205 echo_metrics_on) != -1 && echo_metrics_on) {
3206 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3207 // here, but it appears to be unsuitable currently. Revisit after this is
3208 // investigated: http://b/issue?id=5666755
3209 int erl, erle, rerl, anlp;
3210 if (engine()->voe()->processing()->GetEchoMetrics(
3211 erl, erle, rerl, anlp) != -1) {
3212 echo_return_loss = erl;
3213 echo_return_loss_enhancement = erle;
3214 }
3215
3216 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003217 float dummy;
3218 if (engine()->voe()->processing()->GetEcDelayMetrics(
3219 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003220 echo_delay_median_ms = median;
3221 echo_delay_std_ms = std;
3222 }
3223 }
3224
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003225 webrtc::CallStatistics cs;
3226 unsigned int ssrc;
3227 webrtc::CodecInst codec;
3228 unsigned int level;
3229
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003230 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3231 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003232 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003233
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003234 // Fill in the sender info, based on what we know, and what the
3235 // remote side told us it got from its RTCP report.
3236 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003237
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003238 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3239 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3240 continue;
3241 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003242
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003243 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003244 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3245 sinfo.bytes_sent = cs.bytesSent;
3246 sinfo.packets_sent = cs.packetsSent;
3247 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3248 // returns 0 to indicate an error value.
3249 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3250
3251 // Get data from the last remote RTCP report. Use default values if no data
3252 // available.
3253 sinfo.fraction_lost = -1.0;
3254 sinfo.jitter_ms = -1;
3255 sinfo.packets_lost = -1;
3256 sinfo.ext_seqnum = -1;
3257 std::vector<webrtc::ReportBlock> receive_blocks;
3258 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3259 channel, &receive_blocks) != -1 &&
3260 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3261 std::vector<webrtc::ReportBlock>::iterator iter;
3262 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3263 ++iter) {
3264 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003265 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003266 // Convert Q8 to floating point.
3267 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3268 // Convert samples to milliseconds.
3269 if (codec.plfreq / 1000 > 0) {
3270 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3271 }
3272 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3273 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3274 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003275 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003276 }
3277 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003278
3279 // Local speech level.
3280 sinfo.audio_level = (engine()->voe()->volume()->
3281 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3282
3283 // TODO(xians): We are injecting the same APM logging to all the send
3284 // channels here because there is no good way to know which send channel
3285 // is using the APM. The correct fix is to allow the send channels to have
3286 // their own APM so that we can feed the correct APM logging to different
3287 // send channels. See issue crbug/264611 .
3288 sinfo.echo_return_loss = echo_return_loss;
3289 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3290 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3291 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003292 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3293 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003294 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003295
3296 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003297 }
3298
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003299 // Build the list of receivers, one for each receiving channel, or 1 in
3300 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003301 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003302 for (ChannelMap::const_iterator it = receive_channels_.begin();
3303 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003304 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003305 }
3306 if (channels.empty()) {
3307 channels.push_back(voe_channel());
3308 }
3309
3310 // Get the SSRC and stats for each receiver, based on our own calculations.
3311 for (std::vector<int>::const_iterator it = channels.begin();
3312 it != channels.end(); ++it) {
3313 memset(&cs, 0, sizeof(cs));
3314 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3315 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3316 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3317 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003318 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003319 rinfo.bytes_rcvd = cs.bytesReceived;
3320 rinfo.packets_rcvd = cs.packetsReceived;
3321 // The next four fields are from the most recently sent RTCP report.
3322 // Convert Q8 to floating point.
3323 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3324 rinfo.packets_lost = cs.cumulativeLost;
3325 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003326 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003327 if (codec.pltype != -1) {
3328 rinfo.codec_name = codec.plname;
3329 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003330 // Convert samples to milliseconds.
3331 if (codec.plfreq / 1000 > 0) {
3332 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3333 }
3334
3335 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3336 webrtc::NetworkStatistics ns;
3337 if (engine()->voe()->neteq() &&
3338 engine()->voe()->neteq()->GetNetworkStatistics(
3339 *it, ns) != -1) {
3340 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3341 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3342 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003343 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003344 rinfo.speech_expand_rate =
3345 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3346 rinfo.secondary_decoded_rate =
3347 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003348 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003349
3350 webrtc::AudioDecodingCallStats ds;
3351 if (engine()->voe()->neteq() &&
3352 engine()->voe()->neteq()->GetDecodingCallStatistics(
3353 *it, &ds) != -1) {
3354 rinfo.decoding_calls_to_silence_generator =
3355 ds.calls_to_silence_generator;
3356 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3357 rinfo.decoding_normal = ds.decoded_normal;
3358 rinfo.decoding_plc = ds.decoded_plc;
3359 rinfo.decoding_cng = ds.decoded_cng;
3360 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3361 }
3362
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003363 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003364 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003365 int playout_buffer_delay_ms = 0;
3366 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003367 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3368 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3369 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003370 }
3371
3372 // Get speech level.
3373 rinfo.audio_level = (engine()->voe()->volume()->
3374 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3375 info->receivers.push_back(rinfo);
3376 }
3377 }
3378
3379 return true;
3380}
3381
3382void WebRtcVoiceMediaChannel::GetLastMediaError(
3383 uint32* ssrc, VoiceMediaChannel::Error* error) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003384 DCHECK(ssrc != NULL);
3385 DCHECK(error != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003386 FindSsrc(voe_channel(), ssrc);
3387 *error = WebRtcErrorToChannelError(GetLastEngineError());
3388}
3389
3390bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003391 rtc::CritScope lock(&receive_channels_cs_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003392 DCHECK(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003393 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003394 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3395 // This means the error is not limited to a specific channel. Signal the
3396 // message using ssrc=0. If the current channel is sending, use this
3397 // channel for sending the message.
3398 *ssrc = 0;
3399 return true;
3400 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003401 // Check whether this is a sending channel.
3402 for (ChannelMap::const_iterator it = send_channels_.begin();
3403 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003404 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003405 // This is a sending channel.
3406 uint32 local_ssrc = 0;
3407 if (engine()->voe()->rtp()->GetLocalSSRC(
3408 channel_num, local_ssrc) != -1) {
3409 *ssrc = local_ssrc;
3410 }
3411 return true;
3412 }
3413 }
3414
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003415 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003416 for (ChannelMap::const_iterator it = receive_channels_.begin();
3417 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003418 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003419 *ssrc = it->first;
3420 return true;
3421 }
3422 }
3423 }
3424 return false;
3425}
3426
3427void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003428 if (error == VE_TYPING_NOISE_WARNING) {
3429 typing_noise_detected_ = true;
3430 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3431 typing_noise_detected_ = false;
3432 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003433 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3434}
3435
3436int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3437 unsigned int ulevel;
3438 int ret =
3439 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3440 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3441}
3442
3443int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003444 ChannelMap::iterator it = receive_channels_.find(ssrc);
3445 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003446 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003447 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3448}
3449
3450int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003451 ChannelMap::iterator it = send_channels_.find(ssrc);
3452 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003453 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003454
3455 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003456}
3457
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003458void WebRtcVoiceMediaChannel::SetCall(webrtc::Call* call) {
3459 DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003460 for (const auto& it : receive_channels_) {
3461 TryRemoveAudioRecvStream(it.first);
3462 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003463 call_ = call;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003464 for (const auto& it : receive_channels_) {
3465 TryAddAudioRecvStream(it.first);
3466 }
3467}
3468
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003469bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3470 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3471 // Get the RED encodings from the parameter with no name. This may
3472 // change based on what is discussed on the Jingle list.
3473 // The encoding parameter is of the form "a/b"; we only support where
3474 // a == b. Verify this and parse out the value into red_pt.
3475 // If the parameter value is absent (as it will be until we wire up the
3476 // signaling of this message), use the second codec specified (i.e. the
3477 // one after "red") as the encoding parameter.
3478 int red_pt = -1;
3479 std::string red_params;
3480 CodecParameterMap::const_iterator it = red_codec.params.find("");
3481 if (it != red_codec.params.end()) {
3482 red_params = it->second;
3483 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003484 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003485 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003486 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003487 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3488 return false;
3489 }
3490 } else if (red_codec.params.empty()) {
3491 LOG(LS_WARNING) << "RED params not present, using defaults";
3492 if (all_codecs.size() > 1) {
3493 red_pt = all_codecs[1].id;
3494 }
3495 }
3496
3497 // Try to find red_pt in |codecs|.
3498 std::vector<AudioCodec>::const_iterator codec;
3499 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3500 if (codec->id == red_pt)
3501 break;
3502 }
3503
3504 // If we find the right codec, that will be the codec we pass to
3505 // SetSendCodec, with the desired payload type.
3506 if (codec != all_codecs.end() &&
3507 engine()->FindWebRtcCodec(*codec, send_codec)) {
3508 } else {
3509 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3510 return false;
3511 }
3512
3513 return true;
3514}
3515
3516bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3517 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003518 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003519 return false;
3520 }
3521 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3522 // what we want to do with them.
3523 // engine()->voe().EnableVQMon(voe_channel(), true);
3524 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3525 return true;
3526}
3527
3528bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3529 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3530 for (int i = 0; i < ncodecs; ++i) {
3531 webrtc::CodecInst voe_codec;
3532 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3533 voe_codec.pltype = -1;
3534 if (engine()->voe()->codec()->SetRecPayloadType(
3535 channel, voe_codec) == -1) {
3536 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3537 return false;
3538 }
3539 }
3540 }
3541 return true;
3542}
3543
3544bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3545 if (playout) {
3546 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3547 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3548 LOG_RTCERR1(StartPlayout, channel);
3549 return false;
3550 }
3551 } else {
3552 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3553 engine()->voe()->base()->StopPlayout(channel);
3554 }
3555 return true;
3556}
3557
3558uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3559 bool rtcp) {
3560 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3561 uint32 ssrc = 0;
3562 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003563 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003564 }
3565 return ssrc;
3566}
3567
3568// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3569VoiceMediaChannel::Error
3570 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3571 switch (err_code) {
3572 case 0:
3573 return ERROR_NONE;
3574 case VE_CANNOT_START_RECORDING:
3575 case VE_MIC_VOL_ERROR:
3576 case VE_GET_MIC_VOL_ERROR:
3577 case VE_CANNOT_ACCESS_MIC_VOL:
3578 return ERROR_REC_DEVICE_OPEN_FAILED;
3579 case VE_SATURATION_WARNING:
3580 return ERROR_REC_DEVICE_SATURATION;
3581 case VE_REC_DEVICE_REMOVED:
3582 return ERROR_REC_DEVICE_REMOVED;
3583 case VE_RUNTIME_REC_WARNING:
3584 case VE_RUNTIME_REC_ERROR:
3585 return ERROR_REC_RUNTIME_ERROR;
3586 case VE_CANNOT_START_PLAYOUT:
3587 case VE_SPEAKER_VOL_ERROR:
3588 case VE_GET_SPEAKER_VOL_ERROR:
3589 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3590 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3591 case VE_RUNTIME_PLAY_WARNING:
3592 case VE_RUNTIME_PLAY_ERROR:
3593 return ERROR_PLAY_RUNTIME_ERROR;
3594 case VE_TYPING_NOISE_WARNING:
3595 return ERROR_REC_TYPING_NOISE_DETECTED;
3596 default:
3597 return VoiceMediaChannel::ERROR_OTHER;
3598 }
3599}
3600
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003601bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3602 int channel_id, const RtpHeaderExtension* extension) {
3603 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003604 int id = 0;
3605 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003606 if (extension) {
3607 enable = true;
3608 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003609 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003610 }
3611 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003612 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003613 return false;
3614 }
3615 return true;
3616}
3617
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003618void WebRtcVoiceMediaChannel::TryAddAudioRecvStream(uint32 ssrc) {
3619 DCHECK(thread_checker_.CalledOnValidThread());
3620 // If we are hooked up to a webrtc::Call, create an AudioReceiveStream too.
3621 if (call_ && options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false)) {
3622 DCHECK(receive_streams_.find(ssrc) == receive_streams_.end());
3623 webrtc::AudioReceiveStream::Config config;
3624 config.rtp.remote_ssrc = ssrc;
3625 config.rtp.extensions = recv_rtp_extensions_;
3626 webrtc::AudioReceiveStream* s = call_->CreateAudioReceiveStream(config);
3627 receive_streams_.insert(std::make_pair(ssrc, s));
3628 }
3629}
3630
3631void WebRtcVoiceMediaChannel::TryRemoveAudioRecvStream(uint32 ssrc) {
3632 DCHECK(thread_checker_.CalledOnValidThread());
3633 // If we are hooked up to a webrtc::Call, assume there is an
3634 // AudioReceiveStream to destroy too.
3635 if (call_) {
3636 auto stream_it = receive_streams_.find(ssrc);
3637 if (stream_it != receive_streams_.end()) {
3638 call_->DestroyAudioReceiveStream(stream_it->second);
3639 receive_streams_.erase(stream_it);
3640 }
3641 }
3642}
3643
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003644int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003645 size_t res = 0;
3646 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003647 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003648}
3649
3650int WebRtcSoundclipStream::Rewind() {
3651 mem_.Rewind();
3652 // Return -1 to keep VoiceEngine from looping.
3653 return (loop_) ? 0 : -1;
3654}
3655
3656} // namespace cricket
3657
3658#endif // HAVE_WEBRTC_VOICE