blob: 57405ca7438792645ebcc5ee2a82f052b1c09da4 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#ifdef HAVE_CONFIG_H
29#include <config.h>
30#endif
31
32#ifdef HAVE_WEBRTC_VOICE
33
34#include "talk/media/webrtc/webrtcvoiceengine.h"
35
36#include <algorithm>
37#include <cstdio>
38#include <string>
39#include <vector>
40
Thiago Farinaef883092015-04-06 10:36:41 +000041#include "talk/media/base/audioframe.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000042#include "talk/media/base/audiorenderer.h"
43#include "talk/media/base/constants.h"
44#include "talk/media/base/streamparams.h"
45#include "talk/media/base/voiceprocessor.h"
46#include "talk/media/webrtc/webrtcvoe.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000047#include "webrtc/base/base64.h"
48#include "webrtc/base/byteorder.h"
49#include "webrtc/base/common.h"
50#include "webrtc/base/helpers.h"
51#include "webrtc/base/logging.h"
52#include "webrtc/base/stringencode.h"
53#include "webrtc/base/stringutils.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000054#include "webrtc/common.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055#include "webrtc/modules/audio_processing/include/audio_processing.h"
56
57#ifdef WIN32
58#include <objbase.h> // NOLINT
59#endif
60
61namespace cricket {
62
Brave Yao5225dd82015-03-26 07:39:19 +080063static const int kMaxNumPacketSize = 6;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000064struct CodecPref {
65 const char* name;
66 int clockrate;
67 int channels;
68 int payload_type;
69 bool is_multi_rate;
Brave Yao5225dd82015-03-26 07:39:19 +080070 int packet_sizes_ms[kMaxNumPacketSize];
henrike@webrtc.org28e20752013-07-10 00:45:36 +000071};
Brave Yao5225dd82015-03-26 07:39:19 +080072// Note: keep the supported packet sizes in ascending order.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000073static const CodecPref kCodecPrefs[] = {
Brave Yao5225dd82015-03-26 07:39:19 +080074 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
75 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
76 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +000077 // G722 should be advertised as 8000 Hz because of the RFC "bug".
Brave Yao5225dd82015-03-26 07:39:19 +080078 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
79 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
80 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
81 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
Brave Yao5225dd82015-03-26 07:39:19 +080082 { kCnCodecName, 32000, 1, 106, false, { } },
83 { kCnCodecName, 16000, 1, 105, false, { } },
84 { kCnCodecName, 8000, 1, 13, false, { } },
85 { kRedCodecName, 8000, 1, 127, false, { } },
86 { kDtmfCodecName, 8000, 1, 126, false, { } },
henrike@webrtc.org28e20752013-07-10 00:45:36 +000087};
88
89// For Linux/Mac, using the default device is done by specifying index 0 for
90// VoE 4.0 and not -1 (which was the case for VoE 3.5).
91//
92// On Windows Vista and newer, Microsoft introduced the concept of "Default
93// Communications Device". This means that there are two types of default
94// devices (old Wave Audio style default and Default Communications Device).
95//
96// On Windows systems which only support Wave Audio style default, uses either
97// -1 or 0 to select the default device.
98//
99// On Windows systems which support both "Default Communication Device" and
100// old Wave Audio style default, use -1 for Default Communications Device and
101// -2 for Wave Audio style default, which is what we want to use for clips.
102// It's not clear yet whether the -2 index is handled properly on other OSes.
103
104#ifdef WIN32
105static const int kDefaultAudioDeviceId = -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106#else
107static const int kDefaultAudioDeviceId = 0;
108#endif
109
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110// Parameter used for NACK.
111// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
112static const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000113
114// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000115// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000116
117// Recommended bitrates:
118// 8-12 kb/s for NB speech,
119// 16-20 kb/s for WB speech,
120// 28-40 kb/s for FB speech,
121// 48-64 kb/s for FB mono music, and
122// 64-128 kb/s for FB stereo music.
123// The current implementation applies the following values to mono signals,
124// and multiplies them by 2 for stereo.
125static const int kOpusBitrateNb = 12000;
126static const int kOpusBitrateWb = 20000;
127static const int kOpusBitrateFb = 32000;
128
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000129// Opus bitrate should be in the range between 6000 and 510000.
130static const int kOpusMinBitrate = 6000;
131static const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000132
wu@webrtc.orgde305012013-10-31 15:40:38 +0000133// Default audio dscp value.
134// See http://tools.ietf.org/html/rfc2474 for details.
135// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000136static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000137
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000138// Ensure we open the file in a writeable path on ChromeOS and Android. This
139// workaround can be removed when it's possible to specify a filename for audio
140// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000141//
142// TODO(grunell): Use a string in the options instead of hardcoding it here
143// and let the embedder choose the filename (crbug.com/264223).
144//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000145// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
146// below.
147#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000148static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000149#elif defined(ANDROID)
150static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000151#else
152static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
153#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000154
155// Dumps an AudioCodec in RFC 2327-ish format.
156static std::string ToString(const AudioCodec& codec) {
157 std::stringstream ss;
158 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
159 << " (" << codec.id << ")";
160 return ss.str();
161}
Minyue Li7100dcd2015-03-27 05:05:59 +0100162
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000163static std::string ToString(const webrtc::CodecInst& codec) {
164 std::stringstream ss;
165 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
166 << " (" << codec.pltype << ")";
167 return ss.str();
168}
169
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000170static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000171 const char* delim = "\r\n";
172 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
173 LOG_V(sev) << tok;
174 }
175}
176
177// Severity is an integer because it comes is assumed to be from command line.
178static int SeverityToFilter(int severity) {
179 int filter = webrtc::kTraceNone;
180 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000181 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000182 filter |= webrtc::kTraceAll;
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200183 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000184 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000185 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200186 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000187 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000188 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
Henrik Kjellander7c027b62015-04-22 13:21:30 +0200189 FALLTHROUGH();
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000190 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000191 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
192 }
193 return filter;
194}
195
Minyue Li7100dcd2015-03-27 05:05:59 +0100196static bool IsCodec(const AudioCodec& codec, const char* ref_name) {
197 return (_stricmp(codec.name.c_str(), ref_name) == 0);
198}
199
200static bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
201 return (_stricmp(codec.plname, ref_name) == 0);
202}
203
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000204static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
205 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100206 if (IsCodec(codec, kCodecPrefs[i].name) &&
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000207 kCodecPrefs[i].clockrate == codec.plfreq) {
208 return kCodecPrefs[i].is_multi_rate;
209 }
210 }
211 return false;
212}
213
214static bool FindCodec(const std::vector<AudioCodec>& codecs,
215 const AudioCodec& codec,
216 AudioCodec* found_codec) {
217 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
218 it != codecs.end(); ++it) {
219 if (it->Matches(codec)) {
220 if (found_codec != NULL) {
221 *found_codec = *it;
222 }
223 return true;
224 }
225 }
226 return false;
227}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000228
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000229static bool IsNackEnabled(const AudioCodec& codec) {
230 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
231 kParamValueEmpty));
232}
233
Brave Yao5225dd82015-03-26 07:39:19 +0800234static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
235 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
236 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
237 if (packet_size_ms && packet_size_ms <= ptime_ms) {
238 selected_packet_size_ms = packet_size_ms;
239 }
240 }
241 return selected_packet_size_ms;
242}
243
244// If the AudioCodec param kCodecParamPTime is set, then we will set it to codec
245// pacsize if it's valid, or we will pick the next smallest value we support.
246// TODO(Brave): Query supported packet sizes from ACM when the API is ready.
247static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
248 for (const CodecPref& codec_pref : kCodecPrefs) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100249 if ((IsCodec(*codec, codec_pref.name) &&
Brave Yao5225dd82015-03-26 07:39:19 +0800250 codec_pref.clockrate == codec->plfreq) ||
Minyue Li7100dcd2015-03-27 05:05:59 +0100251 IsCodec(*codec, kG722CodecName)) {
Brave Yao5225dd82015-03-26 07:39:19 +0800252 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
253 if (packet_size_ms) {
254 // Convert unit from milli-seconds to samples.
255 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
256 return true;
257 }
258 }
259 }
260 return false;
261}
262
Minyue Li7100dcd2015-03-27 05:05:59 +0100263// Return true if codec.params[feature] == "1", false otherwise.
264static bool IsCodecFeatureEnabled(const AudioCodec& codec,
265 const char* feature) {
266 int value;
267 return codec.GetParam(feature, &value) && value == 1;
268}
269
270// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
271// otherwise. If the value (either from params or codec.bitrate) <=0, use the
272// default configuration. If the value is beyond feasible bit rate of Opus,
273// clamp it. Returns the Opus bit rate for operation.
274static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
275 int bitrate = 0;
276 bool use_param = true;
277 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
278 bitrate = codec.bitrate;
279 use_param = false;
280 }
281 if (bitrate <= 0) {
282 if (max_playback_rate <= 8000) {
283 bitrate = kOpusBitrateNb;
284 } else if (max_playback_rate <= 16000) {
285 bitrate = kOpusBitrateWb;
286 } else {
287 bitrate = kOpusBitrateFb;
288 }
289
290 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
291 bitrate *= 2;
292 }
293 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
294 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
295 std::string rate_source =
296 use_param ? "Codec parameter \"maxaveragebitrate\"" :
297 "Supplied Opus bitrate";
298 LOG(LS_WARNING) << rate_source
299 << " is invalid and is replaced by: "
300 << bitrate;
301 }
302 return bitrate;
303}
304
305// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
306// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
307static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
308 int value;
309 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
310 return value;
311 }
312 return kOpusDefaultMaxPlaybackRate;
313}
314
315static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
316 bool* enable_codec_fec, int* max_playback_rate,
317 bool* enable_codec_dtx) {
318 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
319 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
320 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
321
322 // If OPUS, change what we send according to the "stereo" codec
323 // parameter, and not the "channels" parameter. We set
324 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
325 // the bitrate is not specified, i.e. is <= zero, we set it to the
326 // appropriate default value for mono or stereo Opus.
327
328 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
329 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
330}
331
332// Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
333// which says that G722 should be advertised as 8 kHz although it is a 16 kHz
334// codec.
335static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
336 if (IsCodec(*voe_codec, kG722CodecName)) {
337 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
338 // has changed, and this special case is no longer needed.
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200339 DCHECK(voe_codec->plfreq != new_plfreq);
Minyue Li7100dcd2015-03-27 05:05:59 +0100340 voe_codec->plfreq = new_plfreq;
341 }
342}
343
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000344// Gets the default set of options applied to the engine. Historically, these
345// were supplied as a combination of flags from the channel manager (ec, agc,
346// ns, and highpass) and the rest hardcoded in InitInternal.
347static AudioOptions GetDefaultEngineOptions() {
348 AudioOptions options;
349 options.echo_cancellation.Set(true);
350 options.auto_gain_control.Set(true);
351 options.noise_suppression.Set(true);
352 options.highpass_filter.Set(true);
353 options.stereo_swapping.Set(false);
Henrik Lundin64dad832015-05-11 12:44:23 +0200354 options.audio_jitter_buffer_max_packets.Set(50);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000355 options.typing_detection.Set(true);
356 options.conference_mode.Set(false);
357 options.adjust_agc_delta.Set(0);
358 options.experimental_agc.Set(false);
359 options.experimental_aec.Set(false);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100360 options.delay_agnostic_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000361 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000362 options.aec_dump.Set(false);
363 return options;
364}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000365
Minyue Li7100dcd2015-03-27 05:05:59 +0100366static std::string GetEnableString(bool enable) {
367 return enable ? "enable" : "disable";
Brave Yao5225dd82015-03-26 07:39:19 +0800368}
369
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000370WebRtcVoiceEngine::WebRtcVoiceEngine()
371 : voe_wrapper_(new VoEWrapper()),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000372 tracing_(new VoETraceWrapper()),
373 adm_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000374 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
375 is_dumping_aec_(false),
376 desired_local_monitor_enable_(false),
377 tx_processor_ssrc_(0),
378 rx_processor_ssrc_(0) {
379 Construct();
380}
381
382WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000383 VoETraceWrapper* tracing)
384 : voe_wrapper_(voe_wrapper),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000385 tracing_(tracing),
386 adm_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000387 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
388 is_dumping_aec_(false),
389 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000390 tx_processor_ssrc_(0),
391 rx_processor_ssrc_(0) {
392 Construct();
393}
394
395void WebRtcVoiceEngine::Construct() {
396 SetTraceFilter(log_filter_);
397 initialized_ = false;
398 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
399 SetTraceOptions("");
400 if (tracing_->SetTraceCallback(this) == -1) {
401 LOG_RTCERR0(SetTraceCallback);
402 }
403 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
404 LOG_RTCERR0(RegisterVoiceEngineObserver);
405 }
406 // Clear the default agc state.
407 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
408
409 // Load our audio codec list.
410 ConstructCodecs();
411
412 // Load our RTP Header extensions.
413 rtp_header_extensions_.push_back(
414 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
415 kRtpAudioLevelHeaderExtensionDefaultId));
416 rtp_header_extensions_.push_back(
417 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
418 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
419 options_ = GetDefaultEngineOptions();
420}
421
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000422void WebRtcVoiceEngine::ConstructCodecs() {
423 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
424 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
425 for (int i = 0; i < ncodecs; ++i) {
426 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000427 if (GetVoeCodec(i, &voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000428 // Skip uncompressed formats.
Minyue Li7100dcd2015-03-27 05:05:59 +0100429 if (IsCodec(voe_codec, kL16CodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000430 continue;
431 }
432
433 const CodecPref* pref = NULL;
434 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100435 if (IsCodec(voe_codec, kCodecPrefs[j].name) &&
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000436 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
437 kCodecPrefs[j].channels == voe_codec.channels) {
438 pref = &kCodecPrefs[j];
439 break;
440 }
441 }
442
443 if (pref) {
444 // Use the payload type that we've configured in our pref table;
445 // use the offset in our pref table to determine the sort order.
446 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
447 voe_codec.rate, voe_codec.channels,
448 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
449 LOG(LS_INFO) << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100450 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000451 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000452 codec.bitrate = 0;
453 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100454 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000455 // Only add fmtp parameters that differ from the spec.
456 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
457 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000458 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000459 }
460 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
461 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000462 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000463 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000464 codec.SetParam(kCodecParamUseInbandFec, 1);
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000465
466 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000467 // when they can be set to values other than the default.
468 }
469 codecs_.push_back(codec);
470 } else {
471 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
472 }
473 }
474 }
475 // Make sure they are in local preference order.
476 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
477}
478
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000479bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst* codec) {
480 if (voe_wrapper_->codec()->GetCodec(index, *codec) == -1) {
481 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000482 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000483 // Change the sample rate of G722 to 8000 to match SDP.
484 MaybeFixupG722(codec, 8000);
485 return true;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000486}
487
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000488WebRtcVoiceEngine::~WebRtcVoiceEngine() {
489 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
490 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
491 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
492 }
493 if (adm_) {
494 voe_wrapper_.reset();
495 adm_->Release();
496 adm_ = NULL;
497 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000498
499 // Test to see if the media processor was deregistered properly
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200500 DCHECK(SignalRxMediaFrame.is_empty());
501 DCHECK(SignalTxMediaFrame.is_empty());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000502
503 tracing_->SetTraceCallback(NULL);
504}
505
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000506bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +0200507 DCHECK(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000508 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
509 bool res = InitInternal();
510 if (res) {
511 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
512 } else {
513 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
514 Terminate();
515 }
516 return res;
517}
518
519bool WebRtcVoiceEngine::InitInternal() {
520 // Temporarily turn logging level up for the Init call
521 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000522 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000523 SetTraceFilter(extended_filter);
524 SetTraceOptions("");
525
526 // Init WebRtc VoiceEngine.
527 if (voe_wrapper_->base()->Init(adm_) == -1) {
528 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
529 SetTraceFilter(old_filter);
530 return false;
531 }
532
533 SetTraceFilter(old_filter);
534 SetTraceOptions(log_options_);
535
536 // Log the VoiceEngine version info
537 char buffer[1024] = "";
538 voe_wrapper_->base()->GetVersion(buffer);
539 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000540 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000541
542 // Save the default AGC configuration settings. This must happen before
543 // calling SetOptions or the default will be overwritten.
544 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
545 LOG_RTCERR0(GetAgcConfig);
546 return false;
547 }
548
549 // Set defaults for options, so that ApplyOptions applies them explicitly
550 // when we clear option (channel) overrides. External clients can still
551 // modify the defaults via SetOptions (on the media engine).
552 if (!SetOptions(GetDefaultEngineOptions())) {
553 return false;
554 }
555
556 // Print our codec list again for the call diagnostic log
557 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
558 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
559 it != codecs_.end(); ++it) {
560 LOG(LS_INFO) << ToString(*it);
561 }
562
563 // Disable the DTMF playout when a tone is sent.
564 // PlayDtmfTone will be used if local playout is needed.
565 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
566 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
567 }
568
569 initialized_ = true;
570 return true;
571}
572
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000573void WebRtcVoiceEngine::Terminate() {
574 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
575 initialized_ = false;
576
577 StopAecDump();
578
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000579 voe_wrapper_->base()->Terminate();
580 desired_local_monitor_enable_ = false;
581}
582
583int WebRtcVoiceEngine::GetCapabilities() {
584 return AUDIO_SEND | AUDIO_RECV;
585}
586
587VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
588 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
589 if (!ch->valid()) {
590 delete ch;
591 ch = NULL;
592 }
593 return ch;
594}
595
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000596bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
597 if (!ApplyOptions(options)) {
598 return false;
599 }
600 options_ = options;
601 return true;
602}
603
604bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
605 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
606 if (!ApplyOptions(overrides)) {
607 return false;
608 }
609 option_overrides_ = overrides;
610 return true;
611}
612
613bool WebRtcVoiceEngine::ClearOptionOverrides() {
614 LOG(LS_INFO) << "Clearing option overrides.";
615 AudioOptions options = options_;
616 // Only call ApplyOptions if |options_overrides_| contains overrided options.
617 // ApplyOptions affects NS, AGC other options that is shared between
618 // all WebRtcVoiceEngineChannels.
619 if (option_overrides_ == AudioOptions()) {
620 return true;
621 }
622
623 if (!ApplyOptions(options)) {
624 return false;
625 }
626 option_overrides_ = AudioOptions();
627 return true;
628}
629
630// AudioOptions defaults are set in InitInternal (for options with corresponding
631// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
632bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
633 AudioOptions options = options_in; // The options are modified below.
634 // kEcConference is AEC with high suppression.
635 webrtc::EcModes ec_mode = webrtc::kEcConference;
636 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
637 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
638 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
639 bool aecm_comfort_noise = false;
640 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
641 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
642 << aecm_comfort_noise << " (default is false).";
643 }
644
645#if defined(IOS)
646 // On iOS, VPIO provides built-in EC and AGC.
647 options.echo_cancellation.Set(false);
648 options.auto_gain_control.Set(false);
649#elif defined(ANDROID)
650 ec_mode = webrtc::kEcAecm;
651#endif
652
653#if defined(IOS) || defined(ANDROID)
654 // Set the AGC mode for iOS as well despite disabling it above, to avoid
655 // unsupported configuration errors from webrtc.
656 agc_mode = webrtc::kAgcFixedDigital;
657 options.typing_detection.Set(false);
658 options.experimental_agc.Set(false);
659 options.experimental_aec.Set(false);
660 options.experimental_ns.Set(false);
661#endif
662
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100663 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
664 // where the feature is not supported.
665 bool use_delay_agnostic_aec = false;
666#if !defined(IOS)
667 if (options.delay_agnostic_aec.Get(&use_delay_agnostic_aec)) {
668 if (use_delay_agnostic_aec) {
669 options.echo_cancellation.Set(true);
670 options.experimental_aec.Set(true);
671 ec_mode = webrtc::kEcConference;
672 }
673 }
674#endif
675
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000676 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
677
678 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
679
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000680 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000681 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000682 // Check if platform supports built-in EC. Currently only supported on
683 // Android and in combination with Java based audio layer.
684 // TODO(henrika): investigate possibility to support built-in EC also
685 // in combination with Open SL ES audio.
686 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
Bjorn Volckerccfc9392015-05-07 07:43:17 +0200687 if (built_in_aec && !use_delay_agnostic_aec) {
688 // Built-in EC exists on this device and use_delay_agnostic_aec is not
689 // overriding it. Enable/Disable it according to the echo_cancellation
690 // audio option.
Bjorn Volcker1d83f1e2015-04-07 15:25:39 +0200691 if (voe_wrapper_->hw()->EnableBuiltInAEC(echo_cancellation) == 0 &&
692 echo_cancellation) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100693 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000694 // i.e., replace the software EC with the built-in EC.
695 options.echo_cancellation.Set(false);
bjornv@webrtc.org3f118232015-03-16 14:22:03 +0000696 echo_cancellation = false;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000697 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
698 }
699 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000700 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
701 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
702 return false;
703 } else {
704 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
705 << " with mode " << ec_mode;
706 }
707#if !defined(ANDROID)
708 // TODO(ajm): Remove the error return on Android from webrtc.
709 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
710 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
711 return false;
712 }
713#endif
714 if (ec_mode == webrtc::kEcAecm) {
715 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
716 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
717 return false;
718 }
719 }
720 }
721
722 bool auto_gain_control;
723 if (options.auto_gain_control.Get(&auto_gain_control)) {
724 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
725 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
726 return false;
727 } else {
728 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
729 << " with mode " << agc_mode;
730 }
731 }
732
733 if (options.tx_agc_target_dbov.IsSet() ||
734 options.tx_agc_digital_compression_gain.IsSet() ||
735 options.tx_agc_limiter.IsSet()) {
736 // Override default_agc_config_. Generally, an unset option means "leave
737 // the VoE bits alone" in this function, so we want whatever is set to be
738 // stored as the new "default". If we didn't, then setting e.g.
739 // tx_agc_target_dbov would reset digital compression gain and limiter
740 // settings.
741 // Also, if we don't update default_agc_config_, then adjust_agc_delta
742 // would be an offset from the original values, and not whatever was set
743 // explicitly.
744 default_agc_config_.targetLeveldBOv =
745 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
746 default_agc_config_.targetLeveldBOv);
747 default_agc_config_.digitalCompressionGaindB =
748 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
749 default_agc_config_.digitalCompressionGaindB);
750 default_agc_config_.limiterEnable =
751 options.tx_agc_limiter.GetWithDefaultIfUnset(
752 default_agc_config_.limiterEnable);
753 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
754 LOG_RTCERR3(SetAgcConfig,
755 default_agc_config_.targetLeveldBOv,
756 default_agc_config_.digitalCompressionGaindB,
757 default_agc_config_.limiterEnable);
758 return false;
759 }
760 }
761
762 bool noise_suppression;
763 if (options.noise_suppression.Get(&noise_suppression)) {
764 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
765 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
766 return false;
767 } else {
768 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
769 << " with mode " << ns_mode;
770 }
771 }
772
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000773 bool highpass_filter;
774 if (options.highpass_filter.Get(&highpass_filter)) {
775 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
776 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
777 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
778 return false;
779 }
780 }
781
782 bool stereo_swapping;
783 if (options.stereo_swapping.Get(&stereo_swapping)) {
784 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
785 voep->EnableStereoChannelSwapping(stereo_swapping);
786 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
787 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
788 return false;
789 }
790 }
791
Henrik Lundin64dad832015-05-11 12:44:23 +0200792 int audio_jitter_buffer_max_packets;
793 if (options.audio_jitter_buffer_max_packets.Get(
794 &audio_jitter_buffer_max_packets)) {
795 LOG(LS_INFO) << "NetEq capacity is " << audio_jitter_buffer_max_packets;
796 voe_config_.Set<webrtc::NetEqCapacityConfig>(
797 new webrtc::NetEqCapacityConfig(audio_jitter_buffer_max_packets));
798 }
799
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000800 bool typing_detection;
801 if (options.typing_detection.Get(&typing_detection)) {
802 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
803 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
804 // In case of error, log the info and continue
805 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
806 }
807 }
808
809 int adjust_agc_delta;
810 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
811 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
812 if (!AdjustAgcLevel(adjust_agc_delta)) {
813 return false;
814 }
815 }
816
817 bool aec_dump;
818 if (options.aec_dump.Get(&aec_dump)) {
819 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
820 if (aec_dump)
821 StartAecDump(kAecDumpByAudioOptionFilename);
822 else
823 StopAecDump();
824 }
825
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000826 webrtc::Config config;
827
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100828 delay_agnostic_aec_.SetFrom(options.delay_agnostic_aec);
829 bool delay_agnostic_aec;
830 if (delay_agnostic_aec_.Get(&delay_agnostic_aec)) {
831 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << delay_agnostic_aec;
832 config.Set<webrtc::ReportedDelay>(
833 new webrtc::ReportedDelay(!delay_agnostic_aec));
834 }
835
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000836 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000837 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000838 if (experimental_aec_.Get(&experimental_aec)) {
839 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
840 config.Set<webrtc::DelayCorrection>(
841 new webrtc::DelayCorrection(experimental_aec));
842 }
843
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000844 experimental_ns_.SetFrom(options.experimental_ns);
845 bool experimental_ns;
846 if (experimental_ns_.Get(&experimental_ns)) {
847 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
848 config.Set<webrtc::ExperimentalNs>(
849 new webrtc::ExperimentalNs(experimental_ns));
850 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000851
852 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
853 // returns NULL on audio_processing().
854 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
855 if (audioproc) {
856 audioproc->SetExtraOptions(config);
857 }
858
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000859 uint32 recording_sample_rate;
860 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
861 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
862 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
863 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
864 }
865 }
866
867 uint32 playout_sample_rate;
868 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
869 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
870 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
871 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
872 }
873 }
874
875 return true;
876}
877
878bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
879 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
880 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
881 LOG_RTCERR1(SetDelayOffsetMs, offset);
882 return false;
883 }
884
885 return true;
886}
887
888struct ResumeEntry {
889 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
890 : channel(c),
891 playout(p),
892 send(s) {
893 }
894
895 WebRtcVoiceMediaChannel *channel;
896 bool playout;
897 SendFlags send;
898};
899
900// TODO(juberti): Refactor this so that the core logic can be used to set the
901// soundclip device. At that time, reinstate the soundclip pause/resume code.
902bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
903 const Device* out_device) {
904#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000905 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000906 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000907 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000908 kDefaultAudioDeviceId;
909 // The device manager uses -1 as the default device, which was the case for
910 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
911#ifndef WIN32
912 if (-1 == in_id) {
913 in_id = kDefaultAudioDeviceId;
914 }
915 if (-1 == out_id) {
916 out_id = kDefaultAudioDeviceId;
917 }
918#endif
919
920 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
921 in_device->name : "Default device";
922 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
923 out_device->name : "Default device";
924 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
925 << ") and speaker to (id=" << out_id << ", name=" << out_name
926 << ")";
927
928 // If we're running the local monitor, we need to stop it first.
929 bool ret = true;
930 if (!PauseLocalMonitor()) {
931 LOG(LS_WARNING) << "Failed to pause local monitor";
932 ret = false;
933 }
934
935 // Must also pause all audio playback and capture.
936 for (ChannelList::const_iterator i = channels_.begin();
937 i != channels_.end(); ++i) {
938 WebRtcVoiceMediaChannel *channel = *i;
939 if (!channel->PausePlayout()) {
940 LOG(LS_WARNING) << "Failed to pause playout";
941 ret = false;
942 }
943 if (!channel->PauseSend()) {
944 LOG(LS_WARNING) << "Failed to pause send";
945 ret = false;
946 }
947 }
948
949 // Find the recording device id in VoiceEngine and set recording device.
950 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
951 ret = false;
952 }
953 if (ret) {
954 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
955 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
956 ret = false;
957 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +0000958 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
959 if (ap)
960 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000961 }
962
963 // Find the playout device id in VoiceEngine and set playout device.
964 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
965 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
966 ret = false;
967 }
968 if (ret) {
969 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000970 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000971 ret = false;
972 }
973 }
974
975 // Resume all audio playback and capture.
976 for (ChannelList::const_iterator i = channels_.begin();
977 i != channels_.end(); ++i) {
978 WebRtcVoiceMediaChannel *channel = *i;
979 if (!channel->ResumePlayout()) {
980 LOG(LS_WARNING) << "Failed to resume playout";
981 ret = false;
982 }
983 if (!channel->ResumeSend()) {
984 LOG(LS_WARNING) << "Failed to resume send";
985 ret = false;
986 }
987 }
988
989 // Resume local monitor.
990 if (!ResumeLocalMonitor()) {
991 LOG(LS_WARNING) << "Failed to resume local monitor";
992 ret = false;
993 }
994
995 if (ret) {
996 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
997 << ") and speaker to (id="<< out_id << " name=" << out_name
998 << ")";
999 }
1000
1001 return ret;
1002#else
1003 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001004#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001005}
1006
1007bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1008 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1009 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001010#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011 *rtc_id = dev_id;
1012 return true;
1013#else
1014 // In Windows and Mac, we need to find the VoiceEngine device id by name
1015 // unless the input dev_id is the default device id.
1016 if (kDefaultAudioDeviceId == dev_id) {
1017 *rtc_id = dev_id;
1018 return true;
1019 }
1020
1021 // Get the number of VoiceEngine audio devices.
1022 int count = 0;
1023 if (is_input) {
1024 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1025 LOG_RTCERR0(GetNumOfRecordingDevices);
1026 return false;
1027 }
1028 } else {
1029 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1030 LOG_RTCERR0(GetNumOfPlayoutDevices);
1031 return false;
1032 }
1033 }
1034
1035 for (int i = 0; i < count; ++i) {
1036 char name[128];
1037 char guid[128];
1038 if (is_input) {
1039 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1040 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1041 } else {
1042 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1043 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1044 }
1045
1046 std::string webrtc_name(name);
1047 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1048 *rtc_id = i;
1049 return true;
1050 }
1051 }
1052 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1053 return false;
1054#endif
1055}
1056
1057bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1058 unsigned int ulevel;
1059 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1060 LOG_RTCERR1(GetSpeakerVolume, level);
1061 return false;
1062 }
1063 *level = ulevel;
1064 return true;
1065}
1066
1067bool WebRtcVoiceEngine::SetOutputVolume(int level) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001068 DCHECK(level >= 0 && level <= 255);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001069 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1070 LOG_RTCERR1(SetSpeakerVolume, level);
1071 return false;
1072 }
1073 return true;
1074}
1075
1076int WebRtcVoiceEngine::GetInputLevel() {
1077 unsigned int ulevel;
1078 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1079 static_cast<int>(ulevel) : -1;
1080}
1081
1082bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1083 desired_local_monitor_enable_ = enable;
1084 return ChangeLocalMonitor(desired_local_monitor_enable_);
1085}
1086
1087bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1088 // The voe file api is not available in chrome.
1089 if (!voe_wrapper_->file()) {
1090 return false;
1091 }
1092 if (enable && !monitor_) {
1093 monitor_.reset(new WebRtcMonitorStream);
1094 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1095 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1096 // Must call Stop() because there are some cases where Start will report
1097 // failure but still change the state, and if we leave VE in the on state
1098 // then it could crash later when trying to invoke methods on our monitor.
1099 voe_wrapper_->file()->StopRecordingMicrophone();
1100 monitor_.reset();
1101 return false;
1102 }
1103 } else if (!enable && monitor_) {
1104 voe_wrapper_->file()->StopRecordingMicrophone();
1105 monitor_.reset();
1106 }
1107 return true;
1108}
1109
1110bool WebRtcVoiceEngine::PauseLocalMonitor() {
1111 return ChangeLocalMonitor(false);
1112}
1113
1114bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1115 return ChangeLocalMonitor(desired_local_monitor_enable_);
1116}
1117
1118const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1119 return codecs_;
1120}
1121
1122bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1123 return FindWebRtcCodec(in, NULL);
1124}
1125
1126// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1127bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1128 webrtc::CodecInst* out) {
1129 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1130 for (int i = 0; i < ncodecs; ++i) {
1131 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001132 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001133 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1134 voe_codec.rate, voe_codec.channels, 0);
1135 bool multi_rate = IsCodecMultiRate(voe_codec);
1136 // Allow arbitrary rates for ISAC to be specified.
1137 if (multi_rate) {
1138 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1139 codec.bitrate = 0;
1140 }
1141 if (codec.Matches(in)) {
1142 if (out) {
1143 // Fixup the payload type.
1144 voe_codec.pltype = in.id;
1145
1146 // Set bitrate if specified.
1147 if (multi_rate && in.bitrate != 0) {
1148 voe_codec.rate = in.bitrate;
1149 }
1150
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001151 // Reset G722 sample rate to 16000 to match WebRTC.
1152 MaybeFixupG722(&voe_codec, 16000);
1153
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001154 // Apply codec-specific settings.
Minyue Li7100dcd2015-03-27 05:05:59 +01001155 if (IsCodec(codec, kIsacCodecName)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001156 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001157 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001158 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1159 }
1160 *out = voe_codec;
1161 }
1162 return true;
1163 }
1164 }
1165 }
1166 return false;
1167}
1168const std::vector<RtpHeaderExtension>&
1169WebRtcVoiceEngine::rtp_header_extensions() const {
1170 return rtp_header_extensions_;
1171}
1172
1173void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1174 // if min_sev == -1, we keep the current log level.
1175 if (min_sev >= 0) {
1176 SetTraceFilter(SeverityToFilter(min_sev));
1177 }
1178 log_options_ = filter;
1179 SetTraceOptions(initialized_ ? log_options_ : "");
1180}
1181
1182int WebRtcVoiceEngine::GetLastEngineError() {
1183 return voe_wrapper_->error();
1184}
1185
1186void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1187 log_filter_ = filter;
1188 tracing_->SetTraceFilter(filter);
1189}
1190
1191// We suppport three different logging settings for VoiceEngine:
1192// 1. Observer callback that goes into talk diagnostic logfile.
1193// Use --logfile and --loglevel
1194//
1195// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1196// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1197//
1198// 3. EC log and dump for debugging QualityEngine.
1199// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1200//
1201// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1202// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1203void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1204 // Set encrypted trace file.
1205 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001206 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001207 std::vector<std::string>::iterator tracefile =
1208 std::find(opts.begin(), opts.end(), "tracefile");
1209 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1210 // Write encrypted debug output (at same loglevel) to file
1211 // EncryptedTraceFile no longer supported.
1212 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1213 LOG_RTCERR1(SetTraceFile, *tracefile);
1214 }
1215 }
1216
wu@webrtc.org97077a32013-10-25 21:18:33 +00001217 // Allow trace options to override the trace filter. We default
1218 // it to log_filter_ (as a translation of libjingle log levels)
1219 // elsewhere, but this allows clients to explicitly set webrtc
1220 // log levels.
1221 std::vector<std::string>::iterator tracefilter =
1222 std::find(opts.begin(), opts.end(), "tracefilter");
1223 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001224 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001225 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1226 }
1227 }
1228
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001229 // Set AEC dump file
1230 std::vector<std::string>::iterator recordEC =
1231 std::find(opts.begin(), opts.end(), "recordEC");
1232 if (recordEC != opts.end()) {
1233 ++recordEC;
1234 if (recordEC != opts.end())
1235 StartAecDump(recordEC->c_str());
1236 else
1237 StopAecDump();
1238 }
1239}
1240
1241// Ignore spammy trace messages, mostly from the stats API when we haven't
1242// gotten RTCP info yet from the remote side.
1243bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1244 static const char* kTracesToIgnore[] = {
1245 "\tfailed to GetReportBlockInformation",
1246 "GetRecCodec() failed to get received codec",
1247 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1248 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1249 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1250 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1251 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1252 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1253 "SenderInfoReceived No received SR",
1254 "StatisticsRTP() no statistics available",
1255 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1256 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1257 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1258 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1259 NULL
1260 };
1261 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1262 if (trace.find(*p) != std::string::npos) {
1263 return true;
1264 }
1265 }
1266 return false;
1267}
1268
1269void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1270 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001271 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001272 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001273 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001274 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001275 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001276 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001277 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001278 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001279 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280
1281 // Skip past boilerplate prefix text
1282 if (length < 72) {
1283 std::string msg(trace, length);
1284 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1285 LOG_V(sev) << msg;
1286 } else {
1287 std::string msg(trace + 71, length - 72);
1288 if (!ShouldIgnoreTrace(msg)) {
1289 LOG_V(sev) << "webrtc: " << msg;
1290 }
1291 }
1292}
1293
1294void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001295 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001296 WebRtcVoiceMediaChannel* channel = NULL;
1297 uint32 ssrc = 0;
1298 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1299 << channel_num << ".";
1300 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001301 DCHECK(channel != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001302 channel->OnError(ssrc, err_code);
1303 } else {
1304 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1305 << " could not be found in channel list when error reported.";
1306 }
1307}
1308
1309bool WebRtcVoiceEngine::FindChannelAndSsrc(
1310 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001311 DCHECK(channel != NULL && ssrc != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001312
1313 *channel = NULL;
1314 *ssrc = 0;
1315 // Find corresponding channel and ssrc
1316 for (ChannelList::const_iterator it = channels_.begin();
1317 it != channels_.end(); ++it) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001318 DCHECK(*it != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001319 if ((*it)->FindSsrc(channel_num, ssrc)) {
1320 *channel = *it;
1321 return true;
1322 }
1323 }
1324
1325 return false;
1326}
1327
1328// This method will search through the WebRtcVoiceMediaChannels and
1329// obtain the voice engine's channel number.
1330bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1331 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001332 DCHECK(channel_num != NULL);
1333 DCHECK(direction == MPD_RX || direction == MPD_TX);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001334
1335 *channel_num = -1;
1336 // Find corresponding channel for ssrc.
1337 for (ChannelList::const_iterator it = channels_.begin();
1338 it != channels_.end(); ++it) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001339 DCHECK(*it != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001340 if (direction & MPD_RX) {
1341 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1342 }
1343 if (*channel_num == -1 && (direction & MPD_TX)) {
1344 *channel_num = (*it)->GetSendChannelNum(ssrc);
1345 }
1346 if (*channel_num != -1) {
1347 return true;
1348 }
1349 }
1350 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1351 return false;
1352}
1353
1354void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001355 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001356 channels_.push_back(channel);
1357}
1358
1359void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001360 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001361 ChannelList::iterator i = std::find(channels_.begin(),
1362 channels_.end(),
1363 channel);
1364 if (i != channels_.end()) {
1365 channels_.erase(i);
1366 }
1367}
1368
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369// Adjusts the default AGC target level by the specified delta.
1370// NB: If we start messing with other config fields, we'll want
1371// to save the current webrtc::AgcConfig as well.
1372bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1373 webrtc::AgcConfig config = default_agc_config_;
1374 config.targetLeveldBOv -= delta;
1375
1376 LOG(LS_INFO) << "Adjusting AGC level from default -"
1377 << default_agc_config_.targetLeveldBOv << "dB to -"
1378 << config.targetLeveldBOv << "dB";
1379
1380 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1381 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1382 return false;
1383 }
1384 return true;
1385}
1386
Fredrik Solenbergccb49e72015-05-19 11:37:56 +02001387bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001388 if (initialized_) {
1389 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1390 return false;
1391 }
1392 if (adm_) {
1393 adm_->Release();
1394 adm_ = NULL;
1395 }
1396 if (adm) {
1397 adm_ = adm;
1398 adm_->AddRef();
1399 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001400 return true;
1401}
1402
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001403bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1404 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001405 if (!aec_dump_file_stream) {
1406 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001407 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001408 LOG(LS_WARNING) << "Could not close file.";
1409 return false;
1410 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001411 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001412 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001413 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001414 LOG_RTCERR0(StartDebugRecording);
1415 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001416 return false;
1417 }
1418 is_dumping_aec_ = true;
1419 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001420}
1421
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001422bool WebRtcVoiceEngine::RegisterProcessor(
1423 uint32 ssrc,
1424 VoiceProcessor* voice_processor,
1425 MediaProcessorDirection direction) {
1426 bool register_with_webrtc = false;
1427 int channel_id = -1;
1428 bool success = false;
1429 uint32* processor_ssrc = NULL;
1430 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1431 if (voice_processor == NULL || !found_channel) {
1432 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1433 << " foundChannel: " << found_channel;
1434 return false;
1435 }
1436
1437 webrtc::ProcessingTypes processing_type;
1438 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001439 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001440 if (direction == MPD_RX) {
1441 processing_type = webrtc::kPlaybackAllChannelsMixed;
1442 if (SignalRxMediaFrame.is_empty()) {
1443 register_with_webrtc = true;
1444 processor_ssrc = &rx_processor_ssrc_;
1445 }
1446 SignalRxMediaFrame.connect(voice_processor,
1447 &VoiceProcessor::OnFrame);
1448 } else {
1449 processing_type = webrtc::kRecordingPerChannel;
1450 if (SignalTxMediaFrame.is_empty()) {
1451 register_with_webrtc = true;
1452 processor_ssrc = &tx_processor_ssrc_;
1453 }
1454 SignalTxMediaFrame.connect(voice_processor,
1455 &VoiceProcessor::OnFrame);
1456 }
1457 }
1458 if (register_with_webrtc) {
1459 // TODO(janahan): when registering consider instantiating a
1460 // a VoeMediaProcess object and not make the engine extend the interface.
1461 if (voe()->media() && voe()->media()->
1462 RegisterExternalMediaProcessing(channel_id,
1463 processing_type,
1464 *this) != -1) {
1465 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1466 << channel_id;
1467 *processor_ssrc = ssrc;
1468 success = true;
1469 } else {
1470 LOG_RTCERR2(RegisterExternalMediaProcessing,
1471 channel_id,
1472 processing_type);
1473 success = false;
1474 }
1475 } else {
1476 // If we don't have to register with the engine, we just needed to
1477 // connect a new processor, set success to true;
1478 success = true;
1479 }
1480 return success;
1481}
1482
1483bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1484 MediaProcessorDirection channel_direction,
1485 uint32 ssrc,
1486 VoiceProcessor* voice_processor,
1487 MediaProcessorDirection processor_direction) {
1488 bool success = true;
1489 FrameSignal* signal;
1490 webrtc::ProcessingTypes processing_type;
1491 uint32* processor_ssrc = NULL;
1492 if (channel_direction == MPD_RX) {
1493 signal = &SignalRxMediaFrame;
1494 processing_type = webrtc::kPlaybackAllChannelsMixed;
1495 processor_ssrc = &rx_processor_ssrc_;
1496 } else {
1497 signal = &SignalTxMediaFrame;
1498 processing_type = webrtc::kRecordingPerChannel;
1499 processor_ssrc = &tx_processor_ssrc_;
1500 }
1501
1502 int deregister_id = -1;
1503 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001504 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001505 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1506 signal->disconnect(voice_processor);
1507 int channel_id = -1;
1508 bool found_channel = FindChannelNumFromSsrc(ssrc,
1509 channel_direction,
1510 &channel_id);
1511 if (signal->is_empty() && found_channel) {
1512 deregister_id = channel_id;
1513 }
1514 }
1515 }
1516 if (deregister_id != -1) {
1517 if (voe()->media() &&
1518 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1519 processing_type) != -1) {
1520 *processor_ssrc = 0;
1521 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1522 << deregister_id;
1523 } else {
1524 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1525 deregister_id,
1526 processing_type);
1527 success = false;
1528 }
1529 }
1530 return success;
1531}
1532
1533bool WebRtcVoiceEngine::UnregisterProcessor(
1534 uint32 ssrc,
1535 VoiceProcessor* voice_processor,
1536 MediaProcessorDirection direction) {
1537 bool success = true;
1538 if (voice_processor == NULL) {
1539 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1540 << ssrc;
1541 return false;
1542 }
1543 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1544 success = false;
1545 }
1546 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1547 success = false;
1548 }
1549 return success;
1550}
1551
1552// Implementing method from WebRtc VoEMediaProcess interface
1553// Do not lock mux_channel_cs_ in this callback.
1554void WebRtcVoiceEngine::Process(int channel,
1555 webrtc::ProcessingTypes type,
1556 int16_t audio10ms[],
1557 int length,
1558 int sampling_freq,
1559 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001560 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001561 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1562 if (type == webrtc::kPlaybackAllChannelsMixed) {
1563 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1564 } else if (type == webrtc::kRecordingPerChannel) {
1565 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1566 } else {
1567 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1568 << " channel: " << channel << " type: " << type
1569 << " tx_ssrc: " << tx_processor_ssrc_
1570 << " rx_ssrc: " << rx_processor_ssrc_;
1571 }
1572}
1573
1574void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1575 if (!is_dumping_aec_) {
1576 // Start dumping AEC when we are not dumping.
1577 if (voe_wrapper_->processing()->StartDebugRecording(
1578 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001579 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001580 } else {
1581 is_dumping_aec_ = true;
1582 }
1583 }
1584}
1585
1586void WebRtcVoiceEngine::StopAecDump() {
1587 if (is_dumping_aec_) {
1588 // Stop dumping AEC when we are dumping.
1589 if (voe_wrapper_->processing()->StopDebugRecording() !=
1590 webrtc::AudioProcessing::kNoError) {
1591 LOG_RTCERR0(StopDebugRecording);
1592 }
1593 is_dumping_aec_ = false;
1594 }
1595}
1596
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001597int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001598 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001599}
1600
1601int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1602 return CreateVoiceChannel(voe_wrapper_.get());
1603}
1604
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001605class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1606 : public AudioRenderer::Sink {
1607 public:
1608 WebRtcVoiceChannelRenderer(int ch,
1609 webrtc::AudioTransport* voe_audio_transport)
1610 : channel_(ch),
1611 voe_audio_transport_(voe_audio_transport),
1612 renderer_(NULL) {
1613 }
Fredrik Solenbergaaf8ff22015-05-07 16:05:53 +02001614 ~WebRtcVoiceChannelRenderer() override { Stop(); }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001615
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001616 // Starts the rendering by setting a sink to the renderer to get data
1617 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001618 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001619 // TODO(xians): Make sure Start() is called only once.
1620 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001621 rtc::CritScope lock(&lock_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001622 DCHECK(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001623 if (renderer_ != NULL) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02001624 DCHECK(renderer_ == renderer);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001625 return;
1626 }
1627
1628 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1629 // in getUserMedia by default.
1630 renderer->AddChannel(channel_);
1631 renderer->SetSink(this);
1632 renderer_ = renderer;
1633 }
1634
1635 // Stops rendering by setting the sink of the renderer to NULL. No data
1636 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001637 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001638 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001639 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001640 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001641 return;
1642
1643 renderer_->RemoveChannel(channel_);
1644 renderer_->SetSink(NULL);
1645 renderer_ = NULL;
1646 }
1647
1648 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001649 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001650 void OnData(const void* audio_data,
1651 int bits_per_sample,
1652 int sample_rate,
1653 int number_of_channels,
1654 int number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001655 voe_audio_transport_->OnData(channel_,
1656 audio_data,
1657 bits_per_sample,
1658 sample_rate,
1659 number_of_channels,
1660 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001661 }
1662
1663 // Callback from the |renderer_| when it is going away. In case Start() has
1664 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001665 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001666 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001667 // Set |renderer_| to NULL to make sure no more callback will get into
1668 // the renderer.
1669 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001670 }
1671
1672 // Accessor to the VoE channel ID.
1673 int channel() const { return channel_; }
1674
1675 private:
1676 const int channel_;
1677 webrtc::AudioTransport* const voe_audio_transport_;
1678
1679 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1680 // PeerConnection will make sure invalidating the pointer before the object
1681 // goes away.
1682 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001683
1684 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001685 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001686};
1687
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001688// WebRtcVoiceMediaChannel
Fredrik Solenberge444a3d2015-05-07 16:42:08 +02001689WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine* engine)
1690 : engine_(engine),
1691 voe_channel_(engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001692 send_bitrate_setting_(false),
1693 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001694 options_(),
1695 dtmf_allowed_(false),
1696 desired_playout_(false),
1697 nack_enabled_(false),
1698 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001699 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001700 desired_send_(SEND_NOTHING),
1701 send_(SEND_NOTHING),
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001702 call_(nullptr),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001703 default_receive_ssrc_(0) {
1704 engine->RegisterChannel(this);
1705 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1706 << voe_channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001707 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001708}
1709
1710WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1711 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1712 << voe_channel();
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001713 DCHECK(receive_streams_.empty() || call_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001714
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001715 // Remove any remaining send streams, the default channel will be deleted
1716 // later.
1717 while (!send_channels_.empty())
1718 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001719
1720 // Unregister ourselves from the engine.
1721 engine()->UnregisterChannel(this);
1722 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001723 while (!receive_channels_.empty()) {
1724 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001725 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001726 DCHECK(receive_streams_.empty());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001727
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001728 // Delete the default channel.
1729 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001730}
1731
1732bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1733 LOG(LS_INFO) << "Setting voice channel options: "
1734 << options.ToString();
1735
wu@webrtc.orgde305012013-10-31 15:40:38 +00001736 // Check if DSCP value is changed from previous.
1737 bool dscp_option_changed = (options_.dscp != options.dscp);
1738
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001739 // TODO(xians): Add support to set different options for different send
1740 // streams after we support multiple APMs.
1741
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001742 // We retain all of the existing options, and apply the given ones
1743 // on top. This means there is no way to "clear" options such that
1744 // they go back to the engine default.
1745 options_.SetAll(options);
1746
1747 if (send_ != SEND_NOTHING) {
1748 if (!engine()->SetOptionOverrides(options_)) {
1749 LOG(LS_WARNING) <<
1750 "Failed to engine SetOptionOverrides during channel SetOptions.";
1751 return false;
1752 }
1753 } else {
1754 // Will be interpreted when appropriate.
1755 }
1756
wu@webrtc.org97077a32013-10-25 21:18:33 +00001757 // Receiver-side auto gain control happens per channel, so set it here from
1758 // options. Note that, like conference mode, setting it on the engine won't
1759 // have the desired effect, since voice channels don't inherit options from
1760 // the media engine when those options are applied per-channel.
1761 bool rx_auto_gain_control;
1762 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1763 if (engine()->voe()->processing()->SetRxAgcStatus(
1764 voe_channel(), rx_auto_gain_control,
1765 webrtc::kAgcFixedDigital) == -1) {
1766 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1767 return false;
1768 } else {
1769 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1770 << " with mode " << webrtc::kAgcFixedDigital;
1771 }
1772 }
1773 if (options.rx_agc_target_dbov.IsSet() ||
1774 options.rx_agc_digital_compression_gain.IsSet() ||
1775 options.rx_agc_limiter.IsSet()) {
1776 webrtc::AgcConfig config;
1777 // If only some of the options are being overridden, get the current
1778 // settings for the channel and bail if they aren't available.
1779 if (!options.rx_agc_target_dbov.IsSet() ||
1780 !options.rx_agc_digital_compression_gain.IsSet() ||
1781 !options.rx_agc_limiter.IsSet()) {
1782 if (engine()->voe()->processing()->GetRxAgcConfig(
1783 voe_channel(), config) != 0) {
1784 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1785 << "channel " << voe_channel() << ". Since not all rx "
1786 << "agc options are specified, unable to safely set rx "
1787 << "agc options.";
1788 return false;
1789 }
1790 }
1791 config.targetLeveldBOv =
1792 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1793 config.targetLeveldBOv);
1794 config.digitalCompressionGaindB =
1795 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1796 config.digitalCompressionGaindB);
1797 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1798 config.limiterEnable);
1799 if (engine()->voe()->processing()->SetRxAgcConfig(
1800 voe_channel(), config) == -1) {
1801 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1802 config.digitalCompressionGaindB, config.limiterEnable);
1803 return false;
1804 }
1805 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001806 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001807 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001808 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001809 dscp = kAudioDscpValue;
1810 if (MediaChannel::SetDscp(dscp) != 0) {
1811 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1812 }
1813 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001814
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02001815 SetCall(call_);
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001816
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001817 LOG(LS_INFO) << "Set voice channel options. Current options: "
1818 << options_.ToString();
1819 return true;
1820}
1821
1822bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1823 const std::vector<AudioCodec>& codecs) {
1824 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001825 LOG(LS_INFO) << "Setting receive voice codecs:";
1826
1827 std::vector<AudioCodec> new_codecs;
1828 // Find all new codecs. We allow adding new codecs but don't allow changing
1829 // the payload type of codecs that is already configured since we might
1830 // already be receiving packets with that payload type.
1831 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001832 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001833 AudioCodec old_codec;
1834 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1835 if (old_codec.id != it->id) {
1836 LOG(LS_ERROR) << it->name << " payload type changed.";
1837 return false;
1838 }
1839 } else {
1840 new_codecs.push_back(*it);
1841 }
1842 }
1843 if (new_codecs.empty()) {
1844 // There are no new codecs to configure. Already configured codecs are
1845 // never removed.
1846 return true;
1847 }
1848
1849 if (playout_) {
1850 // Receive codecs can not be changed while playing. So we temporarily
1851 // pause playout.
1852 PausePlayout();
1853 }
1854
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001855 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001856 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1857 it != new_codecs.end() && ret; ++it) {
1858 webrtc::CodecInst voe_codec;
1859 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1860 LOG(LS_INFO) << ToString(*it);
1861 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001862 if (default_receive_ssrc_ == 0) {
1863 // Set the receive codecs on the default channel explicitly if the
1864 // default channel is not used by |receive_channels_|, this happens in
1865 // conference mode or in non-conference mode when there is no playout
1866 // channel.
1867 // TODO(xians): Figure out how we use the default channel in conference
1868 // mode.
1869 if (engine()->voe()->codec()->SetRecPayloadType(
1870 voe_channel(), voe_codec) == -1) {
1871 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1872 ret = false;
1873 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001874 }
1875
1876 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001877 for (ChannelMap::iterator it = receive_channels_.begin();
1878 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001879 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001880 it->second->channel(), voe_codec) == -1) {
1881 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001882 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001883 ret = false;
1884 }
1885 }
1886 } else {
1887 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1888 ret = false;
1889 }
1890 }
1891 if (ret) {
1892 recv_codecs_ = codecs;
1893 }
1894
1895 if (desired_playout_ && !playout_) {
1896 ResumePlayout();
1897 }
1898 return ret;
1899}
1900
1901bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001902 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001903 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001904 engine()->voe()->codec()->SetVADStatus(channel, false);
1905 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001906 engine()->voe()->rtp()->SetREDStatus(channel, false);
1907 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001908
1909 // Scan through the list to figure out the codec to use for sending, along
1910 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001911 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001912 webrtc::CodecInst send_codec;
1913 memset(&send_codec, 0, sizeof(send_codec));
1914
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001915 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001916 bool enable_codec_fec = false;
Minyue Li7100dcd2015-03-27 05:05:59 +01001917 bool enable_opus_dtx = false;
minyue@webrtc.org26236952014-10-29 02:27:08 +00001918 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001919
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001920 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001921 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1922 it != codecs.end(); ++it) {
1923 // Ignore codecs we don't know about. The negotiation step should prevent
1924 // this, but double-check to be sure.
1925 webrtc::CodecInst voe_codec;
1926 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001927 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001928 continue;
1929 }
1930
Minyue Li7100dcd2015-03-27 05:05:59 +01001931 if (IsCodec(*it, kDtmfCodecName) || IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001932 // Skip telephone-event/CN codec, which will be handled later.
1933 continue;
1934 }
1935
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001936 // We'll use the first codec in the list to actually send audio data.
1937 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001938 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001939 // used is specified in params.
Minyue Li7100dcd2015-03-27 05:05:59 +01001940 if (IsCodec(*it, kRedCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001941 // Parse out the RED parameters. If we fail, just ignore RED;
1942 // we don't support all possible params/usage scenarios.
1943 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
1944 continue;
1945 }
1946
1947 // Enable redundant encoding of the specified codec. Treat any
1948 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001949 LOG(LS_INFO) << "Enabling RED on channel " << channel;
1950 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
1951 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001952 return false;
1953 }
1954 } else {
1955 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001956 nack_enabled = IsNackEnabled(*it);
Minyue Li7100dcd2015-03-27 05:05:59 +01001957 // For Opus as the send codec, we are to determine inband FEC, maximum
1958 // playback rate, and opus internal dtx.
1959 if (IsCodec(*it, kOpusCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00001960 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
Minyue Li7100dcd2015-03-27 05:05:59 +01001961 &opus_max_playback_rate, &enable_opus_dtx);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00001962 }
Brave Yao5225dd82015-03-26 07:39:19 +08001963
1964 // Set packet size if the AudioCodec param kCodecParamPTime is set.
1965 int ptime_ms = 0;
1966 if (it->GetParam(kCodecParamPTime, &ptime_ms)) {
1967 if (!SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
1968 LOG(LS_WARNING) << "Failed to set packet size for codec "
1969 << send_codec.plname;
1970 return false;
1971 }
1972 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001973 }
1974 found_send_codec = true;
1975 break;
1976 }
1977
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001978 if (nack_enabled_ != nack_enabled) {
1979 SetNack(channel, nack_enabled);
1980 nack_enabled_ = nack_enabled;
1981 }
1982
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001983 if (!found_send_codec) {
1984 LOG(LS_WARNING) << "Received empty list of codecs.";
1985 return false;
1986 }
1987
1988 // Set the codec immediately, since SetVADStatus() depends on whether
1989 // the current codec is mono or stereo.
1990 if (!SetSendCodec(channel, send_codec))
1991 return false;
1992
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001993 // FEC should be enabled after SetSendCodec.
1994 if (enable_codec_fec) {
1995 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
1996 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00001997 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
1998 // Enable codec internal FEC. Treat any failure as fatal internal error.
1999 LOG_RTCERR2(SetFECStatus, channel, true);
2000 return false;
2001 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002002 }
2003
Minyue Li7100dcd2015-03-27 05:05:59 +01002004 if (IsCodec(send_codec, kOpusCodecName)) {
2005 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
2006 // send codec has to be Opus.
2007
2008 // Set Opus internal DTX.
2009 LOG(LS_INFO) << "Attempt to "
2010 << GetEnableString(enable_opus_dtx)
2011 << " Opus DTX on channel "
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002012 << channel;
Minyue Li7100dcd2015-03-27 05:05:59 +01002013 if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) {
2014 LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx);
2015 return false;
2016 }
2017
2018 // If opus_max_playback_rate <= 0, the default maximum playback rate
2019 // (48 kHz) will be used.
2020 if (opus_max_playback_rate > 0) {
2021 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
2022 << opus_max_playback_rate
2023 << " Hz on channel "
2024 << channel;
2025 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
2026 channel, opus_max_playback_rate) == -1) {
2027 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate);
2028 return false;
2029 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002030 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002031 }
2032
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002033 // Always update the |send_codec_| to the currently set send codec.
2034 send_codec_.reset(new webrtc::CodecInst(send_codec));
2035
minyue@webrtc.org26236952014-10-29 02:27:08 +00002036 if (send_bitrate_setting_) {
2037 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002038 }
2039
2040 // Loop through the codecs list again to config the telephone-event/CN codec.
2041 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2042 it != codecs.end(); ++it) {
2043 // Ignore codecs we don't know about. The negotiation step should prevent
2044 // this, but double-check to be sure.
2045 webrtc::CodecInst voe_codec;
2046 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2047 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2048 continue;
2049 }
2050
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002051 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2052 // about it.
Minyue Li7100dcd2015-03-27 05:05:59 +01002053 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002054 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2055 channel, it->id) == -1) {
2056 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2057 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002058 }
Minyue Li7100dcd2015-03-27 05:05:59 +01002059 } else if (IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002060 // Turn voice activity detection/comfort noise on if supported.
2061 // Set the wideband CN payload type appropriately.
2062 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002063 webrtc::PayloadFrequencies cn_freq;
2064 switch (it->clockrate) {
2065 case 8000:
2066 cn_freq = webrtc::kFreq8000Hz;
2067 break;
2068 case 16000:
2069 cn_freq = webrtc::kFreq16000Hz;
2070 break;
2071 case 32000:
2072 cn_freq = webrtc::kFreq32000Hz;
2073 break;
2074 default:
2075 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2076 << " not supported.";
2077 continue;
2078 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002079 // Set the CN payloadtype and the VAD status.
2080 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2081 if (cn_freq != webrtc::kFreq8000Hz) {
2082 if (engine()->voe()->codec()->SetSendCNPayloadType(
2083 channel, it->id, cn_freq) == -1) {
2084 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2085 // TODO(ajm): This failure condition will be removed from VoE.
2086 // Restore the return here when we update to a new enough webrtc.
2087 //
2088 // Not returning false because the SetSendCNPayloadType will fail if
2089 // the channel is already sending.
2090 // This can happen if the remote description is applied twice, for
2091 // example in the case of ROAP on top of JSEP, where both side will
2092 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002093 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002094 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002095 // Only turn on VAD if we have a CN payload type that matches the
2096 // clockrate for the codec we are going to use.
Minyue Li7100dcd2015-03-27 05:05:59 +01002097 if (it->clockrate == send_codec.plfreq && send_codec.channels != 2) {
2098 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
2099 // interaction between VAD and Opus FEC.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002100 LOG(LS_INFO) << "Enabling VAD";
2101 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2102 LOG_RTCERR2(SetVADStatus, channel, true);
2103 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002104 }
2105 }
2106 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002107 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002108 return true;
2109}
2110
2111bool WebRtcVoiceMediaChannel::SetSendCodecs(
2112 const std::vector<AudioCodec>& codecs) {
2113 dtmf_allowed_ = false;
2114 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2115 it != codecs.end(); ++it) {
2116 // Find the DTMF telephone event "codec".
Minyue Li7100dcd2015-03-27 05:05:59 +01002117 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002118 dtmf_allowed_ = true;
2119 }
2120 }
2121
2122 // Cache the codecs in order to configure the channel created later.
2123 send_codecs_ = codecs;
2124 for (ChannelMap::iterator iter = send_channels_.begin();
2125 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002126 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002127 return false;
2128 }
2129 }
2130
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002131 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002132 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002133 return true;
2134}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002135
2136void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2137 bool nack_enabled) {
2138 for (ChannelMap::const_iterator it = channels.begin();
2139 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002140 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002141 }
2142}
2143
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002144void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002145 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002146 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002147 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2148 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002149 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002150 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2151 }
2152}
2153
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002154bool WebRtcVoiceMediaChannel::SetSendCodec(
2155 const webrtc::CodecInst& send_codec) {
2156 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2157 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002158 for (ChannelMap::iterator iter = send_channels_.begin();
2159 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002160 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002161 return false;
2162 }
2163
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002164 return true;
2165}
2166
2167bool WebRtcVoiceMediaChannel::SetSendCodec(
2168 int channel, const webrtc::CodecInst& send_codec) {
2169 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2170 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2171
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002172 webrtc::CodecInst current_codec;
2173 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2174 (send_codec == current_codec)) {
2175 // Codec is already configured, we can return without setting it again.
2176 return true;
2177 }
2178
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002179 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2180 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002181 return false;
2182 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002183 return true;
2184}
2185
2186bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2187 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002188 if (receive_extensions_ == extensions) {
2189 return true;
2190 }
2191
2192 // The default channel may or may not be in |receive_channels_|. Set the rtp
2193 // header extensions for default channel regardless.
2194 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2195 return false;
2196 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002197
2198 // Loop through all receive channels and enable/disable the extensions.
2199 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2200 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002201 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2202 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002203 return false;
2204 }
2205 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002206
2207 receive_extensions_ = extensions;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002208
2209 // Recreate AudioReceiveStream:s.
2210 {
2211 std::vector<webrtc::RtpExtension> exts;
2212
2213 const RtpHeaderExtension* audio_level_extension =
2214 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2215 if (audio_level_extension) {
2216 exts.push_back({
2217 kRtpAudioLevelHeaderExtension, audio_level_extension->id});
2218 }
2219
2220 const RtpHeaderExtension* send_time_extension =
2221 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2222 if (send_time_extension) {
2223 exts.push_back({
2224 kRtpAbsoluteSenderTimeHeaderExtension, send_time_extension->id});
2225 }
2226
2227 recv_rtp_extensions_.swap(exts);
2228 SetCall(call_);
2229 }
2230
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002231 return true;
2232}
2233
2234bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2235 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002236 const RtpHeaderExtension* audio_level_extension =
2237 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2238 if (!SetHeaderExtension(
2239 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2240 audio_level_extension)) {
2241 return false;
2242 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002243
2244 const RtpHeaderExtension* send_time_extension =
2245 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2246 if (!SetHeaderExtension(
2247 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2248 send_time_extension)) {
2249 return false;
2250 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002251
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002252 return true;
2253}
2254
2255bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2256 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002257 if (send_extensions_ == extensions) {
2258 return true;
2259 }
2260
2261 // The default channel may or may not be in |send_channels_|. Set the rtp
2262 // header extensions for default channel regardless.
2263
2264 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2265 return false;
2266 }
2267
2268 // Loop through all send channels and enable/disable the extensions.
2269 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2270 channel_it != send_channels_.end(); ++channel_it) {
2271 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2272 extensions)) {
2273 return false;
2274 }
2275 }
2276
2277 send_extensions_ = extensions;
2278 return true;
2279}
2280
2281bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2282 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002283 const RtpHeaderExtension* audio_level_extension =
2284 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002285
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002286 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002287 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002288 audio_level_extension)) {
2289 return false;
2290 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002291
2292 const RtpHeaderExtension* send_time_extension =
2293 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002294 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002295 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002296 send_time_extension)) {
2297 return false;
2298 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002299
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002300 return true;
2301}
2302
2303bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2304 desired_playout_ = playout;
2305 return ChangePlayout(desired_playout_);
2306}
2307
2308bool WebRtcVoiceMediaChannel::PausePlayout() {
2309 return ChangePlayout(false);
2310}
2311
2312bool WebRtcVoiceMediaChannel::ResumePlayout() {
2313 return ChangePlayout(desired_playout_);
2314}
2315
2316bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2317 if (playout_ == playout) {
2318 return true;
2319 }
2320
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002321 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002322 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002323 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002324 // Only toggle the default channel if we don't have any other channels.
2325 result = SetPlayout(voe_channel(), playout);
2326 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002327 for (ChannelMap::iterator it = receive_channels_.begin();
2328 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002329 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002330 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002331 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002332 result = false;
2333 }
2334 }
2335
2336 if (result) {
2337 playout_ = playout;
2338 }
2339 return result;
2340}
2341
2342bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2343 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002344 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002345 return ChangeSend(desired_send_);
2346 return true;
2347}
2348
2349bool WebRtcVoiceMediaChannel::PauseSend() {
2350 return ChangeSend(SEND_NOTHING);
2351}
2352
2353bool WebRtcVoiceMediaChannel::ResumeSend() {
2354 return ChangeSend(desired_send_);
2355}
2356
2357bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2358 if (send_ == send) {
2359 return true;
2360 }
2361
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002362 // Change the settings on each send channel.
2363 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002364 engine()->SetOptionOverrides(options_);
2365
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002366 // Change the settings on each send channel.
2367 for (ChannelMap::iterator iter = send_channels_.begin();
2368 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002369 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002370 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002371 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002372
2373 // Clear up the options after stopping sending.
2374 if (send == SEND_NOTHING)
2375 engine()->ClearOptionOverrides();
2376
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002377 send_ = send;
2378 return true;
2379}
2380
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002381bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2382 if (send == SEND_MICROPHONE) {
2383 if (engine()->voe()->base()->StartSend(channel) == -1) {
2384 LOG_RTCERR1(StartSend, channel);
2385 return false;
2386 }
2387 if (engine()->voe()->file() &&
2388 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2389 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2390 return false;
2391 }
2392 } else { // SEND_NOTHING
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002393 DCHECK(send == SEND_NOTHING);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002394 if (engine()->voe()->base()->StopSend(channel) == -1) {
2395 LOG_RTCERR1(StopSend, channel);
2396 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002397 }
2398 }
2399
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002400 return true;
2401}
2402
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002403// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002404void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2405 if (engine()->voe()->network()->RegisterExternalTransport(
2406 channel, *this) == -1) {
2407 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2408 }
2409
2410 // Enable RTCP (for quality stats and feedback messages)
2411 EnableRtcp(channel);
2412
2413 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2414 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002415
2416 // Set RTP header extension for the new channel.
2417 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002418}
2419
2420bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2421 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2422 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2423 }
2424
2425 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2426 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002427 return false;
2428 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002429
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002430 return true;
2431}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002432
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002433bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2434 // If the default channel is already used for sending create a new channel
2435 // otherwise use the default channel for sending.
2436 int channel = GetSendChannelNum(sp.first_ssrc());
2437 if (channel != -1) {
2438 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2439 return false;
2440 }
2441
2442 bool default_channel_is_available = true;
2443 for (ChannelMap::const_iterator iter = send_channels_.begin();
2444 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002445 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002446 default_channel_is_available = false;
2447 break;
2448 }
2449 }
2450 if (default_channel_is_available) {
2451 channel = voe_channel();
2452 } else {
2453 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002454 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002455 if (channel == -1) {
2456 LOG_RTCERR0(CreateChannel);
2457 return false;
2458 }
2459
2460 ConfigureSendChannel(channel);
2461 }
2462
2463 // Save the channel to send_channels_, so that RemoveSendStream() can still
2464 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002465 webrtc::AudioTransport* audio_transport =
2466 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002467 send_channels_.insert(std::make_pair(
2468 sp.first_ssrc(),
2469 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002470
2471 // Set the send (local) SSRC.
2472 // If there are multiple send SSRCs, we can only set the first one here, and
2473 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2474 // (with a codec requires multiple SSRC(s)).
2475 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2476 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2477 return false;
2478 }
2479
2480 // At this point the channel's local SSRC has been updated. If the channel is
2481 // the default channel make sure that all the receive channels are updated as
2482 // well. Receive channels have to have the same SSRC as the default channel in
2483 // order to send receiver reports with this SSRC.
2484 if (IsDefaultChannel(channel)) {
2485 for (ChannelMap::const_iterator it = receive_channels_.begin();
2486 it != receive_channels_.end(); ++it) {
2487 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002488 if (!IsDefaultChannel(it->second->channel())) {
2489 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002490 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002491 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002492 return false;
2493 }
2494 }
2495 }
2496 }
2497
2498 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002499 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2500 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002501 }
2502
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002503 // Set the current codecs to be used for the new channel.
2504 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002505 return false;
2506
2507 return ChangeSend(channel, desired_send_);
2508}
2509
2510bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2511 ChannelMap::iterator it = send_channels_.find(ssrc);
2512 if (it == send_channels_.end()) {
2513 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2514 << " which doesn't exist.";
2515 return false;
2516 }
2517
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002518 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002519 ChangeSend(channel, SEND_NOTHING);
2520
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002521 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2522 // this will disconnect the audio renderer with the send channel.
2523 delete it->second;
2524 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002525
2526 if (IsDefaultChannel(channel)) {
2527 // Do not delete the default channel since the receive channels depend on
2528 // the default channel, recycle it instead.
2529 ChangeSend(channel, SEND_NOTHING);
2530 } else {
2531 // Clean up and delete the send channel.
2532 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2533 << " with VoiceEngine channel #" << channel << ".";
2534 if (!DeleteChannel(channel))
2535 return false;
2536 }
2537
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002538 if (send_channels_.empty())
2539 ChangeSend(SEND_NOTHING);
2540
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002541 return true;
2542}
2543
2544bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002545 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002546 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002547
2548 if (!VERIFY(sp.ssrcs.size() == 1))
2549 return false;
2550 uint32 ssrc = sp.first_ssrc();
2551
wu@webrtc.org78187522013-10-07 23:32:02 +00002552 if (ssrc == 0) {
2553 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2554 return false;
2555 }
2556
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002557 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2558 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002559 return false;
2560 }
2561
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002562 TryAddAudioRecvStream(ssrc);
2563
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002564 // Reuse default channel for recv stream in non-conference mode call
2565 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002566 webrtc::AudioTransport* audio_transport =
2567 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002568 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002569 LOG(LS_INFO) << "Recv stream " << ssrc << " reuse default channel";
2570 default_receive_ssrc_ = ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002571 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002572 default_receive_ssrc_,
2573 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002574 return SetPlayout(voe_channel(), playout_);
2575 }
2576
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002577 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002578 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002579 if (channel == -1) {
2580 LOG_RTCERR0(CreateChannel);
2581 return false;
2582 }
2583
wu@webrtc.org78187522013-10-07 23:32:02 +00002584 if (!ConfigureRecvChannel(channel)) {
2585 DeleteChannel(channel);
2586 return false;
2587 }
2588
2589 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002590 std::make_pair(
2591 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002592
2593 LOG(LS_INFO) << "New audio stream " << ssrc
2594 << " registered to VoiceEngine channel #"
2595 << channel << ".";
2596 return true;
2597}
2598
2599bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002600 // Configure to use external transport, like our default channel.
2601 if (engine()->voe()->network()->RegisterExternalTransport(
2602 channel, *this) == -1) {
2603 LOG_RTCERR2(SetExternalTransport, channel, this);
2604 return false;
2605 }
2606
2607 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002608 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002609 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2610 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002611 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002612 return false;
2613 }
2614 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002615 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002616 return false;
2617 }
2618
Minyue2013aec2015-05-13 14:14:42 +02002619 // Associate receive channel to default channel (so the receive channel can
2620 // obtain RTT from the send channel)
2621 engine()->voe()->base()->AssociateSendChannel(channel, voe_channel());
2622 LOG(LS_INFO) << "VoiceEngine channel #"
2623 << channel << " is associated with channel #"
2624 << voe_channel() << ".";
2625
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002626 // Use the same recv payload types as our default channel.
2627 ResetRecvCodecs(channel);
2628 if (!recv_codecs_.empty()) {
2629 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2630 it != recv_codecs_.end(); ++it) {
2631 webrtc::CodecInst voe_codec;
2632 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2633 voe_codec.pltype = it->id;
2634 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2635 if (engine()->voe()->codec()->GetRecPayloadType(
2636 voe_channel(), voe_codec) != -1) {
2637 if (engine()->voe()->codec()->SetRecPayloadType(
2638 channel, voe_codec) == -1) {
2639 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2640 return false;
2641 }
2642 }
2643 }
2644 }
2645 }
2646
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002647 if (InConferenceMode()) {
2648 // To be in par with the video, voe_channel() is not used for receiving in
2649 // a conference call.
2650 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2651 // This is the first stream in a multi user meeting. We can now
2652 // disable playback of the default stream. This since the default
2653 // stream will probably have received some initial packets before
2654 // the new stream was added. This will mean that the CN state from
2655 // the default channel will be mixed in with the other streams
2656 // throughout the whole meeting, which might be disturbing.
2657 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2658 SetPlayout(voe_channel(), false);
2659 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002660 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002661 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002662
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002663 // Set RTP header extension for the new channel.
2664 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2665 return false;
2666 }
2667
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002668 return SetPlayout(channel, playout_);
2669}
2670
2671bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002672 DCHECK(thread_checker_.CalledOnValidThread());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002673 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002674 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002675 if (it == receive_channels_.end()) {
2676 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2677 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002678 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002679 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002680
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02002681 TryRemoveAudioRecvStream(ssrc);
2682
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002683 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2684 // will disconnect the audio renderer with the receive channel.
2685 // Cache the channel before the deletion.
2686 const int channel = it->second->channel();
2687 delete it->second;
2688 receive_channels_.erase(it);
2689
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002690 if (ssrc == default_receive_ssrc_) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02002691 DCHECK(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002692 // Recycle the default channel is for recv stream.
2693 if (playout_)
2694 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002695
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002696 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002697 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002698 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002699
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002700 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002701 << " with VoiceEngine channel #" << channel << ".";
2702 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002703 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002704
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002705 bool enable_default_channel_playout = false;
2706 if (receive_channels_.empty()) {
2707 // The last stream was removed. We can now enable the default
2708 // channel for new channels to be played out immediately without
2709 // waiting for AddStream messages.
2710 // We do this for both conference mode and non-conference mode.
2711 // TODO(oja): Does the default channel still have it's CN state?
2712 enable_default_channel_playout = true;
2713 }
2714 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2715 default_receive_ssrc_ != 0) {
2716 // Only the default channel is active, enable the playout on default
2717 // channel.
2718 enable_default_channel_playout = true;
2719 }
2720 if (enable_default_channel_playout && playout_) {
2721 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2722 SetPlayout(voe_channel(), true);
2723 }
2724
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002725 return true;
2726}
2727
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002728bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2729 AudioRenderer* renderer) {
2730 ChannelMap::iterator it = receive_channels_.find(ssrc);
2731 if (it == receive_channels_.end()) {
2732 if (renderer) {
2733 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002734 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002735 return false;
2736 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002737
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002738 // The channel likely has gone away, do nothing.
2739 return true;
2740 }
2741
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002742 if (renderer)
2743 it->second->Start(renderer);
2744 else
2745 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002746
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002747 return true;
2748}
2749
2750bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2751 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002752 ChannelMap::iterator it = send_channels_.find(ssrc);
2753 if (it == send_channels_.end()) {
2754 if (renderer) {
2755 // Return an error if trying to set a valid renderer with an invalid ssrc.
2756 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2757 return false;
2758 }
2759
2760 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002761 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002762 }
2763
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002764 if (renderer)
2765 it->second->Start(renderer);
2766 else
2767 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002768
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002769 return true;
2770}
2771
2772bool WebRtcVoiceMediaChannel::GetActiveStreams(
2773 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002774 // In conference mode, the default channel should not be in
2775 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002776 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002777 for (ChannelMap::iterator it = receive_channels_.begin();
2778 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002779 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002780 if (level > 0) {
2781 actives->push_back(std::make_pair(it->first, level));
2782 }
2783 }
2784 return true;
2785}
2786
2787int WebRtcVoiceMediaChannel::GetOutputLevel() {
2788 // return the highest output level of all streams
2789 int highest = GetOutputLevel(voe_channel());
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());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002793 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002794 }
2795 return highest;
2796}
2797
2798int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2799 int ret;
2800 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2801 // In case of error, log the info and continue
2802 LOG_RTCERR0(TimeSinceLastTyping);
2803 ret = -1;
2804 } else {
2805 ret *= 1000; // We return ms, webrtc returns seconds.
2806 }
2807 return ret;
2808}
2809
2810void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2811 int cost_per_typing, int reporting_threshold, int penalty_decay,
2812 int type_event_delay) {
2813 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2814 time_window, cost_per_typing,
2815 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2816 // In case of error, log the info and continue
2817 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2818 cost_per_typing, reporting_threshold, penalty_decay,
2819 type_event_delay);
2820 }
2821}
2822
2823bool WebRtcVoiceMediaChannel::SetOutputScaling(
2824 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002825 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002826 // Collect the channels to scale the output volume.
2827 std::vector<int> channels;
2828 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002829 // Default channel is not in receive_channels_ if it is not being used for
2830 // playout.
2831 if (default_receive_ssrc_ == 0)
2832 channels.push_back(voe_channel());
2833 for (ChannelMap::const_iterator it = receive_channels_.begin();
2834 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002835 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002836 }
2837 } else { // Collect only the channel of the specified ssrc.
2838 int channel = GetReceiveChannelNum(ssrc);
2839 if (-1 == channel) {
2840 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2841 return false;
2842 }
2843 channels.push_back(channel);
2844 }
2845
2846 // Scale the output volume for the collected channels. We first normalize to
2847 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002848 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002849 if (scale > 0.0001f) {
2850 left /= scale;
2851 right /= scale;
2852 }
2853 for (std::vector<int>::const_iterator it = channels.begin();
2854 it != channels.end(); ++it) {
2855 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2856 *it, scale)) {
2857 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2858 return false;
2859 }
2860 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2861 *it, static_cast<float>(left), static_cast<float>(right))) {
2862 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2863 // Do not return if fails. SetOutputVolumePan is not available for all
2864 // pltforms.
2865 }
2866 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2867 << " right=" << right * scale
2868 << " for channel " << *it << " and ssrc " << ssrc;
2869 }
2870 return true;
2871}
2872
2873bool WebRtcVoiceMediaChannel::GetOutputScaling(
2874 uint32 ssrc, double* left, double* right) {
2875 if (!left || !right) return false;
2876
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002877 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002878 // Determine which channel based on ssrc.
2879 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2880 if (channel == -1) {
2881 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2882 return false;
2883 }
2884
2885 float scaling;
2886 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2887 channel, scaling)) {
2888 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2889 return false;
2890 }
2891
2892 float left_pan;
2893 float right_pan;
2894 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2895 channel, left_pan, right_pan)) {
2896 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2897 // If GetOutputVolumePan fails, we use the default left and right pan.
2898 left_pan = 1.0f;
2899 right_pan = 1.0f;
2900 }
2901
2902 *left = scaling * left_pan;
2903 *right = scaling * right_pan;
2904 return true;
2905}
2906
2907bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2908 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2909 return true;
2910}
2911
2912bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2913 bool play, bool loop) {
2914 if (!ringback_tone_) {
2915 return false;
2916 }
2917
2918 // The voe file api is not available in chrome.
2919 if (!engine()->voe()->file()) {
2920 return false;
2921 }
2922
2923 // Determine which VoiceEngine channel to play on.
2924 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2925 if (channel == -1) {
2926 return false;
2927 }
2928
2929 // Make sure the ringtone is cued properly, and play it out.
2930 if (play) {
2931 ringback_tone_->set_loop(loop);
2932 ringback_tone_->Rewind();
2933 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2934 ringback_tone_.get()) == -1) {
2935 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2936 LOG(LS_ERROR) << "Unable to start ringback tone";
2937 return false;
2938 }
2939 ringback_channels_.insert(channel);
2940 LOG(LS_INFO) << "Started ringback on channel " << channel;
2941 } else {
2942 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2943 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2944 LOG_RTCERR1(StopPlayingFileLocally, channel);
2945 return false;
2946 }
2947 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2948 ringback_channels_.erase(channel);
2949 }
2950
2951 return true;
2952}
2953
2954bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2955 return dtmf_allowed_;
2956}
2957
2958bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2959 int duration, int flags) {
2960 if (!dtmf_allowed_) {
2961 return false;
2962 }
2963
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002964 // Send the event.
2965 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002966 int channel = -1;
2967 if (ssrc == 0) {
2968 bool default_channel_is_inuse = false;
2969 for (ChannelMap::const_iterator iter = send_channels_.begin();
2970 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002971 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002972 default_channel_is_inuse = true;
2973 break;
2974 }
2975 }
2976 if (default_channel_is_inuse) {
2977 channel = voe_channel();
2978 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002979 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002980 }
2981 } else {
2982 channel = GetSendChannelNum(ssrc);
2983 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002984 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002985 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2986 << ssrc << " is not in use.";
2987 return false;
2988 }
2989 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002990 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2991 channel, event, true, duration) == -1) {
2992 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002993 return false;
2994 }
2995 }
2996
2997 // Play the event.
2998 if (flags & cricket::DF_PLAY) {
2999 // Play DTMF tone locally.
3000 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3001 LOG_RTCERR2(PlayDtmfTone, event, duration);
3002 return false;
3003 }
3004 }
3005
3006 return true;
3007}
3008
wu@webrtc.orga9890802013-12-13 00:21:03 +00003009void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003010 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003011 DCHECK(thread_checker_.CalledOnValidThread());
3012
3013 // If hooked up to a "Call", forward packet there too.
3014 if (call_) {
3015 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3016 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3017 }
3018
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003019 // Pick which channel to send this packet to. If this packet doesn't match
3020 // any multiplexed streams, just send it to the default channel. Otherwise,
3021 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003022 int which_channel =
3023 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003024 if (which_channel == -1) {
3025 which_channel = voe_channel();
3026 }
3027
3028 // Stop any ringback that might be playing on the channel.
3029 // It's possible the ringback has already stopped, ih which case we'll just
3030 // use the opportunity to remove the channel from ringback_channels_.
3031 if (engine()->voe()->file()) {
3032 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3033 if (it != ringback_channels_.end()) {
3034 if (engine()->voe()->file()->IsPlayingFileLocally(
3035 which_channel) == 1) {
3036 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3037 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3038 << " due to incoming media";
3039 }
3040 ringback_channels_.erase(which_channel);
3041 }
3042 }
3043
3044 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003045 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003046 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003047 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003048}
3049
wu@webrtc.orga9890802013-12-13 00:21:03 +00003050void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003051 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003052 DCHECK(thread_checker_.CalledOnValidThread());
3053
3054 // If hooked up to a "Call", forward packet there too.
3055 if (call_) {
3056 call_->Receiver()->DeliverPacket(webrtc::MediaType::AUDIO,
3057 reinterpret_cast<const uint8_t*>(packet->data()), packet->size());
3058 }
3059
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003060 // Sending channels need all RTCP packets with feedback information.
3061 // Even sender reports can contain attached report blocks.
3062 // Receiving channels need sender reports in order to create
3063 // correct receiver reports.
3064 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003065 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003066 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3067 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003068 }
3069
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003070 // If it is a sender report, find the channel that is listening.
3071 bool has_sent_to_default_channel = false;
3072 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003073 int which_channel =
3074 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003075 if (which_channel != -1) {
3076 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003077 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003078
3079 if (IsDefaultChannel(which_channel))
3080 has_sent_to_default_channel = true;
3081 }
3082 }
3083
3084 // SR may continue RR and any RR entry may correspond to any one of the send
3085 // channels. So all RTCP packets must be forwarded all send channels. VoE
3086 // will filter out RR internally.
3087 for (ChannelMap::iterator iter = send_channels_.begin();
3088 iter != send_channels_.end(); ++iter) {
3089 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003090 if (IsDefaultChannel(iter->second->channel()) &&
3091 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003092 continue;
3093
3094 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003095 iter->second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003096 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003097}
3098
3099bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003100 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3101 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003102 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3103 return false;
3104 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003105 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3106 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003107 return false;
3108 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003109 // We set the AGC to mute state only when all the channels are muted.
3110 // This implementation is not ideal, instead we should signal the AGC when
3111 // the mic channel is muted/unmuted. We can't do it today because there
3112 // is no good way to know which stream is mapping to the mic channel.
3113 bool all_muted = muted;
3114 for (ChannelMap::const_iterator iter = send_channels_.begin();
3115 iter != send_channels_.end() && all_muted; ++iter) {
3116 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3117 all_muted)) {
3118 LOG_RTCERR1(GetInputMute, iter->second->channel());
3119 return false;
3120 }
3121 }
3122
3123 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3124 if (ap)
3125 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003126 return true;
3127}
3128
minyue@webrtc.org26236952014-10-29 02:27:08 +00003129// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3130// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003131bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003132 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003133
minyue@webrtc.org26236952014-10-29 02:27:08 +00003134 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003135}
3136
minyue@webrtc.org26236952014-10-29 02:27:08 +00003137bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3138 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003139
minyue@webrtc.org26236952014-10-29 02:27:08 +00003140 send_bitrate_setting_ = true;
3141 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003142
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003143 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003144 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003145 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003146 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003147 }
3148
minyue@webrtc.org26236952014-10-29 02:27:08 +00003149 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003150 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3151 // SetMaxSendBandwith(0), the second call removes the previous limit.
3152 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003153 return true;
3154
3155 webrtc::CodecInst codec = *send_codec_;
3156 bool is_multi_rate = IsCodecMultiRate(codec);
3157
3158 if (is_multi_rate) {
3159 // If codec is multi-rate then just set the bitrate.
3160 codec.rate = bps;
3161 if (!SetSendCodec(codec)) {
3162 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3163 << " to bitrate " << bps << " bps.";
3164 return false;
3165 }
3166 return true;
3167 } else {
3168 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3169 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3170 // fixed bitrate then ignore.
3171 if (bps < codec.rate) {
3172 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3173 << " to bitrate " << bps << " bps"
3174 << ", requires at least " << codec.rate << " bps.";
3175 return false;
3176 }
3177 return true;
3178 }
3179}
3180
3181bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003182 bool echo_metrics_on = false;
3183 // These can take on valid negative values, so use the lowest possible level
3184 // as default rather than -1.
3185 int echo_return_loss = -100;
3186 int echo_return_loss_enhancement = -100;
3187 // These can also be negative, but in practice -1 is only used to signal
3188 // insufficient data, since the resolution is limited to multiples of 4 ms.
3189 int echo_delay_median_ms = -1;
3190 int echo_delay_std_ms = -1;
3191 if (engine()->voe()->processing()->GetEcMetricsStatus(
3192 echo_metrics_on) != -1 && echo_metrics_on) {
3193 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3194 // here, but it appears to be unsuitable currently. Revisit after this is
3195 // investigated: http://b/issue?id=5666755
3196 int erl, erle, rerl, anlp;
3197 if (engine()->voe()->processing()->GetEchoMetrics(
3198 erl, erle, rerl, anlp) != -1) {
3199 echo_return_loss = erl;
3200 echo_return_loss_enhancement = erle;
3201 }
3202
3203 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003204 float dummy;
3205 if (engine()->voe()->processing()->GetEcDelayMetrics(
3206 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003207 echo_delay_median_ms = median;
3208 echo_delay_std_ms = std;
3209 }
3210 }
3211
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003212 webrtc::CallStatistics cs;
3213 unsigned int ssrc;
3214 webrtc::CodecInst codec;
3215 unsigned int level;
3216
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003217 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3218 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003219 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003220
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003221 // Fill in the sender info, based on what we know, and what the
3222 // remote side told us it got from its RTCP report.
3223 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003224
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003225 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3226 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3227 continue;
3228 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003229
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003230 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003231 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3232 sinfo.bytes_sent = cs.bytesSent;
3233 sinfo.packets_sent = cs.packetsSent;
3234 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3235 // returns 0 to indicate an error value.
3236 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3237
3238 // Get data from the last remote RTCP report. Use default values if no data
3239 // available.
3240 sinfo.fraction_lost = -1.0;
3241 sinfo.jitter_ms = -1;
3242 sinfo.packets_lost = -1;
3243 sinfo.ext_seqnum = -1;
3244 std::vector<webrtc::ReportBlock> receive_blocks;
3245 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3246 channel, &receive_blocks) != -1 &&
3247 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3248 std::vector<webrtc::ReportBlock>::iterator iter;
3249 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3250 ++iter) {
3251 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003252 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003253 // Convert Q8 to floating point.
3254 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3255 // Convert samples to milliseconds.
3256 if (codec.plfreq / 1000 > 0) {
3257 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3258 }
3259 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3260 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3261 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003262 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003263 }
3264 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003265
3266 // Local speech level.
3267 sinfo.audio_level = (engine()->voe()->volume()->
3268 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3269
3270 // TODO(xians): We are injecting the same APM logging to all the send
3271 // channels here because there is no good way to know which send channel
3272 // is using the APM. The correct fix is to allow the send channels to have
3273 // their own APM so that we can feed the correct APM logging to different
3274 // send channels. See issue crbug/264611 .
3275 sinfo.echo_return_loss = echo_return_loss;
3276 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3277 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3278 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003279 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3280 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003281 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003282
3283 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003284 }
3285
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003286 // Build the list of receivers, one for each receiving channel, or 1 in
3287 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003288 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003289 for (ChannelMap::const_iterator it = receive_channels_.begin();
3290 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003291 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003292 }
3293 if (channels.empty()) {
3294 channels.push_back(voe_channel());
3295 }
3296
3297 // Get the SSRC and stats for each receiver, based on our own calculations.
3298 for (std::vector<int>::const_iterator it = channels.begin();
3299 it != channels.end(); ++it) {
3300 memset(&cs, 0, sizeof(cs));
3301 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3302 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3303 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3304 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003305 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003306 rinfo.bytes_rcvd = cs.bytesReceived;
3307 rinfo.packets_rcvd = cs.packetsReceived;
3308 // The next four fields are from the most recently sent RTCP report.
3309 // Convert Q8 to floating point.
3310 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3311 rinfo.packets_lost = cs.cumulativeLost;
3312 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003313 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003314 if (codec.pltype != -1) {
3315 rinfo.codec_name = codec.plname;
3316 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003317 // Convert samples to milliseconds.
3318 if (codec.plfreq / 1000 > 0) {
3319 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3320 }
3321
3322 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3323 webrtc::NetworkStatistics ns;
3324 if (engine()->voe()->neteq() &&
3325 engine()->voe()->neteq()->GetNetworkStatistics(
3326 *it, ns) != -1) {
3327 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3328 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3329 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003330 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003331 rinfo.speech_expand_rate =
3332 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3333 rinfo.secondary_decoded_rate =
3334 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003335 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003336
3337 webrtc::AudioDecodingCallStats ds;
3338 if (engine()->voe()->neteq() &&
3339 engine()->voe()->neteq()->GetDecodingCallStatistics(
3340 *it, &ds) != -1) {
3341 rinfo.decoding_calls_to_silence_generator =
3342 ds.calls_to_silence_generator;
3343 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3344 rinfo.decoding_normal = ds.decoded_normal;
3345 rinfo.decoding_plc = ds.decoded_plc;
3346 rinfo.decoding_cng = ds.decoded_cng;
3347 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3348 }
3349
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003350 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003351 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003352 int playout_buffer_delay_ms = 0;
3353 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003354 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3355 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3356 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003357 }
3358
3359 // Get speech level.
3360 rinfo.audio_level = (engine()->voe()->volume()->
3361 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3362 info->receivers.push_back(rinfo);
3363 }
3364 }
3365
3366 return true;
3367}
3368
3369void WebRtcVoiceMediaChannel::GetLastMediaError(
3370 uint32* ssrc, VoiceMediaChannel::Error* error) {
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003371 DCHECK(ssrc != NULL);
3372 DCHECK(error != NULL);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003373 FindSsrc(voe_channel(), ssrc);
3374 *error = WebRtcErrorToChannelError(GetLastEngineError());
3375}
3376
3377bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003378 rtc::CritScope lock(&receive_channels_cs_);
Fredrik Solenbergd3ddc1b2015-05-07 17:07:34 +02003379 DCHECK(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003380 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003381 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3382 // This means the error is not limited to a specific channel. Signal the
3383 // message using ssrc=0. If the current channel is sending, use this
3384 // channel for sending the message.
3385 *ssrc = 0;
3386 return true;
3387 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003388 // Check whether this is a sending channel.
3389 for (ChannelMap::const_iterator it = send_channels_.begin();
3390 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003391 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003392 // This is a sending channel.
3393 uint32 local_ssrc = 0;
3394 if (engine()->voe()->rtp()->GetLocalSSRC(
3395 channel_num, local_ssrc) != -1) {
3396 *ssrc = local_ssrc;
3397 }
3398 return true;
3399 }
3400 }
3401
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003402 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003403 for (ChannelMap::const_iterator it = receive_channels_.begin();
3404 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003405 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003406 *ssrc = it->first;
3407 return true;
3408 }
3409 }
3410 }
3411 return false;
3412}
3413
3414void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003415 if (error == VE_TYPING_NOISE_WARNING) {
3416 typing_noise_detected_ = true;
3417 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3418 typing_noise_detected_ = false;
3419 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003420 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3421}
3422
3423int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3424 unsigned int ulevel;
3425 int ret =
3426 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3427 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3428}
3429
3430int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003431 ChannelMap::iterator it = receive_channels_.find(ssrc);
3432 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003433 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003434 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3435}
3436
3437int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003438 ChannelMap::iterator it = send_channels_.find(ssrc);
3439 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003440 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003441
3442 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003443}
3444
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003445void WebRtcVoiceMediaChannel::SetCall(webrtc::Call* call) {
3446 DCHECK(thread_checker_.CalledOnValidThread());
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003447 for (const auto& it : receive_channels_) {
3448 TryRemoveAudioRecvStream(it.first);
3449 }
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003450 call_ = call;
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003451 for (const auto& it : receive_channels_) {
3452 TryAddAudioRecvStream(it.first);
3453 }
3454}
3455
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003456bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3457 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3458 // Get the RED encodings from the parameter with no name. This may
3459 // change based on what is discussed on the Jingle list.
3460 // The encoding parameter is of the form "a/b"; we only support where
3461 // a == b. Verify this and parse out the value into red_pt.
3462 // If the parameter value is absent (as it will be until we wire up the
3463 // signaling of this message), use the second codec specified (i.e. the
3464 // one after "red") as the encoding parameter.
3465 int red_pt = -1;
3466 std::string red_params;
3467 CodecParameterMap::const_iterator it = red_codec.params.find("");
3468 if (it != red_codec.params.end()) {
3469 red_params = it->second;
3470 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003471 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003472 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003473 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003474 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3475 return false;
3476 }
3477 } else if (red_codec.params.empty()) {
3478 LOG(LS_WARNING) << "RED params not present, using defaults";
3479 if (all_codecs.size() > 1) {
3480 red_pt = all_codecs[1].id;
3481 }
3482 }
3483
3484 // Try to find red_pt in |codecs|.
3485 std::vector<AudioCodec>::const_iterator codec;
3486 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3487 if (codec->id == red_pt)
3488 break;
3489 }
3490
3491 // If we find the right codec, that will be the codec we pass to
3492 // SetSendCodec, with the desired payload type.
3493 if (codec != all_codecs.end() &&
3494 engine()->FindWebRtcCodec(*codec, send_codec)) {
3495 } else {
3496 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3497 return false;
3498 }
3499
3500 return true;
3501}
3502
3503bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3504 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003505 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003506 return false;
3507 }
3508 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3509 // what we want to do with them.
3510 // engine()->voe().EnableVQMon(voe_channel(), true);
3511 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3512 return true;
3513}
3514
3515bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3516 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3517 for (int i = 0; i < ncodecs; ++i) {
3518 webrtc::CodecInst voe_codec;
3519 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3520 voe_codec.pltype = -1;
3521 if (engine()->voe()->codec()->SetRecPayloadType(
3522 channel, voe_codec) == -1) {
3523 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3524 return false;
3525 }
3526 }
3527 }
3528 return true;
3529}
3530
3531bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3532 if (playout) {
3533 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3534 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3535 LOG_RTCERR1(StartPlayout, channel);
3536 return false;
3537 }
3538 } else {
3539 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3540 engine()->voe()->base()->StopPlayout(channel);
3541 }
3542 return true;
3543}
3544
3545uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3546 bool rtcp) {
3547 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3548 uint32 ssrc = 0;
3549 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003550 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003551 }
3552 return ssrc;
3553}
3554
3555// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3556VoiceMediaChannel::Error
3557 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3558 switch (err_code) {
3559 case 0:
3560 return ERROR_NONE;
3561 case VE_CANNOT_START_RECORDING:
3562 case VE_MIC_VOL_ERROR:
3563 case VE_GET_MIC_VOL_ERROR:
3564 case VE_CANNOT_ACCESS_MIC_VOL:
3565 return ERROR_REC_DEVICE_OPEN_FAILED;
3566 case VE_SATURATION_WARNING:
3567 return ERROR_REC_DEVICE_SATURATION;
3568 case VE_REC_DEVICE_REMOVED:
3569 return ERROR_REC_DEVICE_REMOVED;
3570 case VE_RUNTIME_REC_WARNING:
3571 case VE_RUNTIME_REC_ERROR:
3572 return ERROR_REC_RUNTIME_ERROR;
3573 case VE_CANNOT_START_PLAYOUT:
3574 case VE_SPEAKER_VOL_ERROR:
3575 case VE_GET_SPEAKER_VOL_ERROR:
3576 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3577 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3578 case VE_RUNTIME_PLAY_WARNING:
3579 case VE_RUNTIME_PLAY_ERROR:
3580 return ERROR_PLAY_RUNTIME_ERROR;
3581 case VE_TYPING_NOISE_WARNING:
3582 return ERROR_REC_TYPING_NOISE_DETECTED;
3583 default:
3584 return VoiceMediaChannel::ERROR_OTHER;
3585 }
3586}
3587
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003588bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3589 int channel_id, const RtpHeaderExtension* extension) {
3590 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003591 int id = 0;
3592 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003593 if (extension) {
3594 enable = true;
3595 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003596 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003597 }
3598 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003599 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003600 return false;
3601 }
3602 return true;
3603}
3604
Fredrik Solenberg4b60c732015-05-07 14:07:48 +02003605void WebRtcVoiceMediaChannel::TryAddAudioRecvStream(uint32 ssrc) {
3606 DCHECK(thread_checker_.CalledOnValidThread());
3607 // If we are hooked up to a webrtc::Call, create an AudioReceiveStream too.
3608 if (call_ && options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false)) {
3609 DCHECK(receive_streams_.find(ssrc) == receive_streams_.end());
3610 webrtc::AudioReceiveStream::Config config;
3611 config.rtp.remote_ssrc = ssrc;
3612 config.rtp.extensions = recv_rtp_extensions_;
3613 webrtc::AudioReceiveStream* s = call_->CreateAudioReceiveStream(config);
3614 receive_streams_.insert(std::make_pair(ssrc, s));
3615 }
3616}
3617
3618void WebRtcVoiceMediaChannel::TryRemoveAudioRecvStream(uint32 ssrc) {
3619 DCHECK(thread_checker_.CalledOnValidThread());
3620 // If we are hooked up to a webrtc::Call, assume there is an
3621 // AudioReceiveStream to destroy too.
3622 if (call_) {
3623 auto stream_it = receive_streams_.find(ssrc);
3624 if (stream_it != receive_streams_.end()) {
3625 call_->DestroyAudioReceiveStream(stream_it->second);
3626 receive_streams_.erase(stream_it);
3627 }
3628 }
3629}
3630
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003631int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003632 size_t res = 0;
3633 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003634 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003635}
3636
3637int WebRtcSoundclipStream::Rewind() {
3638 mem_.Rewind();
3639 // Return -1 to keep VoiceEngine from looping.
3640 return (loop_) ? 0 : -1;
3641}
3642
3643} // namespace cricket
3644
3645#endif // HAVE_WEBRTC_VOICE