blob: 95e16e4ac048ccd222f195adc1bc77f01e53188a [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
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000041#include "talk/media/base/audiorenderer.h"
42#include "talk/media/base/constants.h"
43#include "talk/media/base/streamparams.h"
44#include "talk/media/base/voiceprocessor.h"
45#include "talk/media/webrtc/webrtcvoe.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000046#include "webrtc/base/base64.h"
47#include "webrtc/base/byteorder.h"
48#include "webrtc/base/common.h"
49#include "webrtc/base/helpers.h"
50#include "webrtc/base/logging.h"
51#include "webrtc/base/stringencode.h"
52#include "webrtc/base/stringutils.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000053#include "webrtc/common.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054#include "webrtc/modules/audio_processing/include/audio_processing.h"
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +000055#include "webrtc/video_engine/include/vie_network.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056
57#ifdef WIN32
58#include <objbase.h> // NOLINT
59#endif
60
61namespace cricket {
62
63struct CodecPref {
64 const char* name;
65 int clockrate;
66 int channels;
67 int payload_type;
68 bool is_multi_rate;
69};
70
71static const CodecPref kCodecPrefs[] = {
72 { "OPUS", 48000, 2, 111, true },
73 { "ISAC", 16000, 1, 103, true },
74 { "ISAC", 32000, 1, 104, true },
75 { "CELT", 32000, 1, 109, true },
76 { "CELT", 32000, 2, 110, true },
77 { "G722", 16000, 1, 9, false },
78 { "ILBC", 8000, 1, 102, false },
79 { "PCMU", 8000, 1, 0, false },
80 { "PCMA", 8000, 1, 8, false },
81 { "CN", 48000, 1, 107, false },
82 { "CN", 32000, 1, 106, false },
83 { "CN", 16000, 1, 105, false },
84 { "CN", 8000, 1, 13, false },
85 { "red", 8000, 1, 127, false },
86 { "telephone-event", 8000, 1, 126, false },
87};
88
89// For Linux/Mac, using the default device is done by specifying index 0 for
90// VoE 4.0 and not -1 (which was the case for VoE 3.5).
91//
92// On Windows Vista and newer, Microsoft introduced the concept of "Default
93// Communications Device". This means that there are two types of default
94// devices (old Wave Audio style default and Default Communications Device).
95//
96// On Windows systems which only support Wave Audio style default, uses either
97// -1 or 0 to select the default device.
98//
99// On Windows systems which support both "Default Communication Device" and
100// old Wave Audio style default, use -1 for Default Communications Device and
101// -2 for Wave Audio style default, which is what we want to use for clips.
102// It's not clear yet whether the -2 index is handled properly on other OSes.
103
104#ifdef WIN32
105static const int kDefaultAudioDeviceId = -1;
106static const int kDefaultSoundclipDeviceId = -2;
107#else
108static const int kDefaultAudioDeviceId = 0;
109#endif
110
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111static const char kIsacCodecName[] = "ISAC";
112static const char kL16CodecName[] = "L16";
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000113
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000114// Parameter used for NACK.
115// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
116static const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000117
118// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000119// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000120
121// Recommended bitrates:
122// 8-12 kb/s for NB speech,
123// 16-20 kb/s for WB speech,
124// 28-40 kb/s for FB speech,
125// 48-64 kb/s for FB mono music, and
126// 64-128 kb/s for FB stereo music.
127// The current implementation applies the following values to mono signals,
128// and multiplies them by 2 for stereo.
129static const int kOpusBitrateNb = 12000;
130static const int kOpusBitrateWb = 20000;
131static const int kOpusBitrateFb = 32000;
132
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000133// Opus bitrate should be in the range between 6000 and 510000.
134static const int kOpusMinBitrate = 6000;
135static const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000136
wu@webrtc.orgde305012013-10-31 15:40:38 +0000137// Default audio dscp value.
138// See http://tools.ietf.org/html/rfc2474 for details.
139// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000140static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000141
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000142// Ensure we open the file in a writeable path on ChromeOS and Android. This
143// workaround can be removed when it's possible to specify a filename for audio
144// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000145//
146// TODO(grunell): Use a string in the options instead of hardcoding it here
147// and let the embedder choose the filename (crbug.com/264223).
148//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000149// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
150// below.
151#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000152static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000153#elif defined(ANDROID)
154static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000155#else
156static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
157#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000158
159// Dumps an AudioCodec in RFC 2327-ish format.
160static std::string ToString(const AudioCodec& codec) {
161 std::stringstream ss;
162 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
163 << " (" << codec.id << ")";
164 return ss.str();
165}
166static std::string ToString(const webrtc::CodecInst& codec) {
167 std::stringstream ss;
168 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
169 << " (" << codec.pltype << ")";
170 return ss.str();
171}
172
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000173static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000174 const char* delim = "\r\n";
175 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
176 LOG_V(sev) << tok;
177 }
178}
179
180// Severity is an integer because it comes is assumed to be from command line.
181static int SeverityToFilter(int severity) {
182 int filter = webrtc::kTraceNone;
183 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000184 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000185 filter |= webrtc::kTraceAll;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000186 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000187 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000188 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000189 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000190 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000191 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
192 }
193 return filter;
194}
195
196static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
197 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
198 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
199 kCodecPrefs[i].clockrate == codec.plfreq) {
200 return kCodecPrefs[i].is_multi_rate;
201 }
202 }
203 return false;
204}
205
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000206static bool IsTelephoneEventCodec(const std::string& name) {
207 return _stricmp(name.c_str(), "telephone-event") == 0;
208}
209
210static bool IsCNCodec(const std::string& name) {
211 return _stricmp(name.c_str(), "CN") == 0;
212}
213
214static bool IsRedCodec(const std::string& name) {
215 return _stricmp(name.c_str(), "red") == 0;
216}
217
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000218static bool FindCodec(const std::vector<AudioCodec>& codecs,
219 const AudioCodec& codec,
220 AudioCodec* found_codec) {
221 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
222 it != codecs.end(); ++it) {
223 if (it->Matches(codec)) {
224 if (found_codec != NULL) {
225 *found_codec = *it;
226 }
227 return true;
228 }
229 }
230 return false;
231}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000232
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000233static bool IsNackEnabled(const AudioCodec& codec) {
234 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
235 kParamValueEmpty));
236}
237
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000238// Gets the default set of options applied to the engine. Historically, these
239// were supplied as a combination of flags from the channel manager (ec, agc,
240// ns, and highpass) and the rest hardcoded in InitInternal.
241static AudioOptions GetDefaultEngineOptions() {
242 AudioOptions options;
243 options.echo_cancellation.Set(true);
244 options.auto_gain_control.Set(true);
245 options.noise_suppression.Set(true);
246 options.highpass_filter.Set(true);
247 options.stereo_swapping.Set(false);
248 options.typing_detection.Set(true);
249 options.conference_mode.Set(false);
250 options.adjust_agc_delta.Set(0);
251 options.experimental_agc.Set(false);
252 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000253 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000254 options.aec_dump.Set(false);
255 return options;
256}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000257
258class WebRtcSoundclipMedia : public SoundclipMedia {
259 public:
260 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
261 : engine_(engine), webrtc_channel_(-1) {
262 engine_->RegisterSoundclip(this);
263 }
264
265 virtual ~WebRtcSoundclipMedia() {
266 engine_->UnregisterSoundclip(this);
267 if (webrtc_channel_ != -1) {
268 // We shouldn't have to call Disable() here. DeleteChannel() should call
269 // StopPlayout() while deleting the channel. We should fix the bug
270 // inside WebRTC and remove the Disable() call bellow. This work is
271 // tracked by bug http://b/issue?id=5382855.
272 PlaySound(NULL, 0, 0);
273 Disable();
274 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
275 == -1) {
276 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
277 }
278 }
279 }
280
281 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000282 if (!engine_->voe_sc()) {
283 return false;
284 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000285 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000286 if (webrtc_channel_ == -1) {
287 LOG_RTCERR0(CreateChannel);
288 return false;
289 }
290 return true;
291 }
292
293 bool Enable() {
294 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
295 LOG_RTCERR1(StartPlayout, webrtc_channel_);
296 return false;
297 }
298 return true;
299 }
300
301 bool Disable() {
302 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
303 LOG_RTCERR1(StopPlayout, webrtc_channel_);
304 return false;
305 }
306 return true;
307 }
308
309 virtual bool PlaySound(const char *buf, int len, int flags) {
310 // The voe file api is not available in chrome.
311 if (!engine_->voe_sc()->file()) {
312 return false;
313 }
314 // Must stop playing the current sound (if any), because we are about to
315 // modify the stream.
316 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
317 == -1) {
318 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
319 return false;
320 }
321
322 if (buf) {
323 stream_.reset(new WebRtcSoundclipStream(buf, len));
324 stream_->set_loop((flags & SF_LOOP) != 0);
325 stream_->Rewind();
326
327 // Play it.
328 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
329 webrtc_channel_, stream_.get()) == -1) {
330 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
331 LOG(LS_ERROR) << "Unable to start soundclip";
332 return false;
333 }
334 } else {
335 stream_.reset();
336 }
337 return true;
338 }
339
340 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
341
342 private:
343 WebRtcVoiceEngine *engine_;
344 int webrtc_channel_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000345 rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000346};
347
348WebRtcVoiceEngine::WebRtcVoiceEngine()
349 : voe_wrapper_(new VoEWrapper()),
350 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000351 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000352 tracing_(new VoETraceWrapper()),
353 adm_(NULL),
354 adm_sc_(NULL),
355 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
356 is_dumping_aec_(false),
357 desired_local_monitor_enable_(false),
358 tx_processor_ssrc_(0),
359 rx_processor_ssrc_(0) {
360 Construct();
361}
362
363WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
364 VoEWrapper* voe_wrapper_sc,
365 VoETraceWrapper* tracing)
366 : voe_wrapper_(voe_wrapper),
367 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000368 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000369 tracing_(tracing),
370 adm_(NULL),
371 adm_sc_(NULL),
372 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
373 is_dumping_aec_(false),
374 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000375 tx_processor_ssrc_(0),
376 rx_processor_ssrc_(0) {
377 Construct();
378}
379
380void WebRtcVoiceEngine::Construct() {
381 SetTraceFilter(log_filter_);
382 initialized_ = false;
383 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
384 SetTraceOptions("");
385 if (tracing_->SetTraceCallback(this) == -1) {
386 LOG_RTCERR0(SetTraceCallback);
387 }
388 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
389 LOG_RTCERR0(RegisterVoiceEngineObserver);
390 }
391 // Clear the default agc state.
392 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
393
394 // Load our audio codec list.
395 ConstructCodecs();
396
397 // Load our RTP Header extensions.
398 rtp_header_extensions_.push_back(
399 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
400 kRtpAudioLevelHeaderExtensionDefaultId));
401 rtp_header_extensions_.push_back(
402 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
403 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
404 options_ = GetDefaultEngineOptions();
405}
406
407static bool IsOpus(const AudioCodec& codec) {
408 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
409}
410
411static bool IsIsac(const AudioCodec& codec) {
412 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
413}
414
415// True if params["stereo"] == "1"
416static bool IsOpusStereoEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000417 int value;
418 return codec.GetParam(kCodecParamStereo, &value) && value == 1;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000419}
420
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000421// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
422// otherwise. If the value (either from params or codec.bitrate) <=0, use the
423// default configuration. If the value is beyond feasible bit rate of Opus,
424// clamp it. Returns the Opus bit rate for operation.
buildbot@webrtc.org879fac82014-10-30 07:50:13 +0000425static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000426 int bitrate = 0;
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000427 bool use_param = true;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000428 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000429 bitrate = codec.bitrate;
430 use_param = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000431 }
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000432 if (bitrate <= 0) {
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000433 if (max_playback_rate <= 8000) {
434 bitrate = kOpusBitrateNb;
435 } else if (max_playback_rate <= 16000) {
436 bitrate = kOpusBitrateWb;
437 } else {
438 bitrate = kOpusBitrateFb;
439 }
440
441 if (IsOpusStereoEnabled(codec)) {
442 bitrate *= 2;
443 }
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000444 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
445 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
446 std::string rate_source =
447 use_param ? "Codec parameter \"maxaveragebitrate\"" :
448 "Supplied Opus bitrate";
449 LOG(LS_WARNING) << rate_source
450 << " is invalid and is replaced by: "
451 << bitrate;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000452 }
453 return bitrate;
454}
455
buildbot@webrtc.orgfbd13282014-06-19 19:50:55 +0000456// Return true if params[kCodecParamUseInbandFec] == "1", false
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000457// otherwise.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000458static bool IsOpusFecEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000459 int value;
460 return codec.GetParam(kCodecParamUseInbandFec, &value) && value == 1;
461}
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000462
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000463// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
464// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
465static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
466 int value;
467 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
468 return value;
469 }
470 return kOpusDefaultMaxPlaybackRate;
471}
472
473static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
474 bool* enable_codec_fec, int* max_playback_rate) {
475 *enable_codec_fec = IsOpusFecEnabled(codec);
476 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
477
478 // If OPUS, change what we send according to the "stereo" codec
479 // parameter, and not the "channels" parameter. We set
480 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000481 // the bitrate is not specified, i.e. is <= zero, we set it to the
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000482 // appropriate default value for mono or stereo Opus.
483
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000484 voe_codec->channels = IsOpusStereoEnabled(codec) ? 2 : 1;
buildbot@webrtc.org879fac82014-10-30 07:50:13 +0000485 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000486}
487
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000488void WebRtcVoiceEngine::ConstructCodecs() {
489 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
490 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
491 for (int i = 0; i < ncodecs; ++i) {
492 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.orgdced5d72014-11-06 15:27:43 +0000493 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000494 // Skip uncompressed formats.
495 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
496 continue;
497 }
498
499 const CodecPref* pref = NULL;
500 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
501 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
502 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
503 kCodecPrefs[j].channels == voe_codec.channels) {
504 pref = &kCodecPrefs[j];
505 break;
506 }
507 }
508
509 if (pref) {
510 // Use the payload type that we've configured in our pref table;
511 // use the offset in our pref table to determine the sort order.
512 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
513 voe_codec.rate, voe_codec.channels,
514 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
515 LOG(LS_INFO) << ToString(codec);
516 if (IsIsac(codec)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000517 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000518 codec.bitrate = 0;
519 }
520 if (IsOpus(codec)) {
521 // Only add fmtp parameters that differ from the spec.
522 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
523 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000524 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000525 }
526 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
527 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000528 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000529 }
530 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
531 // when they can be set to values other than the default.
532 }
533 codecs_.push_back(codec);
534 } else {
535 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
536 }
537 }
538 }
539 // Make sure they are in local preference order.
540 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
541}
542
543WebRtcVoiceEngine::~WebRtcVoiceEngine() {
544 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
545 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
546 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
547 }
548 if (adm_) {
549 voe_wrapper_.reset();
550 adm_->Release();
551 adm_ = NULL;
552 }
553 if (adm_sc_) {
554 voe_wrapper_sc_.reset();
555 adm_sc_->Release();
556 adm_sc_ = NULL;
557 }
558
559 // Test to see if the media processor was deregistered properly
560 ASSERT(SignalRxMediaFrame.is_empty());
561 ASSERT(SignalTxMediaFrame.is_empty());
562
563 tracing_->SetTraceCallback(NULL);
564}
565
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000566bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000567 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
568 bool res = InitInternal();
569 if (res) {
570 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
571 } else {
572 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
573 Terminate();
574 }
575 return res;
576}
577
578bool WebRtcVoiceEngine::InitInternal() {
579 // Temporarily turn logging level up for the Init call
580 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000581 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000582 SetTraceFilter(extended_filter);
583 SetTraceOptions("");
584
585 // Init WebRtc VoiceEngine.
586 if (voe_wrapper_->base()->Init(adm_) == -1) {
587 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
588 SetTraceFilter(old_filter);
589 return false;
590 }
591
592 SetTraceFilter(old_filter);
593 SetTraceOptions(log_options_);
594
595 // Log the VoiceEngine version info
596 char buffer[1024] = "";
597 voe_wrapper_->base()->GetVersion(buffer);
598 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000599 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000600
601 // Save the default AGC configuration settings. This must happen before
602 // calling SetOptions or the default will be overwritten.
603 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
604 LOG_RTCERR0(GetAgcConfig);
605 return false;
606 }
607
608 // Set defaults for options, so that ApplyOptions applies them explicitly
609 // when we clear option (channel) overrides. External clients can still
610 // modify the defaults via SetOptions (on the media engine).
611 if (!SetOptions(GetDefaultEngineOptions())) {
612 return false;
613 }
614
615 // Print our codec list again for the call diagnostic log
616 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
617 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
618 it != codecs_.end(); ++it) {
619 LOG(LS_INFO) << ToString(*it);
620 }
621
622 // Disable the DTMF playout when a tone is sent.
623 // PlayDtmfTone will be used if local playout is needed.
624 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
625 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
626 }
627
628 initialized_ = true;
629 return true;
630}
631
632bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
633 if (voe_wrapper_sc_initialized_) {
634 return true;
635 }
636 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
637 // be false, so subsequent calls to EnsureSoundclipEngineInit will
638 // probably just fail again. That's acceptable behavior.
639#if defined(LINUX) && !defined(HAVE_LIBPULSE)
640 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
641#endif
642
643 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
644 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
645 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
646 return false;
647 }
648
649 // On Windows, tell it to use the default sound (not communication) devices.
650 // First check whether there is a valid sound device for playback.
651 // TODO(juberti): Clean this up when we support setting the soundclip device.
652#ifdef WIN32
653 // The SetPlayoutDevice may not be implemented in the case of external ADM.
654 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
655 // PeerConnection interface never set the adm_sc_, so need to check both
656 // in order to determine if the external adm is used.
657 if (!adm_ && !adm_sc_) {
658 int num_of_devices = 0;
659 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
660 num_of_devices > 0) {
661 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
662 == -1) {
663 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
664 voe_wrapper_sc_->error());
665 return false;
666 }
667 } else {
668 LOG(LS_WARNING) << "No valid sound playout device found.";
669 }
670 }
671#endif
672 voe_wrapper_sc_initialized_ = true;
673 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
674 return true;
675}
676
677void WebRtcVoiceEngine::Terminate() {
678 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
679 initialized_ = false;
680
681 StopAecDump();
682
683 if (voe_wrapper_sc_) {
684 voe_wrapper_sc_initialized_ = false;
685 voe_wrapper_sc_->base()->Terminate();
686 }
687 voe_wrapper_->base()->Terminate();
688 desired_local_monitor_enable_ = false;
689}
690
691int WebRtcVoiceEngine::GetCapabilities() {
692 return AUDIO_SEND | AUDIO_RECV;
693}
694
695VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
696 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
697 if (!ch->valid()) {
698 delete ch;
699 ch = NULL;
700 }
701 return ch;
702}
703
704SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
705 if (!EnsureSoundclipEngineInit()) {
706 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
707 << "initialize.";
708 return NULL;
709 }
710 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
711 if (!soundclip->Init() || !soundclip->Enable()) {
712 delete soundclip;
713 return NULL;
714 }
715 return soundclip;
716}
717
718bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
719 if (!ApplyOptions(options)) {
720 return false;
721 }
722 options_ = options;
723 return true;
724}
725
726bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
727 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
728 if (!ApplyOptions(overrides)) {
729 return false;
730 }
731 option_overrides_ = overrides;
732 return true;
733}
734
735bool WebRtcVoiceEngine::ClearOptionOverrides() {
736 LOG(LS_INFO) << "Clearing option overrides.";
737 AudioOptions options = options_;
738 // Only call ApplyOptions if |options_overrides_| contains overrided options.
739 // ApplyOptions affects NS, AGC other options that is shared between
740 // all WebRtcVoiceEngineChannels.
741 if (option_overrides_ == AudioOptions()) {
742 return true;
743 }
744
745 if (!ApplyOptions(options)) {
746 return false;
747 }
748 option_overrides_ = AudioOptions();
749 return true;
750}
751
752// AudioOptions defaults are set in InitInternal (for options with corresponding
753// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
754bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
755 AudioOptions options = options_in; // The options are modified below.
756 // kEcConference is AEC with high suppression.
757 webrtc::EcModes ec_mode = webrtc::kEcConference;
758 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
759 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
760 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
761 bool aecm_comfort_noise = false;
762 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
763 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
764 << aecm_comfort_noise << " (default is false).";
765 }
766
767#if defined(IOS)
768 // On iOS, VPIO provides built-in EC and AGC.
769 options.echo_cancellation.Set(false);
770 options.auto_gain_control.Set(false);
771#elif defined(ANDROID)
772 ec_mode = webrtc::kEcAecm;
773#endif
774
775#if defined(IOS) || defined(ANDROID)
776 // Set the AGC mode for iOS as well despite disabling it above, to avoid
777 // unsupported configuration errors from webrtc.
778 agc_mode = webrtc::kAgcFixedDigital;
779 options.typing_detection.Set(false);
780 options.experimental_agc.Set(false);
781 options.experimental_aec.Set(false);
782 options.experimental_ns.Set(false);
783#endif
784
785 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
786
787 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
788
789 bool echo_cancellation;
790 if (options.echo_cancellation.Get(&echo_cancellation)) {
791 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
792 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
793 return false;
794 } else {
795 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
796 << " with mode " << ec_mode;
797 }
798#if !defined(ANDROID)
799 // TODO(ajm): Remove the error return on Android from webrtc.
800 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
801 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
802 return false;
803 }
804#endif
805 if (ec_mode == webrtc::kEcAecm) {
806 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
807 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
808 return false;
809 }
810 }
811 }
812
813 bool auto_gain_control;
814 if (options.auto_gain_control.Get(&auto_gain_control)) {
815 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
816 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
817 return false;
818 } else {
819 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
820 << " with mode " << agc_mode;
821 }
822 }
823
824 if (options.tx_agc_target_dbov.IsSet() ||
825 options.tx_agc_digital_compression_gain.IsSet() ||
826 options.tx_agc_limiter.IsSet()) {
827 // Override default_agc_config_. Generally, an unset option means "leave
828 // the VoE bits alone" in this function, so we want whatever is set to be
829 // stored as the new "default". If we didn't, then setting e.g.
830 // tx_agc_target_dbov would reset digital compression gain and limiter
831 // settings.
832 // Also, if we don't update default_agc_config_, then adjust_agc_delta
833 // would be an offset from the original values, and not whatever was set
834 // explicitly.
835 default_agc_config_.targetLeveldBOv =
836 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
837 default_agc_config_.targetLeveldBOv);
838 default_agc_config_.digitalCompressionGaindB =
839 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
840 default_agc_config_.digitalCompressionGaindB);
841 default_agc_config_.limiterEnable =
842 options.tx_agc_limiter.GetWithDefaultIfUnset(
843 default_agc_config_.limiterEnable);
844 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
845 LOG_RTCERR3(SetAgcConfig,
846 default_agc_config_.targetLeveldBOv,
847 default_agc_config_.digitalCompressionGaindB,
848 default_agc_config_.limiterEnable);
849 return false;
850 }
851 }
852
853 bool noise_suppression;
854 if (options.noise_suppression.Get(&noise_suppression)) {
855 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
856 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
857 return false;
858 } else {
859 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
860 << " with mode " << ns_mode;
861 }
862 }
863
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000864 bool highpass_filter;
865 if (options.highpass_filter.Get(&highpass_filter)) {
866 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
867 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
868 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
869 return false;
870 }
871 }
872
873 bool stereo_swapping;
874 if (options.stereo_swapping.Get(&stereo_swapping)) {
875 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
876 voep->EnableStereoChannelSwapping(stereo_swapping);
877 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
878 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
879 return false;
880 }
881 }
882
883 bool typing_detection;
884 if (options.typing_detection.Get(&typing_detection)) {
885 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
886 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
887 // In case of error, log the info and continue
888 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
889 }
890 }
891
892 int adjust_agc_delta;
893 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
894 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
895 if (!AdjustAgcLevel(adjust_agc_delta)) {
896 return false;
897 }
898 }
899
900 bool aec_dump;
901 if (options.aec_dump.Get(&aec_dump)) {
902 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
903 if (aec_dump)
904 StartAecDump(kAecDumpByAudioOptionFilename);
905 else
906 StopAecDump();
907 }
908
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000909 webrtc::Config config;
910
911 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000912 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000913 if (experimental_aec_.Get(&experimental_aec)) {
914 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
915 config.Set<webrtc::DelayCorrection>(
916 new webrtc::DelayCorrection(experimental_aec));
917 }
918
919#ifdef USE_WEBRTC_DEV_BRANCH
920 experimental_ns_.SetFrom(options.experimental_ns);
921 bool experimental_ns;
922 if (experimental_ns_.Get(&experimental_ns)) {
923 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
924 config.Set<webrtc::ExperimentalNs>(
925 new webrtc::ExperimentalNs(experimental_ns));
926 }
927#endif
928
929 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
930 // returns NULL on audio_processing().
931 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
932 if (audioproc) {
933 audioproc->SetExtraOptions(config);
934 }
935
936#ifndef USE_WEBRTC_DEV_BRANCH
937 bool experimental_ns;
938 if (options.experimental_ns.Get(&experimental_ns)) {
939 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000940 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
941 // returns NULL on audio_processing().
942 if (audioproc) {
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000943 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
944 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
945 return false;
946 }
947 } else {
948 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
949 << experimental_ns;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000950 }
951 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000952#endif
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000953
954 uint32 recording_sample_rate;
955 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
956 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
957 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
958 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
959 }
960 }
961
962 uint32 playout_sample_rate;
963 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
964 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
965 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
966 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
967 }
968 }
969
970 return true;
971}
972
973bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
974 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
975 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
976 LOG_RTCERR1(SetDelayOffsetMs, offset);
977 return false;
978 }
979
980 return true;
981}
982
983struct ResumeEntry {
984 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
985 : channel(c),
986 playout(p),
987 send(s) {
988 }
989
990 WebRtcVoiceMediaChannel *channel;
991 bool playout;
992 SendFlags send;
993};
994
995// TODO(juberti): Refactor this so that the core logic can be used to set the
996// soundclip device. At that time, reinstate the soundclip pause/resume code.
997bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
998 const Device* out_device) {
999#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001000 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001001 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001002 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001003 kDefaultAudioDeviceId;
1004 // The device manager uses -1 as the default device, which was the case for
1005 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
1006#ifndef WIN32
1007 if (-1 == in_id) {
1008 in_id = kDefaultAudioDeviceId;
1009 }
1010 if (-1 == out_id) {
1011 out_id = kDefaultAudioDeviceId;
1012 }
1013#endif
1014
1015 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
1016 in_device->name : "Default device";
1017 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
1018 out_device->name : "Default device";
1019 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
1020 << ") and speaker to (id=" << out_id << ", name=" << out_name
1021 << ")";
1022
1023 // If we're running the local monitor, we need to stop it first.
1024 bool ret = true;
1025 if (!PauseLocalMonitor()) {
1026 LOG(LS_WARNING) << "Failed to pause local monitor";
1027 ret = false;
1028 }
1029
1030 // Must also pause all audio playback and capture.
1031 for (ChannelList::const_iterator i = channels_.begin();
1032 i != channels_.end(); ++i) {
1033 WebRtcVoiceMediaChannel *channel = *i;
1034 if (!channel->PausePlayout()) {
1035 LOG(LS_WARNING) << "Failed to pause playout";
1036 ret = false;
1037 }
1038 if (!channel->PauseSend()) {
1039 LOG(LS_WARNING) << "Failed to pause send";
1040 ret = false;
1041 }
1042 }
1043
1044 // Find the recording device id in VoiceEngine and set recording device.
1045 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1046 ret = false;
1047 }
1048 if (ret) {
1049 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
1050 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
1051 ret = false;
1052 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00001053 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
1054 if (ap)
1055 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001056 }
1057
1058 // Find the playout device id in VoiceEngine and set playout device.
1059 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1060 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1061 ret = false;
1062 }
1063 if (ret) {
1064 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001065 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001066 ret = false;
1067 }
1068 }
1069
1070 // Resume all audio playback and capture.
1071 for (ChannelList::const_iterator i = channels_.begin();
1072 i != channels_.end(); ++i) {
1073 WebRtcVoiceMediaChannel *channel = *i;
1074 if (!channel->ResumePlayout()) {
1075 LOG(LS_WARNING) << "Failed to resume playout";
1076 ret = false;
1077 }
1078 if (!channel->ResumeSend()) {
1079 LOG(LS_WARNING) << "Failed to resume send";
1080 ret = false;
1081 }
1082 }
1083
1084 // Resume local monitor.
1085 if (!ResumeLocalMonitor()) {
1086 LOG(LS_WARNING) << "Failed to resume local monitor";
1087 ret = false;
1088 }
1089
1090 if (ret) {
1091 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1092 << ") and speaker to (id="<< out_id << " name=" << out_name
1093 << ")";
1094 }
1095
1096 return ret;
1097#else
1098 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001099#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001100}
1101
1102bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1103 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1104 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001105#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001106 *rtc_id = dev_id;
1107 return true;
1108#else
1109 // In Windows and Mac, we need to find the VoiceEngine device id by name
1110 // unless the input dev_id is the default device id.
1111 if (kDefaultAudioDeviceId == dev_id) {
1112 *rtc_id = dev_id;
1113 return true;
1114 }
1115
1116 // Get the number of VoiceEngine audio devices.
1117 int count = 0;
1118 if (is_input) {
1119 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1120 LOG_RTCERR0(GetNumOfRecordingDevices);
1121 return false;
1122 }
1123 } else {
1124 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1125 LOG_RTCERR0(GetNumOfPlayoutDevices);
1126 return false;
1127 }
1128 }
1129
1130 for (int i = 0; i < count; ++i) {
1131 char name[128];
1132 char guid[128];
1133 if (is_input) {
1134 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1135 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1136 } else {
1137 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1138 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1139 }
1140
1141 std::string webrtc_name(name);
1142 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1143 *rtc_id = i;
1144 return true;
1145 }
1146 }
1147 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1148 return false;
1149#endif
1150}
1151
1152bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1153 unsigned int ulevel;
1154 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1155 LOG_RTCERR1(GetSpeakerVolume, level);
1156 return false;
1157 }
1158 *level = ulevel;
1159 return true;
1160}
1161
1162bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1163 ASSERT(level >= 0 && level <= 255);
1164 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1165 LOG_RTCERR1(SetSpeakerVolume, level);
1166 return false;
1167 }
1168 return true;
1169}
1170
1171int WebRtcVoiceEngine::GetInputLevel() {
1172 unsigned int ulevel;
1173 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1174 static_cast<int>(ulevel) : -1;
1175}
1176
1177bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1178 desired_local_monitor_enable_ = enable;
1179 return ChangeLocalMonitor(desired_local_monitor_enable_);
1180}
1181
1182bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1183 // The voe file api is not available in chrome.
1184 if (!voe_wrapper_->file()) {
1185 return false;
1186 }
1187 if (enable && !monitor_) {
1188 monitor_.reset(new WebRtcMonitorStream);
1189 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1190 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1191 // Must call Stop() because there are some cases where Start will report
1192 // failure but still change the state, and if we leave VE in the on state
1193 // then it could crash later when trying to invoke methods on our monitor.
1194 voe_wrapper_->file()->StopRecordingMicrophone();
1195 monitor_.reset();
1196 return false;
1197 }
1198 } else if (!enable && monitor_) {
1199 voe_wrapper_->file()->StopRecordingMicrophone();
1200 monitor_.reset();
1201 }
1202 return true;
1203}
1204
1205bool WebRtcVoiceEngine::PauseLocalMonitor() {
1206 return ChangeLocalMonitor(false);
1207}
1208
1209bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1210 return ChangeLocalMonitor(desired_local_monitor_enable_);
1211}
1212
1213const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1214 return codecs_;
1215}
1216
1217bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1218 return FindWebRtcCodec(in, NULL);
1219}
1220
1221// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1222bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1223 webrtc::CodecInst* out) {
1224 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1225 for (int i = 0; i < ncodecs; ++i) {
1226 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.orgdced5d72014-11-06 15:27:43 +00001227 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001228 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1229 voe_codec.rate, voe_codec.channels, 0);
1230 bool multi_rate = IsCodecMultiRate(voe_codec);
1231 // Allow arbitrary rates for ISAC to be specified.
1232 if (multi_rate) {
1233 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1234 codec.bitrate = 0;
1235 }
1236 if (codec.Matches(in)) {
1237 if (out) {
1238 // Fixup the payload type.
1239 voe_codec.pltype = in.id;
1240
1241 // Set bitrate if specified.
1242 if (multi_rate && in.bitrate != 0) {
1243 voe_codec.rate = in.bitrate;
1244 }
1245
1246 // Apply codec-specific settings.
1247 if (IsIsac(codec)) {
1248 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001249 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001250 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1251 }
1252 *out = voe_codec;
1253 }
1254 return true;
1255 }
1256 }
1257 }
1258 return false;
1259}
1260const std::vector<RtpHeaderExtension>&
1261WebRtcVoiceEngine::rtp_header_extensions() const {
1262 return rtp_header_extensions_;
1263}
1264
1265void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1266 // if min_sev == -1, we keep the current log level.
1267 if (min_sev >= 0) {
1268 SetTraceFilter(SeverityToFilter(min_sev));
1269 }
1270 log_options_ = filter;
1271 SetTraceOptions(initialized_ ? log_options_ : "");
1272}
1273
1274int WebRtcVoiceEngine::GetLastEngineError() {
1275 return voe_wrapper_->error();
1276}
1277
1278void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1279 log_filter_ = filter;
1280 tracing_->SetTraceFilter(filter);
1281}
1282
1283// We suppport three different logging settings for VoiceEngine:
1284// 1. Observer callback that goes into talk diagnostic logfile.
1285// Use --logfile and --loglevel
1286//
1287// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1288// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1289//
1290// 3. EC log and dump for debugging QualityEngine.
1291// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1292//
1293// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1294// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1295void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1296 // Set encrypted trace file.
1297 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001298 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001299 std::vector<std::string>::iterator tracefile =
1300 std::find(opts.begin(), opts.end(), "tracefile");
1301 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1302 // Write encrypted debug output (at same loglevel) to file
1303 // EncryptedTraceFile no longer supported.
1304 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1305 LOG_RTCERR1(SetTraceFile, *tracefile);
1306 }
1307 }
1308
wu@webrtc.org97077a32013-10-25 21:18:33 +00001309 // Allow trace options to override the trace filter. We default
1310 // it to log_filter_ (as a translation of libjingle log levels)
1311 // elsewhere, but this allows clients to explicitly set webrtc
1312 // log levels.
1313 std::vector<std::string>::iterator tracefilter =
1314 std::find(opts.begin(), opts.end(), "tracefilter");
1315 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001316 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001317 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1318 }
1319 }
1320
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001321 // Set AEC dump file
1322 std::vector<std::string>::iterator recordEC =
1323 std::find(opts.begin(), opts.end(), "recordEC");
1324 if (recordEC != opts.end()) {
1325 ++recordEC;
1326 if (recordEC != opts.end())
1327 StartAecDump(recordEC->c_str());
1328 else
1329 StopAecDump();
1330 }
1331}
1332
1333// Ignore spammy trace messages, mostly from the stats API when we haven't
1334// gotten RTCP info yet from the remote side.
1335bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1336 static const char* kTracesToIgnore[] = {
1337 "\tfailed to GetReportBlockInformation",
1338 "GetRecCodec() failed to get received codec",
1339 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1340 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1341 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1342 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1343 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1344 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1345 "SenderInfoReceived No received SR",
1346 "StatisticsRTP() no statistics available",
1347 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1348 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1349 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1350 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1351 NULL
1352 };
1353 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1354 if (trace.find(*p) != std::string::npos) {
1355 return true;
1356 }
1357 }
1358 return false;
1359}
1360
1361void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1362 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001363 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001364 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001365 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001367 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001368 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001369 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001371 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001372
1373 // Skip past boilerplate prefix text
1374 if (length < 72) {
1375 std::string msg(trace, length);
1376 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1377 LOG_V(sev) << msg;
1378 } else {
1379 std::string msg(trace + 71, length - 72);
1380 if (!ShouldIgnoreTrace(msg)) {
1381 LOG_V(sev) << "webrtc: " << msg;
1382 }
1383 }
1384}
1385
1386void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001387 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001388 WebRtcVoiceMediaChannel* channel = NULL;
1389 uint32 ssrc = 0;
1390 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1391 << channel_num << ".";
1392 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1393 ASSERT(channel != NULL);
1394 channel->OnError(ssrc, err_code);
1395 } else {
1396 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1397 << " could not be found in channel list when error reported.";
1398 }
1399}
1400
1401bool WebRtcVoiceEngine::FindChannelAndSsrc(
1402 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1403 ASSERT(channel != NULL && ssrc != NULL);
1404
1405 *channel = NULL;
1406 *ssrc = 0;
1407 // Find corresponding channel and ssrc
1408 for (ChannelList::const_iterator it = channels_.begin();
1409 it != channels_.end(); ++it) {
1410 ASSERT(*it != NULL);
1411 if ((*it)->FindSsrc(channel_num, ssrc)) {
1412 *channel = *it;
1413 return true;
1414 }
1415 }
1416
1417 return false;
1418}
1419
1420// This method will search through the WebRtcVoiceMediaChannels and
1421// obtain the voice engine's channel number.
1422bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1423 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1424 ASSERT(channel_num != NULL);
1425 ASSERT(direction == MPD_RX || direction == MPD_TX);
1426
1427 *channel_num = -1;
1428 // Find corresponding channel for ssrc.
1429 for (ChannelList::const_iterator it = channels_.begin();
1430 it != channels_.end(); ++it) {
1431 ASSERT(*it != NULL);
1432 if (direction & MPD_RX) {
1433 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1434 }
1435 if (*channel_num == -1 && (direction & MPD_TX)) {
1436 *channel_num = (*it)->GetSendChannelNum(ssrc);
1437 }
1438 if (*channel_num != -1) {
1439 return true;
1440 }
1441 }
1442 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1443 return false;
1444}
1445
1446void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001447 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001448 channels_.push_back(channel);
1449}
1450
1451void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001452 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001453 ChannelList::iterator i = std::find(channels_.begin(),
1454 channels_.end(),
1455 channel);
1456 if (i != channels_.end()) {
1457 channels_.erase(i);
1458 }
1459}
1460
1461void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1462 soundclips_.push_back(soundclip);
1463}
1464
1465void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1466 SoundclipList::iterator i = std::find(soundclips_.begin(),
1467 soundclips_.end(),
1468 soundclip);
1469 if (i != soundclips_.end()) {
1470 soundclips_.erase(i);
1471 }
1472}
1473
1474// Adjusts the default AGC target level by the specified delta.
1475// NB: If we start messing with other config fields, we'll want
1476// to save the current webrtc::AgcConfig as well.
1477bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1478 webrtc::AgcConfig config = default_agc_config_;
1479 config.targetLeveldBOv -= delta;
1480
1481 LOG(LS_INFO) << "Adjusting AGC level from default -"
1482 << default_agc_config_.targetLeveldBOv << "dB to -"
1483 << config.targetLeveldBOv << "dB";
1484
1485 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1486 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1487 return false;
1488 }
1489 return true;
1490}
1491
1492bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1493 webrtc::AudioDeviceModule* adm_sc) {
1494 if (initialized_) {
1495 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1496 return false;
1497 }
1498 if (adm_) {
1499 adm_->Release();
1500 adm_ = NULL;
1501 }
1502 if (adm) {
1503 adm_ = adm;
1504 adm_->AddRef();
1505 }
1506
1507 if (adm_sc_) {
1508 adm_sc_->Release();
1509 adm_sc_ = NULL;
1510 }
1511 if (adm_sc) {
1512 adm_sc_ = adm_sc;
1513 adm_sc_->AddRef();
1514 }
1515 return true;
1516}
1517
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001518bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1519 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001520 if (!aec_dump_file_stream) {
1521 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001522 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001523 LOG(LS_WARNING) << "Could not close file.";
1524 return false;
1525 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001526 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001527 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001528 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001529 LOG_RTCERR0(StartDebugRecording);
1530 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001531 return false;
1532 }
1533 is_dumping_aec_ = true;
1534 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001535}
1536
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001537bool WebRtcVoiceEngine::RegisterProcessor(
1538 uint32 ssrc,
1539 VoiceProcessor* voice_processor,
1540 MediaProcessorDirection direction) {
1541 bool register_with_webrtc = false;
1542 int channel_id = -1;
1543 bool success = false;
1544 uint32* processor_ssrc = NULL;
1545 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1546 if (voice_processor == NULL || !found_channel) {
1547 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1548 << " foundChannel: " << found_channel;
1549 return false;
1550 }
1551
1552 webrtc::ProcessingTypes processing_type;
1553 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001554 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001555 if (direction == MPD_RX) {
1556 processing_type = webrtc::kPlaybackAllChannelsMixed;
1557 if (SignalRxMediaFrame.is_empty()) {
1558 register_with_webrtc = true;
1559 processor_ssrc = &rx_processor_ssrc_;
1560 }
1561 SignalRxMediaFrame.connect(voice_processor,
1562 &VoiceProcessor::OnFrame);
1563 } else {
1564 processing_type = webrtc::kRecordingPerChannel;
1565 if (SignalTxMediaFrame.is_empty()) {
1566 register_with_webrtc = true;
1567 processor_ssrc = &tx_processor_ssrc_;
1568 }
1569 SignalTxMediaFrame.connect(voice_processor,
1570 &VoiceProcessor::OnFrame);
1571 }
1572 }
1573 if (register_with_webrtc) {
1574 // TODO(janahan): when registering consider instantiating a
1575 // a VoeMediaProcess object and not make the engine extend the interface.
1576 if (voe()->media() && voe()->media()->
1577 RegisterExternalMediaProcessing(channel_id,
1578 processing_type,
1579 *this) != -1) {
1580 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1581 << channel_id;
1582 *processor_ssrc = ssrc;
1583 success = true;
1584 } else {
1585 LOG_RTCERR2(RegisterExternalMediaProcessing,
1586 channel_id,
1587 processing_type);
1588 success = false;
1589 }
1590 } else {
1591 // If we don't have to register with the engine, we just needed to
1592 // connect a new processor, set success to true;
1593 success = true;
1594 }
1595 return success;
1596}
1597
1598bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1599 MediaProcessorDirection channel_direction,
1600 uint32 ssrc,
1601 VoiceProcessor* voice_processor,
1602 MediaProcessorDirection processor_direction) {
1603 bool success = true;
1604 FrameSignal* signal;
1605 webrtc::ProcessingTypes processing_type;
1606 uint32* processor_ssrc = NULL;
1607 if (channel_direction == MPD_RX) {
1608 signal = &SignalRxMediaFrame;
1609 processing_type = webrtc::kPlaybackAllChannelsMixed;
1610 processor_ssrc = &rx_processor_ssrc_;
1611 } else {
1612 signal = &SignalTxMediaFrame;
1613 processing_type = webrtc::kRecordingPerChannel;
1614 processor_ssrc = &tx_processor_ssrc_;
1615 }
1616
1617 int deregister_id = -1;
1618 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001619 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001620 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1621 signal->disconnect(voice_processor);
1622 int channel_id = -1;
1623 bool found_channel = FindChannelNumFromSsrc(ssrc,
1624 channel_direction,
1625 &channel_id);
1626 if (signal->is_empty() && found_channel) {
1627 deregister_id = channel_id;
1628 }
1629 }
1630 }
1631 if (deregister_id != -1) {
1632 if (voe()->media() &&
1633 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1634 processing_type) != -1) {
1635 *processor_ssrc = 0;
1636 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1637 << deregister_id;
1638 } else {
1639 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1640 deregister_id,
1641 processing_type);
1642 success = false;
1643 }
1644 }
1645 return success;
1646}
1647
1648bool WebRtcVoiceEngine::UnregisterProcessor(
1649 uint32 ssrc,
1650 VoiceProcessor* voice_processor,
1651 MediaProcessorDirection direction) {
1652 bool success = true;
1653 if (voice_processor == NULL) {
1654 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1655 << ssrc;
1656 return false;
1657 }
1658 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1659 success = false;
1660 }
1661 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1662 success = false;
1663 }
1664 return success;
1665}
1666
1667// Implementing method from WebRtc VoEMediaProcess interface
1668// Do not lock mux_channel_cs_ in this callback.
1669void WebRtcVoiceEngine::Process(int channel,
1670 webrtc::ProcessingTypes type,
1671 int16_t audio10ms[],
1672 int length,
1673 int sampling_freq,
1674 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001675 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001676 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1677 if (type == webrtc::kPlaybackAllChannelsMixed) {
1678 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1679 } else if (type == webrtc::kRecordingPerChannel) {
1680 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1681 } else {
1682 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1683 << " channel: " << channel << " type: " << type
1684 << " tx_ssrc: " << tx_processor_ssrc_
1685 << " rx_ssrc: " << rx_processor_ssrc_;
1686 }
1687}
1688
1689void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1690 if (!is_dumping_aec_) {
1691 // Start dumping AEC when we are not dumping.
1692 if (voe_wrapper_->processing()->StartDebugRecording(
1693 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001694 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001695 } else {
1696 is_dumping_aec_ = true;
1697 }
1698 }
1699}
1700
1701void WebRtcVoiceEngine::StopAecDump() {
1702 if (is_dumping_aec_) {
1703 // Stop dumping AEC when we are dumping.
1704 if (voe_wrapper_->processing()->StopDebugRecording() !=
1705 webrtc::AudioProcessing::kNoError) {
1706 LOG_RTCERR0(StopDebugRecording);
1707 }
1708 is_dumping_aec_ = false;
1709 }
1710}
1711
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001712int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001713 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001714}
1715
1716int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1717 return CreateVoiceChannel(voe_wrapper_.get());
1718}
1719
1720int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1721 return CreateVoiceChannel(voe_wrapper_sc_.get());
1722}
1723
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001724class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1725 : public AudioRenderer::Sink {
1726 public:
1727 WebRtcVoiceChannelRenderer(int ch,
1728 webrtc::AudioTransport* voe_audio_transport)
1729 : channel_(ch),
1730 voe_audio_transport_(voe_audio_transport),
1731 renderer_(NULL) {
1732 }
1733 virtual ~WebRtcVoiceChannelRenderer() {
1734 Stop();
1735 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001736
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001737 // Starts the rendering by setting a sink to the renderer to get data
1738 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001739 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001740 // TODO(xians): Make sure Start() is called only once.
1741 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001742 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001743 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001744 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001745 ASSERT(renderer_ == renderer);
1746 return;
1747 }
1748
1749 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1750 // in getUserMedia by default.
1751 renderer->AddChannel(channel_);
1752 renderer->SetSink(this);
1753 renderer_ = renderer;
1754 }
1755
1756 // Stops rendering by setting the sink of the renderer to NULL. No data
1757 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001758 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001759 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001760 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001761 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001762 return;
1763
1764 renderer_->RemoveChannel(channel_);
1765 renderer_->SetSink(NULL);
1766 renderer_ = NULL;
1767 }
1768
1769 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001770 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001771 virtual void OnData(const void* audio_data,
1772 int bits_per_sample,
1773 int sample_rate,
1774 int number_of_channels,
1775 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001776 voe_audio_transport_->OnData(channel_,
1777 audio_data,
1778 bits_per_sample,
1779 sample_rate,
1780 number_of_channels,
1781 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001782 }
1783
1784 // Callback from the |renderer_| when it is going away. In case Start() has
1785 // never been called, this callback won't be triggered.
1786 virtual void OnClose() OVERRIDE {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001787 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001788 // Set |renderer_| to NULL to make sure no more callback will get into
1789 // the renderer.
1790 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001791 }
1792
1793 // Accessor to the VoE channel ID.
1794 int channel() const { return channel_; }
1795
1796 private:
1797 const int channel_;
1798 webrtc::AudioTransport* const voe_audio_transport_;
1799
1800 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1801 // PeerConnection will make sure invalidating the pointer before the object
1802 // goes away.
1803 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001804
1805 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001806 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001807};
1808
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001809// WebRtcVoiceMediaChannel
1810WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1811 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1812 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001813 engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001814 send_bitrate_setting_(false),
1815 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001816 options_(),
1817 dtmf_allowed_(false),
1818 desired_playout_(false),
1819 nack_enabled_(false),
1820 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001821 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001822 desired_send_(SEND_NOTHING),
1823 send_(SEND_NOTHING),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001824 shared_bwe_vie_(NULL),
1825 shared_bwe_vie_channel_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001826 default_receive_ssrc_(0) {
1827 engine->RegisterChannel(this);
1828 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1829 << voe_channel();
1830
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001831 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001832}
1833
1834WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1835 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1836 << voe_channel();
buildbot@webrtc.org6e5c7842014-09-19 06:46:37 +00001837 SetupSharedBandwidthEstimation(NULL, -1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001838
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001839 // Remove any remaining send streams, the default channel will be deleted
1840 // later.
1841 while (!send_channels_.empty())
1842 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001843
1844 // Unregister ourselves from the engine.
1845 engine()->UnregisterChannel(this);
1846 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001847 while (!receive_channels_.empty()) {
1848 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001849 }
1850
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001851 // Delete the default channel.
1852 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001853}
1854
1855bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1856 LOG(LS_INFO) << "Setting voice channel options: "
1857 << options.ToString();
1858
wu@webrtc.orgde305012013-10-31 15:40:38 +00001859 // Check if DSCP value is changed from previous.
1860 bool dscp_option_changed = (options_.dscp != options.dscp);
1861
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001862 // TODO(xians): Add support to set different options for different send
1863 // streams after we support multiple APMs.
1864
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001865 // We retain all of the existing options, and apply the given ones
1866 // on top. This means there is no way to "clear" options such that
1867 // they go back to the engine default.
1868 options_.SetAll(options);
1869
1870 if (send_ != SEND_NOTHING) {
1871 if (!engine()->SetOptionOverrides(options_)) {
1872 LOG(LS_WARNING) <<
1873 "Failed to engine SetOptionOverrides during channel SetOptions.";
1874 return false;
1875 }
1876 } else {
1877 // Will be interpreted when appropriate.
1878 }
1879
wu@webrtc.org97077a32013-10-25 21:18:33 +00001880 // Receiver-side auto gain control happens per channel, so set it here from
1881 // options. Note that, like conference mode, setting it on the engine won't
1882 // have the desired effect, since voice channels don't inherit options from
1883 // the media engine when those options are applied per-channel.
1884 bool rx_auto_gain_control;
1885 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1886 if (engine()->voe()->processing()->SetRxAgcStatus(
1887 voe_channel(), rx_auto_gain_control,
1888 webrtc::kAgcFixedDigital) == -1) {
1889 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1890 return false;
1891 } else {
1892 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1893 << " with mode " << webrtc::kAgcFixedDigital;
1894 }
1895 }
1896 if (options.rx_agc_target_dbov.IsSet() ||
1897 options.rx_agc_digital_compression_gain.IsSet() ||
1898 options.rx_agc_limiter.IsSet()) {
1899 webrtc::AgcConfig config;
1900 // If only some of the options are being overridden, get the current
1901 // settings for the channel and bail if they aren't available.
1902 if (!options.rx_agc_target_dbov.IsSet() ||
1903 !options.rx_agc_digital_compression_gain.IsSet() ||
1904 !options.rx_agc_limiter.IsSet()) {
1905 if (engine()->voe()->processing()->GetRxAgcConfig(
1906 voe_channel(), config) != 0) {
1907 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1908 << "channel " << voe_channel() << ". Since not all rx "
1909 << "agc options are specified, unable to safely set rx "
1910 << "agc options.";
1911 return false;
1912 }
1913 }
1914 config.targetLeveldBOv =
1915 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1916 config.targetLeveldBOv);
1917 config.digitalCompressionGaindB =
1918 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1919 config.digitalCompressionGaindB);
1920 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1921 config.limiterEnable);
1922 if (engine()->voe()->processing()->SetRxAgcConfig(
1923 voe_channel(), config) == -1) {
1924 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1925 config.digitalCompressionGaindB, config.limiterEnable);
1926 return false;
1927 }
1928 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001929 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001930 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001931 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001932 dscp = kAudioDscpValue;
1933 if (MediaChannel::SetDscp(dscp) != 0) {
1934 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1935 }
1936 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001937
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001938 // Force update of Video Engine BWE forwarding to reflect experiment setting.
1939 if (!SetupSharedBandwidthEstimation(shared_bwe_vie_,
1940 shared_bwe_vie_channel_)) {
1941 return false;
1942 }
1943
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001944 LOG(LS_INFO) << "Set voice channel options. Current options: "
1945 << options_.ToString();
1946 return true;
1947}
1948
1949bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1950 const std::vector<AudioCodec>& codecs) {
1951 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001952 LOG(LS_INFO) << "Setting receive voice codecs:";
1953
1954 std::vector<AudioCodec> new_codecs;
1955 // Find all new codecs. We allow adding new codecs but don't allow changing
1956 // the payload type of codecs that is already configured since we might
1957 // already be receiving packets with that payload type.
1958 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001959 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001960 AudioCodec old_codec;
1961 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1962 if (old_codec.id != it->id) {
1963 LOG(LS_ERROR) << it->name << " payload type changed.";
1964 return false;
1965 }
1966 } else {
1967 new_codecs.push_back(*it);
1968 }
1969 }
1970 if (new_codecs.empty()) {
1971 // There are no new codecs to configure. Already configured codecs are
1972 // never removed.
1973 return true;
1974 }
1975
1976 if (playout_) {
1977 // Receive codecs can not be changed while playing. So we temporarily
1978 // pause playout.
1979 PausePlayout();
1980 }
1981
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001982 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001983 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1984 it != new_codecs.end() && ret; ++it) {
1985 webrtc::CodecInst voe_codec;
1986 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1987 LOG(LS_INFO) << ToString(*it);
1988 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001989 if (default_receive_ssrc_ == 0) {
1990 // Set the receive codecs on the default channel explicitly if the
1991 // default channel is not used by |receive_channels_|, this happens in
1992 // conference mode or in non-conference mode when there is no playout
1993 // channel.
1994 // TODO(xians): Figure out how we use the default channel in conference
1995 // mode.
1996 if (engine()->voe()->codec()->SetRecPayloadType(
1997 voe_channel(), voe_codec) == -1) {
1998 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1999 ret = false;
2000 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002001 }
2002
2003 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002004 for (ChannelMap::iterator it = receive_channels_.begin();
2005 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002006 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002007 it->second->channel(), voe_codec) == -1) {
2008 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002009 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002010 ret = false;
2011 }
2012 }
2013 } else {
2014 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2015 ret = false;
2016 }
2017 }
2018 if (ret) {
2019 recv_codecs_ = codecs;
2020 }
2021
2022 if (desired_playout_ && !playout_) {
2023 ResumePlayout();
2024 }
2025 return ret;
2026}
2027
2028bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002029 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002030 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002031 engine()->voe()->codec()->SetVADStatus(channel, false);
2032 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002033#ifdef USE_WEBRTC_DEV_BRANCH
2034 engine()->voe()->rtp()->SetREDStatus(channel, false);
2035 engine()->voe()->codec()->SetFECStatus(channel, false);
2036#else
2037 // TODO(minyue): Remove code under #else case after new WebRTC roll.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002038 engine()->voe()->rtp()->SetFECStatus(channel, false);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002039#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002040
2041 // Scan through the list to figure out the codec to use for sending, along
2042 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002043 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002044 webrtc::CodecInst send_codec;
2045 memset(&send_codec, 0, sizeof(send_codec));
2046
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002047 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002048 bool enable_codec_fec = false;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002049
minyue@webrtc.org26236952014-10-29 02:27:08 +00002050 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002051
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002052 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002053 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2054 it != codecs.end(); ++it) {
2055 // Ignore codecs we don't know about. The negotiation step should prevent
2056 // this, but double-check to be sure.
2057 webrtc::CodecInst voe_codec;
2058 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002059 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002060 continue;
2061 }
2062
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002063 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2064 // Skip telephone-event/CN codec, which will be handled later.
2065 continue;
2066 }
2067
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002068 // We'll use the first codec in the list to actually send audio data.
2069 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002070 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002071 // used is specified in params.
2072 if (IsRedCodec(it->name)) {
2073 // Parse out the RED parameters. If we fail, just ignore RED;
2074 // we don't support all possible params/usage scenarios.
2075 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2076 continue;
2077 }
2078
2079 // Enable redundant encoding of the specified codec. Treat any
2080 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002081#ifdef USE_WEBRTC_DEV_BRANCH
2082 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2083 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2084 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
2085#else
2086 // TODO(minyue): Remove code under #else case after new WebRTC roll.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002087 LOG(LS_INFO) << "Enabling FEC";
2088 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2089 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002090#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002091 return false;
2092 }
2093 } else {
2094 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002095 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002096 // For Opus as the send codec, we are to enable inband FEC if requested
2097 // and set maximum playback rate.
2098 if (IsOpus(*it)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002099 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
2100 &opus_max_playback_rate);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002101 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002102 }
2103 found_send_codec = true;
2104 break;
2105 }
2106
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002107 if (nack_enabled_ != nack_enabled) {
2108 SetNack(channel, nack_enabled);
2109 nack_enabled_ = nack_enabled;
2110 }
2111
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002112 if (!found_send_codec) {
2113 LOG(LS_WARNING) << "Received empty list of codecs.";
2114 return false;
2115 }
2116
2117 // Set the codec immediately, since SetVADStatus() depends on whether
2118 // the current codec is mono or stereo.
2119 if (!SetSendCodec(channel, send_codec))
2120 return false;
2121
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002122 // FEC should be enabled after SetSendCodec.
2123 if (enable_codec_fec) {
2124 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2125 << channel;
2126#ifdef USE_WEBRTC_DEV_BRANCH
2127 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2128 // Enable codec internal FEC. Treat any failure as fatal internal error.
2129 LOG_RTCERR2(SetFECStatus, channel, true);
2130 return false;
2131 }
2132#endif // USE_WEBRTC_DEV_BRANCH
2133 }
2134
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002135 // maxplaybackrate should be set after SetSendCodec.
minyue@webrtc.org26236952014-10-29 02:27:08 +00002136 // If opus_max_playback_rate <= 0, the default maximum playback rate of 48 kHz
2137 // will be used.
2138 if (opus_max_playback_rate > 0) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002139 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002140 << opus_max_playback_rate
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002141 << " Hz on channel "
2142 << channel;
2143#ifdef USE_WEBRTC_DEV_BRANCH
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002144 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
minyue@webrtc.org26236952014-10-29 02:27:08 +00002145 channel, opus_max_playback_rate) == -1) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002146 LOG(LS_WARNING) << "Could not set maximum playback rate.";
2147 }
2148#endif
2149 }
2150
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002151 // Always update the |send_codec_| to the currently set send codec.
2152 send_codec_.reset(new webrtc::CodecInst(send_codec));
2153
minyue@webrtc.org26236952014-10-29 02:27:08 +00002154 if (send_bitrate_setting_) {
2155 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002156 }
2157
2158 // Loop through the codecs list again to config the telephone-event/CN codec.
2159 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2160 it != codecs.end(); ++it) {
2161 // Ignore codecs we don't know about. The negotiation step should prevent
2162 // this, but double-check to be sure.
2163 webrtc::CodecInst voe_codec;
2164 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2165 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2166 continue;
2167 }
2168
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002169 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2170 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002171 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002172 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2173 channel, it->id) == -1) {
2174 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2175 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002176 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002177 } else if (IsCNCodec(it->name)) {
2178 // Turn voice activity detection/comfort noise on if supported.
2179 // Set the wideband CN payload type appropriately.
2180 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002181 webrtc::PayloadFrequencies cn_freq;
2182 switch (it->clockrate) {
2183 case 8000:
2184 cn_freq = webrtc::kFreq8000Hz;
2185 break;
2186 case 16000:
2187 cn_freq = webrtc::kFreq16000Hz;
2188 break;
2189 case 32000:
2190 cn_freq = webrtc::kFreq32000Hz;
2191 break;
2192 default:
2193 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2194 << " not supported.";
2195 continue;
2196 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002197 // Set the CN payloadtype and the VAD status.
2198 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2199 if (cn_freq != webrtc::kFreq8000Hz) {
2200 if (engine()->voe()->codec()->SetSendCNPayloadType(
2201 channel, it->id, cn_freq) == -1) {
2202 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2203 // TODO(ajm): This failure condition will be removed from VoE.
2204 // Restore the return here when we update to a new enough webrtc.
2205 //
2206 // Not returning false because the SetSendCNPayloadType will fail if
2207 // the channel is already sending.
2208 // This can happen if the remote description is applied twice, for
2209 // example in the case of ROAP on top of JSEP, where both side will
2210 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002211 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002212 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002213 // Only turn on VAD if we have a CN payload type that matches the
2214 // clockrate for the codec we are going to use.
2215 if (it->clockrate == send_codec.plfreq) {
2216 LOG(LS_INFO) << "Enabling VAD";
2217 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2218 LOG_RTCERR2(SetVADStatus, channel, true);
2219 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002220 }
2221 }
2222 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002223 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002224 return true;
2225}
2226
2227bool WebRtcVoiceMediaChannel::SetSendCodecs(
2228 const std::vector<AudioCodec>& codecs) {
2229 dtmf_allowed_ = false;
2230 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2231 it != codecs.end(); ++it) {
2232 // Find the DTMF telephone event "codec".
2233 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2234 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2235 dtmf_allowed_ = true;
2236 }
2237 }
2238
2239 // Cache the codecs in order to configure the channel created later.
2240 send_codecs_ = codecs;
2241 for (ChannelMap::iterator iter = send_channels_.begin();
2242 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002243 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002244 return false;
2245 }
2246 }
2247
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002248 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002249 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002250 return true;
2251}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002252
2253void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2254 bool nack_enabled) {
2255 for (ChannelMap::const_iterator it = channels.begin();
2256 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002257 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002258 }
2259}
2260
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002261void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002262 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002263 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002264 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2265 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002266 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002267 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2268 }
2269}
2270
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002271bool WebRtcVoiceMediaChannel::SetSendCodec(
2272 const webrtc::CodecInst& send_codec) {
2273 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2274 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002275 for (ChannelMap::iterator iter = send_channels_.begin();
2276 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002277 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002278 return false;
2279 }
2280
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002281 return true;
2282}
2283
2284bool WebRtcVoiceMediaChannel::SetSendCodec(
2285 int channel, const webrtc::CodecInst& send_codec) {
2286 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2287 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2288
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002289 webrtc::CodecInst current_codec;
2290 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2291 (send_codec == current_codec)) {
2292 // Codec is already configured, we can return without setting it again.
2293 return true;
2294 }
2295
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002296 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2297 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002298 return false;
2299 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002300 return true;
2301}
2302
2303bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2304 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002305 if (receive_extensions_ == extensions) {
2306 return true;
2307 }
2308
2309 // The default channel may or may not be in |receive_channels_|. Set the rtp
2310 // header extensions for default channel regardless.
2311 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2312 return false;
2313 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002314
2315 // Loop through all receive channels and enable/disable the extensions.
2316 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2317 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002318 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2319 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002320 return false;
2321 }
2322 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002323
2324 receive_extensions_ = extensions;
2325 return true;
2326}
2327
2328bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2329 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002330 const RtpHeaderExtension* audio_level_extension =
2331 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2332 if (!SetHeaderExtension(
2333 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2334 audio_level_extension)) {
2335 return false;
2336 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002337
2338 const RtpHeaderExtension* send_time_extension =
2339 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2340 if (!SetHeaderExtension(
2341 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2342 send_time_extension)) {
2343 return false;
2344 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002345 return true;
2346}
2347
2348bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2349 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002350 if (send_extensions_ == extensions) {
2351 return true;
2352 }
2353
2354 // The default channel may or may not be in |send_channels_|. Set the rtp
2355 // header extensions for default channel regardless.
2356
2357 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2358 return false;
2359 }
2360
2361 // Loop through all send channels and enable/disable the extensions.
2362 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2363 channel_it != send_channels_.end(); ++channel_it) {
2364 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2365 extensions)) {
2366 return false;
2367 }
2368 }
2369
2370 send_extensions_ = extensions;
2371 return true;
2372}
2373
2374bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2375 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002376 const RtpHeaderExtension* audio_level_extension =
2377 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002378
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002379 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002380 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002381 audio_level_extension)) {
2382 return false;
2383 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002384
2385 const RtpHeaderExtension* send_time_extension =
2386 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002387 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002388 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002389 send_time_extension)) {
2390 return false;
2391 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002392
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002393 return true;
2394}
2395
2396bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2397 desired_playout_ = playout;
2398 return ChangePlayout(desired_playout_);
2399}
2400
2401bool WebRtcVoiceMediaChannel::PausePlayout() {
2402 return ChangePlayout(false);
2403}
2404
2405bool WebRtcVoiceMediaChannel::ResumePlayout() {
2406 return ChangePlayout(desired_playout_);
2407}
2408
2409bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2410 if (playout_ == playout) {
2411 return true;
2412 }
2413
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002414 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002415 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002416 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002417 // Only toggle the default channel if we don't have any other channels.
2418 result = SetPlayout(voe_channel(), playout);
2419 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002420 for (ChannelMap::iterator it = receive_channels_.begin();
2421 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002422 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002423 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002424 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002425 result = false;
2426 }
2427 }
2428
2429 if (result) {
2430 playout_ = playout;
2431 }
2432 return result;
2433}
2434
2435bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2436 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002437 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002438 return ChangeSend(desired_send_);
2439 return true;
2440}
2441
2442bool WebRtcVoiceMediaChannel::PauseSend() {
2443 return ChangeSend(SEND_NOTHING);
2444}
2445
2446bool WebRtcVoiceMediaChannel::ResumeSend() {
2447 return ChangeSend(desired_send_);
2448}
2449
2450bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2451 if (send_ == send) {
2452 return true;
2453 }
2454
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002455 // Change the settings on each send channel.
2456 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002457 engine()->SetOptionOverrides(options_);
2458
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002459 // Change the settings on each send channel.
2460 for (ChannelMap::iterator iter = send_channels_.begin();
2461 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002462 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002463 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002464 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002465
2466 // Clear up the options after stopping sending.
2467 if (send == SEND_NOTHING)
2468 engine()->ClearOptionOverrides();
2469
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002470 send_ = send;
2471 return true;
2472}
2473
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002474bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2475 if (send == SEND_MICROPHONE) {
2476 if (engine()->voe()->base()->StartSend(channel) == -1) {
2477 LOG_RTCERR1(StartSend, channel);
2478 return false;
2479 }
2480 if (engine()->voe()->file() &&
2481 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2482 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2483 return false;
2484 }
2485 } else { // SEND_NOTHING
2486 ASSERT(send == SEND_NOTHING);
2487 if (engine()->voe()->base()->StopSend(channel) == -1) {
2488 LOG_RTCERR1(StopSend, channel);
2489 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002490 }
2491 }
2492
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002493 return true;
2494}
2495
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002496// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002497void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2498 if (engine()->voe()->network()->RegisterExternalTransport(
2499 channel, *this) == -1) {
2500 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2501 }
2502
2503 // Enable RTCP (for quality stats and feedback messages)
2504 EnableRtcp(channel);
2505
2506 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2507 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002508
2509 // Set RTP header extension for the new channel.
2510 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002511}
2512
2513bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2514 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2515 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2516 }
2517
2518 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2519 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002520 return false;
2521 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002522
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002523 return true;
2524}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002525
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002526bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2527 // If the default channel is already used for sending create a new channel
2528 // otherwise use the default channel for sending.
2529 int channel = GetSendChannelNum(sp.first_ssrc());
2530 if (channel != -1) {
2531 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2532 return false;
2533 }
2534
2535 bool default_channel_is_available = true;
2536 for (ChannelMap::const_iterator iter = send_channels_.begin();
2537 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002538 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002539 default_channel_is_available = false;
2540 break;
2541 }
2542 }
2543 if (default_channel_is_available) {
2544 channel = voe_channel();
2545 } else {
2546 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002547 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002548 if (channel == -1) {
2549 LOG_RTCERR0(CreateChannel);
2550 return false;
2551 }
2552
2553 ConfigureSendChannel(channel);
2554 }
2555
2556 // Save the channel to send_channels_, so that RemoveSendStream() can still
2557 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002558 webrtc::AudioTransport* audio_transport =
2559 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002560 send_channels_.insert(std::make_pair(
2561 sp.first_ssrc(),
2562 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002563
2564 // Set the send (local) SSRC.
2565 // If there are multiple send SSRCs, we can only set the first one here, and
2566 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2567 // (with a codec requires multiple SSRC(s)).
2568 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2569 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2570 return false;
2571 }
2572
2573 // At this point the channel's local SSRC has been updated. If the channel is
2574 // the default channel make sure that all the receive channels are updated as
2575 // well. Receive channels have to have the same SSRC as the default channel in
2576 // order to send receiver reports with this SSRC.
2577 if (IsDefaultChannel(channel)) {
2578 for (ChannelMap::const_iterator it = receive_channels_.begin();
2579 it != receive_channels_.end(); ++it) {
2580 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002581 if (!IsDefaultChannel(it->second->channel())) {
2582 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002583 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002584 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002585 return false;
2586 }
2587 }
2588 }
2589 }
2590
2591 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002592 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2593 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002594 }
2595
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002596 // Set the current codecs to be used for the new channel.
2597 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002598 return false;
2599
2600 return ChangeSend(channel, desired_send_);
2601}
2602
2603bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2604 ChannelMap::iterator it = send_channels_.find(ssrc);
2605 if (it == send_channels_.end()) {
2606 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2607 << " which doesn't exist.";
2608 return false;
2609 }
2610
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002611 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002612 ChangeSend(channel, SEND_NOTHING);
2613
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002614 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2615 // this will disconnect the audio renderer with the send channel.
2616 delete it->second;
2617 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002618
2619 if (IsDefaultChannel(channel)) {
2620 // Do not delete the default channel since the receive channels depend on
2621 // the default channel, recycle it instead.
2622 ChangeSend(channel, SEND_NOTHING);
2623 } else {
2624 // Clean up and delete the send channel.
2625 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2626 << " with VoiceEngine channel #" << channel << ".";
2627 if (!DeleteChannel(channel))
2628 return false;
2629 }
2630
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002631 if (send_channels_.empty())
2632 ChangeSend(SEND_NOTHING);
2633
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002634 return true;
2635}
2636
2637bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002638 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002639
2640 if (!VERIFY(sp.ssrcs.size() == 1))
2641 return false;
2642 uint32 ssrc = sp.first_ssrc();
2643
wu@webrtc.org78187522013-10-07 23:32:02 +00002644 if (ssrc == 0) {
2645 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2646 return false;
2647 }
2648
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002649 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2650 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002651 return false;
2652 }
2653
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002654 // Reuse default channel for recv stream in non-conference mode call
2655 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002656 webrtc::AudioTransport* audio_transport =
2657 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002658 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2659 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2660 << " reuse default channel";
2661 default_receive_ssrc_ = sp.first_ssrc();
2662 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002663 default_receive_ssrc_,
2664 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002665 if (!SetupSharedBweOnChannel(voe_channel())) {
2666 return false;
2667 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002668 return SetPlayout(voe_channel(), playout_);
2669 }
2670
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002671 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002672 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002673 if (channel == -1) {
2674 LOG_RTCERR0(CreateChannel);
2675 return false;
2676 }
2677
wu@webrtc.org78187522013-10-07 23:32:02 +00002678 if (!ConfigureRecvChannel(channel)) {
2679 DeleteChannel(channel);
2680 return false;
2681 }
2682
2683 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002684 std::make_pair(
2685 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002686
2687 LOG(LS_INFO) << "New audio stream " << ssrc
2688 << " registered to VoiceEngine channel #"
2689 << channel << ".";
2690 return true;
2691}
2692
2693bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002694 // Configure to use external transport, like our default channel.
2695 if (engine()->voe()->network()->RegisterExternalTransport(
2696 channel, *this) == -1) {
2697 LOG_RTCERR2(SetExternalTransport, channel, this);
2698 return false;
2699 }
2700
2701 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002702 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002703 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2704 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002705 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002706 return false;
2707 }
2708 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002709 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002710 return false;
2711 }
2712
2713 // Use the same recv payload types as our default channel.
2714 ResetRecvCodecs(channel);
2715 if (!recv_codecs_.empty()) {
2716 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2717 it != recv_codecs_.end(); ++it) {
2718 webrtc::CodecInst voe_codec;
2719 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2720 voe_codec.pltype = it->id;
2721 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2722 if (engine()->voe()->codec()->GetRecPayloadType(
2723 voe_channel(), voe_codec) != -1) {
2724 if (engine()->voe()->codec()->SetRecPayloadType(
2725 channel, voe_codec) == -1) {
2726 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2727 return false;
2728 }
2729 }
2730 }
2731 }
2732 }
2733
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002734 if (InConferenceMode()) {
2735 // To be in par with the video, voe_channel() is not used for receiving in
2736 // a conference call.
2737 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2738 // This is the first stream in a multi user meeting. We can now
2739 // disable playback of the default stream. This since the default
2740 // stream will probably have received some initial packets before
2741 // the new stream was added. This will mean that the CN state from
2742 // the default channel will be mixed in with the other streams
2743 // throughout the whole meeting, which might be disturbing.
2744 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2745 SetPlayout(voe_channel(), false);
2746 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002747 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002748 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002749
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002750 // Set RTP header extension for the new channel.
2751 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2752 return false;
2753 }
2754
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002755 // Set up channel to be able to forward incoming packets to video engine BWE.
2756 if (!SetupSharedBweOnChannel(channel)) {
2757 return false;
2758 }
2759
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002760 return SetPlayout(channel, playout_);
2761}
2762
2763bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002764 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002765 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002766 if (it == receive_channels_.end()) {
2767 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2768 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002769 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002770 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002771
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002772 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2773 // will disconnect the audio renderer with the receive channel.
2774 // Cache the channel before the deletion.
2775 const int channel = it->second->channel();
2776 delete it->second;
2777 receive_channels_.erase(it);
2778
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002779 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002780 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002781 // Recycle the default channel is for recv stream.
2782 if (playout_)
2783 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002784
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002785 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002786 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002787 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002788
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002789 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002790 << " with VoiceEngine channel #" << channel << ".";
2791 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002792 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002793
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002794 bool enable_default_channel_playout = false;
2795 if (receive_channels_.empty()) {
2796 // The last stream was removed. We can now enable the default
2797 // channel for new channels to be played out immediately without
2798 // waiting for AddStream messages.
2799 // We do this for both conference mode and non-conference mode.
2800 // TODO(oja): Does the default channel still have it's CN state?
2801 enable_default_channel_playout = true;
2802 }
2803 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2804 default_receive_ssrc_ != 0) {
2805 // Only the default channel is active, enable the playout on default
2806 // channel.
2807 enable_default_channel_playout = true;
2808 }
2809 if (enable_default_channel_playout && playout_) {
2810 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2811 SetPlayout(voe_channel(), true);
2812 }
2813
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002814 return true;
2815}
2816
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002817bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2818 AudioRenderer* renderer) {
2819 ChannelMap::iterator it = receive_channels_.find(ssrc);
2820 if (it == receive_channels_.end()) {
2821 if (renderer) {
2822 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002823 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002824 return false;
2825 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002826
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002827 // The channel likely has gone away, do nothing.
2828 return true;
2829 }
2830
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002831 if (renderer)
2832 it->second->Start(renderer);
2833 else
2834 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002835
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002836 return true;
2837}
2838
2839bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2840 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002841 ChannelMap::iterator it = send_channels_.find(ssrc);
2842 if (it == send_channels_.end()) {
2843 if (renderer) {
2844 // Return an error if trying to set a valid renderer with an invalid ssrc.
2845 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2846 return false;
2847 }
2848
2849 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002850 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002851 }
2852
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002853 if (renderer)
2854 it->second->Start(renderer);
2855 else
2856 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002857
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002858 return true;
2859}
2860
2861bool WebRtcVoiceMediaChannel::GetActiveStreams(
2862 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002863 // In conference mode, the default channel should not be in
2864 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002865 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002866 for (ChannelMap::iterator it = receive_channels_.begin();
2867 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002868 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002869 if (level > 0) {
2870 actives->push_back(std::make_pair(it->first, level));
2871 }
2872 }
2873 return true;
2874}
2875
2876int WebRtcVoiceMediaChannel::GetOutputLevel() {
2877 // return the highest output level of all streams
2878 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002879 for (ChannelMap::iterator it = receive_channels_.begin();
2880 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002881 int level = GetOutputLevel(it->second->channel());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002882 highest = rtc::_max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002883 }
2884 return highest;
2885}
2886
2887int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2888 int ret;
2889 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2890 // In case of error, log the info and continue
2891 LOG_RTCERR0(TimeSinceLastTyping);
2892 ret = -1;
2893 } else {
2894 ret *= 1000; // We return ms, webrtc returns seconds.
2895 }
2896 return ret;
2897}
2898
2899void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2900 int cost_per_typing, int reporting_threshold, int penalty_decay,
2901 int type_event_delay) {
2902 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2903 time_window, cost_per_typing,
2904 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2905 // In case of error, log the info and continue
2906 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2907 cost_per_typing, reporting_threshold, penalty_decay,
2908 type_event_delay);
2909 }
2910}
2911
2912bool WebRtcVoiceMediaChannel::SetOutputScaling(
2913 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002914 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002915 // Collect the channels to scale the output volume.
2916 std::vector<int> channels;
2917 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002918 // Default channel is not in receive_channels_ if it is not being used for
2919 // playout.
2920 if (default_receive_ssrc_ == 0)
2921 channels.push_back(voe_channel());
2922 for (ChannelMap::const_iterator it = receive_channels_.begin();
2923 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002924 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002925 }
2926 } else { // Collect only the channel of the specified ssrc.
2927 int channel = GetReceiveChannelNum(ssrc);
2928 if (-1 == channel) {
2929 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2930 return false;
2931 }
2932 channels.push_back(channel);
2933 }
2934
2935 // Scale the output volume for the collected channels. We first normalize to
2936 // scale the volume and then set the left and right pan.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002937 float scale = static_cast<float>(rtc::_max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002938 if (scale > 0.0001f) {
2939 left /= scale;
2940 right /= scale;
2941 }
2942 for (std::vector<int>::const_iterator it = channels.begin();
2943 it != channels.end(); ++it) {
2944 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2945 *it, scale)) {
2946 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2947 return false;
2948 }
2949 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2950 *it, static_cast<float>(left), static_cast<float>(right))) {
2951 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2952 // Do not return if fails. SetOutputVolumePan is not available for all
2953 // pltforms.
2954 }
2955 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2956 << " right=" << right * scale
2957 << " for channel " << *it << " and ssrc " << ssrc;
2958 }
2959 return true;
2960}
2961
2962bool WebRtcVoiceMediaChannel::GetOutputScaling(
2963 uint32 ssrc, double* left, double* right) {
2964 if (!left || !right) return false;
2965
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002966 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002967 // Determine which channel based on ssrc.
2968 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2969 if (channel == -1) {
2970 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2971 return false;
2972 }
2973
2974 float scaling;
2975 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2976 channel, scaling)) {
2977 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2978 return false;
2979 }
2980
2981 float left_pan;
2982 float right_pan;
2983 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2984 channel, left_pan, right_pan)) {
2985 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2986 // If GetOutputVolumePan fails, we use the default left and right pan.
2987 left_pan = 1.0f;
2988 right_pan = 1.0f;
2989 }
2990
2991 *left = scaling * left_pan;
2992 *right = scaling * right_pan;
2993 return true;
2994}
2995
2996bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2997 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2998 return true;
2999}
3000
3001bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
3002 bool play, bool loop) {
3003 if (!ringback_tone_) {
3004 return false;
3005 }
3006
3007 // The voe file api is not available in chrome.
3008 if (!engine()->voe()->file()) {
3009 return false;
3010 }
3011
3012 // Determine which VoiceEngine channel to play on.
3013 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
3014 if (channel == -1) {
3015 return false;
3016 }
3017
3018 // Make sure the ringtone is cued properly, and play it out.
3019 if (play) {
3020 ringback_tone_->set_loop(loop);
3021 ringback_tone_->Rewind();
3022 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
3023 ringback_tone_.get()) == -1) {
3024 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
3025 LOG(LS_ERROR) << "Unable to start ringback tone";
3026 return false;
3027 }
3028 ringback_channels_.insert(channel);
3029 LOG(LS_INFO) << "Started ringback on channel " << channel;
3030 } else {
3031 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
3032 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
3033 LOG_RTCERR1(StopPlayingFileLocally, channel);
3034 return false;
3035 }
3036 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
3037 ringback_channels_.erase(channel);
3038 }
3039
3040 return true;
3041}
3042
3043bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3044 return dtmf_allowed_;
3045}
3046
3047bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3048 int duration, int flags) {
3049 if (!dtmf_allowed_) {
3050 return false;
3051 }
3052
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003053 // Send the event.
3054 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003055 int channel = -1;
3056 if (ssrc == 0) {
3057 bool default_channel_is_inuse = false;
3058 for (ChannelMap::const_iterator iter = send_channels_.begin();
3059 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003060 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003061 default_channel_is_inuse = true;
3062 break;
3063 }
3064 }
3065 if (default_channel_is_inuse) {
3066 channel = voe_channel();
3067 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003068 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003069 }
3070 } else {
3071 channel = GetSendChannelNum(ssrc);
3072 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003073 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003074 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3075 << ssrc << " is not in use.";
3076 return false;
3077 }
3078 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003079 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3080 channel, event, true, duration) == -1) {
3081 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003082 return false;
3083 }
3084 }
3085
3086 // Play the event.
3087 if (flags & cricket::DF_PLAY) {
3088 // Play DTMF tone locally.
3089 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3090 LOG_RTCERR2(PlayDtmfTone, event, duration);
3091 return false;
3092 }
3093 }
3094
3095 return true;
3096}
3097
wu@webrtc.orga9890802013-12-13 00:21:03 +00003098void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003099 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003100 // Pick which channel to send this packet to. If this packet doesn't match
3101 // any multiplexed streams, just send it to the default channel. Otherwise,
3102 // send it to the specific decoder instance for that stream.
3103 int which_channel = GetReceiveChannelNum(
3104 ParseSsrc(packet->data(), packet->length(), false));
3105 if (which_channel == -1) {
3106 which_channel = voe_channel();
3107 }
3108
3109 // Stop any ringback that might be playing on the channel.
3110 // It's possible the ringback has already stopped, ih which case we'll just
3111 // use the opportunity to remove the channel from ringback_channels_.
3112 if (engine()->voe()->file()) {
3113 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3114 if (it != ringback_channels_.end()) {
3115 if (engine()->voe()->file()->IsPlayingFileLocally(
3116 which_channel) == 1) {
3117 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3118 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3119 << " due to incoming media";
3120 }
3121 ringback_channels_.erase(which_channel);
3122 }
3123 }
3124
3125 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003126 engine()->voe()->network()->ReceivedRTPPacket(
3127 which_channel,
3128 packet->data(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003129 static_cast<unsigned int>(packet->length()),
3130 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003131}
3132
wu@webrtc.orga9890802013-12-13 00:21:03 +00003133void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003134 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003135 // Sending channels need all RTCP packets with feedback information.
3136 // Even sender reports can contain attached report blocks.
3137 // Receiving channels need sender reports in order to create
3138 // correct receiver reports.
3139 int type = 0;
3140 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3141 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3142 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003143 }
3144
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003145 // If it is a sender report, find the channel that is listening.
3146 bool has_sent_to_default_channel = false;
3147 if (type == kRtcpTypeSR) {
3148 int which_channel = GetReceiveChannelNum(
3149 ParseSsrc(packet->data(), packet->length(), true));
3150 if (which_channel != -1) {
3151 engine()->voe()->network()->ReceivedRTCPPacket(
3152 which_channel,
3153 packet->data(),
3154 static_cast<unsigned int>(packet->length()));
3155
3156 if (IsDefaultChannel(which_channel))
3157 has_sent_to_default_channel = true;
3158 }
3159 }
3160
3161 // SR may continue RR and any RR entry may correspond to any one of the send
3162 // channels. So all RTCP packets must be forwarded all send channels. VoE
3163 // will filter out RR internally.
3164 for (ChannelMap::iterator iter = send_channels_.begin();
3165 iter != send_channels_.end(); ++iter) {
3166 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003167 if (IsDefaultChannel(iter->second->channel()) &&
3168 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003169 continue;
3170
3171 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003172 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003173 packet->data(),
3174 static_cast<unsigned int>(packet->length()));
3175 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003176}
3177
3178bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003179 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3180 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003181 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3182 return false;
3183 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003184 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3185 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003186 return false;
3187 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003188 // We set the AGC to mute state only when all the channels are muted.
3189 // This implementation is not ideal, instead we should signal the AGC when
3190 // the mic channel is muted/unmuted. We can't do it today because there
3191 // is no good way to know which stream is mapping to the mic channel.
3192 bool all_muted = muted;
3193 for (ChannelMap::const_iterator iter = send_channels_.begin();
3194 iter != send_channels_.end() && all_muted; ++iter) {
3195 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3196 all_muted)) {
3197 LOG_RTCERR1(GetInputMute, iter->second->channel());
3198 return false;
3199 }
3200 }
3201
3202 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3203 if (ap)
3204 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003205 return true;
3206}
3207
minyue@webrtc.org26236952014-10-29 02:27:08 +00003208// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3209// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003210bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003211 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003212
minyue@webrtc.org26236952014-10-29 02:27:08 +00003213 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003214}
3215
minyue@webrtc.org26236952014-10-29 02:27:08 +00003216bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3217 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003218
minyue@webrtc.org26236952014-10-29 02:27:08 +00003219 send_bitrate_setting_ = true;
3220 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003221
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003222 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003223 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003224 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003225 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003226 }
3227
minyue@webrtc.org26236952014-10-29 02:27:08 +00003228 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003229 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3230 // SetMaxSendBandwith(0), the second call removes the previous limit.
3231 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003232 return true;
3233
3234 webrtc::CodecInst codec = *send_codec_;
3235 bool is_multi_rate = IsCodecMultiRate(codec);
3236
3237 if (is_multi_rate) {
3238 // If codec is multi-rate then just set the bitrate.
3239 codec.rate = bps;
3240 if (!SetSendCodec(codec)) {
3241 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3242 << " to bitrate " << bps << " bps.";
3243 return false;
3244 }
3245 return true;
3246 } else {
3247 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3248 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3249 // fixed bitrate then ignore.
3250 if (bps < codec.rate) {
3251 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3252 << " to bitrate " << bps << " bps"
3253 << ", requires at least " << codec.rate << " bps.";
3254 return false;
3255 }
3256 return true;
3257 }
3258}
3259
3260bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003261 bool echo_metrics_on = false;
3262 // These can take on valid negative values, so use the lowest possible level
3263 // as default rather than -1.
3264 int echo_return_loss = -100;
3265 int echo_return_loss_enhancement = -100;
3266 // These can also be negative, but in practice -1 is only used to signal
3267 // insufficient data, since the resolution is limited to multiples of 4 ms.
3268 int echo_delay_median_ms = -1;
3269 int echo_delay_std_ms = -1;
3270 if (engine()->voe()->processing()->GetEcMetricsStatus(
3271 echo_metrics_on) != -1 && echo_metrics_on) {
3272 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3273 // here, but it appears to be unsuitable currently. Revisit after this is
3274 // investigated: http://b/issue?id=5666755
3275 int erl, erle, rerl, anlp;
3276 if (engine()->voe()->processing()->GetEchoMetrics(
3277 erl, erle, rerl, anlp) != -1) {
3278 echo_return_loss = erl;
3279 echo_return_loss_enhancement = erle;
3280 }
3281
3282 int median, std;
3283 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3284 echo_delay_median_ms = median;
3285 echo_delay_std_ms = std;
3286 }
3287 }
3288
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003289 webrtc::CallStatistics cs;
3290 unsigned int ssrc;
3291 webrtc::CodecInst codec;
3292 unsigned int level;
3293
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003294 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3295 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003296 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003297
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003298 // Fill in the sender info, based on what we know, and what the
3299 // remote side told us it got from its RTCP report.
3300 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003301
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003302 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3303 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3304 continue;
3305 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003306
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003307 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003308 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3309 sinfo.bytes_sent = cs.bytesSent;
3310 sinfo.packets_sent = cs.packetsSent;
3311 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3312 // returns 0 to indicate an error value.
3313 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3314
3315 // Get data from the last remote RTCP report. Use default values if no data
3316 // available.
3317 sinfo.fraction_lost = -1.0;
3318 sinfo.jitter_ms = -1;
3319 sinfo.packets_lost = -1;
3320 sinfo.ext_seqnum = -1;
3321 std::vector<webrtc::ReportBlock> receive_blocks;
3322 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3323 channel, &receive_blocks) != -1 &&
3324 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3325 std::vector<webrtc::ReportBlock>::iterator iter;
3326 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3327 ++iter) {
3328 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003329 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003330 // Convert Q8 to floating point.
3331 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3332 // Convert samples to milliseconds.
3333 if (codec.plfreq / 1000 > 0) {
3334 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3335 }
3336 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3337 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3338 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003339 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003340 }
3341 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003342
3343 // Local speech level.
3344 sinfo.audio_level = (engine()->voe()->volume()->
3345 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3346
3347 // TODO(xians): We are injecting the same APM logging to all the send
3348 // channels here because there is no good way to know which send channel
3349 // is using the APM. The correct fix is to allow the send channels to have
3350 // their own APM so that we can feed the correct APM logging to different
3351 // send channels. See issue crbug/264611 .
3352 sinfo.echo_return_loss = echo_return_loss;
3353 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3354 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3355 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003356 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3357 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003358 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003359
3360 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003361 }
3362
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003363 // Build the list of receivers, one for each receiving channel, or 1 in
3364 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003365 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003366 for (ChannelMap::const_iterator it = receive_channels_.begin();
3367 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003368 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003369 }
3370 if (channels.empty()) {
3371 channels.push_back(voe_channel());
3372 }
3373
3374 // Get the SSRC and stats for each receiver, based on our own calculations.
3375 for (std::vector<int>::const_iterator it = channels.begin();
3376 it != channels.end(); ++it) {
3377 memset(&cs, 0, sizeof(cs));
3378 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3379 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3380 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3381 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003382 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003383 rinfo.bytes_rcvd = cs.bytesReceived;
3384 rinfo.packets_rcvd = cs.packetsReceived;
3385 // The next four fields are from the most recently sent RTCP report.
3386 // Convert Q8 to floating point.
3387 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3388 rinfo.packets_lost = cs.cumulativeLost;
3389 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003390#ifdef USE_WEBRTC_DEV_BRANCH
3391 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
3392#endif
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003393 if (codec.pltype != -1) {
3394 rinfo.codec_name = codec.plname;
3395 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003396 // Convert samples to milliseconds.
3397 if (codec.plfreq / 1000 > 0) {
3398 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3399 }
3400
3401 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3402 webrtc::NetworkStatistics ns;
3403 if (engine()->voe()->neteq() &&
3404 engine()->voe()->neteq()->GetNetworkStatistics(
3405 *it, ns) != -1) {
3406 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3407 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3408 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003409 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003410 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003411
3412 webrtc::AudioDecodingCallStats ds;
3413 if (engine()->voe()->neteq() &&
3414 engine()->voe()->neteq()->GetDecodingCallStatistics(
3415 *it, &ds) != -1) {
3416 rinfo.decoding_calls_to_silence_generator =
3417 ds.calls_to_silence_generator;
3418 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3419 rinfo.decoding_normal = ds.decoded_normal;
3420 rinfo.decoding_plc = ds.decoded_plc;
3421 rinfo.decoding_cng = ds.decoded_cng;
3422 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3423 }
3424
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003425 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003426 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003427 int playout_buffer_delay_ms = 0;
3428 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003429 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3430 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3431 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003432 }
3433
3434 // Get speech level.
3435 rinfo.audio_level = (engine()->voe()->volume()->
3436 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3437 info->receivers.push_back(rinfo);
3438 }
3439 }
3440
3441 return true;
3442}
3443
3444void WebRtcVoiceMediaChannel::GetLastMediaError(
3445 uint32* ssrc, VoiceMediaChannel::Error* error) {
3446 ASSERT(ssrc != NULL);
3447 ASSERT(error != NULL);
3448 FindSsrc(voe_channel(), ssrc);
3449 *error = WebRtcErrorToChannelError(GetLastEngineError());
3450}
3451
3452bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003453 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003454 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003455 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003456 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3457 // This means the error is not limited to a specific channel. Signal the
3458 // message using ssrc=0. If the current channel is sending, use this
3459 // channel for sending the message.
3460 *ssrc = 0;
3461 return true;
3462 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003463 // Check whether this is a sending channel.
3464 for (ChannelMap::const_iterator it = send_channels_.begin();
3465 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003466 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003467 // This is a sending channel.
3468 uint32 local_ssrc = 0;
3469 if (engine()->voe()->rtp()->GetLocalSSRC(
3470 channel_num, local_ssrc) != -1) {
3471 *ssrc = local_ssrc;
3472 }
3473 return true;
3474 }
3475 }
3476
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003477 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003478 for (ChannelMap::const_iterator it = receive_channels_.begin();
3479 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003480 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003481 *ssrc = it->first;
3482 return true;
3483 }
3484 }
3485 }
3486 return false;
3487}
3488
3489void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003490 if (error == VE_TYPING_NOISE_WARNING) {
3491 typing_noise_detected_ = true;
3492 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3493 typing_noise_detected_ = false;
3494 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003495 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3496}
3497
3498int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3499 unsigned int ulevel;
3500 int ret =
3501 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3502 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3503}
3504
3505int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003506 ChannelMap::iterator it = receive_channels_.find(ssrc);
3507 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003508 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003509 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3510}
3511
3512int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003513 ChannelMap::iterator it = send_channels_.find(ssrc);
3514 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003515 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003516
3517 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003518}
3519
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003520bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
3521 webrtc::VideoEngine* vie, int vie_channel) {
3522 shared_bwe_vie_ = vie;
3523 shared_bwe_vie_channel_ = vie_channel;
3524
3525 if (!SetupSharedBweOnChannel(voe_channel())) {
3526 return false;
3527 }
3528 for (ChannelMap::iterator it = receive_channels_.begin();
3529 it != receive_channels_.end(); ++it) {
3530 if (!SetupSharedBweOnChannel(it->second->channel())) {
3531 return false;
3532 }
3533 }
3534 return true;
3535}
3536
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003537bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3538 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3539 // Get the RED encodings from the parameter with no name. This may
3540 // change based on what is discussed on the Jingle list.
3541 // The encoding parameter is of the form "a/b"; we only support where
3542 // a == b. Verify this and parse out the value into red_pt.
3543 // If the parameter value is absent (as it will be until we wire up the
3544 // signaling of this message), use the second codec specified (i.e. the
3545 // one after "red") as the encoding parameter.
3546 int red_pt = -1;
3547 std::string red_params;
3548 CodecParameterMap::const_iterator it = red_codec.params.find("");
3549 if (it != red_codec.params.end()) {
3550 red_params = it->second;
3551 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003552 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003553 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003554 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003555 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3556 return false;
3557 }
3558 } else if (red_codec.params.empty()) {
3559 LOG(LS_WARNING) << "RED params not present, using defaults";
3560 if (all_codecs.size() > 1) {
3561 red_pt = all_codecs[1].id;
3562 }
3563 }
3564
3565 // Try to find red_pt in |codecs|.
3566 std::vector<AudioCodec>::const_iterator codec;
3567 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3568 if (codec->id == red_pt)
3569 break;
3570 }
3571
3572 // If we find the right codec, that will be the codec we pass to
3573 // SetSendCodec, with the desired payload type.
3574 if (codec != all_codecs.end() &&
3575 engine()->FindWebRtcCodec(*codec, send_codec)) {
3576 } else {
3577 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3578 return false;
3579 }
3580
3581 return true;
3582}
3583
3584bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3585 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003586 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003587 return false;
3588 }
3589 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3590 // what we want to do with them.
3591 // engine()->voe().EnableVQMon(voe_channel(), true);
3592 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3593 return true;
3594}
3595
3596bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3597 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3598 for (int i = 0; i < ncodecs; ++i) {
3599 webrtc::CodecInst voe_codec;
3600 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3601 voe_codec.pltype = -1;
3602 if (engine()->voe()->codec()->SetRecPayloadType(
3603 channel, voe_codec) == -1) {
3604 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3605 return false;
3606 }
3607 }
3608 }
3609 return true;
3610}
3611
3612bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3613 if (playout) {
3614 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3615 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3616 LOG_RTCERR1(StartPlayout, channel);
3617 return false;
3618 }
3619 } else {
3620 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3621 engine()->voe()->base()->StopPlayout(channel);
3622 }
3623 return true;
3624}
3625
3626uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3627 bool rtcp) {
3628 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3629 uint32 ssrc = 0;
3630 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003631 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003632 }
3633 return ssrc;
3634}
3635
3636// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3637VoiceMediaChannel::Error
3638 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3639 switch (err_code) {
3640 case 0:
3641 return ERROR_NONE;
3642 case VE_CANNOT_START_RECORDING:
3643 case VE_MIC_VOL_ERROR:
3644 case VE_GET_MIC_VOL_ERROR:
3645 case VE_CANNOT_ACCESS_MIC_VOL:
3646 return ERROR_REC_DEVICE_OPEN_FAILED;
3647 case VE_SATURATION_WARNING:
3648 return ERROR_REC_DEVICE_SATURATION;
3649 case VE_REC_DEVICE_REMOVED:
3650 return ERROR_REC_DEVICE_REMOVED;
3651 case VE_RUNTIME_REC_WARNING:
3652 case VE_RUNTIME_REC_ERROR:
3653 return ERROR_REC_RUNTIME_ERROR;
3654 case VE_CANNOT_START_PLAYOUT:
3655 case VE_SPEAKER_VOL_ERROR:
3656 case VE_GET_SPEAKER_VOL_ERROR:
3657 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3658 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3659 case VE_RUNTIME_PLAY_WARNING:
3660 case VE_RUNTIME_PLAY_ERROR:
3661 return ERROR_PLAY_RUNTIME_ERROR;
3662 case VE_TYPING_NOISE_WARNING:
3663 return ERROR_REC_TYPING_NOISE_DETECTED;
3664 default:
3665 return VoiceMediaChannel::ERROR_OTHER;
3666 }
3667}
3668
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003669bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3670 int channel_id, const RtpHeaderExtension* extension) {
3671 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003672 int id = 0;
3673 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003674 if (extension) {
3675 enable = true;
3676 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003677 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003678 }
3679 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003680 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003681 return false;
3682 }
3683 return true;
3684}
3685
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003686bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
3687 webrtc::ViENetwork* vie_network = NULL;
3688 int vie_channel = -1;
3689 if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
3690 shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
3691 vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
3692 vie_channel = shared_bwe_vie_channel_;
3693 }
3694 if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
3695 vie_channel) == -1) {
3696 LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
3697 if (vie_network != NULL) {
3698 // Don't fail if we're tearing down.
3699 return false;
3700 }
3701 }
3702 return true;
3703}
3704
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003705int WebRtcSoundclipStream::Read(void *buf, int len) {
3706 size_t res = 0;
3707 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003708 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003709}
3710
3711int WebRtcSoundclipStream::Rewind() {
3712 mem_.Rewind();
3713 // Return -1 to keep VoiceEngine from looping.
3714 return (loop_) ? 0 : -1;
3715}
3716
3717} // namespace cricket
3718
3719#endif // HAVE_WEBRTC_VOICE