blob: 66408f018f69b4faae3b557b6b56dc0b01e5064e [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 },
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +000077 // G722 should be advertised as 8000 Hz because of the RFC "bug".
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +000078 { "G722", 8000, 1, 9, false },
henrike@webrtc.org28e20752013-07-10 00:45:36 +000079 { "ILBC", 8000, 1, 102, false },
80 { "PCMU", 8000, 1, 0, false },
81 { "PCMA", 8000, 1, 8, false },
82 { "CN", 48000, 1, 107, false },
83 { "CN", 32000, 1, 106, false },
84 { "CN", 16000, 1, 105, false },
85 { "CN", 8000, 1, 13, false },
86 { "red", 8000, 1, 127, false },
87 { "telephone-event", 8000, 1, 126, false },
88};
89
90// For Linux/Mac, using the default device is done by specifying index 0 for
91// VoE 4.0 and not -1 (which was the case for VoE 3.5).
92//
93// On Windows Vista and newer, Microsoft introduced the concept of "Default
94// Communications Device". This means that there are two types of default
95// devices (old Wave Audio style default and Default Communications Device).
96//
97// On Windows systems which only support Wave Audio style default, uses either
98// -1 or 0 to select the default device.
99//
100// On Windows systems which support both "Default Communication Device" and
101// old Wave Audio style default, use -1 for Default Communications Device and
102// -2 for Wave Audio style default, which is what we want to use for clips.
103// It's not clear yet whether the -2 index is handled properly on other OSes.
104
105#ifdef WIN32
106static const int kDefaultAudioDeviceId = -1;
107static const int kDefaultSoundclipDeviceId = -2;
108#else
109static const int kDefaultAudioDeviceId = 0;
110#endif
111
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112static const char kIsacCodecName[] = "ISAC";
113static const char kL16CodecName[] = "L16";
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000114static const char kG722CodecName[] = "G722";
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000115
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000116// Parameter used for NACK.
117// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
118static const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000119
120// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000121// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000122
123// Recommended bitrates:
124// 8-12 kb/s for NB speech,
125// 16-20 kb/s for WB speech,
126// 28-40 kb/s for FB speech,
127// 48-64 kb/s for FB mono music, and
128// 64-128 kb/s for FB stereo music.
129// The current implementation applies the following values to mono signals,
130// and multiplies them by 2 for stereo.
131static const int kOpusBitrateNb = 12000;
132static const int kOpusBitrateWb = 20000;
133static const int kOpusBitrateFb = 32000;
134
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000135// Opus bitrate should be in the range between 6000 and 510000.
136static const int kOpusMinBitrate = 6000;
137static const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000138
wu@webrtc.orgde305012013-10-31 15:40:38 +0000139// Default audio dscp value.
140// See http://tools.ietf.org/html/rfc2474 for details.
141// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000142static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000143
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000144// Ensure we open the file in a writeable path on ChromeOS and Android. This
145// workaround can be removed when it's possible to specify a filename for audio
146// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000147//
148// TODO(grunell): Use a string in the options instead of hardcoding it here
149// and let the embedder choose the filename (crbug.com/264223).
150//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000151// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
152// below.
153#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000154static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000155#elif defined(ANDROID)
156static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000157#else
158static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
159#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000160
161// Dumps an AudioCodec in RFC 2327-ish format.
162static std::string ToString(const AudioCodec& codec) {
163 std::stringstream ss;
164 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
165 << " (" << codec.id << ")";
166 return ss.str();
167}
168static std::string ToString(const webrtc::CodecInst& codec) {
169 std::stringstream ss;
170 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
171 << " (" << codec.pltype << ")";
172 return ss.str();
173}
174
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000175static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000176 const char* delim = "\r\n";
177 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
178 LOG_V(sev) << tok;
179 }
180}
181
182// Severity is an integer because it comes is assumed to be from command line.
183static int SeverityToFilter(int severity) {
184 int filter = webrtc::kTraceNone;
185 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000186 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000187 filter |= webrtc::kTraceAll;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000188 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000189 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000190 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000191 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000192 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000193 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
194 }
195 return filter;
196}
197
198static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
199 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
200 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
201 kCodecPrefs[i].clockrate == codec.plfreq) {
202 return kCodecPrefs[i].is_multi_rate;
203 }
204 }
205 return false;
206}
207
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000208static bool IsTelephoneEventCodec(const std::string& name) {
209 return _stricmp(name.c_str(), "telephone-event") == 0;
210}
211
212static bool IsCNCodec(const std::string& name) {
213 return _stricmp(name.c_str(), "CN") == 0;
214}
215
216static bool IsRedCodec(const std::string& name) {
217 return _stricmp(name.c_str(), "red") == 0;
218}
219
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000220static bool FindCodec(const std::vector<AudioCodec>& codecs,
221 const AudioCodec& codec,
222 AudioCodec* found_codec) {
223 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
224 it != codecs.end(); ++it) {
225 if (it->Matches(codec)) {
226 if (found_codec != NULL) {
227 *found_codec = *it;
228 }
229 return true;
230 }
231 }
232 return false;
233}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000234
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000235static bool IsNackEnabled(const AudioCodec& codec) {
236 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
237 kParamValueEmpty));
238}
239
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000240// Gets the default set of options applied to the engine. Historically, these
241// were supplied as a combination of flags from the channel manager (ec, agc,
242// ns, and highpass) and the rest hardcoded in InitInternal.
243static AudioOptions GetDefaultEngineOptions() {
244 AudioOptions options;
245 options.echo_cancellation.Set(true);
246 options.auto_gain_control.Set(true);
247 options.noise_suppression.Set(true);
248 options.highpass_filter.Set(true);
249 options.stereo_swapping.Set(false);
250 options.typing_detection.Set(true);
251 options.conference_mode.Set(false);
252 options.adjust_agc_delta.Set(0);
253 options.experimental_agc.Set(false);
254 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000255 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000256 options.aec_dump.Set(false);
257 return options;
258}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000259
260class WebRtcSoundclipMedia : public SoundclipMedia {
261 public:
262 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
263 : engine_(engine), webrtc_channel_(-1) {
264 engine_->RegisterSoundclip(this);
265 }
266
267 virtual ~WebRtcSoundclipMedia() {
268 engine_->UnregisterSoundclip(this);
269 if (webrtc_channel_ != -1) {
270 // We shouldn't have to call Disable() here. DeleteChannel() should call
271 // StopPlayout() while deleting the channel. We should fix the bug
272 // inside WebRTC and remove the Disable() call bellow. This work is
273 // tracked by bug http://b/issue?id=5382855.
274 PlaySound(NULL, 0, 0);
275 Disable();
276 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
277 == -1) {
278 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
279 }
280 }
281 }
282
283 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000284 if (!engine_->voe_sc()) {
285 return false;
286 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000287 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000288 if (webrtc_channel_ == -1) {
289 LOG_RTCERR0(CreateChannel);
290 return false;
291 }
292 return true;
293 }
294
295 bool Enable() {
296 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
297 LOG_RTCERR1(StartPlayout, webrtc_channel_);
298 return false;
299 }
300 return true;
301 }
302
303 bool Disable() {
304 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
305 LOG_RTCERR1(StopPlayout, webrtc_channel_);
306 return false;
307 }
308 return true;
309 }
310
311 virtual bool PlaySound(const char *buf, int len, int flags) {
312 // The voe file api is not available in chrome.
313 if (!engine_->voe_sc()->file()) {
314 return false;
315 }
316 // Must stop playing the current sound (if any), because we are about to
317 // modify the stream.
318 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
319 == -1) {
320 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
321 return false;
322 }
323
324 if (buf) {
325 stream_.reset(new WebRtcSoundclipStream(buf, len));
326 stream_->set_loop((flags & SF_LOOP) != 0);
327 stream_->Rewind();
328
329 // Play it.
330 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
331 webrtc_channel_, stream_.get()) == -1) {
332 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
333 LOG(LS_ERROR) << "Unable to start soundclip";
334 return false;
335 }
336 } else {
337 stream_.reset();
338 }
339 return true;
340 }
341
342 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
343
344 private:
345 WebRtcVoiceEngine *engine_;
346 int webrtc_channel_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000347 rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000348};
349
350WebRtcVoiceEngine::WebRtcVoiceEngine()
351 : voe_wrapper_(new VoEWrapper()),
352 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000353 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000354 tracing_(new VoETraceWrapper()),
355 adm_(NULL),
356 adm_sc_(NULL),
357 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
358 is_dumping_aec_(false),
359 desired_local_monitor_enable_(false),
360 tx_processor_ssrc_(0),
361 rx_processor_ssrc_(0) {
362 Construct();
363}
364
365WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
366 VoEWrapper* voe_wrapper_sc,
367 VoETraceWrapper* tracing)
368 : voe_wrapper_(voe_wrapper),
369 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000370 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000371 tracing_(tracing),
372 adm_(NULL),
373 adm_sc_(NULL),
374 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
375 is_dumping_aec_(false),
376 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000377 tx_processor_ssrc_(0),
378 rx_processor_ssrc_(0) {
379 Construct();
380}
381
382void WebRtcVoiceEngine::Construct() {
383 SetTraceFilter(log_filter_);
384 initialized_ = false;
385 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
386 SetTraceOptions("");
387 if (tracing_->SetTraceCallback(this) == -1) {
388 LOG_RTCERR0(SetTraceCallback);
389 }
390 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
391 LOG_RTCERR0(RegisterVoiceEngineObserver);
392 }
393 // Clear the default agc state.
394 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
395
396 // Load our audio codec list.
397 ConstructCodecs();
398
399 // Load our RTP Header extensions.
400 rtp_header_extensions_.push_back(
401 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
402 kRtpAudioLevelHeaderExtensionDefaultId));
403 rtp_header_extensions_.push_back(
404 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
405 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
406 options_ = GetDefaultEngineOptions();
407}
408
409static bool IsOpus(const AudioCodec& codec) {
410 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
411}
412
413static bool IsIsac(const AudioCodec& codec) {
414 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
415}
416
417// True if params["stereo"] == "1"
418static bool IsOpusStereoEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000419 int value;
420 return codec.GetParam(kCodecParamStereo, &value) && value == 1;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000421}
422
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000423// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
424// otherwise. If the value (either from params or codec.bitrate) <=0, use the
425// default configuration. If the value is beyond feasible bit rate of Opus,
426// clamp it. Returns the Opus bit rate for operation.
buildbot@webrtc.org879fac82014-10-30 07:50:13 +0000427static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000428 int bitrate = 0;
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000429 bool use_param = true;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000430 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000431 bitrate = codec.bitrate;
432 use_param = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000433 }
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000434 if (bitrate <= 0) {
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000435 if (max_playback_rate <= 8000) {
436 bitrate = kOpusBitrateNb;
437 } else if (max_playback_rate <= 16000) {
438 bitrate = kOpusBitrateWb;
439 } else {
440 bitrate = kOpusBitrateFb;
441 }
442
443 if (IsOpusStereoEnabled(codec)) {
444 bitrate *= 2;
445 }
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000446 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
447 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
448 std::string rate_source =
449 use_param ? "Codec parameter \"maxaveragebitrate\"" :
450 "Supplied Opus bitrate";
451 LOG(LS_WARNING) << rate_source
452 << " is invalid and is replaced by: "
453 << bitrate;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000454 }
455 return bitrate;
456}
457
buildbot@webrtc.orgfbd13282014-06-19 19:50:55 +0000458// Return true if params[kCodecParamUseInbandFec] == "1", false
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000459// otherwise.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000460static bool IsOpusFecEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000461 int value;
462 return codec.GetParam(kCodecParamUseInbandFec, &value) && value == 1;
463}
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000464
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000465// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
466// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
467static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
468 int value;
469 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
470 return value;
471 }
472 return kOpusDefaultMaxPlaybackRate;
473}
474
475static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
476 bool* enable_codec_fec, int* max_playback_rate) {
477 *enable_codec_fec = IsOpusFecEnabled(codec);
478 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
479
480 // If OPUS, change what we send according to the "stereo" codec
481 // parameter, and not the "channels" parameter. We set
482 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000483 // the bitrate is not specified, i.e. is <= zero, we set it to the
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000484 // appropriate default value for mono or stereo Opus.
485
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000486 voe_codec->channels = IsOpusStereoEnabled(codec) ? 2 : 1;
buildbot@webrtc.org879fac82014-10-30 07:50:13 +0000487 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000488}
489
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000490// Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
491// which says that G722 should be advertised as 8 kHz although it is a 16 kHz
492// codec.
493static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
494 if (_stricmp(voe_codec->plname, kG722CodecName) == 0) {
495 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
496 // has changed, and this special case is no longer needed.
497 ASSERT(voe_codec->plfreq != new_plfreq);
498 voe_codec->plfreq = new_plfreq;
499 }
500}
501
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000502void WebRtcVoiceEngine::ConstructCodecs() {
503 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
504 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
505 for (int i = 0; i < ncodecs; ++i) {
506 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000507 if (GetVoeCodec(i, &voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000508 // Skip uncompressed formats.
509 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
510 continue;
511 }
512
513 const CodecPref* pref = NULL;
514 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
515 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
516 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
517 kCodecPrefs[j].channels == voe_codec.channels) {
518 pref = &kCodecPrefs[j];
519 break;
520 }
521 }
522
523 if (pref) {
524 // Use the payload type that we've configured in our pref table;
525 // use the offset in our pref table to determine the sort order.
526 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
527 voe_codec.rate, voe_codec.channels,
528 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
529 LOG(LS_INFO) << ToString(codec);
530 if (IsIsac(codec)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000531 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000532 codec.bitrate = 0;
533 }
534 if (IsOpus(codec)) {
535 // Only add fmtp parameters that differ from the spec.
536 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
537 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000538 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000539 }
540 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
541 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000542 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000543 }
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000544 codec.SetParam(kCodecParamUseInbandFec, "1");
545
546 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000547 // when they can be set to values other than the default.
548 }
549 codecs_.push_back(codec);
550 } else {
551 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
552 }
553 }
554 }
555 // Make sure they are in local preference order.
556 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
557}
558
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000559bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst* codec) {
560 if (voe_wrapper_->codec()->GetCodec(index, *codec) == -1) {
561 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000562 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000563 // Change the sample rate of G722 to 8000 to match SDP.
564 MaybeFixupG722(codec, 8000);
565 return true;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000566}
567
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000568WebRtcVoiceEngine::~WebRtcVoiceEngine() {
569 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
570 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
571 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
572 }
573 if (adm_) {
574 voe_wrapper_.reset();
575 adm_->Release();
576 adm_ = NULL;
577 }
578 if (adm_sc_) {
579 voe_wrapper_sc_.reset();
580 adm_sc_->Release();
581 adm_sc_ = NULL;
582 }
583
584 // Test to see if the media processor was deregistered properly
585 ASSERT(SignalRxMediaFrame.is_empty());
586 ASSERT(SignalTxMediaFrame.is_empty());
587
588 tracing_->SetTraceCallback(NULL);
589}
590
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000591bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000592 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
593 bool res = InitInternal();
594 if (res) {
595 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
596 } else {
597 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
598 Terminate();
599 }
600 return res;
601}
602
603bool WebRtcVoiceEngine::InitInternal() {
604 // Temporarily turn logging level up for the Init call
605 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000606 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000607 SetTraceFilter(extended_filter);
608 SetTraceOptions("");
609
610 // Init WebRtc VoiceEngine.
611 if (voe_wrapper_->base()->Init(adm_) == -1) {
612 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
613 SetTraceFilter(old_filter);
614 return false;
615 }
616
617 SetTraceFilter(old_filter);
618 SetTraceOptions(log_options_);
619
620 // Log the VoiceEngine version info
621 char buffer[1024] = "";
622 voe_wrapper_->base()->GetVersion(buffer);
623 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000624 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000625
626 // Save the default AGC configuration settings. This must happen before
627 // calling SetOptions or the default will be overwritten.
628 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
629 LOG_RTCERR0(GetAgcConfig);
630 return false;
631 }
632
633 // Set defaults for options, so that ApplyOptions applies them explicitly
634 // when we clear option (channel) overrides. External clients can still
635 // modify the defaults via SetOptions (on the media engine).
636 if (!SetOptions(GetDefaultEngineOptions())) {
637 return false;
638 }
639
640 // Print our codec list again for the call diagnostic log
641 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
642 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
643 it != codecs_.end(); ++it) {
644 LOG(LS_INFO) << ToString(*it);
645 }
646
647 // Disable the DTMF playout when a tone is sent.
648 // PlayDtmfTone will be used if local playout is needed.
649 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
650 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
651 }
652
653 initialized_ = true;
654 return true;
655}
656
657bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
658 if (voe_wrapper_sc_initialized_) {
659 return true;
660 }
661 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
662 // be false, so subsequent calls to EnsureSoundclipEngineInit will
663 // probably just fail again. That's acceptable behavior.
664#if defined(LINUX) && !defined(HAVE_LIBPULSE)
665 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
666#endif
667
668 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
669 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
670 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
671 return false;
672 }
673
674 // On Windows, tell it to use the default sound (not communication) devices.
675 // First check whether there is a valid sound device for playback.
676 // TODO(juberti): Clean this up when we support setting the soundclip device.
677#ifdef WIN32
678 // The SetPlayoutDevice may not be implemented in the case of external ADM.
679 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
680 // PeerConnection interface never set the adm_sc_, so need to check both
681 // in order to determine if the external adm is used.
682 if (!adm_ && !adm_sc_) {
683 int num_of_devices = 0;
684 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
685 num_of_devices > 0) {
686 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
687 == -1) {
688 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
689 voe_wrapper_sc_->error());
690 return false;
691 }
692 } else {
693 LOG(LS_WARNING) << "No valid sound playout device found.";
694 }
695 }
696#endif
697 voe_wrapper_sc_initialized_ = true;
698 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
699 return true;
700}
701
702void WebRtcVoiceEngine::Terminate() {
703 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
704 initialized_ = false;
705
706 StopAecDump();
707
708 if (voe_wrapper_sc_) {
709 voe_wrapper_sc_initialized_ = false;
710 voe_wrapper_sc_->base()->Terminate();
711 }
712 voe_wrapper_->base()->Terminate();
713 desired_local_monitor_enable_ = false;
714}
715
716int WebRtcVoiceEngine::GetCapabilities() {
717 return AUDIO_SEND | AUDIO_RECV;
718}
719
720VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
721 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
722 if (!ch->valid()) {
723 delete ch;
724 ch = NULL;
725 }
726 return ch;
727}
728
729SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
730 if (!EnsureSoundclipEngineInit()) {
731 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
732 << "initialize.";
733 return NULL;
734 }
735 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
736 if (!soundclip->Init() || !soundclip->Enable()) {
737 delete soundclip;
738 return NULL;
739 }
740 return soundclip;
741}
742
743bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
744 if (!ApplyOptions(options)) {
745 return false;
746 }
747 options_ = options;
748 return true;
749}
750
751bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
752 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
753 if (!ApplyOptions(overrides)) {
754 return false;
755 }
756 option_overrides_ = overrides;
757 return true;
758}
759
760bool WebRtcVoiceEngine::ClearOptionOverrides() {
761 LOG(LS_INFO) << "Clearing option overrides.";
762 AudioOptions options = options_;
763 // Only call ApplyOptions if |options_overrides_| contains overrided options.
764 // ApplyOptions affects NS, AGC other options that is shared between
765 // all WebRtcVoiceEngineChannels.
766 if (option_overrides_ == AudioOptions()) {
767 return true;
768 }
769
770 if (!ApplyOptions(options)) {
771 return false;
772 }
773 option_overrides_ = AudioOptions();
774 return true;
775}
776
777// AudioOptions defaults are set in InitInternal (for options with corresponding
778// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
779bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
780 AudioOptions options = options_in; // The options are modified below.
781 // kEcConference is AEC with high suppression.
782 webrtc::EcModes ec_mode = webrtc::kEcConference;
783 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
784 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
785 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
786 bool aecm_comfort_noise = false;
787 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
788 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
789 << aecm_comfort_noise << " (default is false).";
790 }
791
792#if defined(IOS)
793 // On iOS, VPIO provides built-in EC and AGC.
794 options.echo_cancellation.Set(false);
795 options.auto_gain_control.Set(false);
796#elif defined(ANDROID)
797 ec_mode = webrtc::kEcAecm;
798#endif
799
800#if defined(IOS) || defined(ANDROID)
801 // Set the AGC mode for iOS as well despite disabling it above, to avoid
802 // unsupported configuration errors from webrtc.
803 agc_mode = webrtc::kAgcFixedDigital;
804 options.typing_detection.Set(false);
805 options.experimental_agc.Set(false);
806 options.experimental_aec.Set(false);
807 options.experimental_ns.Set(false);
808#endif
809
810 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
811
812 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
813
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000814 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000815 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000816 // Check if platform supports built-in EC. Currently only supported on
817 // Android and in combination with Java based audio layer.
818 // TODO(henrika): investigate possibility to support built-in EC also
819 // in combination with Open SL ES audio.
820 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
821 if (built_in_aec) {
822 // Set mode of built-in EC according to the audio options.
823 voe_wrapper_->hw()->EnableBuiltInAEC(echo_cancellation);
824 if (echo_cancellation) {
825 // Disable internal software EC if device has its own built-in EC,
826 // i.e., replace the software EC with the built-in EC.
827 options.echo_cancellation.Set(false);
828 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
829 }
830 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000831 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
832 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
833 return false;
834 } else {
835 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
836 << " with mode " << ec_mode;
837 }
838#if !defined(ANDROID)
839 // TODO(ajm): Remove the error return on Android from webrtc.
840 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
841 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
842 return false;
843 }
844#endif
845 if (ec_mode == webrtc::kEcAecm) {
846 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
847 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
848 return false;
849 }
850 }
851 }
852
853 bool auto_gain_control;
854 if (options.auto_gain_control.Get(&auto_gain_control)) {
855 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
856 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
857 return false;
858 } else {
859 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
860 << " with mode " << agc_mode;
861 }
862 }
863
864 if (options.tx_agc_target_dbov.IsSet() ||
865 options.tx_agc_digital_compression_gain.IsSet() ||
866 options.tx_agc_limiter.IsSet()) {
867 // Override default_agc_config_. Generally, an unset option means "leave
868 // the VoE bits alone" in this function, so we want whatever is set to be
869 // stored as the new "default". If we didn't, then setting e.g.
870 // tx_agc_target_dbov would reset digital compression gain and limiter
871 // settings.
872 // Also, if we don't update default_agc_config_, then adjust_agc_delta
873 // would be an offset from the original values, and not whatever was set
874 // explicitly.
875 default_agc_config_.targetLeveldBOv =
876 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
877 default_agc_config_.targetLeveldBOv);
878 default_agc_config_.digitalCompressionGaindB =
879 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
880 default_agc_config_.digitalCompressionGaindB);
881 default_agc_config_.limiterEnable =
882 options.tx_agc_limiter.GetWithDefaultIfUnset(
883 default_agc_config_.limiterEnable);
884 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
885 LOG_RTCERR3(SetAgcConfig,
886 default_agc_config_.targetLeveldBOv,
887 default_agc_config_.digitalCompressionGaindB,
888 default_agc_config_.limiterEnable);
889 return false;
890 }
891 }
892
893 bool noise_suppression;
894 if (options.noise_suppression.Get(&noise_suppression)) {
895 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
896 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
897 return false;
898 } else {
899 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
900 << " with mode " << ns_mode;
901 }
902 }
903
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000904 bool highpass_filter;
905 if (options.highpass_filter.Get(&highpass_filter)) {
906 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
907 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
908 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
909 return false;
910 }
911 }
912
913 bool stereo_swapping;
914 if (options.stereo_swapping.Get(&stereo_swapping)) {
915 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
916 voep->EnableStereoChannelSwapping(stereo_swapping);
917 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
918 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
919 return false;
920 }
921 }
922
923 bool typing_detection;
924 if (options.typing_detection.Get(&typing_detection)) {
925 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
926 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
927 // In case of error, log the info and continue
928 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
929 }
930 }
931
932 int adjust_agc_delta;
933 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
934 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
935 if (!AdjustAgcLevel(adjust_agc_delta)) {
936 return false;
937 }
938 }
939
940 bool aec_dump;
941 if (options.aec_dump.Get(&aec_dump)) {
942 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
943 if (aec_dump)
944 StartAecDump(kAecDumpByAudioOptionFilename);
945 else
946 StopAecDump();
947 }
948
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000949 webrtc::Config config;
950
951 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000952 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000953 if (experimental_aec_.Get(&experimental_aec)) {
954 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
955 config.Set<webrtc::DelayCorrection>(
956 new webrtc::DelayCorrection(experimental_aec));
957 }
958
959#ifdef USE_WEBRTC_DEV_BRANCH
960 experimental_ns_.SetFrom(options.experimental_ns);
961 bool experimental_ns;
962 if (experimental_ns_.Get(&experimental_ns)) {
963 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
964 config.Set<webrtc::ExperimentalNs>(
965 new webrtc::ExperimentalNs(experimental_ns));
966 }
967#endif
968
969 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
970 // returns NULL on audio_processing().
971 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
972 if (audioproc) {
973 audioproc->SetExtraOptions(config);
974 }
975
976#ifndef USE_WEBRTC_DEV_BRANCH
977 bool experimental_ns;
978 if (options.experimental_ns.Get(&experimental_ns)) {
979 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000980 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
981 // returns NULL on audio_processing().
982 if (audioproc) {
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000983 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
984 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
985 return false;
986 }
987 } else {
988 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
989 << experimental_ns;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000990 }
991 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000992#endif
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000993
994 uint32 recording_sample_rate;
995 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
996 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
997 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
998 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
999 }
1000 }
1001
1002 uint32 playout_sample_rate;
1003 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
1004 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
1005 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
1006 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
1007 }
1008 }
1009
1010 return true;
1011}
1012
1013bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
1014 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
1015 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
1016 LOG_RTCERR1(SetDelayOffsetMs, offset);
1017 return false;
1018 }
1019
1020 return true;
1021}
1022
1023struct ResumeEntry {
1024 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
1025 : channel(c),
1026 playout(p),
1027 send(s) {
1028 }
1029
1030 WebRtcVoiceMediaChannel *channel;
1031 bool playout;
1032 SendFlags send;
1033};
1034
1035// TODO(juberti): Refactor this so that the core logic can be used to set the
1036// soundclip device. At that time, reinstate the soundclip pause/resume code.
1037bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
1038 const Device* out_device) {
1039#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001040 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001041 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001042 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001043 kDefaultAudioDeviceId;
1044 // The device manager uses -1 as the default device, which was the case for
1045 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
1046#ifndef WIN32
1047 if (-1 == in_id) {
1048 in_id = kDefaultAudioDeviceId;
1049 }
1050 if (-1 == out_id) {
1051 out_id = kDefaultAudioDeviceId;
1052 }
1053#endif
1054
1055 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
1056 in_device->name : "Default device";
1057 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
1058 out_device->name : "Default device";
1059 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
1060 << ") and speaker to (id=" << out_id << ", name=" << out_name
1061 << ")";
1062
1063 // If we're running the local monitor, we need to stop it first.
1064 bool ret = true;
1065 if (!PauseLocalMonitor()) {
1066 LOG(LS_WARNING) << "Failed to pause local monitor";
1067 ret = false;
1068 }
1069
1070 // Must also pause 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->PausePlayout()) {
1075 LOG(LS_WARNING) << "Failed to pause playout";
1076 ret = false;
1077 }
1078 if (!channel->PauseSend()) {
1079 LOG(LS_WARNING) << "Failed to pause send";
1080 ret = false;
1081 }
1082 }
1083
1084 // Find the recording device id in VoiceEngine and set recording device.
1085 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1086 ret = false;
1087 }
1088 if (ret) {
1089 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
1090 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
1091 ret = false;
1092 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00001093 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
1094 if (ap)
1095 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001096 }
1097
1098 // Find the playout device id in VoiceEngine and set playout device.
1099 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1100 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1101 ret = false;
1102 }
1103 if (ret) {
1104 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001105 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001106 ret = false;
1107 }
1108 }
1109
1110 // Resume all audio playback and capture.
1111 for (ChannelList::const_iterator i = channels_.begin();
1112 i != channels_.end(); ++i) {
1113 WebRtcVoiceMediaChannel *channel = *i;
1114 if (!channel->ResumePlayout()) {
1115 LOG(LS_WARNING) << "Failed to resume playout";
1116 ret = false;
1117 }
1118 if (!channel->ResumeSend()) {
1119 LOG(LS_WARNING) << "Failed to resume send";
1120 ret = false;
1121 }
1122 }
1123
1124 // Resume local monitor.
1125 if (!ResumeLocalMonitor()) {
1126 LOG(LS_WARNING) << "Failed to resume local monitor";
1127 ret = false;
1128 }
1129
1130 if (ret) {
1131 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1132 << ") and speaker to (id="<< out_id << " name=" << out_name
1133 << ")";
1134 }
1135
1136 return ret;
1137#else
1138 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001139#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001140}
1141
1142bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1143 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1144 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001145#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001146 *rtc_id = dev_id;
1147 return true;
1148#else
1149 // In Windows and Mac, we need to find the VoiceEngine device id by name
1150 // unless the input dev_id is the default device id.
1151 if (kDefaultAudioDeviceId == dev_id) {
1152 *rtc_id = dev_id;
1153 return true;
1154 }
1155
1156 // Get the number of VoiceEngine audio devices.
1157 int count = 0;
1158 if (is_input) {
1159 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1160 LOG_RTCERR0(GetNumOfRecordingDevices);
1161 return false;
1162 }
1163 } else {
1164 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1165 LOG_RTCERR0(GetNumOfPlayoutDevices);
1166 return false;
1167 }
1168 }
1169
1170 for (int i = 0; i < count; ++i) {
1171 char name[128];
1172 char guid[128];
1173 if (is_input) {
1174 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1175 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1176 } else {
1177 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1178 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1179 }
1180
1181 std::string webrtc_name(name);
1182 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1183 *rtc_id = i;
1184 return true;
1185 }
1186 }
1187 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1188 return false;
1189#endif
1190}
1191
1192bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1193 unsigned int ulevel;
1194 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1195 LOG_RTCERR1(GetSpeakerVolume, level);
1196 return false;
1197 }
1198 *level = ulevel;
1199 return true;
1200}
1201
1202bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1203 ASSERT(level >= 0 && level <= 255);
1204 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1205 LOG_RTCERR1(SetSpeakerVolume, level);
1206 return false;
1207 }
1208 return true;
1209}
1210
1211int WebRtcVoiceEngine::GetInputLevel() {
1212 unsigned int ulevel;
1213 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1214 static_cast<int>(ulevel) : -1;
1215}
1216
1217bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1218 desired_local_monitor_enable_ = enable;
1219 return ChangeLocalMonitor(desired_local_monitor_enable_);
1220}
1221
1222bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1223 // The voe file api is not available in chrome.
1224 if (!voe_wrapper_->file()) {
1225 return false;
1226 }
1227 if (enable && !monitor_) {
1228 monitor_.reset(new WebRtcMonitorStream);
1229 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1230 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1231 // Must call Stop() because there are some cases where Start will report
1232 // failure but still change the state, and if we leave VE in the on state
1233 // then it could crash later when trying to invoke methods on our monitor.
1234 voe_wrapper_->file()->StopRecordingMicrophone();
1235 monitor_.reset();
1236 return false;
1237 }
1238 } else if (!enable && monitor_) {
1239 voe_wrapper_->file()->StopRecordingMicrophone();
1240 monitor_.reset();
1241 }
1242 return true;
1243}
1244
1245bool WebRtcVoiceEngine::PauseLocalMonitor() {
1246 return ChangeLocalMonitor(false);
1247}
1248
1249bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1250 return ChangeLocalMonitor(desired_local_monitor_enable_);
1251}
1252
1253const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1254 return codecs_;
1255}
1256
1257bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1258 return FindWebRtcCodec(in, NULL);
1259}
1260
1261// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1262bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1263 webrtc::CodecInst* out) {
1264 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1265 for (int i = 0; i < ncodecs; ++i) {
1266 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001267 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001268 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1269 voe_codec.rate, voe_codec.channels, 0);
1270 bool multi_rate = IsCodecMultiRate(voe_codec);
1271 // Allow arbitrary rates for ISAC to be specified.
1272 if (multi_rate) {
1273 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1274 codec.bitrate = 0;
1275 }
1276 if (codec.Matches(in)) {
1277 if (out) {
1278 // Fixup the payload type.
1279 voe_codec.pltype = in.id;
1280
1281 // Set bitrate if specified.
1282 if (multi_rate && in.bitrate != 0) {
1283 voe_codec.rate = in.bitrate;
1284 }
1285
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001286 // Reset G722 sample rate to 16000 to match WebRTC.
1287 MaybeFixupG722(&voe_codec, 16000);
1288
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001289 // Apply codec-specific settings.
1290 if (IsIsac(codec)) {
1291 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001292 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1294 }
1295 *out = voe_codec;
1296 }
1297 return true;
1298 }
1299 }
1300 }
1301 return false;
1302}
1303const std::vector<RtpHeaderExtension>&
1304WebRtcVoiceEngine::rtp_header_extensions() const {
1305 return rtp_header_extensions_;
1306}
1307
1308void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1309 // if min_sev == -1, we keep the current log level.
1310 if (min_sev >= 0) {
1311 SetTraceFilter(SeverityToFilter(min_sev));
1312 }
1313 log_options_ = filter;
1314 SetTraceOptions(initialized_ ? log_options_ : "");
1315}
1316
1317int WebRtcVoiceEngine::GetLastEngineError() {
1318 return voe_wrapper_->error();
1319}
1320
1321void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1322 log_filter_ = filter;
1323 tracing_->SetTraceFilter(filter);
1324}
1325
1326// We suppport three different logging settings for VoiceEngine:
1327// 1. Observer callback that goes into talk diagnostic logfile.
1328// Use --logfile and --loglevel
1329//
1330// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1331// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1332//
1333// 3. EC log and dump for debugging QualityEngine.
1334// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1335//
1336// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1337// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1338void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1339 // Set encrypted trace file.
1340 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001341 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001342 std::vector<std::string>::iterator tracefile =
1343 std::find(opts.begin(), opts.end(), "tracefile");
1344 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1345 // Write encrypted debug output (at same loglevel) to file
1346 // EncryptedTraceFile no longer supported.
1347 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1348 LOG_RTCERR1(SetTraceFile, *tracefile);
1349 }
1350 }
1351
wu@webrtc.org97077a32013-10-25 21:18:33 +00001352 // Allow trace options to override the trace filter. We default
1353 // it to log_filter_ (as a translation of libjingle log levels)
1354 // elsewhere, but this allows clients to explicitly set webrtc
1355 // log levels.
1356 std::vector<std::string>::iterator tracefilter =
1357 std::find(opts.begin(), opts.end(), "tracefilter");
1358 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001359 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001360 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1361 }
1362 }
1363
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001364 // Set AEC dump file
1365 std::vector<std::string>::iterator recordEC =
1366 std::find(opts.begin(), opts.end(), "recordEC");
1367 if (recordEC != opts.end()) {
1368 ++recordEC;
1369 if (recordEC != opts.end())
1370 StartAecDump(recordEC->c_str());
1371 else
1372 StopAecDump();
1373 }
1374}
1375
1376// Ignore spammy trace messages, mostly from the stats API when we haven't
1377// gotten RTCP info yet from the remote side.
1378bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1379 static const char* kTracesToIgnore[] = {
1380 "\tfailed to GetReportBlockInformation",
1381 "GetRecCodec() failed to get received codec",
1382 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1383 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1384 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1385 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1386 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1387 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1388 "SenderInfoReceived No received SR",
1389 "StatisticsRTP() no statistics available",
1390 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1391 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1392 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1393 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1394 NULL
1395 };
1396 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1397 if (trace.find(*p) != std::string::npos) {
1398 return true;
1399 }
1400 }
1401 return false;
1402}
1403
1404void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1405 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001406 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001407 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001408 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001409 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001410 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001411 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001412 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001413 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001414 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001415
1416 // Skip past boilerplate prefix text
1417 if (length < 72) {
1418 std::string msg(trace, length);
1419 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1420 LOG_V(sev) << msg;
1421 } else {
1422 std::string msg(trace + 71, length - 72);
1423 if (!ShouldIgnoreTrace(msg)) {
1424 LOG_V(sev) << "webrtc: " << msg;
1425 }
1426 }
1427}
1428
1429void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001430 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001431 WebRtcVoiceMediaChannel* channel = NULL;
1432 uint32 ssrc = 0;
1433 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1434 << channel_num << ".";
1435 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1436 ASSERT(channel != NULL);
1437 channel->OnError(ssrc, err_code);
1438 } else {
1439 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1440 << " could not be found in channel list when error reported.";
1441 }
1442}
1443
1444bool WebRtcVoiceEngine::FindChannelAndSsrc(
1445 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1446 ASSERT(channel != NULL && ssrc != NULL);
1447
1448 *channel = NULL;
1449 *ssrc = 0;
1450 // Find corresponding channel and ssrc
1451 for (ChannelList::const_iterator it = channels_.begin();
1452 it != channels_.end(); ++it) {
1453 ASSERT(*it != NULL);
1454 if ((*it)->FindSsrc(channel_num, ssrc)) {
1455 *channel = *it;
1456 return true;
1457 }
1458 }
1459
1460 return false;
1461}
1462
1463// This method will search through the WebRtcVoiceMediaChannels and
1464// obtain the voice engine's channel number.
1465bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1466 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1467 ASSERT(channel_num != NULL);
1468 ASSERT(direction == MPD_RX || direction == MPD_TX);
1469
1470 *channel_num = -1;
1471 // Find corresponding channel for ssrc.
1472 for (ChannelList::const_iterator it = channels_.begin();
1473 it != channels_.end(); ++it) {
1474 ASSERT(*it != NULL);
1475 if (direction & MPD_RX) {
1476 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1477 }
1478 if (*channel_num == -1 && (direction & MPD_TX)) {
1479 *channel_num = (*it)->GetSendChannelNum(ssrc);
1480 }
1481 if (*channel_num != -1) {
1482 return true;
1483 }
1484 }
1485 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1486 return false;
1487}
1488
1489void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001490 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001491 channels_.push_back(channel);
1492}
1493
1494void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001495 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001496 ChannelList::iterator i = std::find(channels_.begin(),
1497 channels_.end(),
1498 channel);
1499 if (i != channels_.end()) {
1500 channels_.erase(i);
1501 }
1502}
1503
1504void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1505 soundclips_.push_back(soundclip);
1506}
1507
1508void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1509 SoundclipList::iterator i = std::find(soundclips_.begin(),
1510 soundclips_.end(),
1511 soundclip);
1512 if (i != soundclips_.end()) {
1513 soundclips_.erase(i);
1514 }
1515}
1516
1517// Adjusts the default AGC target level by the specified delta.
1518// NB: If we start messing with other config fields, we'll want
1519// to save the current webrtc::AgcConfig as well.
1520bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1521 webrtc::AgcConfig config = default_agc_config_;
1522 config.targetLeveldBOv -= delta;
1523
1524 LOG(LS_INFO) << "Adjusting AGC level from default -"
1525 << default_agc_config_.targetLeveldBOv << "dB to -"
1526 << config.targetLeveldBOv << "dB";
1527
1528 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1529 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1530 return false;
1531 }
1532 return true;
1533}
1534
1535bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1536 webrtc::AudioDeviceModule* adm_sc) {
1537 if (initialized_) {
1538 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1539 return false;
1540 }
1541 if (adm_) {
1542 adm_->Release();
1543 adm_ = NULL;
1544 }
1545 if (adm) {
1546 adm_ = adm;
1547 adm_->AddRef();
1548 }
1549
1550 if (adm_sc_) {
1551 adm_sc_->Release();
1552 adm_sc_ = NULL;
1553 }
1554 if (adm_sc) {
1555 adm_sc_ = adm_sc;
1556 adm_sc_->AddRef();
1557 }
1558 return true;
1559}
1560
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001561bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1562 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001563 if (!aec_dump_file_stream) {
1564 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001565 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001566 LOG(LS_WARNING) << "Could not close file.";
1567 return false;
1568 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001569 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001570 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001571 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001572 LOG_RTCERR0(StartDebugRecording);
1573 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001574 return false;
1575 }
1576 is_dumping_aec_ = true;
1577 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001578}
1579
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001580bool WebRtcVoiceEngine::RegisterProcessor(
1581 uint32 ssrc,
1582 VoiceProcessor* voice_processor,
1583 MediaProcessorDirection direction) {
1584 bool register_with_webrtc = false;
1585 int channel_id = -1;
1586 bool success = false;
1587 uint32* processor_ssrc = NULL;
1588 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1589 if (voice_processor == NULL || !found_channel) {
1590 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1591 << " foundChannel: " << found_channel;
1592 return false;
1593 }
1594
1595 webrtc::ProcessingTypes processing_type;
1596 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001597 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001598 if (direction == MPD_RX) {
1599 processing_type = webrtc::kPlaybackAllChannelsMixed;
1600 if (SignalRxMediaFrame.is_empty()) {
1601 register_with_webrtc = true;
1602 processor_ssrc = &rx_processor_ssrc_;
1603 }
1604 SignalRxMediaFrame.connect(voice_processor,
1605 &VoiceProcessor::OnFrame);
1606 } else {
1607 processing_type = webrtc::kRecordingPerChannel;
1608 if (SignalTxMediaFrame.is_empty()) {
1609 register_with_webrtc = true;
1610 processor_ssrc = &tx_processor_ssrc_;
1611 }
1612 SignalTxMediaFrame.connect(voice_processor,
1613 &VoiceProcessor::OnFrame);
1614 }
1615 }
1616 if (register_with_webrtc) {
1617 // TODO(janahan): when registering consider instantiating a
1618 // a VoeMediaProcess object and not make the engine extend the interface.
1619 if (voe()->media() && voe()->media()->
1620 RegisterExternalMediaProcessing(channel_id,
1621 processing_type,
1622 *this) != -1) {
1623 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1624 << channel_id;
1625 *processor_ssrc = ssrc;
1626 success = true;
1627 } else {
1628 LOG_RTCERR2(RegisterExternalMediaProcessing,
1629 channel_id,
1630 processing_type);
1631 success = false;
1632 }
1633 } else {
1634 // If we don't have to register with the engine, we just needed to
1635 // connect a new processor, set success to true;
1636 success = true;
1637 }
1638 return success;
1639}
1640
1641bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1642 MediaProcessorDirection channel_direction,
1643 uint32 ssrc,
1644 VoiceProcessor* voice_processor,
1645 MediaProcessorDirection processor_direction) {
1646 bool success = true;
1647 FrameSignal* signal;
1648 webrtc::ProcessingTypes processing_type;
1649 uint32* processor_ssrc = NULL;
1650 if (channel_direction == MPD_RX) {
1651 signal = &SignalRxMediaFrame;
1652 processing_type = webrtc::kPlaybackAllChannelsMixed;
1653 processor_ssrc = &rx_processor_ssrc_;
1654 } else {
1655 signal = &SignalTxMediaFrame;
1656 processing_type = webrtc::kRecordingPerChannel;
1657 processor_ssrc = &tx_processor_ssrc_;
1658 }
1659
1660 int deregister_id = -1;
1661 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001662 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001663 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1664 signal->disconnect(voice_processor);
1665 int channel_id = -1;
1666 bool found_channel = FindChannelNumFromSsrc(ssrc,
1667 channel_direction,
1668 &channel_id);
1669 if (signal->is_empty() && found_channel) {
1670 deregister_id = channel_id;
1671 }
1672 }
1673 }
1674 if (deregister_id != -1) {
1675 if (voe()->media() &&
1676 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1677 processing_type) != -1) {
1678 *processor_ssrc = 0;
1679 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1680 << deregister_id;
1681 } else {
1682 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1683 deregister_id,
1684 processing_type);
1685 success = false;
1686 }
1687 }
1688 return success;
1689}
1690
1691bool WebRtcVoiceEngine::UnregisterProcessor(
1692 uint32 ssrc,
1693 VoiceProcessor* voice_processor,
1694 MediaProcessorDirection direction) {
1695 bool success = true;
1696 if (voice_processor == NULL) {
1697 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1698 << ssrc;
1699 return false;
1700 }
1701 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1702 success = false;
1703 }
1704 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1705 success = false;
1706 }
1707 return success;
1708}
1709
1710// Implementing method from WebRtc VoEMediaProcess interface
1711// Do not lock mux_channel_cs_ in this callback.
1712void WebRtcVoiceEngine::Process(int channel,
1713 webrtc::ProcessingTypes type,
1714 int16_t audio10ms[],
1715 int length,
1716 int sampling_freq,
1717 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001718 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001719 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1720 if (type == webrtc::kPlaybackAllChannelsMixed) {
1721 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1722 } else if (type == webrtc::kRecordingPerChannel) {
1723 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1724 } else {
1725 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1726 << " channel: " << channel << " type: " << type
1727 << " tx_ssrc: " << tx_processor_ssrc_
1728 << " rx_ssrc: " << rx_processor_ssrc_;
1729 }
1730}
1731
1732void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1733 if (!is_dumping_aec_) {
1734 // Start dumping AEC when we are not dumping.
1735 if (voe_wrapper_->processing()->StartDebugRecording(
1736 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001737 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001738 } else {
1739 is_dumping_aec_ = true;
1740 }
1741 }
1742}
1743
1744void WebRtcVoiceEngine::StopAecDump() {
1745 if (is_dumping_aec_) {
1746 // Stop dumping AEC when we are dumping.
1747 if (voe_wrapper_->processing()->StopDebugRecording() !=
1748 webrtc::AudioProcessing::kNoError) {
1749 LOG_RTCERR0(StopDebugRecording);
1750 }
1751 is_dumping_aec_ = false;
1752 }
1753}
1754
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001755int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001756 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001757}
1758
1759int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1760 return CreateVoiceChannel(voe_wrapper_.get());
1761}
1762
1763int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1764 return CreateVoiceChannel(voe_wrapper_sc_.get());
1765}
1766
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001767class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1768 : public AudioRenderer::Sink {
1769 public:
1770 WebRtcVoiceChannelRenderer(int ch,
1771 webrtc::AudioTransport* voe_audio_transport)
1772 : channel_(ch),
1773 voe_audio_transport_(voe_audio_transport),
1774 renderer_(NULL) {
1775 }
1776 virtual ~WebRtcVoiceChannelRenderer() {
1777 Stop();
1778 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001779
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001780 // Starts the rendering by setting a sink to the renderer to get data
1781 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001782 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001783 // TODO(xians): Make sure Start() is called only once.
1784 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001785 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001786 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001787 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001788 ASSERT(renderer_ == renderer);
1789 return;
1790 }
1791
1792 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1793 // in getUserMedia by default.
1794 renderer->AddChannel(channel_);
1795 renderer->SetSink(this);
1796 renderer_ = renderer;
1797 }
1798
1799 // Stops rendering by setting the sink of the renderer to NULL. No data
1800 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001801 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001802 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001803 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001804 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001805 return;
1806
1807 renderer_->RemoveChannel(channel_);
1808 renderer_->SetSink(NULL);
1809 renderer_ = NULL;
1810 }
1811
1812 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001813 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001814 virtual void OnData(const void* audio_data,
1815 int bits_per_sample,
1816 int sample_rate,
1817 int number_of_channels,
1818 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001819 voe_audio_transport_->OnData(channel_,
1820 audio_data,
1821 bits_per_sample,
1822 sample_rate,
1823 number_of_channels,
1824 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001825 }
1826
1827 // Callback from the |renderer_| when it is going away. In case Start() has
1828 // never been called, this callback won't be triggered.
1829 virtual void OnClose() OVERRIDE {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001830 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001831 // Set |renderer_| to NULL to make sure no more callback will get into
1832 // the renderer.
1833 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001834 }
1835
1836 // Accessor to the VoE channel ID.
1837 int channel() const { return channel_; }
1838
1839 private:
1840 const int channel_;
1841 webrtc::AudioTransport* const voe_audio_transport_;
1842
1843 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1844 // PeerConnection will make sure invalidating the pointer before the object
1845 // goes away.
1846 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001847
1848 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001849 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001850};
1851
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001852// WebRtcVoiceMediaChannel
1853WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1854 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1855 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001856 engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001857 send_bitrate_setting_(false),
1858 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001859 options_(),
1860 dtmf_allowed_(false),
1861 desired_playout_(false),
1862 nack_enabled_(false),
1863 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001864 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001865 desired_send_(SEND_NOTHING),
1866 send_(SEND_NOTHING),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001867 shared_bwe_vie_(NULL),
1868 shared_bwe_vie_channel_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001869 default_receive_ssrc_(0) {
1870 engine->RegisterChannel(this);
1871 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1872 << voe_channel();
1873
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001874 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001875}
1876
1877WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1878 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1879 << voe_channel();
buildbot@webrtc.org6e5c7842014-09-19 06:46:37 +00001880 SetupSharedBandwidthEstimation(NULL, -1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001881
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001882 // Remove any remaining send streams, the default channel will be deleted
1883 // later.
1884 while (!send_channels_.empty())
1885 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001886
1887 // Unregister ourselves from the engine.
1888 engine()->UnregisterChannel(this);
1889 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001890 while (!receive_channels_.empty()) {
1891 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001892 }
1893
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001894 // Delete the default channel.
1895 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001896}
1897
1898bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1899 LOG(LS_INFO) << "Setting voice channel options: "
1900 << options.ToString();
1901
wu@webrtc.orgde305012013-10-31 15:40:38 +00001902 // Check if DSCP value is changed from previous.
1903 bool dscp_option_changed = (options_.dscp != options.dscp);
1904
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001905 // TODO(xians): Add support to set different options for different send
1906 // streams after we support multiple APMs.
1907
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001908 // We retain all of the existing options, and apply the given ones
1909 // on top. This means there is no way to "clear" options such that
1910 // they go back to the engine default.
1911 options_.SetAll(options);
1912
1913 if (send_ != SEND_NOTHING) {
1914 if (!engine()->SetOptionOverrides(options_)) {
1915 LOG(LS_WARNING) <<
1916 "Failed to engine SetOptionOverrides during channel SetOptions.";
1917 return false;
1918 }
1919 } else {
1920 // Will be interpreted when appropriate.
1921 }
1922
wu@webrtc.org97077a32013-10-25 21:18:33 +00001923 // Receiver-side auto gain control happens per channel, so set it here from
1924 // options. Note that, like conference mode, setting it on the engine won't
1925 // have the desired effect, since voice channels don't inherit options from
1926 // the media engine when those options are applied per-channel.
1927 bool rx_auto_gain_control;
1928 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1929 if (engine()->voe()->processing()->SetRxAgcStatus(
1930 voe_channel(), rx_auto_gain_control,
1931 webrtc::kAgcFixedDigital) == -1) {
1932 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1933 return false;
1934 } else {
1935 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1936 << " with mode " << webrtc::kAgcFixedDigital;
1937 }
1938 }
1939 if (options.rx_agc_target_dbov.IsSet() ||
1940 options.rx_agc_digital_compression_gain.IsSet() ||
1941 options.rx_agc_limiter.IsSet()) {
1942 webrtc::AgcConfig config;
1943 // If only some of the options are being overridden, get the current
1944 // settings for the channel and bail if they aren't available.
1945 if (!options.rx_agc_target_dbov.IsSet() ||
1946 !options.rx_agc_digital_compression_gain.IsSet() ||
1947 !options.rx_agc_limiter.IsSet()) {
1948 if (engine()->voe()->processing()->GetRxAgcConfig(
1949 voe_channel(), config) != 0) {
1950 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1951 << "channel " << voe_channel() << ". Since not all rx "
1952 << "agc options are specified, unable to safely set rx "
1953 << "agc options.";
1954 return false;
1955 }
1956 }
1957 config.targetLeveldBOv =
1958 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1959 config.targetLeveldBOv);
1960 config.digitalCompressionGaindB =
1961 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1962 config.digitalCompressionGaindB);
1963 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1964 config.limiterEnable);
1965 if (engine()->voe()->processing()->SetRxAgcConfig(
1966 voe_channel(), config) == -1) {
1967 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1968 config.digitalCompressionGaindB, config.limiterEnable);
1969 return false;
1970 }
1971 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001972 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001973 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001974 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001975 dscp = kAudioDscpValue;
1976 if (MediaChannel::SetDscp(dscp) != 0) {
1977 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1978 }
1979 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001980
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001981 // Force update of Video Engine BWE forwarding to reflect experiment setting.
1982 if (!SetupSharedBandwidthEstimation(shared_bwe_vie_,
1983 shared_bwe_vie_channel_)) {
1984 return false;
1985 }
1986
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001987 LOG(LS_INFO) << "Set voice channel options. Current options: "
1988 << options_.ToString();
1989 return true;
1990}
1991
1992bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1993 const std::vector<AudioCodec>& codecs) {
1994 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001995 LOG(LS_INFO) << "Setting receive voice codecs:";
1996
1997 std::vector<AudioCodec> new_codecs;
1998 // Find all new codecs. We allow adding new codecs but don't allow changing
1999 // the payload type of codecs that is already configured since we might
2000 // already be receiving packets with that payload type.
2001 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002002 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002003 AudioCodec old_codec;
2004 if (FindCodec(recv_codecs_, *it, &old_codec)) {
2005 if (old_codec.id != it->id) {
2006 LOG(LS_ERROR) << it->name << " payload type changed.";
2007 return false;
2008 }
2009 } else {
2010 new_codecs.push_back(*it);
2011 }
2012 }
2013 if (new_codecs.empty()) {
2014 // There are no new codecs to configure. Already configured codecs are
2015 // never removed.
2016 return true;
2017 }
2018
2019 if (playout_) {
2020 // Receive codecs can not be changed while playing. So we temporarily
2021 // pause playout.
2022 PausePlayout();
2023 }
2024
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002025 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002026 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
2027 it != new_codecs.end() && ret; ++it) {
2028 webrtc::CodecInst voe_codec;
2029 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2030 LOG(LS_INFO) << ToString(*it);
2031 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002032 if (default_receive_ssrc_ == 0) {
2033 // Set the receive codecs on the default channel explicitly if the
2034 // default channel is not used by |receive_channels_|, this happens in
2035 // conference mode or in non-conference mode when there is no playout
2036 // channel.
2037 // TODO(xians): Figure out how we use the default channel in conference
2038 // mode.
2039 if (engine()->voe()->codec()->SetRecPayloadType(
2040 voe_channel(), voe_codec) == -1) {
2041 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
2042 ret = false;
2043 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002044 }
2045
2046 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002047 for (ChannelMap::iterator it = receive_channels_.begin();
2048 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002049 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002050 it->second->channel(), voe_codec) == -1) {
2051 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002052 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002053 ret = false;
2054 }
2055 }
2056 } else {
2057 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2058 ret = false;
2059 }
2060 }
2061 if (ret) {
2062 recv_codecs_ = codecs;
2063 }
2064
2065 if (desired_playout_ && !playout_) {
2066 ResumePlayout();
2067 }
2068 return ret;
2069}
2070
2071bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002072 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002073 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002074 engine()->voe()->codec()->SetVADStatus(channel, false);
2075 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002076#ifdef USE_WEBRTC_DEV_BRANCH
2077 engine()->voe()->rtp()->SetREDStatus(channel, false);
2078 engine()->voe()->codec()->SetFECStatus(channel, false);
2079#else
2080 // TODO(minyue): Remove code under #else case after new WebRTC roll.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002081 engine()->voe()->rtp()->SetFECStatus(channel, false);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002082#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002083
2084 // Scan through the list to figure out the codec to use for sending, along
2085 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002086 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002087 webrtc::CodecInst send_codec;
2088 memset(&send_codec, 0, sizeof(send_codec));
2089
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002090 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002091 bool enable_codec_fec = false;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002092
minyue@webrtc.org26236952014-10-29 02:27:08 +00002093 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002094
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002095 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002096 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2097 it != codecs.end(); ++it) {
2098 // Ignore codecs we don't know about. The negotiation step should prevent
2099 // this, but double-check to be sure.
2100 webrtc::CodecInst voe_codec;
2101 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002102 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002103 continue;
2104 }
2105
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002106 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2107 // Skip telephone-event/CN codec, which will be handled later.
2108 continue;
2109 }
2110
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002111 // We'll use the first codec in the list to actually send audio data.
2112 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002113 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002114 // used is specified in params.
2115 if (IsRedCodec(it->name)) {
2116 // Parse out the RED parameters. If we fail, just ignore RED;
2117 // we don't support all possible params/usage scenarios.
2118 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2119 continue;
2120 }
2121
2122 // Enable redundant encoding of the specified codec. Treat any
2123 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002124#ifdef USE_WEBRTC_DEV_BRANCH
2125 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2126 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2127 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
2128#else
2129 // TODO(minyue): Remove code under #else case after new WebRTC roll.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002130 LOG(LS_INFO) << "Enabling FEC";
2131 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2132 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002133#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002134 return false;
2135 }
2136 } else {
2137 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002138 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002139 // For Opus as the send codec, we are to enable inband FEC if requested
2140 // and set maximum playback rate.
2141 if (IsOpus(*it)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002142 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
2143 &opus_max_playback_rate);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002144 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002145 }
2146 found_send_codec = true;
2147 break;
2148 }
2149
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002150 if (nack_enabled_ != nack_enabled) {
2151 SetNack(channel, nack_enabled);
2152 nack_enabled_ = nack_enabled;
2153 }
2154
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002155 if (!found_send_codec) {
2156 LOG(LS_WARNING) << "Received empty list of codecs.";
2157 return false;
2158 }
2159
2160 // Set the codec immediately, since SetVADStatus() depends on whether
2161 // the current codec is mono or stereo.
2162 if (!SetSendCodec(channel, send_codec))
2163 return false;
2164
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002165 // FEC should be enabled after SetSendCodec.
2166 if (enable_codec_fec) {
2167 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2168 << channel;
2169#ifdef USE_WEBRTC_DEV_BRANCH
2170 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2171 // Enable codec internal FEC. Treat any failure as fatal internal error.
2172 LOG_RTCERR2(SetFECStatus, channel, true);
2173 return false;
2174 }
2175#endif // USE_WEBRTC_DEV_BRANCH
2176 }
2177
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002178 // maxplaybackrate should be set after SetSendCodec.
minyue@webrtc.org26236952014-10-29 02:27:08 +00002179 // If opus_max_playback_rate <= 0, the default maximum playback rate of 48 kHz
2180 // will be used.
2181 if (opus_max_playback_rate > 0) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002182 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002183 << opus_max_playback_rate
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002184 << " Hz on channel "
2185 << channel;
2186#ifdef USE_WEBRTC_DEV_BRANCH
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002187 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
minyue@webrtc.org26236952014-10-29 02:27:08 +00002188 channel, opus_max_playback_rate) == -1) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002189 LOG(LS_WARNING) << "Could not set maximum playback rate.";
2190 }
2191#endif
2192 }
2193
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002194 // Always update the |send_codec_| to the currently set send codec.
2195 send_codec_.reset(new webrtc::CodecInst(send_codec));
2196
minyue@webrtc.org26236952014-10-29 02:27:08 +00002197 if (send_bitrate_setting_) {
2198 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002199 }
2200
2201 // Loop through the codecs list again to config the telephone-event/CN codec.
2202 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2203 it != codecs.end(); ++it) {
2204 // Ignore codecs we don't know about. The negotiation step should prevent
2205 // this, but double-check to be sure.
2206 webrtc::CodecInst voe_codec;
2207 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2208 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2209 continue;
2210 }
2211
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002212 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2213 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002214 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002215 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2216 channel, it->id) == -1) {
2217 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2218 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002219 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002220 } else if (IsCNCodec(it->name)) {
2221 // Turn voice activity detection/comfort noise on if supported.
2222 // Set the wideband CN payload type appropriately.
2223 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002224 webrtc::PayloadFrequencies cn_freq;
2225 switch (it->clockrate) {
2226 case 8000:
2227 cn_freq = webrtc::kFreq8000Hz;
2228 break;
2229 case 16000:
2230 cn_freq = webrtc::kFreq16000Hz;
2231 break;
2232 case 32000:
2233 cn_freq = webrtc::kFreq32000Hz;
2234 break;
2235 default:
2236 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2237 << " not supported.";
2238 continue;
2239 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002240 // Set the CN payloadtype and the VAD status.
2241 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2242 if (cn_freq != webrtc::kFreq8000Hz) {
2243 if (engine()->voe()->codec()->SetSendCNPayloadType(
2244 channel, it->id, cn_freq) == -1) {
2245 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2246 // TODO(ajm): This failure condition will be removed from VoE.
2247 // Restore the return here when we update to a new enough webrtc.
2248 //
2249 // Not returning false because the SetSendCNPayloadType will fail if
2250 // the channel is already sending.
2251 // This can happen if the remote description is applied twice, for
2252 // example in the case of ROAP on top of JSEP, where both side will
2253 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002254 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002255 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002256 // Only turn on VAD if we have a CN payload type that matches the
2257 // clockrate for the codec we are going to use.
2258 if (it->clockrate == send_codec.plfreq) {
2259 LOG(LS_INFO) << "Enabling VAD";
2260 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2261 LOG_RTCERR2(SetVADStatus, channel, true);
2262 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002263 }
2264 }
2265 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002266 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002267 return true;
2268}
2269
2270bool WebRtcVoiceMediaChannel::SetSendCodecs(
2271 const std::vector<AudioCodec>& codecs) {
2272 dtmf_allowed_ = false;
2273 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2274 it != codecs.end(); ++it) {
2275 // Find the DTMF telephone event "codec".
2276 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2277 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2278 dtmf_allowed_ = true;
2279 }
2280 }
2281
2282 // Cache the codecs in order to configure the channel created later.
2283 send_codecs_ = codecs;
2284 for (ChannelMap::iterator iter = send_channels_.begin();
2285 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002286 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002287 return false;
2288 }
2289 }
2290
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002291 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002292 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002293 return true;
2294}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002295
2296void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2297 bool nack_enabled) {
2298 for (ChannelMap::const_iterator it = channels.begin();
2299 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002300 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002301 }
2302}
2303
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002304void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002305 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002306 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002307 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2308 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002309 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002310 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2311 }
2312}
2313
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002314bool WebRtcVoiceMediaChannel::SetSendCodec(
2315 const webrtc::CodecInst& send_codec) {
2316 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2317 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002318 for (ChannelMap::iterator iter = send_channels_.begin();
2319 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002320 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002321 return false;
2322 }
2323
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002324 return true;
2325}
2326
2327bool WebRtcVoiceMediaChannel::SetSendCodec(
2328 int channel, const webrtc::CodecInst& send_codec) {
2329 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2330 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2331
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002332 webrtc::CodecInst current_codec;
2333 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2334 (send_codec == current_codec)) {
2335 // Codec is already configured, we can return without setting it again.
2336 return true;
2337 }
2338
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002339 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2340 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002341 return false;
2342 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002343 return true;
2344}
2345
2346bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2347 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002348 if (receive_extensions_ == extensions) {
2349 return true;
2350 }
2351
2352 // The default channel may or may not be in |receive_channels_|. Set the rtp
2353 // header extensions for default channel regardless.
2354 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2355 return false;
2356 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002357
2358 // Loop through all receive channels and enable/disable the extensions.
2359 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2360 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002361 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2362 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002363 return false;
2364 }
2365 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002366
2367 receive_extensions_ = extensions;
2368 return true;
2369}
2370
2371bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2372 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002373 const RtpHeaderExtension* audio_level_extension =
2374 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2375 if (!SetHeaderExtension(
2376 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2377 audio_level_extension)) {
2378 return false;
2379 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002380
2381 const RtpHeaderExtension* send_time_extension =
2382 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2383 if (!SetHeaderExtension(
2384 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2385 send_time_extension)) {
2386 return false;
2387 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002388 return true;
2389}
2390
2391bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2392 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002393 if (send_extensions_ == extensions) {
2394 return true;
2395 }
2396
2397 // The default channel may or may not be in |send_channels_|. Set the rtp
2398 // header extensions for default channel regardless.
2399
2400 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2401 return false;
2402 }
2403
2404 // Loop through all send channels and enable/disable the extensions.
2405 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2406 channel_it != send_channels_.end(); ++channel_it) {
2407 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2408 extensions)) {
2409 return false;
2410 }
2411 }
2412
2413 send_extensions_ = extensions;
2414 return true;
2415}
2416
2417bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2418 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002419 const RtpHeaderExtension* audio_level_extension =
2420 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002421
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002422 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002423 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002424 audio_level_extension)) {
2425 return false;
2426 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002427
2428 const RtpHeaderExtension* send_time_extension =
2429 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002430 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002431 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002432 send_time_extension)) {
2433 return false;
2434 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002435
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002436 return true;
2437}
2438
2439bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2440 desired_playout_ = playout;
2441 return ChangePlayout(desired_playout_);
2442}
2443
2444bool WebRtcVoiceMediaChannel::PausePlayout() {
2445 return ChangePlayout(false);
2446}
2447
2448bool WebRtcVoiceMediaChannel::ResumePlayout() {
2449 return ChangePlayout(desired_playout_);
2450}
2451
2452bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2453 if (playout_ == playout) {
2454 return true;
2455 }
2456
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002457 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002458 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002459 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002460 // Only toggle the default channel if we don't have any other channels.
2461 result = SetPlayout(voe_channel(), playout);
2462 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002463 for (ChannelMap::iterator it = receive_channels_.begin();
2464 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002465 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002466 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002467 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002468 result = false;
2469 }
2470 }
2471
2472 if (result) {
2473 playout_ = playout;
2474 }
2475 return result;
2476}
2477
2478bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2479 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002480 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002481 return ChangeSend(desired_send_);
2482 return true;
2483}
2484
2485bool WebRtcVoiceMediaChannel::PauseSend() {
2486 return ChangeSend(SEND_NOTHING);
2487}
2488
2489bool WebRtcVoiceMediaChannel::ResumeSend() {
2490 return ChangeSend(desired_send_);
2491}
2492
2493bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2494 if (send_ == send) {
2495 return true;
2496 }
2497
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002498 // Change the settings on each send channel.
2499 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002500 engine()->SetOptionOverrides(options_);
2501
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002502 // Change the settings on each send channel.
2503 for (ChannelMap::iterator iter = send_channels_.begin();
2504 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002505 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002506 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002507 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002508
2509 // Clear up the options after stopping sending.
2510 if (send == SEND_NOTHING)
2511 engine()->ClearOptionOverrides();
2512
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002513 send_ = send;
2514 return true;
2515}
2516
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002517bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2518 if (send == SEND_MICROPHONE) {
2519 if (engine()->voe()->base()->StartSend(channel) == -1) {
2520 LOG_RTCERR1(StartSend, channel);
2521 return false;
2522 }
2523 if (engine()->voe()->file() &&
2524 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2525 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2526 return false;
2527 }
2528 } else { // SEND_NOTHING
2529 ASSERT(send == SEND_NOTHING);
2530 if (engine()->voe()->base()->StopSend(channel) == -1) {
2531 LOG_RTCERR1(StopSend, channel);
2532 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002533 }
2534 }
2535
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002536 return true;
2537}
2538
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002539// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002540void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2541 if (engine()->voe()->network()->RegisterExternalTransport(
2542 channel, *this) == -1) {
2543 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2544 }
2545
2546 // Enable RTCP (for quality stats and feedback messages)
2547 EnableRtcp(channel);
2548
2549 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2550 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002551
2552 // Set RTP header extension for the new channel.
2553 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002554}
2555
2556bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2557 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2558 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2559 }
2560
2561 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2562 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002563 return false;
2564 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002565
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002566 return true;
2567}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002568
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002569bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2570 // If the default channel is already used for sending create a new channel
2571 // otherwise use the default channel for sending.
2572 int channel = GetSendChannelNum(sp.first_ssrc());
2573 if (channel != -1) {
2574 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2575 return false;
2576 }
2577
2578 bool default_channel_is_available = true;
2579 for (ChannelMap::const_iterator iter = send_channels_.begin();
2580 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002581 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002582 default_channel_is_available = false;
2583 break;
2584 }
2585 }
2586 if (default_channel_is_available) {
2587 channel = voe_channel();
2588 } else {
2589 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002590 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002591 if (channel == -1) {
2592 LOG_RTCERR0(CreateChannel);
2593 return false;
2594 }
2595
2596 ConfigureSendChannel(channel);
2597 }
2598
2599 // Save the channel to send_channels_, so that RemoveSendStream() can still
2600 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002601 webrtc::AudioTransport* audio_transport =
2602 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002603 send_channels_.insert(std::make_pair(
2604 sp.first_ssrc(),
2605 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002606
2607 // Set the send (local) SSRC.
2608 // If there are multiple send SSRCs, we can only set the first one here, and
2609 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2610 // (with a codec requires multiple SSRC(s)).
2611 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2612 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2613 return false;
2614 }
2615
2616 // At this point the channel's local SSRC has been updated. If the channel is
2617 // the default channel make sure that all the receive channels are updated as
2618 // well. Receive channels have to have the same SSRC as the default channel in
2619 // order to send receiver reports with this SSRC.
2620 if (IsDefaultChannel(channel)) {
2621 for (ChannelMap::const_iterator it = receive_channels_.begin();
2622 it != receive_channels_.end(); ++it) {
2623 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002624 if (!IsDefaultChannel(it->second->channel())) {
2625 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002626 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002627 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002628 return false;
2629 }
2630 }
2631 }
2632 }
2633
2634 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002635 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2636 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002637 }
2638
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002639 // Set the current codecs to be used for the new channel.
2640 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002641 return false;
2642
2643 return ChangeSend(channel, desired_send_);
2644}
2645
2646bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2647 ChannelMap::iterator it = send_channels_.find(ssrc);
2648 if (it == send_channels_.end()) {
2649 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2650 << " which doesn't exist.";
2651 return false;
2652 }
2653
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002654 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002655 ChangeSend(channel, SEND_NOTHING);
2656
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002657 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2658 // this will disconnect the audio renderer with the send channel.
2659 delete it->second;
2660 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002661
2662 if (IsDefaultChannel(channel)) {
2663 // Do not delete the default channel since the receive channels depend on
2664 // the default channel, recycle it instead.
2665 ChangeSend(channel, SEND_NOTHING);
2666 } else {
2667 // Clean up and delete the send channel.
2668 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2669 << " with VoiceEngine channel #" << channel << ".";
2670 if (!DeleteChannel(channel))
2671 return false;
2672 }
2673
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002674 if (send_channels_.empty())
2675 ChangeSend(SEND_NOTHING);
2676
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002677 return true;
2678}
2679
2680bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002681 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002682
2683 if (!VERIFY(sp.ssrcs.size() == 1))
2684 return false;
2685 uint32 ssrc = sp.first_ssrc();
2686
wu@webrtc.org78187522013-10-07 23:32:02 +00002687 if (ssrc == 0) {
2688 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2689 return false;
2690 }
2691
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002692 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2693 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002694 return false;
2695 }
2696
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002697 // Reuse default channel for recv stream in non-conference mode call
2698 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002699 webrtc::AudioTransport* audio_transport =
2700 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002701 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2702 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2703 << " reuse default channel";
2704 default_receive_ssrc_ = sp.first_ssrc();
2705 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002706 default_receive_ssrc_,
2707 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002708 if (!SetupSharedBweOnChannel(voe_channel())) {
2709 return false;
2710 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002711 return SetPlayout(voe_channel(), playout_);
2712 }
2713
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002714 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002715 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002716 if (channel == -1) {
2717 LOG_RTCERR0(CreateChannel);
2718 return false;
2719 }
2720
wu@webrtc.org78187522013-10-07 23:32:02 +00002721 if (!ConfigureRecvChannel(channel)) {
2722 DeleteChannel(channel);
2723 return false;
2724 }
2725
2726 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002727 std::make_pair(
2728 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002729
2730 LOG(LS_INFO) << "New audio stream " << ssrc
2731 << " registered to VoiceEngine channel #"
2732 << channel << ".";
2733 return true;
2734}
2735
2736bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002737 // Configure to use external transport, like our default channel.
2738 if (engine()->voe()->network()->RegisterExternalTransport(
2739 channel, *this) == -1) {
2740 LOG_RTCERR2(SetExternalTransport, channel, this);
2741 return false;
2742 }
2743
2744 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002745 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002746 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2747 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002748 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002749 return false;
2750 }
2751 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002752 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002753 return false;
2754 }
2755
2756 // Use the same recv payload types as our default channel.
2757 ResetRecvCodecs(channel);
2758 if (!recv_codecs_.empty()) {
2759 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2760 it != recv_codecs_.end(); ++it) {
2761 webrtc::CodecInst voe_codec;
2762 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2763 voe_codec.pltype = it->id;
2764 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2765 if (engine()->voe()->codec()->GetRecPayloadType(
2766 voe_channel(), voe_codec) != -1) {
2767 if (engine()->voe()->codec()->SetRecPayloadType(
2768 channel, voe_codec) == -1) {
2769 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2770 return false;
2771 }
2772 }
2773 }
2774 }
2775 }
2776
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002777 if (InConferenceMode()) {
2778 // To be in par with the video, voe_channel() is not used for receiving in
2779 // a conference call.
2780 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2781 // This is the first stream in a multi user meeting. We can now
2782 // disable playback of the default stream. This since the default
2783 // stream will probably have received some initial packets before
2784 // the new stream was added. This will mean that the CN state from
2785 // the default channel will be mixed in with the other streams
2786 // throughout the whole meeting, which might be disturbing.
2787 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2788 SetPlayout(voe_channel(), false);
2789 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002790 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002791 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002792
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002793 // Set RTP header extension for the new channel.
2794 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2795 return false;
2796 }
2797
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002798 // Set up channel to be able to forward incoming packets to video engine BWE.
2799 if (!SetupSharedBweOnChannel(channel)) {
2800 return false;
2801 }
2802
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002803 return SetPlayout(channel, playout_);
2804}
2805
2806bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002807 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002808 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002809 if (it == receive_channels_.end()) {
2810 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2811 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002812 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002813 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002814
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002815 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2816 // will disconnect the audio renderer with the receive channel.
2817 // Cache the channel before the deletion.
2818 const int channel = it->second->channel();
2819 delete it->second;
2820 receive_channels_.erase(it);
2821
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002822 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002823 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002824 // Recycle the default channel is for recv stream.
2825 if (playout_)
2826 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002827
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002828 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002829 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002830 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002831
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002832 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002833 << " with VoiceEngine channel #" << channel << ".";
2834 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002835 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002836
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002837 bool enable_default_channel_playout = false;
2838 if (receive_channels_.empty()) {
2839 // The last stream was removed. We can now enable the default
2840 // channel for new channels to be played out immediately without
2841 // waiting for AddStream messages.
2842 // We do this for both conference mode and non-conference mode.
2843 // TODO(oja): Does the default channel still have it's CN state?
2844 enable_default_channel_playout = true;
2845 }
2846 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2847 default_receive_ssrc_ != 0) {
2848 // Only the default channel is active, enable the playout on default
2849 // channel.
2850 enable_default_channel_playout = true;
2851 }
2852 if (enable_default_channel_playout && playout_) {
2853 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2854 SetPlayout(voe_channel(), true);
2855 }
2856
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002857 return true;
2858}
2859
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002860bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2861 AudioRenderer* renderer) {
2862 ChannelMap::iterator it = receive_channels_.find(ssrc);
2863 if (it == receive_channels_.end()) {
2864 if (renderer) {
2865 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002866 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002867 return false;
2868 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002869
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002870 // The channel likely has gone away, do nothing.
2871 return true;
2872 }
2873
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002874 if (renderer)
2875 it->second->Start(renderer);
2876 else
2877 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002878
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002879 return true;
2880}
2881
2882bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2883 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002884 ChannelMap::iterator it = send_channels_.find(ssrc);
2885 if (it == send_channels_.end()) {
2886 if (renderer) {
2887 // Return an error if trying to set a valid renderer with an invalid ssrc.
2888 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2889 return false;
2890 }
2891
2892 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002893 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002894 }
2895
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002896 if (renderer)
2897 it->second->Start(renderer);
2898 else
2899 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002900
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002901 return true;
2902}
2903
2904bool WebRtcVoiceMediaChannel::GetActiveStreams(
2905 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002906 // In conference mode, the default channel should not be in
2907 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002908 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002909 for (ChannelMap::iterator it = receive_channels_.begin();
2910 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002911 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002912 if (level > 0) {
2913 actives->push_back(std::make_pair(it->first, level));
2914 }
2915 }
2916 return true;
2917}
2918
2919int WebRtcVoiceMediaChannel::GetOutputLevel() {
2920 // return the highest output level of all streams
2921 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002922 for (ChannelMap::iterator it = receive_channels_.begin();
2923 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002924 int level = GetOutputLevel(it->second->channel());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002925 highest = rtc::_max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002926 }
2927 return highest;
2928}
2929
2930int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2931 int ret;
2932 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2933 // In case of error, log the info and continue
2934 LOG_RTCERR0(TimeSinceLastTyping);
2935 ret = -1;
2936 } else {
2937 ret *= 1000; // We return ms, webrtc returns seconds.
2938 }
2939 return ret;
2940}
2941
2942void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2943 int cost_per_typing, int reporting_threshold, int penalty_decay,
2944 int type_event_delay) {
2945 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2946 time_window, cost_per_typing,
2947 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2948 // In case of error, log the info and continue
2949 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2950 cost_per_typing, reporting_threshold, penalty_decay,
2951 type_event_delay);
2952 }
2953}
2954
2955bool WebRtcVoiceMediaChannel::SetOutputScaling(
2956 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002957 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002958 // Collect the channels to scale the output volume.
2959 std::vector<int> channels;
2960 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002961 // Default channel is not in receive_channels_ if it is not being used for
2962 // playout.
2963 if (default_receive_ssrc_ == 0)
2964 channels.push_back(voe_channel());
2965 for (ChannelMap::const_iterator it = receive_channels_.begin();
2966 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002967 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002968 }
2969 } else { // Collect only the channel of the specified ssrc.
2970 int channel = GetReceiveChannelNum(ssrc);
2971 if (-1 == channel) {
2972 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2973 return false;
2974 }
2975 channels.push_back(channel);
2976 }
2977
2978 // Scale the output volume for the collected channels. We first normalize to
2979 // scale the volume and then set the left and right pan.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002980 float scale = static_cast<float>(rtc::_max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002981 if (scale > 0.0001f) {
2982 left /= scale;
2983 right /= scale;
2984 }
2985 for (std::vector<int>::const_iterator it = channels.begin();
2986 it != channels.end(); ++it) {
2987 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2988 *it, scale)) {
2989 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2990 return false;
2991 }
2992 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2993 *it, static_cast<float>(left), static_cast<float>(right))) {
2994 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2995 // Do not return if fails. SetOutputVolumePan is not available for all
2996 // pltforms.
2997 }
2998 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2999 << " right=" << right * scale
3000 << " for channel " << *it << " and ssrc " << ssrc;
3001 }
3002 return true;
3003}
3004
3005bool WebRtcVoiceMediaChannel::GetOutputScaling(
3006 uint32 ssrc, double* left, double* right) {
3007 if (!left || !right) return false;
3008
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003009 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003010 // Determine which channel based on ssrc.
3011 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
3012 if (channel == -1) {
3013 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
3014 return false;
3015 }
3016
3017 float scaling;
3018 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
3019 channel, scaling)) {
3020 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
3021 return false;
3022 }
3023
3024 float left_pan;
3025 float right_pan;
3026 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
3027 channel, left_pan, right_pan)) {
3028 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
3029 // If GetOutputVolumePan fails, we use the default left and right pan.
3030 left_pan = 1.0f;
3031 right_pan = 1.0f;
3032 }
3033
3034 *left = scaling * left_pan;
3035 *right = scaling * right_pan;
3036 return true;
3037}
3038
3039bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
3040 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
3041 return true;
3042}
3043
3044bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
3045 bool play, bool loop) {
3046 if (!ringback_tone_) {
3047 return false;
3048 }
3049
3050 // The voe file api is not available in chrome.
3051 if (!engine()->voe()->file()) {
3052 return false;
3053 }
3054
3055 // Determine which VoiceEngine channel to play on.
3056 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
3057 if (channel == -1) {
3058 return false;
3059 }
3060
3061 // Make sure the ringtone is cued properly, and play it out.
3062 if (play) {
3063 ringback_tone_->set_loop(loop);
3064 ringback_tone_->Rewind();
3065 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
3066 ringback_tone_.get()) == -1) {
3067 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
3068 LOG(LS_ERROR) << "Unable to start ringback tone";
3069 return false;
3070 }
3071 ringback_channels_.insert(channel);
3072 LOG(LS_INFO) << "Started ringback on channel " << channel;
3073 } else {
3074 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
3075 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
3076 LOG_RTCERR1(StopPlayingFileLocally, channel);
3077 return false;
3078 }
3079 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
3080 ringback_channels_.erase(channel);
3081 }
3082
3083 return true;
3084}
3085
3086bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3087 return dtmf_allowed_;
3088}
3089
3090bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3091 int duration, int flags) {
3092 if (!dtmf_allowed_) {
3093 return false;
3094 }
3095
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003096 // Send the event.
3097 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003098 int channel = -1;
3099 if (ssrc == 0) {
3100 bool default_channel_is_inuse = false;
3101 for (ChannelMap::const_iterator iter = send_channels_.begin();
3102 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003103 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003104 default_channel_is_inuse = true;
3105 break;
3106 }
3107 }
3108 if (default_channel_is_inuse) {
3109 channel = voe_channel();
3110 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003111 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003112 }
3113 } else {
3114 channel = GetSendChannelNum(ssrc);
3115 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003116 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003117 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3118 << ssrc << " is not in use.";
3119 return false;
3120 }
3121 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003122 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3123 channel, event, true, duration) == -1) {
3124 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003125 return false;
3126 }
3127 }
3128
3129 // Play the event.
3130 if (flags & cricket::DF_PLAY) {
3131 // Play DTMF tone locally.
3132 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3133 LOG_RTCERR2(PlayDtmfTone, event, duration);
3134 return false;
3135 }
3136 }
3137
3138 return true;
3139}
3140
wu@webrtc.orga9890802013-12-13 00:21:03 +00003141void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003142 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003143 // Pick which channel to send this packet to. If this packet doesn't match
3144 // any multiplexed streams, just send it to the default channel. Otherwise,
3145 // send it to the specific decoder instance for that stream.
3146 int which_channel = GetReceiveChannelNum(
3147 ParseSsrc(packet->data(), packet->length(), false));
3148 if (which_channel == -1) {
3149 which_channel = voe_channel();
3150 }
3151
3152 // Stop any ringback that might be playing on the channel.
3153 // It's possible the ringback has already stopped, ih which case we'll just
3154 // use the opportunity to remove the channel from ringback_channels_.
3155 if (engine()->voe()->file()) {
3156 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3157 if (it != ringback_channels_.end()) {
3158 if (engine()->voe()->file()->IsPlayingFileLocally(
3159 which_channel) == 1) {
3160 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3161 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3162 << " due to incoming media";
3163 }
3164 ringback_channels_.erase(which_channel);
3165 }
3166 }
3167
3168 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003169 engine()->voe()->network()->ReceivedRTPPacket(
3170 which_channel,
3171 packet->data(),
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003172 packet->length(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003173 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003174}
3175
wu@webrtc.orga9890802013-12-13 00:21:03 +00003176void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003177 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003178 // Sending channels need all RTCP packets with feedback information.
3179 // Even sender reports can contain attached report blocks.
3180 // Receiving channels need sender reports in order to create
3181 // correct receiver reports.
3182 int type = 0;
3183 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3184 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3185 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003186 }
3187
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003188 // If it is a sender report, find the channel that is listening.
3189 bool has_sent_to_default_channel = false;
3190 if (type == kRtcpTypeSR) {
3191 int which_channel = GetReceiveChannelNum(
3192 ParseSsrc(packet->data(), packet->length(), true));
3193 if (which_channel != -1) {
3194 engine()->voe()->network()->ReceivedRTCPPacket(
3195 which_channel,
3196 packet->data(),
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003197 packet->length());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003198
3199 if (IsDefaultChannel(which_channel))
3200 has_sent_to_default_channel = true;
3201 }
3202 }
3203
3204 // SR may continue RR and any RR entry may correspond to any one of the send
3205 // channels. So all RTCP packets must be forwarded all send channels. VoE
3206 // will filter out RR internally.
3207 for (ChannelMap::iterator iter = send_channels_.begin();
3208 iter != send_channels_.end(); ++iter) {
3209 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003210 if (IsDefaultChannel(iter->second->channel()) &&
3211 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003212 continue;
3213
3214 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003215 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003216 packet->data(),
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003217 packet->length());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003218 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003219}
3220
3221bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003222 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3223 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003224 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3225 return false;
3226 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003227 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3228 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003229 return false;
3230 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003231 // We set the AGC to mute state only when all the channels are muted.
3232 // This implementation is not ideal, instead we should signal the AGC when
3233 // the mic channel is muted/unmuted. We can't do it today because there
3234 // is no good way to know which stream is mapping to the mic channel.
3235 bool all_muted = muted;
3236 for (ChannelMap::const_iterator iter = send_channels_.begin();
3237 iter != send_channels_.end() && all_muted; ++iter) {
3238 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3239 all_muted)) {
3240 LOG_RTCERR1(GetInputMute, iter->second->channel());
3241 return false;
3242 }
3243 }
3244
3245 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3246 if (ap)
3247 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003248 return true;
3249}
3250
minyue@webrtc.org26236952014-10-29 02:27:08 +00003251// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3252// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003253bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003254 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003255
minyue@webrtc.org26236952014-10-29 02:27:08 +00003256 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003257}
3258
minyue@webrtc.org26236952014-10-29 02:27:08 +00003259bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3260 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003261
minyue@webrtc.org26236952014-10-29 02:27:08 +00003262 send_bitrate_setting_ = true;
3263 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003264
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003265 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003266 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003267 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003268 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003269 }
3270
minyue@webrtc.org26236952014-10-29 02:27:08 +00003271 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003272 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3273 // SetMaxSendBandwith(0), the second call removes the previous limit.
3274 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003275 return true;
3276
3277 webrtc::CodecInst codec = *send_codec_;
3278 bool is_multi_rate = IsCodecMultiRate(codec);
3279
3280 if (is_multi_rate) {
3281 // If codec is multi-rate then just set the bitrate.
3282 codec.rate = bps;
3283 if (!SetSendCodec(codec)) {
3284 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3285 << " to bitrate " << bps << " bps.";
3286 return false;
3287 }
3288 return true;
3289 } else {
3290 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3291 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3292 // fixed bitrate then ignore.
3293 if (bps < codec.rate) {
3294 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3295 << " to bitrate " << bps << " bps"
3296 << ", requires at least " << codec.rate << " bps.";
3297 return false;
3298 }
3299 return true;
3300 }
3301}
3302
3303bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003304 bool echo_metrics_on = false;
3305 // These can take on valid negative values, so use the lowest possible level
3306 // as default rather than -1.
3307 int echo_return_loss = -100;
3308 int echo_return_loss_enhancement = -100;
3309 // These can also be negative, but in practice -1 is only used to signal
3310 // insufficient data, since the resolution is limited to multiples of 4 ms.
3311 int echo_delay_median_ms = -1;
3312 int echo_delay_std_ms = -1;
3313 if (engine()->voe()->processing()->GetEcMetricsStatus(
3314 echo_metrics_on) != -1 && echo_metrics_on) {
3315 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3316 // here, but it appears to be unsuitable currently. Revisit after this is
3317 // investigated: http://b/issue?id=5666755
3318 int erl, erle, rerl, anlp;
3319 if (engine()->voe()->processing()->GetEchoMetrics(
3320 erl, erle, rerl, anlp) != -1) {
3321 echo_return_loss = erl;
3322 echo_return_loss_enhancement = erle;
3323 }
3324
3325 int median, std;
3326 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3327 echo_delay_median_ms = median;
3328 echo_delay_std_ms = std;
3329 }
3330 }
3331
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003332 webrtc::CallStatistics cs;
3333 unsigned int ssrc;
3334 webrtc::CodecInst codec;
3335 unsigned int level;
3336
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003337 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3338 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003339 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003340
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003341 // Fill in the sender info, based on what we know, and what the
3342 // remote side told us it got from its RTCP report.
3343 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003344
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003345 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3346 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3347 continue;
3348 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003349
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003350 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003351 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3352 sinfo.bytes_sent = cs.bytesSent;
3353 sinfo.packets_sent = cs.packetsSent;
3354 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3355 // returns 0 to indicate an error value.
3356 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3357
3358 // Get data from the last remote RTCP report. Use default values if no data
3359 // available.
3360 sinfo.fraction_lost = -1.0;
3361 sinfo.jitter_ms = -1;
3362 sinfo.packets_lost = -1;
3363 sinfo.ext_seqnum = -1;
3364 std::vector<webrtc::ReportBlock> receive_blocks;
3365 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3366 channel, &receive_blocks) != -1 &&
3367 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3368 std::vector<webrtc::ReportBlock>::iterator iter;
3369 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3370 ++iter) {
3371 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003372 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003373 // Convert Q8 to floating point.
3374 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3375 // Convert samples to milliseconds.
3376 if (codec.plfreq / 1000 > 0) {
3377 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3378 }
3379 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3380 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3381 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003382 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003383 }
3384 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003385
3386 // Local speech level.
3387 sinfo.audio_level = (engine()->voe()->volume()->
3388 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3389
3390 // TODO(xians): We are injecting the same APM logging to all the send
3391 // channels here because there is no good way to know which send channel
3392 // is using the APM. The correct fix is to allow the send channels to have
3393 // their own APM so that we can feed the correct APM logging to different
3394 // send channels. See issue crbug/264611 .
3395 sinfo.echo_return_loss = echo_return_loss;
3396 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3397 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3398 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003399 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3400 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003401 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003402
3403 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003404 }
3405
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003406 // Build the list of receivers, one for each receiving channel, or 1 in
3407 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003408 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003409 for (ChannelMap::const_iterator it = receive_channels_.begin();
3410 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003411 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003412 }
3413 if (channels.empty()) {
3414 channels.push_back(voe_channel());
3415 }
3416
3417 // Get the SSRC and stats for each receiver, based on our own calculations.
3418 for (std::vector<int>::const_iterator it = channels.begin();
3419 it != channels.end(); ++it) {
3420 memset(&cs, 0, sizeof(cs));
3421 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3422 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3423 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3424 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003425 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003426 rinfo.bytes_rcvd = cs.bytesReceived;
3427 rinfo.packets_rcvd = cs.packetsReceived;
3428 // The next four fields are from the most recently sent RTCP report.
3429 // Convert Q8 to floating point.
3430 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3431 rinfo.packets_lost = cs.cumulativeLost;
3432 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003433#ifdef USE_WEBRTC_DEV_BRANCH
3434 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
3435#endif
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003436 if (codec.pltype != -1) {
3437 rinfo.codec_name = codec.plname;
3438 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003439 // Convert samples to milliseconds.
3440 if (codec.plfreq / 1000 > 0) {
3441 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3442 }
3443
3444 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3445 webrtc::NetworkStatistics ns;
3446 if (engine()->voe()->neteq() &&
3447 engine()->voe()->neteq()->GetNetworkStatistics(
3448 *it, ns) != -1) {
3449 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3450 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3451 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003452 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003453 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003454
3455 webrtc::AudioDecodingCallStats ds;
3456 if (engine()->voe()->neteq() &&
3457 engine()->voe()->neteq()->GetDecodingCallStatistics(
3458 *it, &ds) != -1) {
3459 rinfo.decoding_calls_to_silence_generator =
3460 ds.calls_to_silence_generator;
3461 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3462 rinfo.decoding_normal = ds.decoded_normal;
3463 rinfo.decoding_plc = ds.decoded_plc;
3464 rinfo.decoding_cng = ds.decoded_cng;
3465 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3466 }
3467
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003468 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003469 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003470 int playout_buffer_delay_ms = 0;
3471 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003472 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3473 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3474 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003475 }
3476
3477 // Get speech level.
3478 rinfo.audio_level = (engine()->voe()->volume()->
3479 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3480 info->receivers.push_back(rinfo);
3481 }
3482 }
3483
3484 return true;
3485}
3486
3487void WebRtcVoiceMediaChannel::GetLastMediaError(
3488 uint32* ssrc, VoiceMediaChannel::Error* error) {
3489 ASSERT(ssrc != NULL);
3490 ASSERT(error != NULL);
3491 FindSsrc(voe_channel(), ssrc);
3492 *error = WebRtcErrorToChannelError(GetLastEngineError());
3493}
3494
3495bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003496 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003497 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003498 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003499 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3500 // This means the error is not limited to a specific channel. Signal the
3501 // message using ssrc=0. If the current channel is sending, use this
3502 // channel for sending the message.
3503 *ssrc = 0;
3504 return true;
3505 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003506 // Check whether this is a sending channel.
3507 for (ChannelMap::const_iterator it = send_channels_.begin();
3508 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003509 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003510 // This is a sending channel.
3511 uint32 local_ssrc = 0;
3512 if (engine()->voe()->rtp()->GetLocalSSRC(
3513 channel_num, local_ssrc) != -1) {
3514 *ssrc = local_ssrc;
3515 }
3516 return true;
3517 }
3518 }
3519
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003520 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003521 for (ChannelMap::const_iterator it = receive_channels_.begin();
3522 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003523 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003524 *ssrc = it->first;
3525 return true;
3526 }
3527 }
3528 }
3529 return false;
3530}
3531
3532void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003533 if (error == VE_TYPING_NOISE_WARNING) {
3534 typing_noise_detected_ = true;
3535 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3536 typing_noise_detected_ = false;
3537 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003538 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3539}
3540
3541int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3542 unsigned int ulevel;
3543 int ret =
3544 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3545 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3546}
3547
3548int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003549 ChannelMap::iterator it = receive_channels_.find(ssrc);
3550 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003551 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003552 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3553}
3554
3555int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003556 ChannelMap::iterator it = send_channels_.find(ssrc);
3557 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003558 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003559
3560 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003561}
3562
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003563bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
3564 webrtc::VideoEngine* vie, int vie_channel) {
3565 shared_bwe_vie_ = vie;
3566 shared_bwe_vie_channel_ = vie_channel;
3567
3568 if (!SetupSharedBweOnChannel(voe_channel())) {
3569 return false;
3570 }
3571 for (ChannelMap::iterator it = receive_channels_.begin();
3572 it != receive_channels_.end(); ++it) {
3573 if (!SetupSharedBweOnChannel(it->second->channel())) {
3574 return false;
3575 }
3576 }
3577 return true;
3578}
3579
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003580bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3581 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3582 // Get the RED encodings from the parameter with no name. This may
3583 // change based on what is discussed on the Jingle list.
3584 // The encoding parameter is of the form "a/b"; we only support where
3585 // a == b. Verify this and parse out the value into red_pt.
3586 // If the parameter value is absent (as it will be until we wire up the
3587 // signaling of this message), use the second codec specified (i.e. the
3588 // one after "red") as the encoding parameter.
3589 int red_pt = -1;
3590 std::string red_params;
3591 CodecParameterMap::const_iterator it = red_codec.params.find("");
3592 if (it != red_codec.params.end()) {
3593 red_params = it->second;
3594 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003595 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003596 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003597 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003598 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3599 return false;
3600 }
3601 } else if (red_codec.params.empty()) {
3602 LOG(LS_WARNING) << "RED params not present, using defaults";
3603 if (all_codecs.size() > 1) {
3604 red_pt = all_codecs[1].id;
3605 }
3606 }
3607
3608 // Try to find red_pt in |codecs|.
3609 std::vector<AudioCodec>::const_iterator codec;
3610 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3611 if (codec->id == red_pt)
3612 break;
3613 }
3614
3615 // If we find the right codec, that will be the codec we pass to
3616 // SetSendCodec, with the desired payload type.
3617 if (codec != all_codecs.end() &&
3618 engine()->FindWebRtcCodec(*codec, send_codec)) {
3619 } else {
3620 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3621 return false;
3622 }
3623
3624 return true;
3625}
3626
3627bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3628 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003629 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003630 return false;
3631 }
3632 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3633 // what we want to do with them.
3634 // engine()->voe().EnableVQMon(voe_channel(), true);
3635 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3636 return true;
3637}
3638
3639bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3640 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3641 for (int i = 0; i < ncodecs; ++i) {
3642 webrtc::CodecInst voe_codec;
3643 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3644 voe_codec.pltype = -1;
3645 if (engine()->voe()->codec()->SetRecPayloadType(
3646 channel, voe_codec) == -1) {
3647 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3648 return false;
3649 }
3650 }
3651 }
3652 return true;
3653}
3654
3655bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3656 if (playout) {
3657 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3658 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3659 LOG_RTCERR1(StartPlayout, channel);
3660 return false;
3661 }
3662 } else {
3663 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3664 engine()->voe()->base()->StopPlayout(channel);
3665 }
3666 return true;
3667}
3668
3669uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3670 bool rtcp) {
3671 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3672 uint32 ssrc = 0;
3673 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003674 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003675 }
3676 return ssrc;
3677}
3678
3679// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3680VoiceMediaChannel::Error
3681 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3682 switch (err_code) {
3683 case 0:
3684 return ERROR_NONE;
3685 case VE_CANNOT_START_RECORDING:
3686 case VE_MIC_VOL_ERROR:
3687 case VE_GET_MIC_VOL_ERROR:
3688 case VE_CANNOT_ACCESS_MIC_VOL:
3689 return ERROR_REC_DEVICE_OPEN_FAILED;
3690 case VE_SATURATION_WARNING:
3691 return ERROR_REC_DEVICE_SATURATION;
3692 case VE_REC_DEVICE_REMOVED:
3693 return ERROR_REC_DEVICE_REMOVED;
3694 case VE_RUNTIME_REC_WARNING:
3695 case VE_RUNTIME_REC_ERROR:
3696 return ERROR_REC_RUNTIME_ERROR;
3697 case VE_CANNOT_START_PLAYOUT:
3698 case VE_SPEAKER_VOL_ERROR:
3699 case VE_GET_SPEAKER_VOL_ERROR:
3700 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3701 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3702 case VE_RUNTIME_PLAY_WARNING:
3703 case VE_RUNTIME_PLAY_ERROR:
3704 return ERROR_PLAY_RUNTIME_ERROR;
3705 case VE_TYPING_NOISE_WARNING:
3706 return ERROR_REC_TYPING_NOISE_DETECTED;
3707 default:
3708 return VoiceMediaChannel::ERROR_OTHER;
3709 }
3710}
3711
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003712bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3713 int channel_id, const RtpHeaderExtension* extension) {
3714 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003715 int id = 0;
3716 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003717 if (extension) {
3718 enable = true;
3719 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003720 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003721 }
3722 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003723 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003724 return false;
3725 }
3726 return true;
3727}
3728
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003729bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
3730 webrtc::ViENetwork* vie_network = NULL;
3731 int vie_channel = -1;
3732 if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
3733 shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
3734 vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
3735 vie_channel = shared_bwe_vie_channel_;
3736 }
3737 if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
3738 vie_channel) == -1) {
3739 LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
3740 if (vie_network != NULL) {
3741 // Don't fail if we're tearing down.
3742 return false;
3743 }
3744 }
3745 return true;
3746}
3747
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003748int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003749 size_t res = 0;
3750 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003751 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003752}
3753
3754int WebRtcSoundclipStream::Rewind() {
3755 mem_.Rewind();
3756 // Return -1 to keep VoiceEngine from looping.
3757 return (loop_) ? 0 : -1;
3758}
3759
3760} // namespace cricket
3761
3762#endif // HAVE_WEBRTC_VOICE