blob: 32a80bb456c6332b10dc2c1f38d65f3fec10f7c2 [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"
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +000056#include "webrtc/video_engine/include/vie_network.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
58#ifdef WIN32
59#include <objbase.h> // NOLINT
60#endif
61
62namespace cricket {
63
Brave Yao5225dd82015-03-26 07:39:19 +080064static const int kMaxNumPacketSize = 6;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000065struct CodecPref {
66 const char* name;
67 int clockrate;
68 int channels;
69 int payload_type;
70 bool is_multi_rate;
Brave Yao5225dd82015-03-26 07:39:19 +080071 int packet_sizes_ms[kMaxNumPacketSize];
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072};
Brave Yao5225dd82015-03-26 07:39:19 +080073// Note: keep the supported packet sizes in ascending order.
henrike@webrtc.org28e20752013-07-10 00:45:36 +000074static const CodecPref kCodecPrefs[] = {
Brave Yao5225dd82015-03-26 07:39:19 +080075 { kOpusCodecName, 48000, 2, 111, true, { 10, 20, 40, 60 } },
76 { kIsacCodecName, 16000, 1, 103, true, { 30, 60 } },
77 { kIsacCodecName, 32000, 1, 104, true, { 30 } },
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +000078 // G722 should be advertised as 8000 Hz because of the RFC "bug".
Brave Yao5225dd82015-03-26 07:39:19 +080079 { kG722CodecName, 8000, 1, 9, false, { 10, 20, 30, 40, 50, 60 } },
80 { kIlbcCodecName, 8000, 1, 102, false, { 20, 30, 40, 60 } },
81 { kPcmuCodecName, 8000, 1, 0, false, { 10, 20, 30, 40, 50, 60 } },
82 { kPcmaCodecName, 8000, 1, 8, false, { 10, 20, 30, 40, 50, 60 } },
Brave Yao5225dd82015-03-26 07:39:19 +080083 { kCnCodecName, 32000, 1, 106, false, { } },
84 { kCnCodecName, 16000, 1, 105, false, { } },
85 { kCnCodecName, 8000, 1, 13, false, { } },
86 { kRedCodecName, 8000, 1, 127, false, { } },
87 { kDtmfCodecName, 8000, 1, 126, false, { } },
henrike@webrtc.org28e20752013-07-10 00:45:36 +000088};
89
90// For Linux/Mac, using the default device is done by specifying index 0 for
91// VoE 4.0 and not -1 (which was the case for VoE 3.5).
92//
93// On Windows Vista and newer, Microsoft introduced the concept of "Default
94// Communications Device". This means that there are two types of default
95// devices (old Wave Audio style default and Default Communications Device).
96//
97// On Windows systems which only support Wave Audio style default, uses either
98// -1 or 0 to select the default device.
99//
100// On Windows systems which support both "Default Communication Device" and
101// old Wave Audio style default, use -1 for Default Communications Device and
102// -2 for Wave Audio style default, which is what we want to use for clips.
103// It's not clear yet whether the -2 index is handled properly on other OSes.
104
105#ifdef WIN32
106static const int kDefaultAudioDeviceId = -1;
107static const int kDefaultSoundclipDeviceId = -2;
108#else
109static const int kDefaultAudioDeviceId = 0;
110#endif
111
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112// Parameter used for NACK.
113// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
114static const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000115
116// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000117// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000118
119// Recommended bitrates:
120// 8-12 kb/s for NB speech,
121// 16-20 kb/s for WB speech,
122// 28-40 kb/s for FB speech,
123// 48-64 kb/s for FB mono music, and
124// 64-128 kb/s for FB stereo music.
125// The current implementation applies the following values to mono signals,
126// and multiplies them by 2 for stereo.
127static const int kOpusBitrateNb = 12000;
128static const int kOpusBitrateWb = 20000;
129static const int kOpusBitrateFb = 32000;
130
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000131// Opus bitrate should be in the range between 6000 and 510000.
132static const int kOpusMinBitrate = 6000;
133static const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000134
wu@webrtc.orgde305012013-10-31 15:40:38 +0000135// Default audio dscp value.
136// See http://tools.ietf.org/html/rfc2474 for details.
137// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000138static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000139
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000140// Ensure we open the file in a writeable path on ChromeOS and Android. This
141// workaround can be removed when it's possible to specify a filename for audio
142// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000143//
144// TODO(grunell): Use a string in the options instead of hardcoding it here
145// and let the embedder choose the filename (crbug.com/264223).
146//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000147// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
148// below.
149#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000150static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000151#elif defined(ANDROID)
152static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000153#else
154static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
155#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000156
157// Dumps an AudioCodec in RFC 2327-ish format.
158static std::string ToString(const AudioCodec& codec) {
159 std::stringstream ss;
160 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
161 << " (" << codec.id << ")";
162 return ss.str();
163}
Minyue Li7100dcd2015-03-27 05:05:59 +0100164
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000165static std::string ToString(const webrtc::CodecInst& codec) {
166 std::stringstream ss;
167 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
168 << " (" << codec.pltype << ")";
169 return ss.str();
170}
171
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000172static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000173 const char* delim = "\r\n";
174 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
175 LOG_V(sev) << tok;
176 }
177}
178
179// Severity is an integer because it comes is assumed to be from command line.
180static int SeverityToFilter(int severity) {
181 int filter = webrtc::kTraceNone;
182 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000183 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000184 filter |= webrtc::kTraceAll;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000185 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000186 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
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);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000189 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000190 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
191 }
192 return filter;
193}
194
Minyue Li7100dcd2015-03-27 05:05:59 +0100195static bool IsCodec(const AudioCodec& codec, const char* ref_name) {
196 return (_stricmp(codec.name.c_str(), ref_name) == 0);
197}
198
199static bool IsCodec(const webrtc::CodecInst& codec, const char* ref_name) {
200 return (_stricmp(codec.plname, ref_name) == 0);
201}
202
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000203static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
204 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100205 if (IsCodec(codec, kCodecPrefs[i].name) &&
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000206 kCodecPrefs[i].clockrate == codec.plfreq) {
207 return kCodecPrefs[i].is_multi_rate;
208 }
209 }
210 return false;
211}
212
213static bool FindCodec(const std::vector<AudioCodec>& codecs,
214 const AudioCodec& codec,
215 AudioCodec* found_codec) {
216 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
217 it != codecs.end(); ++it) {
218 if (it->Matches(codec)) {
219 if (found_codec != NULL) {
220 *found_codec = *it;
221 }
222 return true;
223 }
224 }
225 return false;
226}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000227
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000228static bool IsNackEnabled(const AudioCodec& codec) {
229 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
230 kParamValueEmpty));
231}
232
Brave Yao5225dd82015-03-26 07:39:19 +0800233static int SelectPacketSize(const CodecPref& codec_pref, int ptime_ms) {
234 int selected_packet_size_ms = codec_pref.packet_sizes_ms[0];
235 for (int packet_size_ms : codec_pref.packet_sizes_ms) {
236 if (packet_size_ms && packet_size_ms <= ptime_ms) {
237 selected_packet_size_ms = packet_size_ms;
238 }
239 }
240 return selected_packet_size_ms;
241}
242
243// If the AudioCodec param kCodecParamPTime is set, then we will set it to codec
244// pacsize if it's valid, or we will pick the next smallest value we support.
245// TODO(Brave): Query supported packet sizes from ACM when the API is ready.
246static bool SetPTimeAsPacketSize(webrtc::CodecInst* codec, int ptime_ms) {
247 for (const CodecPref& codec_pref : kCodecPrefs) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100248 if ((IsCodec(*codec, codec_pref.name) &&
Brave Yao5225dd82015-03-26 07:39:19 +0800249 codec_pref.clockrate == codec->plfreq) ||
Minyue Li7100dcd2015-03-27 05:05:59 +0100250 IsCodec(*codec, kG722CodecName)) {
Brave Yao5225dd82015-03-26 07:39:19 +0800251 int packet_size_ms = SelectPacketSize(codec_pref, ptime_ms);
252 if (packet_size_ms) {
253 // Convert unit from milli-seconds to samples.
254 codec->pacsize = (codec->plfreq / 1000) * packet_size_ms;
255 return true;
256 }
257 }
258 }
259 return false;
260}
261
Minyue Li7100dcd2015-03-27 05:05:59 +0100262// Return true if codec.params[feature] == "1", false otherwise.
263static bool IsCodecFeatureEnabled(const AudioCodec& codec,
264 const char* feature) {
265 int value;
266 return codec.GetParam(feature, &value) && value == 1;
267}
268
269// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
270// otherwise. If the value (either from params or codec.bitrate) <=0, use the
271// default configuration. If the value is beyond feasible bit rate of Opus,
272// clamp it. Returns the Opus bit rate for operation.
273static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
274 int bitrate = 0;
275 bool use_param = true;
276 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
277 bitrate = codec.bitrate;
278 use_param = false;
279 }
280 if (bitrate <= 0) {
281 if (max_playback_rate <= 8000) {
282 bitrate = kOpusBitrateNb;
283 } else if (max_playback_rate <= 16000) {
284 bitrate = kOpusBitrateWb;
285 } else {
286 bitrate = kOpusBitrateFb;
287 }
288
289 if (IsCodecFeatureEnabled(codec, kCodecParamStereo)) {
290 bitrate *= 2;
291 }
292 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
293 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
294 std::string rate_source =
295 use_param ? "Codec parameter \"maxaveragebitrate\"" :
296 "Supplied Opus bitrate";
297 LOG(LS_WARNING) << rate_source
298 << " is invalid and is replaced by: "
299 << bitrate;
300 }
301 return bitrate;
302}
303
304// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
305// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
306static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
307 int value;
308 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
309 return value;
310 }
311 return kOpusDefaultMaxPlaybackRate;
312}
313
314static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
315 bool* enable_codec_fec, int* max_playback_rate,
316 bool* enable_codec_dtx) {
317 *enable_codec_fec = IsCodecFeatureEnabled(codec, kCodecParamUseInbandFec);
318 *enable_codec_dtx = IsCodecFeatureEnabled(codec, kCodecParamUseDtx);
319 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
320
321 // If OPUS, change what we send according to the "stereo" codec
322 // parameter, and not the "channels" parameter. We set
323 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
324 // the bitrate is not specified, i.e. is <= zero, we set it to the
325 // appropriate default value for mono or stereo Opus.
326
327 voe_codec->channels = IsCodecFeatureEnabled(codec, kCodecParamStereo) ? 2 : 1;
328 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
329}
330
331// Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
332// which says that G722 should be advertised as 8 kHz although it is a 16 kHz
333// codec.
334static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
335 if (IsCodec(*voe_codec, kG722CodecName)) {
336 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
337 // has changed, and this special case is no longer needed.
338 ASSERT(voe_codec->plfreq != new_plfreq);
339 voe_codec->plfreq = new_plfreq;
340 }
341}
342
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000343// Gets the default set of options applied to the engine. Historically, these
344// were supplied as a combination of flags from the channel manager (ec, agc,
345// ns, and highpass) and the rest hardcoded in InitInternal.
346static AudioOptions GetDefaultEngineOptions() {
347 AudioOptions options;
348 options.echo_cancellation.Set(true);
349 options.auto_gain_control.Set(true);
350 options.noise_suppression.Set(true);
351 options.highpass_filter.Set(true);
352 options.stereo_swapping.Set(false);
353 options.typing_detection.Set(true);
354 options.conference_mode.Set(false);
355 options.adjust_agc_delta.Set(0);
356 options.experimental_agc.Set(false);
357 options.experimental_aec.Set(false);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100358 options.delay_agnostic_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000359 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000360 options.aec_dump.Set(false);
361 return options;
362}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000363
Minyue Li7100dcd2015-03-27 05:05:59 +0100364static std::string GetEnableString(bool enable) {
365 return enable ? "enable" : "disable";
Brave Yao5225dd82015-03-26 07:39:19 +0800366}
367
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000368class WebRtcSoundclipMedia : public SoundclipMedia {
369 public:
370 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
371 : engine_(engine), webrtc_channel_(-1) {
372 engine_->RegisterSoundclip(this);
373 }
374
375 virtual ~WebRtcSoundclipMedia() {
376 engine_->UnregisterSoundclip(this);
377 if (webrtc_channel_ != -1) {
378 // We shouldn't have to call Disable() here. DeleteChannel() should call
379 // StopPlayout() while deleting the channel. We should fix the bug
380 // inside WebRTC and remove the Disable() call bellow. This work is
381 // tracked by bug http://b/issue?id=5382855.
382 PlaySound(NULL, 0, 0);
383 Disable();
384 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
385 == -1) {
386 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
387 }
388 }
389 }
390
391 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000392 if (!engine_->voe_sc()) {
393 return false;
394 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000395 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000396 if (webrtc_channel_ == -1) {
397 LOG_RTCERR0(CreateChannel);
398 return false;
399 }
400 return true;
401 }
402
403 bool Enable() {
404 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
405 LOG_RTCERR1(StartPlayout, webrtc_channel_);
406 return false;
407 }
408 return true;
409 }
410
411 bool Disable() {
412 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
413 LOG_RTCERR1(StopPlayout, webrtc_channel_);
414 return false;
415 }
416 return true;
417 }
418
419 virtual bool PlaySound(const char *buf, int len, int flags) {
420 // The voe file api is not available in chrome.
421 if (!engine_->voe_sc()->file()) {
422 return false;
423 }
424 // Must stop playing the current sound (if any), because we are about to
425 // modify the stream.
426 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
427 == -1) {
428 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
429 return false;
430 }
431
432 if (buf) {
433 stream_.reset(new WebRtcSoundclipStream(buf, len));
434 stream_->set_loop((flags & SF_LOOP) != 0);
435 stream_->Rewind();
436
437 // Play it.
438 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
439 webrtc_channel_, stream_.get()) == -1) {
440 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
441 LOG(LS_ERROR) << "Unable to start soundclip";
442 return false;
443 }
444 } else {
445 stream_.reset();
446 }
447 return true;
448 }
449
450 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
451
452 private:
453 WebRtcVoiceEngine *engine_;
454 int webrtc_channel_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000455 rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000456};
457
458WebRtcVoiceEngine::WebRtcVoiceEngine()
459 : voe_wrapper_(new VoEWrapper()),
460 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000461 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000462 tracing_(new VoETraceWrapper()),
463 adm_(NULL),
464 adm_sc_(NULL),
465 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
466 is_dumping_aec_(false),
467 desired_local_monitor_enable_(false),
468 tx_processor_ssrc_(0),
469 rx_processor_ssrc_(0) {
470 Construct();
471}
472
473WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
474 VoEWrapper* voe_wrapper_sc,
475 VoETraceWrapper* tracing)
476 : voe_wrapper_(voe_wrapper),
477 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000478 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000479 tracing_(tracing),
480 adm_(NULL),
481 adm_sc_(NULL),
482 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
483 is_dumping_aec_(false),
484 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000485 tx_processor_ssrc_(0),
486 rx_processor_ssrc_(0) {
487 Construct();
488}
489
490void WebRtcVoiceEngine::Construct() {
491 SetTraceFilter(log_filter_);
492 initialized_ = false;
493 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
494 SetTraceOptions("");
495 if (tracing_->SetTraceCallback(this) == -1) {
496 LOG_RTCERR0(SetTraceCallback);
497 }
498 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
499 LOG_RTCERR0(RegisterVoiceEngineObserver);
500 }
501 // Clear the default agc state.
502 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
503
504 // Load our audio codec list.
505 ConstructCodecs();
506
507 // Load our RTP Header extensions.
508 rtp_header_extensions_.push_back(
509 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
510 kRtpAudioLevelHeaderExtensionDefaultId));
511 rtp_header_extensions_.push_back(
512 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
513 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
514 options_ = GetDefaultEngineOptions();
515}
516
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000517void WebRtcVoiceEngine::ConstructCodecs() {
518 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
519 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
520 for (int i = 0; i < ncodecs; ++i) {
521 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000522 if (GetVoeCodec(i, &voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000523 // Skip uncompressed formats.
Minyue Li7100dcd2015-03-27 05:05:59 +0100524 if (IsCodec(voe_codec, kL16CodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000525 continue;
526 }
527
528 const CodecPref* pref = NULL;
529 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
Minyue Li7100dcd2015-03-27 05:05:59 +0100530 if (IsCodec(voe_codec, kCodecPrefs[j].name) &&
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000531 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
532 kCodecPrefs[j].channels == voe_codec.channels) {
533 pref = &kCodecPrefs[j];
534 break;
535 }
536 }
537
538 if (pref) {
539 // Use the payload type that we've configured in our pref table;
540 // use the offset in our pref table to determine the sort order.
541 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
542 voe_codec.rate, voe_codec.channels,
543 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
544 LOG(LS_INFO) << ToString(codec);
Minyue Li7100dcd2015-03-27 05:05:59 +0100545 if (IsCodec(codec, kIsacCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000546 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000547 codec.bitrate = 0;
548 }
Minyue Li7100dcd2015-03-27 05:05:59 +0100549 if (IsCodec(codec, kOpusCodecName)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000550 // Only add fmtp parameters that differ from the spec.
551 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
552 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000553 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000554 }
555 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
556 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000557 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000558 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000559 codec.SetParam(kCodecParamUseInbandFec, 1);
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000560
561 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000562 // when they can be set to values other than the default.
563 }
564 codecs_.push_back(codec);
565 } else {
566 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
567 }
568 }
569 }
570 // Make sure they are in local preference order.
571 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
572}
573
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000574bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst* codec) {
575 if (voe_wrapper_->codec()->GetCodec(index, *codec) == -1) {
576 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000577 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000578 // Change the sample rate of G722 to 8000 to match SDP.
579 MaybeFixupG722(codec, 8000);
580 return true;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000581}
582
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000583WebRtcVoiceEngine::~WebRtcVoiceEngine() {
584 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
585 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
586 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
587 }
588 if (adm_) {
589 voe_wrapper_.reset();
590 adm_->Release();
591 adm_ = NULL;
592 }
593 if (adm_sc_) {
594 voe_wrapper_sc_.reset();
595 adm_sc_->Release();
596 adm_sc_ = NULL;
597 }
598
599 // Test to see if the media processor was deregistered properly
600 ASSERT(SignalRxMediaFrame.is_empty());
601 ASSERT(SignalTxMediaFrame.is_empty());
602
603 tracing_->SetTraceCallback(NULL);
604}
605
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000606bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
henrika@webrtc.org62f6e752015-02-11 08:38:35 +0000607 ASSERT(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000608 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
609 bool res = InitInternal();
610 if (res) {
611 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
612 } else {
613 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
614 Terminate();
615 }
616 return res;
617}
618
619bool WebRtcVoiceEngine::InitInternal() {
620 // Temporarily turn logging level up for the Init call
621 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000622 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000623 SetTraceFilter(extended_filter);
624 SetTraceOptions("");
625
626 // Init WebRtc VoiceEngine.
627 if (voe_wrapper_->base()->Init(adm_) == -1) {
628 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
629 SetTraceFilter(old_filter);
630 return false;
631 }
632
633 SetTraceFilter(old_filter);
634 SetTraceOptions(log_options_);
635
636 // Log the VoiceEngine version info
637 char buffer[1024] = "";
638 voe_wrapper_->base()->GetVersion(buffer);
639 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000640 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000641
642 // Save the default AGC configuration settings. This must happen before
643 // calling SetOptions or the default will be overwritten.
644 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
645 LOG_RTCERR0(GetAgcConfig);
646 return false;
647 }
648
649 // Set defaults for options, so that ApplyOptions applies them explicitly
650 // when we clear option (channel) overrides. External clients can still
651 // modify the defaults via SetOptions (on the media engine).
652 if (!SetOptions(GetDefaultEngineOptions())) {
653 return false;
654 }
655
656 // Print our codec list again for the call diagnostic log
657 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
658 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
659 it != codecs_.end(); ++it) {
660 LOG(LS_INFO) << ToString(*it);
661 }
662
663 // Disable the DTMF playout when a tone is sent.
664 // PlayDtmfTone will be used if local playout is needed.
665 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
666 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
667 }
668
669 initialized_ = true;
670 return true;
671}
672
673bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
674 if (voe_wrapper_sc_initialized_) {
675 return true;
676 }
677 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
678 // be false, so subsequent calls to EnsureSoundclipEngineInit will
679 // probably just fail again. That's acceptable behavior.
680#if defined(LINUX) && !defined(HAVE_LIBPULSE)
681 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
682#endif
683
684 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
685 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
686 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
687 return false;
688 }
689
690 // On Windows, tell it to use the default sound (not communication) devices.
691 // First check whether there is a valid sound device for playback.
692 // TODO(juberti): Clean this up when we support setting the soundclip device.
693#ifdef WIN32
694 // The SetPlayoutDevice may not be implemented in the case of external ADM.
695 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
696 // PeerConnection interface never set the adm_sc_, so need to check both
697 // in order to determine if the external adm is used.
698 if (!adm_ && !adm_sc_) {
699 int num_of_devices = 0;
700 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
701 num_of_devices > 0) {
702 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
703 == -1) {
704 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
705 voe_wrapper_sc_->error());
706 return false;
707 }
708 } else {
709 LOG(LS_WARNING) << "No valid sound playout device found.";
710 }
711 }
712#endif
713 voe_wrapper_sc_initialized_ = true;
714 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
715 return true;
716}
717
718void WebRtcVoiceEngine::Terminate() {
719 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
720 initialized_ = false;
721
722 StopAecDump();
723
724 if (voe_wrapper_sc_) {
725 voe_wrapper_sc_initialized_ = false;
726 voe_wrapper_sc_->base()->Terminate();
727 }
728 voe_wrapper_->base()->Terminate();
729 desired_local_monitor_enable_ = false;
730}
731
732int WebRtcVoiceEngine::GetCapabilities() {
733 return AUDIO_SEND | AUDIO_RECV;
734}
735
736VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
737 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
738 if (!ch->valid()) {
739 delete ch;
740 ch = NULL;
741 }
742 return ch;
743}
744
745SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
746 if (!EnsureSoundclipEngineInit()) {
747 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
748 << "initialize.";
749 return NULL;
750 }
751 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
752 if (!soundclip->Init() || !soundclip->Enable()) {
753 delete soundclip;
754 return NULL;
755 }
756 return soundclip;
757}
758
759bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
760 if (!ApplyOptions(options)) {
761 return false;
762 }
763 options_ = options;
764 return true;
765}
766
767bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
768 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
769 if (!ApplyOptions(overrides)) {
770 return false;
771 }
772 option_overrides_ = overrides;
773 return true;
774}
775
776bool WebRtcVoiceEngine::ClearOptionOverrides() {
777 LOG(LS_INFO) << "Clearing option overrides.";
778 AudioOptions options = options_;
779 // Only call ApplyOptions if |options_overrides_| contains overrided options.
780 // ApplyOptions affects NS, AGC other options that is shared between
781 // all WebRtcVoiceEngineChannels.
782 if (option_overrides_ == AudioOptions()) {
783 return true;
784 }
785
786 if (!ApplyOptions(options)) {
787 return false;
788 }
789 option_overrides_ = AudioOptions();
790 return true;
791}
792
793// AudioOptions defaults are set in InitInternal (for options with corresponding
794// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
795bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
796 AudioOptions options = options_in; // The options are modified below.
797 // kEcConference is AEC with high suppression.
798 webrtc::EcModes ec_mode = webrtc::kEcConference;
799 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
800 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
801 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
802 bool aecm_comfort_noise = false;
803 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
804 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
805 << aecm_comfort_noise << " (default is false).";
806 }
807
808#if defined(IOS)
809 // On iOS, VPIO provides built-in EC and AGC.
810 options.echo_cancellation.Set(false);
811 options.auto_gain_control.Set(false);
812#elif defined(ANDROID)
813 ec_mode = webrtc::kEcAecm;
814#endif
815
816#if defined(IOS) || defined(ANDROID)
817 // Set the AGC mode for iOS as well despite disabling it above, to avoid
818 // unsupported configuration errors from webrtc.
819 agc_mode = webrtc::kAgcFixedDigital;
820 options.typing_detection.Set(false);
821 options.experimental_agc.Set(false);
822 options.experimental_aec.Set(false);
823 options.experimental_ns.Set(false);
824#endif
825
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100826 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
827 // where the feature is not supported.
828 bool use_delay_agnostic_aec = false;
829#if !defined(IOS)
830 if (options.delay_agnostic_aec.Get(&use_delay_agnostic_aec)) {
831 if (use_delay_agnostic_aec) {
832 options.echo_cancellation.Set(true);
833 options.experimental_aec.Set(true);
834 ec_mode = webrtc::kEcConference;
835 }
836 }
837#endif
838
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000839 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
840
841 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
842
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000843 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000844 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000845 // Check if platform supports built-in EC. Currently only supported on
846 // Android and in combination with Java based audio layer.
847 // TODO(henrika): investigate possibility to support built-in EC also
848 // in combination with Open SL ES audio.
849 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
850 if (built_in_aec) {
Bjorn Volcker1d83f1e2015-04-07 15:25:39 +0200851 // Built-in EC exists on this device. Enable/Disable it according to the
852 // echo_cancellation audio option.
853 if (voe_wrapper_->hw()->EnableBuiltInAEC(echo_cancellation) == 0 &&
854 echo_cancellation) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100855 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000856 // i.e., replace the software EC with the built-in EC.
857 options.echo_cancellation.Set(false);
bjornv@webrtc.org3f118232015-03-16 14:22:03 +0000858 echo_cancellation = false;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000859 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
860 }
861 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000862 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
863 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
864 return false;
865 } else {
866 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
867 << " with mode " << ec_mode;
868 }
869#if !defined(ANDROID)
870 // TODO(ajm): Remove the error return on Android from webrtc.
871 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
872 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
873 return false;
874 }
875#endif
876 if (ec_mode == webrtc::kEcAecm) {
877 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
878 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
879 return false;
880 }
881 }
882 }
883
884 bool auto_gain_control;
885 if (options.auto_gain_control.Get(&auto_gain_control)) {
886 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
887 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
888 return false;
889 } else {
890 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
891 << " with mode " << agc_mode;
892 }
893 }
894
895 if (options.tx_agc_target_dbov.IsSet() ||
896 options.tx_agc_digital_compression_gain.IsSet() ||
897 options.tx_agc_limiter.IsSet()) {
898 // Override default_agc_config_. Generally, an unset option means "leave
899 // the VoE bits alone" in this function, so we want whatever is set to be
900 // stored as the new "default". If we didn't, then setting e.g.
901 // tx_agc_target_dbov would reset digital compression gain and limiter
902 // settings.
903 // Also, if we don't update default_agc_config_, then adjust_agc_delta
904 // would be an offset from the original values, and not whatever was set
905 // explicitly.
906 default_agc_config_.targetLeveldBOv =
907 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
908 default_agc_config_.targetLeveldBOv);
909 default_agc_config_.digitalCompressionGaindB =
910 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
911 default_agc_config_.digitalCompressionGaindB);
912 default_agc_config_.limiterEnable =
913 options.tx_agc_limiter.GetWithDefaultIfUnset(
914 default_agc_config_.limiterEnable);
915 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
916 LOG_RTCERR3(SetAgcConfig,
917 default_agc_config_.targetLeveldBOv,
918 default_agc_config_.digitalCompressionGaindB,
919 default_agc_config_.limiterEnable);
920 return false;
921 }
922 }
923
924 bool noise_suppression;
925 if (options.noise_suppression.Get(&noise_suppression)) {
926 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
927 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
928 return false;
929 } else {
930 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
931 << " with mode " << ns_mode;
932 }
933 }
934
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000935 bool highpass_filter;
936 if (options.highpass_filter.Get(&highpass_filter)) {
937 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
938 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
939 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
940 return false;
941 }
942 }
943
944 bool stereo_swapping;
945 if (options.stereo_swapping.Get(&stereo_swapping)) {
946 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
947 voep->EnableStereoChannelSwapping(stereo_swapping);
948 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
949 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
950 return false;
951 }
952 }
953
954 bool typing_detection;
955 if (options.typing_detection.Get(&typing_detection)) {
956 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
957 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
958 // In case of error, log the info and continue
959 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
960 }
961 }
962
963 int adjust_agc_delta;
964 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
965 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
966 if (!AdjustAgcLevel(adjust_agc_delta)) {
967 return false;
968 }
969 }
970
971 bool aec_dump;
972 if (options.aec_dump.Get(&aec_dump)) {
973 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
974 if (aec_dump)
975 StartAecDump(kAecDumpByAudioOptionFilename);
976 else
977 StopAecDump();
978 }
979
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000980 webrtc::Config config;
981
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100982 delay_agnostic_aec_.SetFrom(options.delay_agnostic_aec);
983 bool delay_agnostic_aec;
984 if (delay_agnostic_aec_.Get(&delay_agnostic_aec)) {
985 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << delay_agnostic_aec;
986 config.Set<webrtc::ReportedDelay>(
987 new webrtc::ReportedDelay(!delay_agnostic_aec));
988 }
989
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000990 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000991 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000992 if (experimental_aec_.Get(&experimental_aec)) {
993 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
994 config.Set<webrtc::DelayCorrection>(
995 new webrtc::DelayCorrection(experimental_aec));
996 }
997
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000998 experimental_ns_.SetFrom(options.experimental_ns);
999 bool experimental_ns;
1000 if (experimental_ns_.Get(&experimental_ns)) {
1001 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
1002 config.Set<webrtc::ExperimentalNs>(
1003 new webrtc::ExperimentalNs(experimental_ns));
1004 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +00001005
1006 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
1007 // returns NULL on audio_processing().
1008 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
1009 if (audioproc) {
1010 audioproc->SetExtraOptions(config);
1011 }
1012
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001013 uint32 recording_sample_rate;
1014 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
1015 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
1016 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
1017 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
1018 }
1019 }
1020
1021 uint32 playout_sample_rate;
1022 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
1023 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
1024 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
1025 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
1026 }
1027 }
1028
1029 return true;
1030}
1031
1032bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
1033 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
1034 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
1035 LOG_RTCERR1(SetDelayOffsetMs, offset);
1036 return false;
1037 }
1038
1039 return true;
1040}
1041
1042struct ResumeEntry {
1043 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
1044 : channel(c),
1045 playout(p),
1046 send(s) {
1047 }
1048
1049 WebRtcVoiceMediaChannel *channel;
1050 bool playout;
1051 SendFlags send;
1052};
1053
1054// TODO(juberti): Refactor this so that the core logic can be used to set the
1055// soundclip device. At that time, reinstate the soundclip pause/resume code.
1056bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
1057 const Device* out_device) {
1058#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001059 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001060 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001061 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001062 kDefaultAudioDeviceId;
1063 // The device manager uses -1 as the default device, which was the case for
1064 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
1065#ifndef WIN32
1066 if (-1 == in_id) {
1067 in_id = kDefaultAudioDeviceId;
1068 }
1069 if (-1 == out_id) {
1070 out_id = kDefaultAudioDeviceId;
1071 }
1072#endif
1073
1074 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
1075 in_device->name : "Default device";
1076 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
1077 out_device->name : "Default device";
1078 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
1079 << ") and speaker to (id=" << out_id << ", name=" << out_name
1080 << ")";
1081
1082 // If we're running the local monitor, we need to stop it first.
1083 bool ret = true;
1084 if (!PauseLocalMonitor()) {
1085 LOG(LS_WARNING) << "Failed to pause local monitor";
1086 ret = false;
1087 }
1088
1089 // Must also pause all audio playback and capture.
1090 for (ChannelList::const_iterator i = channels_.begin();
1091 i != channels_.end(); ++i) {
1092 WebRtcVoiceMediaChannel *channel = *i;
1093 if (!channel->PausePlayout()) {
1094 LOG(LS_WARNING) << "Failed to pause playout";
1095 ret = false;
1096 }
1097 if (!channel->PauseSend()) {
1098 LOG(LS_WARNING) << "Failed to pause send";
1099 ret = false;
1100 }
1101 }
1102
1103 // Find the recording device id in VoiceEngine and set recording device.
1104 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1105 ret = false;
1106 }
1107 if (ret) {
1108 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
1109 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
1110 ret = false;
1111 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00001112 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
1113 if (ap)
1114 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001115 }
1116
1117 // Find the playout device id in VoiceEngine and set playout device.
1118 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1119 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1120 ret = false;
1121 }
1122 if (ret) {
1123 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001124 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001125 ret = false;
1126 }
1127 }
1128
1129 // Resume all audio playback and capture.
1130 for (ChannelList::const_iterator i = channels_.begin();
1131 i != channels_.end(); ++i) {
1132 WebRtcVoiceMediaChannel *channel = *i;
1133 if (!channel->ResumePlayout()) {
1134 LOG(LS_WARNING) << "Failed to resume playout";
1135 ret = false;
1136 }
1137 if (!channel->ResumeSend()) {
1138 LOG(LS_WARNING) << "Failed to resume send";
1139 ret = false;
1140 }
1141 }
1142
1143 // Resume local monitor.
1144 if (!ResumeLocalMonitor()) {
1145 LOG(LS_WARNING) << "Failed to resume local monitor";
1146 ret = false;
1147 }
1148
1149 if (ret) {
1150 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1151 << ") and speaker to (id="<< out_id << " name=" << out_name
1152 << ")";
1153 }
1154
1155 return ret;
1156#else
1157 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001158#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001159}
1160
1161bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1162 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1163 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001164#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001165 *rtc_id = dev_id;
1166 return true;
1167#else
1168 // In Windows and Mac, we need to find the VoiceEngine device id by name
1169 // unless the input dev_id is the default device id.
1170 if (kDefaultAudioDeviceId == dev_id) {
1171 *rtc_id = dev_id;
1172 return true;
1173 }
1174
1175 // Get the number of VoiceEngine audio devices.
1176 int count = 0;
1177 if (is_input) {
1178 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1179 LOG_RTCERR0(GetNumOfRecordingDevices);
1180 return false;
1181 }
1182 } else {
1183 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1184 LOG_RTCERR0(GetNumOfPlayoutDevices);
1185 return false;
1186 }
1187 }
1188
1189 for (int i = 0; i < count; ++i) {
1190 char name[128];
1191 char guid[128];
1192 if (is_input) {
1193 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1194 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1195 } else {
1196 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1197 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1198 }
1199
1200 std::string webrtc_name(name);
1201 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1202 *rtc_id = i;
1203 return true;
1204 }
1205 }
1206 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1207 return false;
1208#endif
1209}
1210
1211bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1212 unsigned int ulevel;
1213 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1214 LOG_RTCERR1(GetSpeakerVolume, level);
1215 return false;
1216 }
1217 *level = ulevel;
1218 return true;
1219}
1220
1221bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1222 ASSERT(level >= 0 && level <= 255);
1223 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1224 LOG_RTCERR1(SetSpeakerVolume, level);
1225 return false;
1226 }
1227 return true;
1228}
1229
1230int WebRtcVoiceEngine::GetInputLevel() {
1231 unsigned int ulevel;
1232 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1233 static_cast<int>(ulevel) : -1;
1234}
1235
1236bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1237 desired_local_monitor_enable_ = enable;
1238 return ChangeLocalMonitor(desired_local_monitor_enable_);
1239}
1240
1241bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1242 // The voe file api is not available in chrome.
1243 if (!voe_wrapper_->file()) {
1244 return false;
1245 }
1246 if (enable && !monitor_) {
1247 monitor_.reset(new WebRtcMonitorStream);
1248 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1249 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1250 // Must call Stop() because there are some cases where Start will report
1251 // failure but still change the state, and if we leave VE in the on state
1252 // then it could crash later when trying to invoke methods on our monitor.
1253 voe_wrapper_->file()->StopRecordingMicrophone();
1254 monitor_.reset();
1255 return false;
1256 }
1257 } else if (!enable && monitor_) {
1258 voe_wrapper_->file()->StopRecordingMicrophone();
1259 monitor_.reset();
1260 }
1261 return true;
1262}
1263
1264bool WebRtcVoiceEngine::PauseLocalMonitor() {
1265 return ChangeLocalMonitor(false);
1266}
1267
1268bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1269 return ChangeLocalMonitor(desired_local_monitor_enable_);
1270}
1271
1272const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1273 return codecs_;
1274}
1275
1276bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1277 return FindWebRtcCodec(in, NULL);
1278}
1279
1280// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1281bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1282 webrtc::CodecInst* out) {
1283 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1284 for (int i = 0; i < ncodecs; ++i) {
1285 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001286 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001287 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1288 voe_codec.rate, voe_codec.channels, 0);
1289 bool multi_rate = IsCodecMultiRate(voe_codec);
1290 // Allow arbitrary rates for ISAC to be specified.
1291 if (multi_rate) {
1292 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1293 codec.bitrate = 0;
1294 }
1295 if (codec.Matches(in)) {
1296 if (out) {
1297 // Fixup the payload type.
1298 voe_codec.pltype = in.id;
1299
1300 // Set bitrate if specified.
1301 if (multi_rate && in.bitrate != 0) {
1302 voe_codec.rate = in.bitrate;
1303 }
1304
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001305 // Reset G722 sample rate to 16000 to match WebRTC.
1306 MaybeFixupG722(&voe_codec, 16000);
1307
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001308 // Apply codec-specific settings.
Minyue Li7100dcd2015-03-27 05:05:59 +01001309 if (IsCodec(codec, kIsacCodecName)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001310 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001311 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001312 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1313 }
1314 *out = voe_codec;
1315 }
1316 return true;
1317 }
1318 }
1319 }
1320 return false;
1321}
1322const std::vector<RtpHeaderExtension>&
1323WebRtcVoiceEngine::rtp_header_extensions() const {
1324 return rtp_header_extensions_;
1325}
1326
1327void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1328 // if min_sev == -1, we keep the current log level.
1329 if (min_sev >= 0) {
1330 SetTraceFilter(SeverityToFilter(min_sev));
1331 }
1332 log_options_ = filter;
1333 SetTraceOptions(initialized_ ? log_options_ : "");
1334}
1335
1336int WebRtcVoiceEngine::GetLastEngineError() {
1337 return voe_wrapper_->error();
1338}
1339
1340void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1341 log_filter_ = filter;
1342 tracing_->SetTraceFilter(filter);
1343}
1344
1345// We suppport three different logging settings for VoiceEngine:
1346// 1. Observer callback that goes into talk diagnostic logfile.
1347// Use --logfile and --loglevel
1348//
1349// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1350// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1351//
1352// 3. EC log and dump for debugging QualityEngine.
1353// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1354//
1355// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1356// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1357void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1358 // Set encrypted trace file.
1359 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001360 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001361 std::vector<std::string>::iterator tracefile =
1362 std::find(opts.begin(), opts.end(), "tracefile");
1363 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1364 // Write encrypted debug output (at same loglevel) to file
1365 // EncryptedTraceFile no longer supported.
1366 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1367 LOG_RTCERR1(SetTraceFile, *tracefile);
1368 }
1369 }
1370
wu@webrtc.org97077a32013-10-25 21:18:33 +00001371 // Allow trace options to override the trace filter. We default
1372 // it to log_filter_ (as a translation of libjingle log levels)
1373 // elsewhere, but this allows clients to explicitly set webrtc
1374 // log levels.
1375 std::vector<std::string>::iterator tracefilter =
1376 std::find(opts.begin(), opts.end(), "tracefilter");
1377 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001378 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001379 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1380 }
1381 }
1382
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001383 // Set AEC dump file
1384 std::vector<std::string>::iterator recordEC =
1385 std::find(opts.begin(), opts.end(), "recordEC");
1386 if (recordEC != opts.end()) {
1387 ++recordEC;
1388 if (recordEC != opts.end())
1389 StartAecDump(recordEC->c_str());
1390 else
1391 StopAecDump();
1392 }
1393}
1394
1395// Ignore spammy trace messages, mostly from the stats API when we haven't
1396// gotten RTCP info yet from the remote side.
1397bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1398 static const char* kTracesToIgnore[] = {
1399 "\tfailed to GetReportBlockInformation",
1400 "GetRecCodec() failed to get received codec",
1401 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1402 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1403 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1404 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1405 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1406 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1407 "SenderInfoReceived No received SR",
1408 "StatisticsRTP() no statistics available",
1409 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1410 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1411 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1412 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1413 NULL
1414 };
1415 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1416 if (trace.find(*p) != std::string::npos) {
1417 return true;
1418 }
1419 }
1420 return false;
1421}
1422
1423void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1424 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001425 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001426 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001427 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001428 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001429 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001430 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001431 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001432 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001433 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001434
1435 // Skip past boilerplate prefix text
1436 if (length < 72) {
1437 std::string msg(trace, length);
1438 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1439 LOG_V(sev) << msg;
1440 } else {
1441 std::string msg(trace + 71, length - 72);
1442 if (!ShouldIgnoreTrace(msg)) {
1443 LOG_V(sev) << "webrtc: " << msg;
1444 }
1445 }
1446}
1447
1448void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001449 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001450 WebRtcVoiceMediaChannel* channel = NULL;
1451 uint32 ssrc = 0;
1452 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1453 << channel_num << ".";
1454 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1455 ASSERT(channel != NULL);
1456 channel->OnError(ssrc, err_code);
1457 } else {
1458 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1459 << " could not be found in channel list when error reported.";
1460 }
1461}
1462
1463bool WebRtcVoiceEngine::FindChannelAndSsrc(
1464 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1465 ASSERT(channel != NULL && ssrc != NULL);
1466
1467 *channel = NULL;
1468 *ssrc = 0;
1469 // Find corresponding channel and ssrc
1470 for (ChannelList::const_iterator it = channels_.begin();
1471 it != channels_.end(); ++it) {
1472 ASSERT(*it != NULL);
1473 if ((*it)->FindSsrc(channel_num, ssrc)) {
1474 *channel = *it;
1475 return true;
1476 }
1477 }
1478
1479 return false;
1480}
1481
1482// This method will search through the WebRtcVoiceMediaChannels and
1483// obtain the voice engine's channel number.
1484bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1485 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1486 ASSERT(channel_num != NULL);
1487 ASSERT(direction == MPD_RX || direction == MPD_TX);
1488
1489 *channel_num = -1;
1490 // Find corresponding channel for ssrc.
1491 for (ChannelList::const_iterator it = channels_.begin();
1492 it != channels_.end(); ++it) {
1493 ASSERT(*it != NULL);
1494 if (direction & MPD_RX) {
1495 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1496 }
1497 if (*channel_num == -1 && (direction & MPD_TX)) {
1498 *channel_num = (*it)->GetSendChannelNum(ssrc);
1499 }
1500 if (*channel_num != -1) {
1501 return true;
1502 }
1503 }
1504 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1505 return false;
1506}
1507
1508void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001509 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001510 channels_.push_back(channel);
1511}
1512
1513void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001514 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001515 ChannelList::iterator i = std::find(channels_.begin(),
1516 channels_.end(),
1517 channel);
1518 if (i != channels_.end()) {
1519 channels_.erase(i);
1520 }
1521}
1522
1523void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1524 soundclips_.push_back(soundclip);
1525}
1526
1527void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1528 SoundclipList::iterator i = std::find(soundclips_.begin(),
1529 soundclips_.end(),
1530 soundclip);
1531 if (i != soundclips_.end()) {
1532 soundclips_.erase(i);
1533 }
1534}
1535
1536// Adjusts the default AGC target level by the specified delta.
1537// NB: If we start messing with other config fields, we'll want
1538// to save the current webrtc::AgcConfig as well.
1539bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1540 webrtc::AgcConfig config = default_agc_config_;
1541 config.targetLeveldBOv -= delta;
1542
1543 LOG(LS_INFO) << "Adjusting AGC level from default -"
1544 << default_agc_config_.targetLeveldBOv << "dB to -"
1545 << config.targetLeveldBOv << "dB";
1546
1547 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1548 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1549 return false;
1550 }
1551 return true;
1552}
1553
1554bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1555 webrtc::AudioDeviceModule* adm_sc) {
1556 if (initialized_) {
1557 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1558 return false;
1559 }
1560 if (adm_) {
1561 adm_->Release();
1562 adm_ = NULL;
1563 }
1564 if (adm) {
1565 adm_ = adm;
1566 adm_->AddRef();
1567 }
1568
1569 if (adm_sc_) {
1570 adm_sc_->Release();
1571 adm_sc_ = NULL;
1572 }
1573 if (adm_sc) {
1574 adm_sc_ = adm_sc;
1575 adm_sc_->AddRef();
1576 }
1577 return true;
1578}
1579
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001580bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1581 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001582 if (!aec_dump_file_stream) {
1583 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001584 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001585 LOG(LS_WARNING) << "Could not close file.";
1586 return false;
1587 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001588 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001589 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001590 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001591 LOG_RTCERR0(StartDebugRecording);
1592 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001593 return false;
1594 }
1595 is_dumping_aec_ = true;
1596 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001597}
1598
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001599bool WebRtcVoiceEngine::RegisterProcessor(
1600 uint32 ssrc,
1601 VoiceProcessor* voice_processor,
1602 MediaProcessorDirection direction) {
1603 bool register_with_webrtc = false;
1604 int channel_id = -1;
1605 bool success = false;
1606 uint32* processor_ssrc = NULL;
1607 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1608 if (voice_processor == NULL || !found_channel) {
1609 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1610 << " foundChannel: " << found_channel;
1611 return false;
1612 }
1613
1614 webrtc::ProcessingTypes processing_type;
1615 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001616 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001617 if (direction == MPD_RX) {
1618 processing_type = webrtc::kPlaybackAllChannelsMixed;
1619 if (SignalRxMediaFrame.is_empty()) {
1620 register_with_webrtc = true;
1621 processor_ssrc = &rx_processor_ssrc_;
1622 }
1623 SignalRxMediaFrame.connect(voice_processor,
1624 &VoiceProcessor::OnFrame);
1625 } else {
1626 processing_type = webrtc::kRecordingPerChannel;
1627 if (SignalTxMediaFrame.is_empty()) {
1628 register_with_webrtc = true;
1629 processor_ssrc = &tx_processor_ssrc_;
1630 }
1631 SignalTxMediaFrame.connect(voice_processor,
1632 &VoiceProcessor::OnFrame);
1633 }
1634 }
1635 if (register_with_webrtc) {
1636 // TODO(janahan): when registering consider instantiating a
1637 // a VoeMediaProcess object and not make the engine extend the interface.
1638 if (voe()->media() && voe()->media()->
1639 RegisterExternalMediaProcessing(channel_id,
1640 processing_type,
1641 *this) != -1) {
1642 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1643 << channel_id;
1644 *processor_ssrc = ssrc;
1645 success = true;
1646 } else {
1647 LOG_RTCERR2(RegisterExternalMediaProcessing,
1648 channel_id,
1649 processing_type);
1650 success = false;
1651 }
1652 } else {
1653 // If we don't have to register with the engine, we just needed to
1654 // connect a new processor, set success to true;
1655 success = true;
1656 }
1657 return success;
1658}
1659
1660bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1661 MediaProcessorDirection channel_direction,
1662 uint32 ssrc,
1663 VoiceProcessor* voice_processor,
1664 MediaProcessorDirection processor_direction) {
1665 bool success = true;
1666 FrameSignal* signal;
1667 webrtc::ProcessingTypes processing_type;
1668 uint32* processor_ssrc = NULL;
1669 if (channel_direction == MPD_RX) {
1670 signal = &SignalRxMediaFrame;
1671 processing_type = webrtc::kPlaybackAllChannelsMixed;
1672 processor_ssrc = &rx_processor_ssrc_;
1673 } else {
1674 signal = &SignalTxMediaFrame;
1675 processing_type = webrtc::kRecordingPerChannel;
1676 processor_ssrc = &tx_processor_ssrc_;
1677 }
1678
1679 int deregister_id = -1;
1680 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001681 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001682 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1683 signal->disconnect(voice_processor);
1684 int channel_id = -1;
1685 bool found_channel = FindChannelNumFromSsrc(ssrc,
1686 channel_direction,
1687 &channel_id);
1688 if (signal->is_empty() && found_channel) {
1689 deregister_id = channel_id;
1690 }
1691 }
1692 }
1693 if (deregister_id != -1) {
1694 if (voe()->media() &&
1695 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1696 processing_type) != -1) {
1697 *processor_ssrc = 0;
1698 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1699 << deregister_id;
1700 } else {
1701 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1702 deregister_id,
1703 processing_type);
1704 success = false;
1705 }
1706 }
1707 return success;
1708}
1709
1710bool WebRtcVoiceEngine::UnregisterProcessor(
1711 uint32 ssrc,
1712 VoiceProcessor* voice_processor,
1713 MediaProcessorDirection direction) {
1714 bool success = true;
1715 if (voice_processor == NULL) {
1716 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1717 << ssrc;
1718 return false;
1719 }
1720 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1721 success = false;
1722 }
1723 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1724 success = false;
1725 }
1726 return success;
1727}
1728
1729// Implementing method from WebRtc VoEMediaProcess interface
1730// Do not lock mux_channel_cs_ in this callback.
1731void WebRtcVoiceEngine::Process(int channel,
1732 webrtc::ProcessingTypes type,
1733 int16_t audio10ms[],
1734 int length,
1735 int sampling_freq,
1736 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001737 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001738 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1739 if (type == webrtc::kPlaybackAllChannelsMixed) {
1740 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1741 } else if (type == webrtc::kRecordingPerChannel) {
1742 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1743 } else {
1744 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1745 << " channel: " << channel << " type: " << type
1746 << " tx_ssrc: " << tx_processor_ssrc_
1747 << " rx_ssrc: " << rx_processor_ssrc_;
1748 }
1749}
1750
1751void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1752 if (!is_dumping_aec_) {
1753 // Start dumping AEC when we are not dumping.
1754 if (voe_wrapper_->processing()->StartDebugRecording(
1755 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001756 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001757 } else {
1758 is_dumping_aec_ = true;
1759 }
1760 }
1761}
1762
1763void WebRtcVoiceEngine::StopAecDump() {
1764 if (is_dumping_aec_) {
1765 // Stop dumping AEC when we are dumping.
1766 if (voe_wrapper_->processing()->StopDebugRecording() !=
1767 webrtc::AudioProcessing::kNoError) {
1768 LOG_RTCERR0(StopDebugRecording);
1769 }
1770 is_dumping_aec_ = false;
1771 }
1772}
1773
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001774int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001775 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001776}
1777
1778int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1779 return CreateVoiceChannel(voe_wrapper_.get());
1780}
1781
1782int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1783 return CreateVoiceChannel(voe_wrapper_sc_.get());
1784}
1785
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001786class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1787 : public AudioRenderer::Sink {
1788 public:
1789 WebRtcVoiceChannelRenderer(int ch,
1790 webrtc::AudioTransport* voe_audio_transport)
1791 : channel_(ch),
1792 voe_audio_transport_(voe_audio_transport),
1793 renderer_(NULL) {
1794 }
1795 virtual ~WebRtcVoiceChannelRenderer() {
1796 Stop();
1797 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001798
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001799 // Starts the rendering by setting a sink to the renderer to get data
1800 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001801 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001802 // TODO(xians): Make sure Start() is called only once.
1803 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001804 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001805 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001806 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001807 ASSERT(renderer_ == renderer);
1808 return;
1809 }
1810
1811 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1812 // in getUserMedia by default.
1813 renderer->AddChannel(channel_);
1814 renderer->SetSink(this);
1815 renderer_ = renderer;
1816 }
1817
1818 // Stops rendering by setting the sink of the renderer to NULL. No data
1819 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001820 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001821 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001822 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001823 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001824 return;
1825
1826 renderer_->RemoveChannel(channel_);
1827 renderer_->SetSink(NULL);
1828 renderer_ = NULL;
1829 }
1830
1831 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001832 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001833 void OnData(const void* audio_data,
1834 int bits_per_sample,
1835 int sample_rate,
1836 int number_of_channels,
1837 int number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001838 voe_audio_transport_->OnData(channel_,
1839 audio_data,
1840 bits_per_sample,
1841 sample_rate,
1842 number_of_channels,
1843 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001844 }
1845
1846 // Callback from the |renderer_| when it is going away. In case Start() has
1847 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001848 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001849 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001850 // Set |renderer_| to NULL to make sure no more callback will get into
1851 // the renderer.
1852 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001853 }
1854
1855 // Accessor to the VoE channel ID.
1856 int channel() const { return channel_; }
1857
1858 private:
1859 const int channel_;
1860 webrtc::AudioTransport* const voe_audio_transport_;
1861
1862 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1863 // PeerConnection will make sure invalidating the pointer before the object
1864 // goes away.
1865 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001866
1867 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001868 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001869};
1870
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001871// WebRtcVoiceMediaChannel
1872WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1873 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1874 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001875 engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001876 send_bitrate_setting_(false),
1877 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001878 options_(),
1879 dtmf_allowed_(false),
1880 desired_playout_(false),
1881 nack_enabled_(false),
1882 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001883 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001884 desired_send_(SEND_NOTHING),
1885 send_(SEND_NOTHING),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001886 shared_bwe_vie_(NULL),
1887 shared_bwe_vie_channel_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001888 default_receive_ssrc_(0) {
1889 engine->RegisterChannel(this);
1890 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1891 << voe_channel();
1892
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001893 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001894}
1895
1896WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1897 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1898 << voe_channel();
buildbot@webrtc.org6e5c7842014-09-19 06:46:37 +00001899 SetupSharedBandwidthEstimation(NULL, -1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001900
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001901 // Remove any remaining send streams, the default channel will be deleted
1902 // later.
1903 while (!send_channels_.empty())
1904 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001905
1906 // Unregister ourselves from the engine.
1907 engine()->UnregisterChannel(this);
1908 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001909 while (!receive_channels_.empty()) {
1910 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001911 }
1912
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001913 // Delete the default channel.
1914 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001915}
1916
1917bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1918 LOG(LS_INFO) << "Setting voice channel options: "
1919 << options.ToString();
1920
wu@webrtc.orgde305012013-10-31 15:40:38 +00001921 // Check if DSCP value is changed from previous.
1922 bool dscp_option_changed = (options_.dscp != options.dscp);
1923
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001924 // TODO(xians): Add support to set different options for different send
1925 // streams after we support multiple APMs.
1926
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001927 // We retain all of the existing options, and apply the given ones
1928 // on top. This means there is no way to "clear" options such that
1929 // they go back to the engine default.
1930 options_.SetAll(options);
1931
1932 if (send_ != SEND_NOTHING) {
1933 if (!engine()->SetOptionOverrides(options_)) {
1934 LOG(LS_WARNING) <<
1935 "Failed to engine SetOptionOverrides during channel SetOptions.";
1936 return false;
1937 }
1938 } else {
1939 // Will be interpreted when appropriate.
1940 }
1941
wu@webrtc.org97077a32013-10-25 21:18:33 +00001942 // Receiver-side auto gain control happens per channel, so set it here from
1943 // options. Note that, like conference mode, setting it on the engine won't
1944 // have the desired effect, since voice channels don't inherit options from
1945 // the media engine when those options are applied per-channel.
1946 bool rx_auto_gain_control;
1947 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1948 if (engine()->voe()->processing()->SetRxAgcStatus(
1949 voe_channel(), rx_auto_gain_control,
1950 webrtc::kAgcFixedDigital) == -1) {
1951 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1952 return false;
1953 } else {
1954 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1955 << " with mode " << webrtc::kAgcFixedDigital;
1956 }
1957 }
1958 if (options.rx_agc_target_dbov.IsSet() ||
1959 options.rx_agc_digital_compression_gain.IsSet() ||
1960 options.rx_agc_limiter.IsSet()) {
1961 webrtc::AgcConfig config;
1962 // If only some of the options are being overridden, get the current
1963 // settings for the channel and bail if they aren't available.
1964 if (!options.rx_agc_target_dbov.IsSet() ||
1965 !options.rx_agc_digital_compression_gain.IsSet() ||
1966 !options.rx_agc_limiter.IsSet()) {
1967 if (engine()->voe()->processing()->GetRxAgcConfig(
1968 voe_channel(), config) != 0) {
1969 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1970 << "channel " << voe_channel() << ". Since not all rx "
1971 << "agc options are specified, unable to safely set rx "
1972 << "agc options.";
1973 return false;
1974 }
1975 }
1976 config.targetLeveldBOv =
1977 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1978 config.targetLeveldBOv);
1979 config.digitalCompressionGaindB =
1980 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1981 config.digitalCompressionGaindB);
1982 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1983 config.limiterEnable);
1984 if (engine()->voe()->processing()->SetRxAgcConfig(
1985 voe_channel(), config) == -1) {
1986 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1987 config.digitalCompressionGaindB, config.limiterEnable);
1988 return false;
1989 }
1990 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001991 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001992 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001993 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001994 dscp = kAudioDscpValue;
1995 if (MediaChannel::SetDscp(dscp) != 0) {
1996 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1997 }
1998 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001999
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002000 // Force update of Video Engine BWE forwarding to reflect experiment setting.
2001 if (!SetupSharedBandwidthEstimation(shared_bwe_vie_,
2002 shared_bwe_vie_channel_)) {
2003 return false;
2004 }
2005
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002006 LOG(LS_INFO) << "Set voice channel options. Current options: "
2007 << options_.ToString();
2008 return true;
2009}
2010
2011bool WebRtcVoiceMediaChannel::SetRecvCodecs(
2012 const std::vector<AudioCodec>& codecs) {
2013 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002014 LOG(LS_INFO) << "Setting receive voice codecs:";
2015
2016 std::vector<AudioCodec> new_codecs;
2017 // Find all new codecs. We allow adding new codecs but don't allow changing
2018 // the payload type of codecs that is already configured since we might
2019 // already be receiving packets with that payload type.
2020 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002021 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002022 AudioCodec old_codec;
2023 if (FindCodec(recv_codecs_, *it, &old_codec)) {
2024 if (old_codec.id != it->id) {
2025 LOG(LS_ERROR) << it->name << " payload type changed.";
2026 return false;
2027 }
2028 } else {
2029 new_codecs.push_back(*it);
2030 }
2031 }
2032 if (new_codecs.empty()) {
2033 // There are no new codecs to configure. Already configured codecs are
2034 // never removed.
2035 return true;
2036 }
2037
2038 if (playout_) {
2039 // Receive codecs can not be changed while playing. So we temporarily
2040 // pause playout.
2041 PausePlayout();
2042 }
2043
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002044 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002045 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
2046 it != new_codecs.end() && ret; ++it) {
2047 webrtc::CodecInst voe_codec;
2048 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2049 LOG(LS_INFO) << ToString(*it);
2050 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002051 if (default_receive_ssrc_ == 0) {
2052 // Set the receive codecs on the default channel explicitly if the
2053 // default channel is not used by |receive_channels_|, this happens in
2054 // conference mode or in non-conference mode when there is no playout
2055 // channel.
2056 // TODO(xians): Figure out how we use the default channel in conference
2057 // mode.
2058 if (engine()->voe()->codec()->SetRecPayloadType(
2059 voe_channel(), voe_codec) == -1) {
2060 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
2061 ret = false;
2062 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002063 }
2064
2065 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002066 for (ChannelMap::iterator it = receive_channels_.begin();
2067 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002068 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002069 it->second->channel(), voe_codec) == -1) {
2070 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002071 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002072 ret = false;
2073 }
2074 }
2075 } else {
2076 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2077 ret = false;
2078 }
2079 }
2080 if (ret) {
2081 recv_codecs_ = codecs;
2082 }
2083
2084 if (desired_playout_ && !playout_) {
2085 ResumePlayout();
2086 }
2087 return ret;
2088}
2089
2090bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002091 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002092 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002093 engine()->voe()->codec()->SetVADStatus(channel, false);
2094 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002095 engine()->voe()->rtp()->SetREDStatus(channel, false);
2096 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002097
2098 // Scan through the list to figure out the codec to use for sending, along
2099 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002100 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002101 webrtc::CodecInst send_codec;
2102 memset(&send_codec, 0, sizeof(send_codec));
2103
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002104 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002105 bool enable_codec_fec = false;
Minyue Li7100dcd2015-03-27 05:05:59 +01002106 bool enable_opus_dtx = false;
minyue@webrtc.org26236952014-10-29 02:27:08 +00002107 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002108
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002109 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002110 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2111 it != codecs.end(); ++it) {
2112 // Ignore codecs we don't know about. The negotiation step should prevent
2113 // this, but double-check to be sure.
2114 webrtc::CodecInst voe_codec;
2115 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002116 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002117 continue;
2118 }
2119
Minyue Li7100dcd2015-03-27 05:05:59 +01002120 if (IsCodec(*it, kDtmfCodecName) || IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002121 // Skip telephone-event/CN codec, which will be handled later.
2122 continue;
2123 }
2124
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002125 // We'll use the first codec in the list to actually send audio data.
2126 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002127 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002128 // used is specified in params.
Minyue Li7100dcd2015-03-27 05:05:59 +01002129 if (IsCodec(*it, kRedCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002130 // Parse out the RED parameters. If we fail, just ignore RED;
2131 // we don't support all possible params/usage scenarios.
2132 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2133 continue;
2134 }
2135
2136 // Enable redundant encoding of the specified codec. Treat any
2137 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002138 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2139 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2140 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002141 return false;
2142 }
2143 } else {
2144 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002145 nack_enabled = IsNackEnabled(*it);
Minyue Li7100dcd2015-03-27 05:05:59 +01002146 // For Opus as the send codec, we are to determine inband FEC, maximum
2147 // playback rate, and opus internal dtx.
2148 if (IsCodec(*it, kOpusCodecName)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002149 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
Minyue Li7100dcd2015-03-27 05:05:59 +01002150 &opus_max_playback_rate, &enable_opus_dtx);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002151 }
Brave Yao5225dd82015-03-26 07:39:19 +08002152
2153 // Set packet size if the AudioCodec param kCodecParamPTime is set.
2154 int ptime_ms = 0;
2155 if (it->GetParam(kCodecParamPTime, &ptime_ms)) {
2156 if (!SetPTimeAsPacketSize(&send_codec, ptime_ms)) {
2157 LOG(LS_WARNING) << "Failed to set packet size for codec "
2158 << send_codec.plname;
2159 return false;
2160 }
2161 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002162 }
2163 found_send_codec = true;
2164 break;
2165 }
2166
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002167 if (nack_enabled_ != nack_enabled) {
2168 SetNack(channel, nack_enabled);
2169 nack_enabled_ = nack_enabled;
2170 }
2171
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002172 if (!found_send_codec) {
2173 LOG(LS_WARNING) << "Received empty list of codecs.";
2174 return false;
2175 }
2176
2177 // Set the codec immediately, since SetVADStatus() depends on whether
2178 // the current codec is mono or stereo.
2179 if (!SetSendCodec(channel, send_codec))
2180 return false;
2181
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002182 // FEC should be enabled after SetSendCodec.
2183 if (enable_codec_fec) {
2184 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2185 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002186 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2187 // Enable codec internal FEC. Treat any failure as fatal internal error.
2188 LOG_RTCERR2(SetFECStatus, channel, true);
2189 return false;
2190 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002191 }
2192
Minyue Li7100dcd2015-03-27 05:05:59 +01002193 if (IsCodec(send_codec, kOpusCodecName)) {
2194 // DTX and maxplaybackrate should be set after SetSendCodec. Because current
2195 // send codec has to be Opus.
2196
2197 // Set Opus internal DTX.
2198 LOG(LS_INFO) << "Attempt to "
2199 << GetEnableString(enable_opus_dtx)
2200 << " Opus DTX on channel "
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002201 << channel;
Minyue Li7100dcd2015-03-27 05:05:59 +01002202 if (engine()->voe()->codec()->SetOpusDtx(channel, enable_opus_dtx)) {
2203 LOG_RTCERR2(SetOpusDtx, channel, enable_opus_dtx);
2204 return false;
2205 }
2206
2207 // If opus_max_playback_rate <= 0, the default maximum playback rate
2208 // (48 kHz) will be used.
2209 if (opus_max_playback_rate > 0) {
2210 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
2211 << opus_max_playback_rate
2212 << " Hz on channel "
2213 << channel;
2214 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
2215 channel, opus_max_playback_rate) == -1) {
2216 LOG_RTCERR2(SetOpusMaxPlaybackRate, channel, opus_max_playback_rate);
2217 return false;
2218 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002219 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002220 }
2221
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002222 // Always update the |send_codec_| to the currently set send codec.
2223 send_codec_.reset(new webrtc::CodecInst(send_codec));
2224
minyue@webrtc.org26236952014-10-29 02:27:08 +00002225 if (send_bitrate_setting_) {
2226 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002227 }
2228
2229 // Loop through the codecs list again to config the telephone-event/CN codec.
2230 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2231 it != codecs.end(); ++it) {
2232 // Ignore codecs we don't know about. The negotiation step should prevent
2233 // this, but double-check to be sure.
2234 webrtc::CodecInst voe_codec;
2235 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2236 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2237 continue;
2238 }
2239
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002240 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2241 // about it.
Minyue Li7100dcd2015-03-27 05:05:59 +01002242 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002243 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2244 channel, it->id) == -1) {
2245 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2246 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002247 }
Minyue Li7100dcd2015-03-27 05:05:59 +01002248 } else if (IsCodec(*it, kCnCodecName)) {
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002249 // Turn voice activity detection/comfort noise on if supported.
2250 // Set the wideband CN payload type appropriately.
2251 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002252 webrtc::PayloadFrequencies cn_freq;
2253 switch (it->clockrate) {
2254 case 8000:
2255 cn_freq = webrtc::kFreq8000Hz;
2256 break;
2257 case 16000:
2258 cn_freq = webrtc::kFreq16000Hz;
2259 break;
2260 case 32000:
2261 cn_freq = webrtc::kFreq32000Hz;
2262 break;
2263 default:
2264 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2265 << " not supported.";
2266 continue;
2267 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002268 // Set the CN payloadtype and the VAD status.
2269 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2270 if (cn_freq != webrtc::kFreq8000Hz) {
2271 if (engine()->voe()->codec()->SetSendCNPayloadType(
2272 channel, it->id, cn_freq) == -1) {
2273 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2274 // TODO(ajm): This failure condition will be removed from VoE.
2275 // Restore the return here when we update to a new enough webrtc.
2276 //
2277 // Not returning false because the SetSendCNPayloadType will fail if
2278 // the channel is already sending.
2279 // This can happen if the remote description is applied twice, for
2280 // example in the case of ROAP on top of JSEP, where both side will
2281 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002282 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002283 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002284 // Only turn on VAD if we have a CN payload type that matches the
2285 // clockrate for the codec we are going to use.
Minyue Li7100dcd2015-03-27 05:05:59 +01002286 if (it->clockrate == send_codec.plfreq && send_codec.channels != 2) {
2287 // TODO(minyue): If CN frequency == 48000 Hz is allowed, consider the
2288 // interaction between VAD and Opus FEC.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002289 LOG(LS_INFO) << "Enabling VAD";
2290 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2291 LOG_RTCERR2(SetVADStatus, channel, true);
2292 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002293 }
2294 }
2295 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002296 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002297 return true;
2298}
2299
2300bool WebRtcVoiceMediaChannel::SetSendCodecs(
2301 const std::vector<AudioCodec>& codecs) {
2302 dtmf_allowed_ = false;
2303 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2304 it != codecs.end(); ++it) {
2305 // Find the DTMF telephone event "codec".
Minyue Li7100dcd2015-03-27 05:05:59 +01002306 if (IsCodec(*it, kDtmfCodecName)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002307 dtmf_allowed_ = true;
2308 }
2309 }
2310
2311 // Cache the codecs in order to configure the channel created later.
2312 send_codecs_ = codecs;
2313 for (ChannelMap::iterator iter = send_channels_.begin();
2314 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002315 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002316 return false;
2317 }
2318 }
2319
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002320 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002321 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002322 return true;
2323}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002324
2325void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2326 bool nack_enabled) {
2327 for (ChannelMap::const_iterator it = channels.begin();
2328 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002329 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002330 }
2331}
2332
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002333void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002334 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002335 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002336 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2337 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002338 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002339 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2340 }
2341}
2342
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002343bool WebRtcVoiceMediaChannel::SetSendCodec(
2344 const webrtc::CodecInst& send_codec) {
2345 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2346 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002347 for (ChannelMap::iterator iter = send_channels_.begin();
2348 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002349 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002350 return false;
2351 }
2352
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002353 return true;
2354}
2355
2356bool WebRtcVoiceMediaChannel::SetSendCodec(
2357 int channel, const webrtc::CodecInst& send_codec) {
2358 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2359 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2360
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002361 webrtc::CodecInst current_codec;
2362 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2363 (send_codec == current_codec)) {
2364 // Codec is already configured, we can return without setting it again.
2365 return true;
2366 }
2367
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002368 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2369 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002370 return false;
2371 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002372 return true;
2373}
2374
2375bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2376 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002377 if (receive_extensions_ == extensions) {
2378 return true;
2379 }
2380
2381 // The default channel may or may not be in |receive_channels_|. Set the rtp
2382 // header extensions for default channel regardless.
2383 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2384 return false;
2385 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002386
2387 // Loop through all receive channels and enable/disable the extensions.
2388 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2389 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002390 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2391 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002392 return false;
2393 }
2394 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002395
2396 receive_extensions_ = extensions;
2397 return true;
2398}
2399
2400bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2401 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002402 const RtpHeaderExtension* audio_level_extension =
2403 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2404 if (!SetHeaderExtension(
2405 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2406 audio_level_extension)) {
2407 return false;
2408 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002409
2410 const RtpHeaderExtension* send_time_extension =
2411 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2412 if (!SetHeaderExtension(
2413 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2414 send_time_extension)) {
2415 return false;
2416 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002417 return true;
2418}
2419
2420bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2421 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002422 if (send_extensions_ == extensions) {
2423 return true;
2424 }
2425
2426 // The default channel may or may not be in |send_channels_|. Set the rtp
2427 // header extensions for default channel regardless.
2428
2429 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2430 return false;
2431 }
2432
2433 // Loop through all send channels and enable/disable the extensions.
2434 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2435 channel_it != send_channels_.end(); ++channel_it) {
2436 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2437 extensions)) {
2438 return false;
2439 }
2440 }
2441
2442 send_extensions_ = extensions;
2443 return true;
2444}
2445
2446bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2447 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002448 const RtpHeaderExtension* audio_level_extension =
2449 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002450
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002451 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002452 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002453 audio_level_extension)) {
2454 return false;
2455 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002456
2457 const RtpHeaderExtension* send_time_extension =
2458 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002459 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002460 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002461 send_time_extension)) {
2462 return false;
2463 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002464
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002465 return true;
2466}
2467
2468bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2469 desired_playout_ = playout;
2470 return ChangePlayout(desired_playout_);
2471}
2472
2473bool WebRtcVoiceMediaChannel::PausePlayout() {
2474 return ChangePlayout(false);
2475}
2476
2477bool WebRtcVoiceMediaChannel::ResumePlayout() {
2478 return ChangePlayout(desired_playout_);
2479}
2480
2481bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2482 if (playout_ == playout) {
2483 return true;
2484 }
2485
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002486 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002487 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002488 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002489 // Only toggle the default channel if we don't have any other channels.
2490 result = SetPlayout(voe_channel(), playout);
2491 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002492 for (ChannelMap::iterator it = receive_channels_.begin();
2493 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002494 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002495 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002496 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002497 result = false;
2498 }
2499 }
2500
2501 if (result) {
2502 playout_ = playout;
2503 }
2504 return result;
2505}
2506
2507bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2508 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002509 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002510 return ChangeSend(desired_send_);
2511 return true;
2512}
2513
2514bool WebRtcVoiceMediaChannel::PauseSend() {
2515 return ChangeSend(SEND_NOTHING);
2516}
2517
2518bool WebRtcVoiceMediaChannel::ResumeSend() {
2519 return ChangeSend(desired_send_);
2520}
2521
2522bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2523 if (send_ == send) {
2524 return true;
2525 }
2526
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002527 // Change the settings on each send channel.
2528 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002529 engine()->SetOptionOverrides(options_);
2530
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002531 // Change the settings on each send channel.
2532 for (ChannelMap::iterator iter = send_channels_.begin();
2533 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002534 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002535 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002536 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002537
2538 // Clear up the options after stopping sending.
2539 if (send == SEND_NOTHING)
2540 engine()->ClearOptionOverrides();
2541
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002542 send_ = send;
2543 return true;
2544}
2545
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002546bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2547 if (send == SEND_MICROPHONE) {
2548 if (engine()->voe()->base()->StartSend(channel) == -1) {
2549 LOG_RTCERR1(StartSend, channel);
2550 return false;
2551 }
2552 if (engine()->voe()->file() &&
2553 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2554 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2555 return false;
2556 }
2557 } else { // SEND_NOTHING
2558 ASSERT(send == SEND_NOTHING);
2559 if (engine()->voe()->base()->StopSend(channel) == -1) {
2560 LOG_RTCERR1(StopSend, channel);
2561 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002562 }
2563 }
2564
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002565 return true;
2566}
2567
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002568// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002569void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2570 if (engine()->voe()->network()->RegisterExternalTransport(
2571 channel, *this) == -1) {
2572 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2573 }
2574
2575 // Enable RTCP (for quality stats and feedback messages)
2576 EnableRtcp(channel);
2577
2578 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2579 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002580
2581 // Set RTP header extension for the new channel.
2582 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002583}
2584
2585bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2586 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2587 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2588 }
2589
2590 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2591 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002592 return false;
2593 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002594
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002595 return true;
2596}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002597
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002598bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2599 // If the default channel is already used for sending create a new channel
2600 // otherwise use the default channel for sending.
2601 int channel = GetSendChannelNum(sp.first_ssrc());
2602 if (channel != -1) {
2603 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2604 return false;
2605 }
2606
2607 bool default_channel_is_available = true;
2608 for (ChannelMap::const_iterator iter = send_channels_.begin();
2609 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002610 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002611 default_channel_is_available = false;
2612 break;
2613 }
2614 }
2615 if (default_channel_is_available) {
2616 channel = voe_channel();
2617 } else {
2618 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002619 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002620 if (channel == -1) {
2621 LOG_RTCERR0(CreateChannel);
2622 return false;
2623 }
2624
2625 ConfigureSendChannel(channel);
2626 }
2627
2628 // Save the channel to send_channels_, so that RemoveSendStream() can still
2629 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002630 webrtc::AudioTransport* audio_transport =
2631 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002632 send_channels_.insert(std::make_pair(
2633 sp.first_ssrc(),
2634 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002635
2636 // Set the send (local) SSRC.
2637 // If there are multiple send SSRCs, we can only set the first one here, and
2638 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2639 // (with a codec requires multiple SSRC(s)).
2640 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2641 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2642 return false;
2643 }
2644
2645 // At this point the channel's local SSRC has been updated. If the channel is
2646 // the default channel make sure that all the receive channels are updated as
2647 // well. Receive channels have to have the same SSRC as the default channel in
2648 // order to send receiver reports with this SSRC.
2649 if (IsDefaultChannel(channel)) {
2650 for (ChannelMap::const_iterator it = receive_channels_.begin();
2651 it != receive_channels_.end(); ++it) {
2652 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002653 if (!IsDefaultChannel(it->second->channel())) {
2654 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002655 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002656 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002657 return false;
2658 }
2659 }
2660 }
2661 }
2662
2663 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002664 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2665 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002666 }
2667
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002668 // Set the current codecs to be used for the new channel.
2669 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002670 return false;
2671
2672 return ChangeSend(channel, desired_send_);
2673}
2674
2675bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2676 ChannelMap::iterator it = send_channels_.find(ssrc);
2677 if (it == send_channels_.end()) {
2678 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2679 << " which doesn't exist.";
2680 return false;
2681 }
2682
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002683 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002684 ChangeSend(channel, SEND_NOTHING);
2685
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002686 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2687 // this will disconnect the audio renderer with the send channel.
2688 delete it->second;
2689 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002690
2691 if (IsDefaultChannel(channel)) {
2692 // Do not delete the default channel since the receive channels depend on
2693 // the default channel, recycle it instead.
2694 ChangeSend(channel, SEND_NOTHING);
2695 } else {
2696 // Clean up and delete the send channel.
2697 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2698 << " with VoiceEngine channel #" << channel << ".";
2699 if (!DeleteChannel(channel))
2700 return false;
2701 }
2702
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002703 if (send_channels_.empty())
2704 ChangeSend(SEND_NOTHING);
2705
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002706 return true;
2707}
2708
2709bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002710 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002711
2712 if (!VERIFY(sp.ssrcs.size() == 1))
2713 return false;
2714 uint32 ssrc = sp.first_ssrc();
2715
wu@webrtc.org78187522013-10-07 23:32:02 +00002716 if (ssrc == 0) {
2717 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2718 return false;
2719 }
2720
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002721 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2722 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002723 return false;
2724 }
2725
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002726 // Reuse default channel for recv stream in non-conference mode call
2727 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002728 webrtc::AudioTransport* audio_transport =
2729 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002730 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2731 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2732 << " reuse default channel";
2733 default_receive_ssrc_ = sp.first_ssrc();
2734 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002735 default_receive_ssrc_,
2736 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002737 if (!SetupSharedBweOnChannel(voe_channel())) {
2738 return false;
2739 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002740 return SetPlayout(voe_channel(), playout_);
2741 }
2742
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002743 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002744 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002745 if (channel == -1) {
2746 LOG_RTCERR0(CreateChannel);
2747 return false;
2748 }
2749
wu@webrtc.org78187522013-10-07 23:32:02 +00002750 if (!ConfigureRecvChannel(channel)) {
2751 DeleteChannel(channel);
2752 return false;
2753 }
2754
2755 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002756 std::make_pair(
2757 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002758
2759 LOG(LS_INFO) << "New audio stream " << ssrc
2760 << " registered to VoiceEngine channel #"
2761 << channel << ".";
2762 return true;
2763}
2764
2765bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002766 // Configure to use external transport, like our default channel.
2767 if (engine()->voe()->network()->RegisterExternalTransport(
2768 channel, *this) == -1) {
2769 LOG_RTCERR2(SetExternalTransport, channel, this);
2770 return false;
2771 }
2772
2773 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002774 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002775 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2776 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002777 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002778 return false;
2779 }
2780 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002781 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002782 return false;
2783 }
2784
2785 // Use the same recv payload types as our default channel.
2786 ResetRecvCodecs(channel);
2787 if (!recv_codecs_.empty()) {
2788 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2789 it != recv_codecs_.end(); ++it) {
2790 webrtc::CodecInst voe_codec;
2791 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2792 voe_codec.pltype = it->id;
2793 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2794 if (engine()->voe()->codec()->GetRecPayloadType(
2795 voe_channel(), voe_codec) != -1) {
2796 if (engine()->voe()->codec()->SetRecPayloadType(
2797 channel, voe_codec) == -1) {
2798 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2799 return false;
2800 }
2801 }
2802 }
2803 }
2804 }
2805
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002806 if (InConferenceMode()) {
2807 // To be in par with the video, voe_channel() is not used for receiving in
2808 // a conference call.
2809 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2810 // This is the first stream in a multi user meeting. We can now
2811 // disable playback of the default stream. This since the default
2812 // stream will probably have received some initial packets before
2813 // the new stream was added. This will mean that the CN state from
2814 // the default channel will be mixed in with the other streams
2815 // throughout the whole meeting, which might be disturbing.
2816 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2817 SetPlayout(voe_channel(), false);
2818 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002819 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002820 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002821
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002822 // Set RTP header extension for the new channel.
2823 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2824 return false;
2825 }
2826
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002827 // Set up channel to be able to forward incoming packets to video engine BWE.
2828 if (!SetupSharedBweOnChannel(channel)) {
2829 return false;
2830 }
2831
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002832 return SetPlayout(channel, playout_);
2833}
2834
2835bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002836 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002837 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002838 if (it == receive_channels_.end()) {
2839 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2840 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002841 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002842 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002843
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002844 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2845 // will disconnect the audio renderer with the receive channel.
2846 // Cache the channel before the deletion.
2847 const int channel = it->second->channel();
2848 delete it->second;
2849 receive_channels_.erase(it);
2850
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002851 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002852 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002853 // Recycle the default channel is for recv stream.
2854 if (playout_)
2855 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002856
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002857 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002858 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002859 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002860
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002861 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002862 << " with VoiceEngine channel #" << channel << ".";
2863 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002864 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002865
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002866 bool enable_default_channel_playout = false;
2867 if (receive_channels_.empty()) {
2868 // The last stream was removed. We can now enable the default
2869 // channel for new channels to be played out immediately without
2870 // waiting for AddStream messages.
2871 // We do this for both conference mode and non-conference mode.
2872 // TODO(oja): Does the default channel still have it's CN state?
2873 enable_default_channel_playout = true;
2874 }
2875 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2876 default_receive_ssrc_ != 0) {
2877 // Only the default channel is active, enable the playout on default
2878 // channel.
2879 enable_default_channel_playout = true;
2880 }
2881 if (enable_default_channel_playout && playout_) {
2882 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2883 SetPlayout(voe_channel(), true);
2884 }
2885
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002886 return true;
2887}
2888
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002889bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2890 AudioRenderer* renderer) {
2891 ChannelMap::iterator it = receive_channels_.find(ssrc);
2892 if (it == receive_channels_.end()) {
2893 if (renderer) {
2894 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002895 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002896 return false;
2897 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002898
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002899 // The channel likely has gone away, do nothing.
2900 return true;
2901 }
2902
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002903 if (renderer)
2904 it->second->Start(renderer);
2905 else
2906 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002907
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002908 return true;
2909}
2910
2911bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2912 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002913 ChannelMap::iterator it = send_channels_.find(ssrc);
2914 if (it == send_channels_.end()) {
2915 if (renderer) {
2916 // Return an error if trying to set a valid renderer with an invalid ssrc.
2917 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2918 return false;
2919 }
2920
2921 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002922 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002923 }
2924
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002925 if (renderer)
2926 it->second->Start(renderer);
2927 else
2928 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002929
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002930 return true;
2931}
2932
2933bool WebRtcVoiceMediaChannel::GetActiveStreams(
2934 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002935 // In conference mode, the default channel should not be in
2936 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002937 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002938 for (ChannelMap::iterator it = receive_channels_.begin();
2939 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002940 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002941 if (level > 0) {
2942 actives->push_back(std::make_pair(it->first, level));
2943 }
2944 }
2945 return true;
2946}
2947
2948int WebRtcVoiceMediaChannel::GetOutputLevel() {
2949 // return the highest output level of all streams
2950 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002951 for (ChannelMap::iterator it = receive_channels_.begin();
2952 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002953 int level = GetOutputLevel(it->second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002954 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002955 }
2956 return highest;
2957}
2958
2959int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2960 int ret;
2961 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2962 // In case of error, log the info and continue
2963 LOG_RTCERR0(TimeSinceLastTyping);
2964 ret = -1;
2965 } else {
2966 ret *= 1000; // We return ms, webrtc returns seconds.
2967 }
2968 return ret;
2969}
2970
2971void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2972 int cost_per_typing, int reporting_threshold, int penalty_decay,
2973 int type_event_delay) {
2974 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2975 time_window, cost_per_typing,
2976 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2977 // In case of error, log the info and continue
2978 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2979 cost_per_typing, reporting_threshold, penalty_decay,
2980 type_event_delay);
2981 }
2982}
2983
2984bool WebRtcVoiceMediaChannel::SetOutputScaling(
2985 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002986 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002987 // Collect the channels to scale the output volume.
2988 std::vector<int> channels;
2989 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002990 // Default channel is not in receive_channels_ if it is not being used for
2991 // playout.
2992 if (default_receive_ssrc_ == 0)
2993 channels.push_back(voe_channel());
2994 for (ChannelMap::const_iterator it = receive_channels_.begin();
2995 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002996 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002997 }
2998 } else { // Collect only the channel of the specified ssrc.
2999 int channel = GetReceiveChannelNum(ssrc);
3000 if (-1 == channel) {
3001 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
3002 return false;
3003 }
3004 channels.push_back(channel);
3005 }
3006
3007 // Scale the output volume for the collected channels. We first normalize to
3008 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00003009 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003010 if (scale > 0.0001f) {
3011 left /= scale;
3012 right /= scale;
3013 }
3014 for (std::vector<int>::const_iterator it = channels.begin();
3015 it != channels.end(); ++it) {
3016 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
3017 *it, scale)) {
3018 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
3019 return false;
3020 }
3021 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
3022 *it, static_cast<float>(left), static_cast<float>(right))) {
3023 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
3024 // Do not return if fails. SetOutputVolumePan is not available for all
3025 // pltforms.
3026 }
3027 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
3028 << " right=" << right * scale
3029 << " for channel " << *it << " and ssrc " << ssrc;
3030 }
3031 return true;
3032}
3033
3034bool WebRtcVoiceMediaChannel::GetOutputScaling(
3035 uint32 ssrc, double* left, double* right) {
3036 if (!left || !right) return false;
3037
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003038 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003039 // Determine which channel based on ssrc.
3040 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
3041 if (channel == -1) {
3042 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
3043 return false;
3044 }
3045
3046 float scaling;
3047 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
3048 channel, scaling)) {
3049 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
3050 return false;
3051 }
3052
3053 float left_pan;
3054 float right_pan;
3055 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
3056 channel, left_pan, right_pan)) {
3057 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
3058 // If GetOutputVolumePan fails, we use the default left and right pan.
3059 left_pan = 1.0f;
3060 right_pan = 1.0f;
3061 }
3062
3063 *left = scaling * left_pan;
3064 *right = scaling * right_pan;
3065 return true;
3066}
3067
3068bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
3069 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
3070 return true;
3071}
3072
3073bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
3074 bool play, bool loop) {
3075 if (!ringback_tone_) {
3076 return false;
3077 }
3078
3079 // The voe file api is not available in chrome.
3080 if (!engine()->voe()->file()) {
3081 return false;
3082 }
3083
3084 // Determine which VoiceEngine channel to play on.
3085 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
3086 if (channel == -1) {
3087 return false;
3088 }
3089
3090 // Make sure the ringtone is cued properly, and play it out.
3091 if (play) {
3092 ringback_tone_->set_loop(loop);
3093 ringback_tone_->Rewind();
3094 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
3095 ringback_tone_.get()) == -1) {
3096 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
3097 LOG(LS_ERROR) << "Unable to start ringback tone";
3098 return false;
3099 }
3100 ringback_channels_.insert(channel);
3101 LOG(LS_INFO) << "Started ringback on channel " << channel;
3102 } else {
3103 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
3104 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
3105 LOG_RTCERR1(StopPlayingFileLocally, channel);
3106 return false;
3107 }
3108 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
3109 ringback_channels_.erase(channel);
3110 }
3111
3112 return true;
3113}
3114
3115bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3116 return dtmf_allowed_;
3117}
3118
3119bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3120 int duration, int flags) {
3121 if (!dtmf_allowed_) {
3122 return false;
3123 }
3124
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003125 // Send the event.
3126 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003127 int channel = -1;
3128 if (ssrc == 0) {
3129 bool default_channel_is_inuse = false;
3130 for (ChannelMap::const_iterator iter = send_channels_.begin();
3131 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003132 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003133 default_channel_is_inuse = true;
3134 break;
3135 }
3136 }
3137 if (default_channel_is_inuse) {
3138 channel = voe_channel();
3139 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003140 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003141 }
3142 } else {
3143 channel = GetSendChannelNum(ssrc);
3144 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003145 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003146 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3147 << ssrc << " is not in use.";
3148 return false;
3149 }
3150 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003151 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3152 channel, event, true, duration) == -1) {
3153 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003154 return false;
3155 }
3156 }
3157
3158 // Play the event.
3159 if (flags & cricket::DF_PLAY) {
3160 // Play DTMF tone locally.
3161 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3162 LOG_RTCERR2(PlayDtmfTone, event, duration);
3163 return false;
3164 }
3165 }
3166
3167 return true;
3168}
3169
wu@webrtc.orga9890802013-12-13 00:21:03 +00003170void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003171 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003172 // Pick which channel to send this packet to. If this packet doesn't match
3173 // any multiplexed streams, just send it to the default channel. Otherwise,
3174 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003175 int which_channel =
3176 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003177 if (which_channel == -1) {
3178 which_channel = voe_channel();
3179 }
3180
3181 // Stop any ringback that might be playing on the channel.
3182 // It's possible the ringback has already stopped, ih which case we'll just
3183 // use the opportunity to remove the channel from ringback_channels_.
3184 if (engine()->voe()->file()) {
3185 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3186 if (it != ringback_channels_.end()) {
3187 if (engine()->voe()->file()->IsPlayingFileLocally(
3188 which_channel) == 1) {
3189 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3190 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3191 << " due to incoming media";
3192 }
3193 ringback_channels_.erase(which_channel);
3194 }
3195 }
3196
3197 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003198 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003199 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003200 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003201}
3202
wu@webrtc.orga9890802013-12-13 00:21:03 +00003203void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003204 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003205 // Sending channels need all RTCP packets with feedback information.
3206 // Even sender reports can contain attached report blocks.
3207 // Receiving channels need sender reports in order to create
3208 // correct receiver reports.
3209 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003210 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003211 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3212 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003213 }
3214
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003215 // If it is a sender report, find the channel that is listening.
3216 bool has_sent_to_default_channel = false;
3217 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003218 int which_channel =
3219 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003220 if (which_channel != -1) {
3221 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003222 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003223
3224 if (IsDefaultChannel(which_channel))
3225 has_sent_to_default_channel = true;
3226 }
3227 }
3228
3229 // SR may continue RR and any RR entry may correspond to any one of the send
3230 // channels. So all RTCP packets must be forwarded all send channels. VoE
3231 // will filter out RR internally.
3232 for (ChannelMap::iterator iter = send_channels_.begin();
3233 iter != send_channels_.end(); ++iter) {
3234 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003235 if (IsDefaultChannel(iter->second->channel()) &&
3236 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003237 continue;
3238
3239 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003240 iter->second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003241 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003242}
3243
3244bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003245 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3246 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003247 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3248 return false;
3249 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003250 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3251 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003252 return false;
3253 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003254 // We set the AGC to mute state only when all the channels are muted.
3255 // This implementation is not ideal, instead we should signal the AGC when
3256 // the mic channel is muted/unmuted. We can't do it today because there
3257 // is no good way to know which stream is mapping to the mic channel.
3258 bool all_muted = muted;
3259 for (ChannelMap::const_iterator iter = send_channels_.begin();
3260 iter != send_channels_.end() && all_muted; ++iter) {
3261 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3262 all_muted)) {
3263 LOG_RTCERR1(GetInputMute, iter->second->channel());
3264 return false;
3265 }
3266 }
3267
3268 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3269 if (ap)
3270 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003271 return true;
3272}
3273
minyue@webrtc.org26236952014-10-29 02:27:08 +00003274// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3275// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003276bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003277 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003278
minyue@webrtc.org26236952014-10-29 02:27:08 +00003279 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003280}
3281
minyue@webrtc.org26236952014-10-29 02:27:08 +00003282bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3283 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003284
minyue@webrtc.org26236952014-10-29 02:27:08 +00003285 send_bitrate_setting_ = true;
3286 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003287
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003288 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003289 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003290 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003291 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003292 }
3293
minyue@webrtc.org26236952014-10-29 02:27:08 +00003294 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003295 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3296 // SetMaxSendBandwith(0), the second call removes the previous limit.
3297 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003298 return true;
3299
3300 webrtc::CodecInst codec = *send_codec_;
3301 bool is_multi_rate = IsCodecMultiRate(codec);
3302
3303 if (is_multi_rate) {
3304 // If codec is multi-rate then just set the bitrate.
3305 codec.rate = bps;
3306 if (!SetSendCodec(codec)) {
3307 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3308 << " to bitrate " << bps << " bps.";
3309 return false;
3310 }
3311 return true;
3312 } else {
3313 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3314 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3315 // fixed bitrate then ignore.
3316 if (bps < codec.rate) {
3317 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3318 << " to bitrate " << bps << " bps"
3319 << ", requires at least " << codec.rate << " bps.";
3320 return false;
3321 }
3322 return true;
3323 }
3324}
3325
3326bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003327 bool echo_metrics_on = false;
3328 // These can take on valid negative values, so use the lowest possible level
3329 // as default rather than -1.
3330 int echo_return_loss = -100;
3331 int echo_return_loss_enhancement = -100;
3332 // These can also be negative, but in practice -1 is only used to signal
3333 // insufficient data, since the resolution is limited to multiples of 4 ms.
3334 int echo_delay_median_ms = -1;
3335 int echo_delay_std_ms = -1;
3336 if (engine()->voe()->processing()->GetEcMetricsStatus(
3337 echo_metrics_on) != -1 && echo_metrics_on) {
3338 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3339 // here, but it appears to be unsuitable currently. Revisit after this is
3340 // investigated: http://b/issue?id=5666755
3341 int erl, erle, rerl, anlp;
3342 if (engine()->voe()->processing()->GetEchoMetrics(
3343 erl, erle, rerl, anlp) != -1) {
3344 echo_return_loss = erl;
3345 echo_return_loss_enhancement = erle;
3346 }
3347
3348 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003349 float dummy;
3350 if (engine()->voe()->processing()->GetEcDelayMetrics(
3351 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003352 echo_delay_median_ms = median;
3353 echo_delay_std_ms = std;
3354 }
3355 }
3356
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003357 webrtc::CallStatistics cs;
3358 unsigned int ssrc;
3359 webrtc::CodecInst codec;
3360 unsigned int level;
3361
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003362 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3363 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003364 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003365
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003366 // Fill in the sender info, based on what we know, and what the
3367 // remote side told us it got from its RTCP report.
3368 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003369
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003370 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3371 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3372 continue;
3373 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003374
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003375 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003376 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3377 sinfo.bytes_sent = cs.bytesSent;
3378 sinfo.packets_sent = cs.packetsSent;
3379 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3380 // returns 0 to indicate an error value.
3381 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3382
3383 // Get data from the last remote RTCP report. Use default values if no data
3384 // available.
3385 sinfo.fraction_lost = -1.0;
3386 sinfo.jitter_ms = -1;
3387 sinfo.packets_lost = -1;
3388 sinfo.ext_seqnum = -1;
3389 std::vector<webrtc::ReportBlock> receive_blocks;
3390 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3391 channel, &receive_blocks) != -1 &&
3392 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3393 std::vector<webrtc::ReportBlock>::iterator iter;
3394 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3395 ++iter) {
3396 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003397 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003398 // Convert Q8 to floating point.
3399 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3400 // Convert samples to milliseconds.
3401 if (codec.plfreq / 1000 > 0) {
3402 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3403 }
3404 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3405 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3406 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003407 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003408 }
3409 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003410
3411 // Local speech level.
3412 sinfo.audio_level = (engine()->voe()->volume()->
3413 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3414
3415 // TODO(xians): We are injecting the same APM logging to all the send
3416 // channels here because there is no good way to know which send channel
3417 // is using the APM. The correct fix is to allow the send channels to have
3418 // their own APM so that we can feed the correct APM logging to different
3419 // send channels. See issue crbug/264611 .
3420 sinfo.echo_return_loss = echo_return_loss;
3421 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3422 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3423 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003424 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3425 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003426 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003427
3428 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003429 }
3430
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003431 // Build the list of receivers, one for each receiving channel, or 1 in
3432 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003433 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003434 for (ChannelMap::const_iterator it = receive_channels_.begin();
3435 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003436 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003437 }
3438 if (channels.empty()) {
3439 channels.push_back(voe_channel());
3440 }
3441
3442 // Get the SSRC and stats for each receiver, based on our own calculations.
3443 for (std::vector<int>::const_iterator it = channels.begin();
3444 it != channels.end(); ++it) {
3445 memset(&cs, 0, sizeof(cs));
3446 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3447 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3448 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3449 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003450 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003451 rinfo.bytes_rcvd = cs.bytesReceived;
3452 rinfo.packets_rcvd = cs.packetsReceived;
3453 // The next four fields are from the most recently sent RTCP report.
3454 // Convert Q8 to floating point.
3455 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3456 rinfo.packets_lost = cs.cumulativeLost;
3457 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003458 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003459 if (codec.pltype != -1) {
3460 rinfo.codec_name = codec.plname;
3461 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003462 // Convert samples to milliseconds.
3463 if (codec.plfreq / 1000 > 0) {
3464 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3465 }
3466
3467 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3468 webrtc::NetworkStatistics ns;
3469 if (engine()->voe()->neteq() &&
3470 engine()->voe()->neteq()->GetNetworkStatistics(
3471 *it, ns) != -1) {
3472 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3473 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3474 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003475 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003476 rinfo.speech_expand_rate =
3477 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3478 rinfo.secondary_decoded_rate =
3479 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003480 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003481
3482 webrtc::AudioDecodingCallStats ds;
3483 if (engine()->voe()->neteq() &&
3484 engine()->voe()->neteq()->GetDecodingCallStatistics(
3485 *it, &ds) != -1) {
3486 rinfo.decoding_calls_to_silence_generator =
3487 ds.calls_to_silence_generator;
3488 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3489 rinfo.decoding_normal = ds.decoded_normal;
3490 rinfo.decoding_plc = ds.decoded_plc;
3491 rinfo.decoding_cng = ds.decoded_cng;
3492 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3493 }
3494
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003495 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003496 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003497 int playout_buffer_delay_ms = 0;
3498 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003499 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3500 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3501 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003502 }
3503
3504 // Get speech level.
3505 rinfo.audio_level = (engine()->voe()->volume()->
3506 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3507 info->receivers.push_back(rinfo);
3508 }
3509 }
3510
3511 return true;
3512}
3513
3514void WebRtcVoiceMediaChannel::GetLastMediaError(
3515 uint32* ssrc, VoiceMediaChannel::Error* error) {
3516 ASSERT(ssrc != NULL);
3517 ASSERT(error != NULL);
3518 FindSsrc(voe_channel(), ssrc);
3519 *error = WebRtcErrorToChannelError(GetLastEngineError());
3520}
3521
3522bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003523 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003524 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003525 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003526 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3527 // This means the error is not limited to a specific channel. Signal the
3528 // message using ssrc=0. If the current channel is sending, use this
3529 // channel for sending the message.
3530 *ssrc = 0;
3531 return true;
3532 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003533 // Check whether this is a sending channel.
3534 for (ChannelMap::const_iterator it = send_channels_.begin();
3535 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003536 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003537 // This is a sending channel.
3538 uint32 local_ssrc = 0;
3539 if (engine()->voe()->rtp()->GetLocalSSRC(
3540 channel_num, local_ssrc) != -1) {
3541 *ssrc = local_ssrc;
3542 }
3543 return true;
3544 }
3545 }
3546
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003547 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003548 for (ChannelMap::const_iterator it = receive_channels_.begin();
3549 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003550 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003551 *ssrc = it->first;
3552 return true;
3553 }
3554 }
3555 }
3556 return false;
3557}
3558
3559void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003560 if (error == VE_TYPING_NOISE_WARNING) {
3561 typing_noise_detected_ = true;
3562 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3563 typing_noise_detected_ = false;
3564 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003565 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3566}
3567
3568int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3569 unsigned int ulevel;
3570 int ret =
3571 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3572 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3573}
3574
3575int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003576 ChannelMap::iterator it = receive_channels_.find(ssrc);
3577 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003578 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003579 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3580}
3581
3582int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003583 ChannelMap::iterator it = send_channels_.find(ssrc);
3584 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003585 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003586
3587 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003588}
3589
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003590bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
3591 webrtc::VideoEngine* vie, int vie_channel) {
3592 shared_bwe_vie_ = vie;
3593 shared_bwe_vie_channel_ = vie_channel;
3594
3595 if (!SetupSharedBweOnChannel(voe_channel())) {
3596 return false;
3597 }
3598 for (ChannelMap::iterator it = receive_channels_.begin();
3599 it != receive_channels_.end(); ++it) {
3600 if (!SetupSharedBweOnChannel(it->second->channel())) {
3601 return false;
3602 }
3603 }
3604 return true;
3605}
3606
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003607bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3608 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3609 // Get the RED encodings from the parameter with no name. This may
3610 // change based on what is discussed on the Jingle list.
3611 // The encoding parameter is of the form "a/b"; we only support where
3612 // a == b. Verify this and parse out the value into red_pt.
3613 // If the parameter value is absent (as it will be until we wire up the
3614 // signaling of this message), use the second codec specified (i.e. the
3615 // one after "red") as the encoding parameter.
3616 int red_pt = -1;
3617 std::string red_params;
3618 CodecParameterMap::const_iterator it = red_codec.params.find("");
3619 if (it != red_codec.params.end()) {
3620 red_params = it->second;
3621 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003622 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003623 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003624 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003625 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3626 return false;
3627 }
3628 } else if (red_codec.params.empty()) {
3629 LOG(LS_WARNING) << "RED params not present, using defaults";
3630 if (all_codecs.size() > 1) {
3631 red_pt = all_codecs[1].id;
3632 }
3633 }
3634
3635 // Try to find red_pt in |codecs|.
3636 std::vector<AudioCodec>::const_iterator codec;
3637 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3638 if (codec->id == red_pt)
3639 break;
3640 }
3641
3642 // If we find the right codec, that will be the codec we pass to
3643 // SetSendCodec, with the desired payload type.
3644 if (codec != all_codecs.end() &&
3645 engine()->FindWebRtcCodec(*codec, send_codec)) {
3646 } else {
3647 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3648 return false;
3649 }
3650
3651 return true;
3652}
3653
3654bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3655 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003656 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003657 return false;
3658 }
3659 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3660 // what we want to do with them.
3661 // engine()->voe().EnableVQMon(voe_channel(), true);
3662 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3663 return true;
3664}
3665
3666bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3667 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3668 for (int i = 0; i < ncodecs; ++i) {
3669 webrtc::CodecInst voe_codec;
3670 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3671 voe_codec.pltype = -1;
3672 if (engine()->voe()->codec()->SetRecPayloadType(
3673 channel, voe_codec) == -1) {
3674 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3675 return false;
3676 }
3677 }
3678 }
3679 return true;
3680}
3681
3682bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3683 if (playout) {
3684 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3685 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3686 LOG_RTCERR1(StartPlayout, channel);
3687 return false;
3688 }
3689 } else {
3690 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3691 engine()->voe()->base()->StopPlayout(channel);
3692 }
3693 return true;
3694}
3695
3696uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3697 bool rtcp) {
3698 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3699 uint32 ssrc = 0;
3700 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003701 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003702 }
3703 return ssrc;
3704}
3705
3706// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3707VoiceMediaChannel::Error
3708 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3709 switch (err_code) {
3710 case 0:
3711 return ERROR_NONE;
3712 case VE_CANNOT_START_RECORDING:
3713 case VE_MIC_VOL_ERROR:
3714 case VE_GET_MIC_VOL_ERROR:
3715 case VE_CANNOT_ACCESS_MIC_VOL:
3716 return ERROR_REC_DEVICE_OPEN_FAILED;
3717 case VE_SATURATION_WARNING:
3718 return ERROR_REC_DEVICE_SATURATION;
3719 case VE_REC_DEVICE_REMOVED:
3720 return ERROR_REC_DEVICE_REMOVED;
3721 case VE_RUNTIME_REC_WARNING:
3722 case VE_RUNTIME_REC_ERROR:
3723 return ERROR_REC_RUNTIME_ERROR;
3724 case VE_CANNOT_START_PLAYOUT:
3725 case VE_SPEAKER_VOL_ERROR:
3726 case VE_GET_SPEAKER_VOL_ERROR:
3727 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3728 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3729 case VE_RUNTIME_PLAY_WARNING:
3730 case VE_RUNTIME_PLAY_ERROR:
3731 return ERROR_PLAY_RUNTIME_ERROR;
3732 case VE_TYPING_NOISE_WARNING:
3733 return ERROR_REC_TYPING_NOISE_DETECTED;
3734 default:
3735 return VoiceMediaChannel::ERROR_OTHER;
3736 }
3737}
3738
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003739bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3740 int channel_id, const RtpHeaderExtension* extension) {
3741 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003742 int id = 0;
3743 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003744 if (extension) {
3745 enable = true;
3746 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003747 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003748 }
3749 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003750 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003751 return false;
3752 }
3753 return true;
3754}
3755
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003756bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
3757 webrtc::ViENetwork* vie_network = NULL;
3758 int vie_channel = -1;
3759 if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
3760 shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
3761 vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
3762 vie_channel = shared_bwe_vie_channel_;
3763 }
3764 if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
3765 vie_channel) == -1) {
3766 LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
3767 if (vie_network != NULL) {
3768 // Don't fail if we're tearing down.
3769 return false;
3770 }
3771 }
3772 return true;
3773}
3774
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003775int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003776 size_t res = 0;
3777 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003778 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003779}
3780
3781int WebRtcSoundclipStream::Rewind() {
3782 mem_.Rewind();
3783 // Return -1 to keep VoiceEngine from looping.
3784 return (loop_) ? 0 : -1;
3785}
3786
3787} // namespace cricket
3788
3789#endif // HAVE_WEBRTC_VOICE