blob: c335626dc229525da6b8435b945d96e13c7d1b23 [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
814 bool echo_cancellation;
815 if (options.echo_cancellation.Get(&echo_cancellation)) {
816 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
817 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
818 return false;
819 } else {
820 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
821 << " with mode " << ec_mode;
822 }
823#if !defined(ANDROID)
824 // TODO(ajm): Remove the error return on Android from webrtc.
825 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
826 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
827 return false;
828 }
829#endif
830 if (ec_mode == webrtc::kEcAecm) {
831 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
832 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
833 return false;
834 }
835 }
836 }
837
838 bool auto_gain_control;
839 if (options.auto_gain_control.Get(&auto_gain_control)) {
840 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
841 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
842 return false;
843 } else {
844 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
845 << " with mode " << agc_mode;
846 }
847 }
848
849 if (options.tx_agc_target_dbov.IsSet() ||
850 options.tx_agc_digital_compression_gain.IsSet() ||
851 options.tx_agc_limiter.IsSet()) {
852 // Override default_agc_config_. Generally, an unset option means "leave
853 // the VoE bits alone" in this function, so we want whatever is set to be
854 // stored as the new "default". If we didn't, then setting e.g.
855 // tx_agc_target_dbov would reset digital compression gain and limiter
856 // settings.
857 // Also, if we don't update default_agc_config_, then adjust_agc_delta
858 // would be an offset from the original values, and not whatever was set
859 // explicitly.
860 default_agc_config_.targetLeveldBOv =
861 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
862 default_agc_config_.targetLeveldBOv);
863 default_agc_config_.digitalCompressionGaindB =
864 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
865 default_agc_config_.digitalCompressionGaindB);
866 default_agc_config_.limiterEnable =
867 options.tx_agc_limiter.GetWithDefaultIfUnset(
868 default_agc_config_.limiterEnable);
869 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
870 LOG_RTCERR3(SetAgcConfig,
871 default_agc_config_.targetLeveldBOv,
872 default_agc_config_.digitalCompressionGaindB,
873 default_agc_config_.limiterEnable);
874 return false;
875 }
876 }
877
878 bool noise_suppression;
879 if (options.noise_suppression.Get(&noise_suppression)) {
880 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
881 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
882 return false;
883 } else {
884 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
885 << " with mode " << ns_mode;
886 }
887 }
888
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000889 bool highpass_filter;
890 if (options.highpass_filter.Get(&highpass_filter)) {
891 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
892 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
893 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
894 return false;
895 }
896 }
897
898 bool stereo_swapping;
899 if (options.stereo_swapping.Get(&stereo_swapping)) {
900 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
901 voep->EnableStereoChannelSwapping(stereo_swapping);
902 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
903 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
904 return false;
905 }
906 }
907
908 bool typing_detection;
909 if (options.typing_detection.Get(&typing_detection)) {
910 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
911 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
912 // In case of error, log the info and continue
913 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
914 }
915 }
916
917 int adjust_agc_delta;
918 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
919 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
920 if (!AdjustAgcLevel(adjust_agc_delta)) {
921 return false;
922 }
923 }
924
925 bool aec_dump;
926 if (options.aec_dump.Get(&aec_dump)) {
927 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
928 if (aec_dump)
929 StartAecDump(kAecDumpByAudioOptionFilename);
930 else
931 StopAecDump();
932 }
933
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000934 webrtc::Config config;
935
936 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000937 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000938 if (experimental_aec_.Get(&experimental_aec)) {
939 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
940 config.Set<webrtc::DelayCorrection>(
941 new webrtc::DelayCorrection(experimental_aec));
942 }
943
944#ifdef USE_WEBRTC_DEV_BRANCH
945 experimental_ns_.SetFrom(options.experimental_ns);
946 bool experimental_ns;
947 if (experimental_ns_.Get(&experimental_ns)) {
948 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
949 config.Set<webrtc::ExperimentalNs>(
950 new webrtc::ExperimentalNs(experimental_ns));
951 }
952#endif
953
954 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
955 // returns NULL on audio_processing().
956 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
957 if (audioproc) {
958 audioproc->SetExtraOptions(config);
959 }
960
961#ifndef USE_WEBRTC_DEV_BRANCH
962 bool experimental_ns;
963 if (options.experimental_ns.Get(&experimental_ns)) {
964 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000965 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
966 // returns NULL on audio_processing().
967 if (audioproc) {
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000968 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
969 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
970 return false;
971 }
972 } else {
973 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
974 << experimental_ns;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000975 }
976 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000977#endif
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000978
979 uint32 recording_sample_rate;
980 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
981 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
982 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
983 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
984 }
985 }
986
987 uint32 playout_sample_rate;
988 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
989 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
990 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
991 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
992 }
993 }
994
995 return true;
996}
997
998bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
999 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
1000 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
1001 LOG_RTCERR1(SetDelayOffsetMs, offset);
1002 return false;
1003 }
1004
1005 return true;
1006}
1007
1008struct ResumeEntry {
1009 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
1010 : channel(c),
1011 playout(p),
1012 send(s) {
1013 }
1014
1015 WebRtcVoiceMediaChannel *channel;
1016 bool playout;
1017 SendFlags send;
1018};
1019
1020// TODO(juberti): Refactor this so that the core logic can be used to set the
1021// soundclip device. At that time, reinstate the soundclip pause/resume code.
1022bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
1023 const Device* out_device) {
1024#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001025 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001026 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001027 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001028 kDefaultAudioDeviceId;
1029 // The device manager uses -1 as the default device, which was the case for
1030 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
1031#ifndef WIN32
1032 if (-1 == in_id) {
1033 in_id = kDefaultAudioDeviceId;
1034 }
1035 if (-1 == out_id) {
1036 out_id = kDefaultAudioDeviceId;
1037 }
1038#endif
1039
1040 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
1041 in_device->name : "Default device";
1042 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
1043 out_device->name : "Default device";
1044 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
1045 << ") and speaker to (id=" << out_id << ", name=" << out_name
1046 << ")";
1047
1048 // If we're running the local monitor, we need to stop it first.
1049 bool ret = true;
1050 if (!PauseLocalMonitor()) {
1051 LOG(LS_WARNING) << "Failed to pause local monitor";
1052 ret = false;
1053 }
1054
1055 // Must also pause all audio playback and capture.
1056 for (ChannelList::const_iterator i = channels_.begin();
1057 i != channels_.end(); ++i) {
1058 WebRtcVoiceMediaChannel *channel = *i;
1059 if (!channel->PausePlayout()) {
1060 LOG(LS_WARNING) << "Failed to pause playout";
1061 ret = false;
1062 }
1063 if (!channel->PauseSend()) {
1064 LOG(LS_WARNING) << "Failed to pause send";
1065 ret = false;
1066 }
1067 }
1068
1069 // Find the recording device id in VoiceEngine and set recording device.
1070 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1071 ret = false;
1072 }
1073 if (ret) {
1074 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
1075 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
1076 ret = false;
1077 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00001078 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
1079 if (ap)
1080 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001081 }
1082
1083 // Find the playout device id in VoiceEngine and set playout device.
1084 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1085 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1086 ret = false;
1087 }
1088 if (ret) {
1089 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001090 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091 ret = false;
1092 }
1093 }
1094
1095 // Resume all audio playback and capture.
1096 for (ChannelList::const_iterator i = channels_.begin();
1097 i != channels_.end(); ++i) {
1098 WebRtcVoiceMediaChannel *channel = *i;
1099 if (!channel->ResumePlayout()) {
1100 LOG(LS_WARNING) << "Failed to resume playout";
1101 ret = false;
1102 }
1103 if (!channel->ResumeSend()) {
1104 LOG(LS_WARNING) << "Failed to resume send";
1105 ret = false;
1106 }
1107 }
1108
1109 // Resume local monitor.
1110 if (!ResumeLocalMonitor()) {
1111 LOG(LS_WARNING) << "Failed to resume local monitor";
1112 ret = false;
1113 }
1114
1115 if (ret) {
1116 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1117 << ") and speaker to (id="<< out_id << " name=" << out_name
1118 << ")";
1119 }
1120
1121 return ret;
1122#else
1123 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001124#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001125}
1126
1127bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1128 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1129 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001130#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001131 *rtc_id = dev_id;
1132 return true;
1133#else
1134 // In Windows and Mac, we need to find the VoiceEngine device id by name
1135 // unless the input dev_id is the default device id.
1136 if (kDefaultAudioDeviceId == dev_id) {
1137 *rtc_id = dev_id;
1138 return true;
1139 }
1140
1141 // Get the number of VoiceEngine audio devices.
1142 int count = 0;
1143 if (is_input) {
1144 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1145 LOG_RTCERR0(GetNumOfRecordingDevices);
1146 return false;
1147 }
1148 } else {
1149 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1150 LOG_RTCERR0(GetNumOfPlayoutDevices);
1151 return false;
1152 }
1153 }
1154
1155 for (int i = 0; i < count; ++i) {
1156 char name[128];
1157 char guid[128];
1158 if (is_input) {
1159 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1160 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1161 } else {
1162 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1163 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1164 }
1165
1166 std::string webrtc_name(name);
1167 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1168 *rtc_id = i;
1169 return true;
1170 }
1171 }
1172 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1173 return false;
1174#endif
1175}
1176
1177bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1178 unsigned int ulevel;
1179 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1180 LOG_RTCERR1(GetSpeakerVolume, level);
1181 return false;
1182 }
1183 *level = ulevel;
1184 return true;
1185}
1186
1187bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1188 ASSERT(level >= 0 && level <= 255);
1189 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1190 LOG_RTCERR1(SetSpeakerVolume, level);
1191 return false;
1192 }
1193 return true;
1194}
1195
1196int WebRtcVoiceEngine::GetInputLevel() {
1197 unsigned int ulevel;
1198 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1199 static_cast<int>(ulevel) : -1;
1200}
1201
1202bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1203 desired_local_monitor_enable_ = enable;
1204 return ChangeLocalMonitor(desired_local_monitor_enable_);
1205}
1206
1207bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1208 // The voe file api is not available in chrome.
1209 if (!voe_wrapper_->file()) {
1210 return false;
1211 }
1212 if (enable && !monitor_) {
1213 monitor_.reset(new WebRtcMonitorStream);
1214 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1215 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1216 // Must call Stop() because there are some cases where Start will report
1217 // failure but still change the state, and if we leave VE in the on state
1218 // then it could crash later when trying to invoke methods on our monitor.
1219 voe_wrapper_->file()->StopRecordingMicrophone();
1220 monitor_.reset();
1221 return false;
1222 }
1223 } else if (!enable && monitor_) {
1224 voe_wrapper_->file()->StopRecordingMicrophone();
1225 monitor_.reset();
1226 }
1227 return true;
1228}
1229
1230bool WebRtcVoiceEngine::PauseLocalMonitor() {
1231 return ChangeLocalMonitor(false);
1232}
1233
1234bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1235 return ChangeLocalMonitor(desired_local_monitor_enable_);
1236}
1237
1238const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1239 return codecs_;
1240}
1241
1242bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1243 return FindWebRtcCodec(in, NULL);
1244}
1245
1246// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1247bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1248 webrtc::CodecInst* out) {
1249 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1250 for (int i = 0; i < ncodecs; ++i) {
1251 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001252 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001253 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1254 voe_codec.rate, voe_codec.channels, 0);
1255 bool multi_rate = IsCodecMultiRate(voe_codec);
1256 // Allow arbitrary rates for ISAC to be specified.
1257 if (multi_rate) {
1258 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1259 codec.bitrate = 0;
1260 }
1261 if (codec.Matches(in)) {
1262 if (out) {
1263 // Fixup the payload type.
1264 voe_codec.pltype = in.id;
1265
1266 // Set bitrate if specified.
1267 if (multi_rate && in.bitrate != 0) {
1268 voe_codec.rate = in.bitrate;
1269 }
1270
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001271 // Reset G722 sample rate to 16000 to match WebRTC.
1272 MaybeFixupG722(&voe_codec, 16000);
1273
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001274 // Apply codec-specific settings.
1275 if (IsIsac(codec)) {
1276 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001277 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001278 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1279 }
1280 *out = voe_codec;
1281 }
1282 return true;
1283 }
1284 }
1285 }
1286 return false;
1287}
1288const std::vector<RtpHeaderExtension>&
1289WebRtcVoiceEngine::rtp_header_extensions() const {
1290 return rtp_header_extensions_;
1291}
1292
1293void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1294 // if min_sev == -1, we keep the current log level.
1295 if (min_sev >= 0) {
1296 SetTraceFilter(SeverityToFilter(min_sev));
1297 }
1298 log_options_ = filter;
1299 SetTraceOptions(initialized_ ? log_options_ : "");
1300}
1301
1302int WebRtcVoiceEngine::GetLastEngineError() {
1303 return voe_wrapper_->error();
1304}
1305
1306void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1307 log_filter_ = filter;
1308 tracing_->SetTraceFilter(filter);
1309}
1310
1311// We suppport three different logging settings for VoiceEngine:
1312// 1. Observer callback that goes into talk diagnostic logfile.
1313// Use --logfile and --loglevel
1314//
1315// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1316// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1317//
1318// 3. EC log and dump for debugging QualityEngine.
1319// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1320//
1321// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1322// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1323void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1324 // Set encrypted trace file.
1325 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001326 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001327 std::vector<std::string>::iterator tracefile =
1328 std::find(opts.begin(), opts.end(), "tracefile");
1329 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1330 // Write encrypted debug output (at same loglevel) to file
1331 // EncryptedTraceFile no longer supported.
1332 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1333 LOG_RTCERR1(SetTraceFile, *tracefile);
1334 }
1335 }
1336
wu@webrtc.org97077a32013-10-25 21:18:33 +00001337 // Allow trace options to override the trace filter. We default
1338 // it to log_filter_ (as a translation of libjingle log levels)
1339 // elsewhere, but this allows clients to explicitly set webrtc
1340 // log levels.
1341 std::vector<std::string>::iterator tracefilter =
1342 std::find(opts.begin(), opts.end(), "tracefilter");
1343 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001344 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001345 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1346 }
1347 }
1348
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349 // Set AEC dump file
1350 std::vector<std::string>::iterator recordEC =
1351 std::find(opts.begin(), opts.end(), "recordEC");
1352 if (recordEC != opts.end()) {
1353 ++recordEC;
1354 if (recordEC != opts.end())
1355 StartAecDump(recordEC->c_str());
1356 else
1357 StopAecDump();
1358 }
1359}
1360
1361// Ignore spammy trace messages, mostly from the stats API when we haven't
1362// gotten RTCP info yet from the remote side.
1363bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1364 static const char* kTracesToIgnore[] = {
1365 "\tfailed to GetReportBlockInformation",
1366 "GetRecCodec() failed to get received codec",
1367 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1368 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1369 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1370 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1371 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1372 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1373 "SenderInfoReceived No received SR",
1374 "StatisticsRTP() no statistics available",
1375 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1376 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1377 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1378 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1379 NULL
1380 };
1381 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1382 if (trace.find(*p) != std::string::npos) {
1383 return true;
1384 }
1385 }
1386 return false;
1387}
1388
1389void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1390 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001391 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001393 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001394 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001395 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001396 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001397 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001398 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001399 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001400
1401 // Skip past boilerplate prefix text
1402 if (length < 72) {
1403 std::string msg(trace, length);
1404 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1405 LOG_V(sev) << msg;
1406 } else {
1407 std::string msg(trace + 71, length - 72);
1408 if (!ShouldIgnoreTrace(msg)) {
1409 LOG_V(sev) << "webrtc: " << msg;
1410 }
1411 }
1412}
1413
1414void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001415 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001416 WebRtcVoiceMediaChannel* channel = NULL;
1417 uint32 ssrc = 0;
1418 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1419 << channel_num << ".";
1420 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1421 ASSERT(channel != NULL);
1422 channel->OnError(ssrc, err_code);
1423 } else {
1424 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1425 << " could not be found in channel list when error reported.";
1426 }
1427}
1428
1429bool WebRtcVoiceEngine::FindChannelAndSsrc(
1430 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1431 ASSERT(channel != NULL && ssrc != NULL);
1432
1433 *channel = NULL;
1434 *ssrc = 0;
1435 // Find corresponding channel and ssrc
1436 for (ChannelList::const_iterator it = channels_.begin();
1437 it != channels_.end(); ++it) {
1438 ASSERT(*it != NULL);
1439 if ((*it)->FindSsrc(channel_num, ssrc)) {
1440 *channel = *it;
1441 return true;
1442 }
1443 }
1444
1445 return false;
1446}
1447
1448// This method will search through the WebRtcVoiceMediaChannels and
1449// obtain the voice engine's channel number.
1450bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1451 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1452 ASSERT(channel_num != NULL);
1453 ASSERT(direction == MPD_RX || direction == MPD_TX);
1454
1455 *channel_num = -1;
1456 // Find corresponding channel for ssrc.
1457 for (ChannelList::const_iterator it = channels_.begin();
1458 it != channels_.end(); ++it) {
1459 ASSERT(*it != NULL);
1460 if (direction & MPD_RX) {
1461 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1462 }
1463 if (*channel_num == -1 && (direction & MPD_TX)) {
1464 *channel_num = (*it)->GetSendChannelNum(ssrc);
1465 }
1466 if (*channel_num != -1) {
1467 return true;
1468 }
1469 }
1470 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1471 return false;
1472}
1473
1474void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001475 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001476 channels_.push_back(channel);
1477}
1478
1479void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001480 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001481 ChannelList::iterator i = std::find(channels_.begin(),
1482 channels_.end(),
1483 channel);
1484 if (i != channels_.end()) {
1485 channels_.erase(i);
1486 }
1487}
1488
1489void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1490 soundclips_.push_back(soundclip);
1491}
1492
1493void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1494 SoundclipList::iterator i = std::find(soundclips_.begin(),
1495 soundclips_.end(),
1496 soundclip);
1497 if (i != soundclips_.end()) {
1498 soundclips_.erase(i);
1499 }
1500}
1501
1502// Adjusts the default AGC target level by the specified delta.
1503// NB: If we start messing with other config fields, we'll want
1504// to save the current webrtc::AgcConfig as well.
1505bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1506 webrtc::AgcConfig config = default_agc_config_;
1507 config.targetLeveldBOv -= delta;
1508
1509 LOG(LS_INFO) << "Adjusting AGC level from default -"
1510 << default_agc_config_.targetLeveldBOv << "dB to -"
1511 << config.targetLeveldBOv << "dB";
1512
1513 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1514 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1515 return false;
1516 }
1517 return true;
1518}
1519
1520bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1521 webrtc::AudioDeviceModule* adm_sc) {
1522 if (initialized_) {
1523 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1524 return false;
1525 }
1526 if (adm_) {
1527 adm_->Release();
1528 adm_ = NULL;
1529 }
1530 if (adm) {
1531 adm_ = adm;
1532 adm_->AddRef();
1533 }
1534
1535 if (adm_sc_) {
1536 adm_sc_->Release();
1537 adm_sc_ = NULL;
1538 }
1539 if (adm_sc) {
1540 adm_sc_ = adm_sc;
1541 adm_sc_->AddRef();
1542 }
1543 return true;
1544}
1545
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001546bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1547 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001548 if (!aec_dump_file_stream) {
1549 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001550 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001551 LOG(LS_WARNING) << "Could not close file.";
1552 return false;
1553 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001554 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001555 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001556 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001557 LOG_RTCERR0(StartDebugRecording);
1558 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001559 return false;
1560 }
1561 is_dumping_aec_ = true;
1562 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001563}
1564
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001565bool WebRtcVoiceEngine::RegisterProcessor(
1566 uint32 ssrc,
1567 VoiceProcessor* voice_processor,
1568 MediaProcessorDirection direction) {
1569 bool register_with_webrtc = false;
1570 int channel_id = -1;
1571 bool success = false;
1572 uint32* processor_ssrc = NULL;
1573 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1574 if (voice_processor == NULL || !found_channel) {
1575 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1576 << " foundChannel: " << found_channel;
1577 return false;
1578 }
1579
1580 webrtc::ProcessingTypes processing_type;
1581 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001582 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001583 if (direction == MPD_RX) {
1584 processing_type = webrtc::kPlaybackAllChannelsMixed;
1585 if (SignalRxMediaFrame.is_empty()) {
1586 register_with_webrtc = true;
1587 processor_ssrc = &rx_processor_ssrc_;
1588 }
1589 SignalRxMediaFrame.connect(voice_processor,
1590 &VoiceProcessor::OnFrame);
1591 } else {
1592 processing_type = webrtc::kRecordingPerChannel;
1593 if (SignalTxMediaFrame.is_empty()) {
1594 register_with_webrtc = true;
1595 processor_ssrc = &tx_processor_ssrc_;
1596 }
1597 SignalTxMediaFrame.connect(voice_processor,
1598 &VoiceProcessor::OnFrame);
1599 }
1600 }
1601 if (register_with_webrtc) {
1602 // TODO(janahan): when registering consider instantiating a
1603 // a VoeMediaProcess object and not make the engine extend the interface.
1604 if (voe()->media() && voe()->media()->
1605 RegisterExternalMediaProcessing(channel_id,
1606 processing_type,
1607 *this) != -1) {
1608 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1609 << channel_id;
1610 *processor_ssrc = ssrc;
1611 success = true;
1612 } else {
1613 LOG_RTCERR2(RegisterExternalMediaProcessing,
1614 channel_id,
1615 processing_type);
1616 success = false;
1617 }
1618 } else {
1619 // If we don't have to register with the engine, we just needed to
1620 // connect a new processor, set success to true;
1621 success = true;
1622 }
1623 return success;
1624}
1625
1626bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1627 MediaProcessorDirection channel_direction,
1628 uint32 ssrc,
1629 VoiceProcessor* voice_processor,
1630 MediaProcessorDirection processor_direction) {
1631 bool success = true;
1632 FrameSignal* signal;
1633 webrtc::ProcessingTypes processing_type;
1634 uint32* processor_ssrc = NULL;
1635 if (channel_direction == MPD_RX) {
1636 signal = &SignalRxMediaFrame;
1637 processing_type = webrtc::kPlaybackAllChannelsMixed;
1638 processor_ssrc = &rx_processor_ssrc_;
1639 } else {
1640 signal = &SignalTxMediaFrame;
1641 processing_type = webrtc::kRecordingPerChannel;
1642 processor_ssrc = &tx_processor_ssrc_;
1643 }
1644
1645 int deregister_id = -1;
1646 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001647 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001648 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1649 signal->disconnect(voice_processor);
1650 int channel_id = -1;
1651 bool found_channel = FindChannelNumFromSsrc(ssrc,
1652 channel_direction,
1653 &channel_id);
1654 if (signal->is_empty() && found_channel) {
1655 deregister_id = channel_id;
1656 }
1657 }
1658 }
1659 if (deregister_id != -1) {
1660 if (voe()->media() &&
1661 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1662 processing_type) != -1) {
1663 *processor_ssrc = 0;
1664 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1665 << deregister_id;
1666 } else {
1667 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1668 deregister_id,
1669 processing_type);
1670 success = false;
1671 }
1672 }
1673 return success;
1674}
1675
1676bool WebRtcVoiceEngine::UnregisterProcessor(
1677 uint32 ssrc,
1678 VoiceProcessor* voice_processor,
1679 MediaProcessorDirection direction) {
1680 bool success = true;
1681 if (voice_processor == NULL) {
1682 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1683 << ssrc;
1684 return false;
1685 }
1686 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1687 success = false;
1688 }
1689 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1690 success = false;
1691 }
1692 return success;
1693}
1694
1695// Implementing method from WebRtc VoEMediaProcess interface
1696// Do not lock mux_channel_cs_ in this callback.
1697void WebRtcVoiceEngine::Process(int channel,
1698 webrtc::ProcessingTypes type,
1699 int16_t audio10ms[],
1700 int length,
1701 int sampling_freq,
1702 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001703 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001704 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1705 if (type == webrtc::kPlaybackAllChannelsMixed) {
1706 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1707 } else if (type == webrtc::kRecordingPerChannel) {
1708 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1709 } else {
1710 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1711 << " channel: " << channel << " type: " << type
1712 << " tx_ssrc: " << tx_processor_ssrc_
1713 << " rx_ssrc: " << rx_processor_ssrc_;
1714 }
1715}
1716
1717void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1718 if (!is_dumping_aec_) {
1719 // Start dumping AEC when we are not dumping.
1720 if (voe_wrapper_->processing()->StartDebugRecording(
1721 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001722 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001723 } else {
1724 is_dumping_aec_ = true;
1725 }
1726 }
1727}
1728
1729void WebRtcVoiceEngine::StopAecDump() {
1730 if (is_dumping_aec_) {
1731 // Stop dumping AEC when we are dumping.
1732 if (voe_wrapper_->processing()->StopDebugRecording() !=
1733 webrtc::AudioProcessing::kNoError) {
1734 LOG_RTCERR0(StopDebugRecording);
1735 }
1736 is_dumping_aec_ = false;
1737 }
1738}
1739
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001740int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001741 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001742}
1743
1744int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1745 return CreateVoiceChannel(voe_wrapper_.get());
1746}
1747
1748int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1749 return CreateVoiceChannel(voe_wrapper_sc_.get());
1750}
1751
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001752class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1753 : public AudioRenderer::Sink {
1754 public:
1755 WebRtcVoiceChannelRenderer(int ch,
1756 webrtc::AudioTransport* voe_audio_transport)
1757 : channel_(ch),
1758 voe_audio_transport_(voe_audio_transport),
1759 renderer_(NULL) {
1760 }
1761 virtual ~WebRtcVoiceChannelRenderer() {
1762 Stop();
1763 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001764
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001765 // Starts the rendering by setting a sink to the renderer to get data
1766 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001767 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001768 // TODO(xians): Make sure Start() is called only once.
1769 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001770 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001771 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001772 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001773 ASSERT(renderer_ == renderer);
1774 return;
1775 }
1776
1777 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1778 // in getUserMedia by default.
1779 renderer->AddChannel(channel_);
1780 renderer->SetSink(this);
1781 renderer_ = renderer;
1782 }
1783
1784 // Stops rendering by setting the sink of the renderer to NULL. No data
1785 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001786 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001787 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001788 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001789 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001790 return;
1791
1792 renderer_->RemoveChannel(channel_);
1793 renderer_->SetSink(NULL);
1794 renderer_ = NULL;
1795 }
1796
1797 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001798 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001799 virtual void OnData(const void* audio_data,
1800 int bits_per_sample,
1801 int sample_rate,
1802 int number_of_channels,
1803 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001804 voe_audio_transport_->OnData(channel_,
1805 audio_data,
1806 bits_per_sample,
1807 sample_rate,
1808 number_of_channels,
1809 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001810 }
1811
1812 // Callback from the |renderer_| when it is going away. In case Start() has
1813 // never been called, this callback won't be triggered.
1814 virtual void OnClose() OVERRIDE {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001815 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001816 // Set |renderer_| to NULL to make sure no more callback will get into
1817 // the renderer.
1818 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001819 }
1820
1821 // Accessor to the VoE channel ID.
1822 int channel() const { return channel_; }
1823
1824 private:
1825 const int channel_;
1826 webrtc::AudioTransport* const voe_audio_transport_;
1827
1828 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1829 // PeerConnection will make sure invalidating the pointer before the object
1830 // goes away.
1831 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001832
1833 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001834 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001835};
1836
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001837// WebRtcVoiceMediaChannel
1838WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1839 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1840 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001841 engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001842 send_bitrate_setting_(false),
1843 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001844 options_(),
1845 dtmf_allowed_(false),
1846 desired_playout_(false),
1847 nack_enabled_(false),
1848 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001849 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001850 desired_send_(SEND_NOTHING),
1851 send_(SEND_NOTHING),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001852 shared_bwe_vie_(NULL),
1853 shared_bwe_vie_channel_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001854 default_receive_ssrc_(0) {
1855 engine->RegisterChannel(this);
1856 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1857 << voe_channel();
1858
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001859 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001860}
1861
1862WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1863 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1864 << voe_channel();
buildbot@webrtc.org6e5c7842014-09-19 06:46:37 +00001865 SetupSharedBandwidthEstimation(NULL, -1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001866
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001867 // Remove any remaining send streams, the default channel will be deleted
1868 // later.
1869 while (!send_channels_.empty())
1870 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001871
1872 // Unregister ourselves from the engine.
1873 engine()->UnregisterChannel(this);
1874 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001875 while (!receive_channels_.empty()) {
1876 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001877 }
1878
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001879 // Delete the default channel.
1880 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001881}
1882
1883bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1884 LOG(LS_INFO) << "Setting voice channel options: "
1885 << options.ToString();
1886
wu@webrtc.orgde305012013-10-31 15:40:38 +00001887 // Check if DSCP value is changed from previous.
1888 bool dscp_option_changed = (options_.dscp != options.dscp);
1889
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001890 // TODO(xians): Add support to set different options for different send
1891 // streams after we support multiple APMs.
1892
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001893 // We retain all of the existing options, and apply the given ones
1894 // on top. This means there is no way to "clear" options such that
1895 // they go back to the engine default.
1896 options_.SetAll(options);
1897
1898 if (send_ != SEND_NOTHING) {
1899 if (!engine()->SetOptionOverrides(options_)) {
1900 LOG(LS_WARNING) <<
1901 "Failed to engine SetOptionOverrides during channel SetOptions.";
1902 return false;
1903 }
1904 } else {
1905 // Will be interpreted when appropriate.
1906 }
1907
wu@webrtc.org97077a32013-10-25 21:18:33 +00001908 // Receiver-side auto gain control happens per channel, so set it here from
1909 // options. Note that, like conference mode, setting it on the engine won't
1910 // have the desired effect, since voice channels don't inherit options from
1911 // the media engine when those options are applied per-channel.
1912 bool rx_auto_gain_control;
1913 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1914 if (engine()->voe()->processing()->SetRxAgcStatus(
1915 voe_channel(), rx_auto_gain_control,
1916 webrtc::kAgcFixedDigital) == -1) {
1917 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1918 return false;
1919 } else {
1920 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1921 << " with mode " << webrtc::kAgcFixedDigital;
1922 }
1923 }
1924 if (options.rx_agc_target_dbov.IsSet() ||
1925 options.rx_agc_digital_compression_gain.IsSet() ||
1926 options.rx_agc_limiter.IsSet()) {
1927 webrtc::AgcConfig config;
1928 // If only some of the options are being overridden, get the current
1929 // settings for the channel and bail if they aren't available.
1930 if (!options.rx_agc_target_dbov.IsSet() ||
1931 !options.rx_agc_digital_compression_gain.IsSet() ||
1932 !options.rx_agc_limiter.IsSet()) {
1933 if (engine()->voe()->processing()->GetRxAgcConfig(
1934 voe_channel(), config) != 0) {
1935 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1936 << "channel " << voe_channel() << ". Since not all rx "
1937 << "agc options are specified, unable to safely set rx "
1938 << "agc options.";
1939 return false;
1940 }
1941 }
1942 config.targetLeveldBOv =
1943 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1944 config.targetLeveldBOv);
1945 config.digitalCompressionGaindB =
1946 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1947 config.digitalCompressionGaindB);
1948 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1949 config.limiterEnable);
1950 if (engine()->voe()->processing()->SetRxAgcConfig(
1951 voe_channel(), config) == -1) {
1952 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1953 config.digitalCompressionGaindB, config.limiterEnable);
1954 return false;
1955 }
1956 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001957 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001958 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001959 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001960 dscp = kAudioDscpValue;
1961 if (MediaChannel::SetDscp(dscp) != 0) {
1962 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1963 }
1964 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001965
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001966 // Force update of Video Engine BWE forwarding to reflect experiment setting.
1967 if (!SetupSharedBandwidthEstimation(shared_bwe_vie_,
1968 shared_bwe_vie_channel_)) {
1969 return false;
1970 }
1971
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001972 LOG(LS_INFO) << "Set voice channel options. Current options: "
1973 << options_.ToString();
1974 return true;
1975}
1976
1977bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1978 const std::vector<AudioCodec>& codecs) {
1979 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001980 LOG(LS_INFO) << "Setting receive voice codecs:";
1981
1982 std::vector<AudioCodec> new_codecs;
1983 // Find all new codecs. We allow adding new codecs but don't allow changing
1984 // the payload type of codecs that is already configured since we might
1985 // already be receiving packets with that payload type.
1986 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001987 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001988 AudioCodec old_codec;
1989 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1990 if (old_codec.id != it->id) {
1991 LOG(LS_ERROR) << it->name << " payload type changed.";
1992 return false;
1993 }
1994 } else {
1995 new_codecs.push_back(*it);
1996 }
1997 }
1998 if (new_codecs.empty()) {
1999 // There are no new codecs to configure. Already configured codecs are
2000 // never removed.
2001 return true;
2002 }
2003
2004 if (playout_) {
2005 // Receive codecs can not be changed while playing. So we temporarily
2006 // pause playout.
2007 PausePlayout();
2008 }
2009
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002010 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002011 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
2012 it != new_codecs.end() && ret; ++it) {
2013 webrtc::CodecInst voe_codec;
2014 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2015 LOG(LS_INFO) << ToString(*it);
2016 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002017 if (default_receive_ssrc_ == 0) {
2018 // Set the receive codecs on the default channel explicitly if the
2019 // default channel is not used by |receive_channels_|, this happens in
2020 // conference mode or in non-conference mode when there is no playout
2021 // channel.
2022 // TODO(xians): Figure out how we use the default channel in conference
2023 // mode.
2024 if (engine()->voe()->codec()->SetRecPayloadType(
2025 voe_channel(), voe_codec) == -1) {
2026 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
2027 ret = false;
2028 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002029 }
2030
2031 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002032 for (ChannelMap::iterator it = receive_channels_.begin();
2033 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002034 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002035 it->second->channel(), voe_codec) == -1) {
2036 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002037 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002038 ret = false;
2039 }
2040 }
2041 } else {
2042 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2043 ret = false;
2044 }
2045 }
2046 if (ret) {
2047 recv_codecs_ = codecs;
2048 }
2049
2050 if (desired_playout_ && !playout_) {
2051 ResumePlayout();
2052 }
2053 return ret;
2054}
2055
2056bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002057 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002058 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002059 engine()->voe()->codec()->SetVADStatus(channel, false);
2060 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002061#ifdef USE_WEBRTC_DEV_BRANCH
2062 engine()->voe()->rtp()->SetREDStatus(channel, false);
2063 engine()->voe()->codec()->SetFECStatus(channel, false);
2064#else
2065 // TODO(minyue): Remove code under #else case after new WebRTC roll.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002066 engine()->voe()->rtp()->SetFECStatus(channel, false);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002067#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002068
2069 // Scan through the list to figure out the codec to use for sending, along
2070 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002071 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002072 webrtc::CodecInst send_codec;
2073 memset(&send_codec, 0, sizeof(send_codec));
2074
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002075 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002076 bool enable_codec_fec = false;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002077
minyue@webrtc.org26236952014-10-29 02:27:08 +00002078 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002079
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002080 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002081 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2082 it != codecs.end(); ++it) {
2083 // Ignore codecs we don't know about. The negotiation step should prevent
2084 // this, but double-check to be sure.
2085 webrtc::CodecInst voe_codec;
2086 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002087 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002088 continue;
2089 }
2090
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002091 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2092 // Skip telephone-event/CN codec, which will be handled later.
2093 continue;
2094 }
2095
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002096 // We'll use the first codec in the list to actually send audio data.
2097 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002098 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002099 // used is specified in params.
2100 if (IsRedCodec(it->name)) {
2101 // Parse out the RED parameters. If we fail, just ignore RED;
2102 // we don't support all possible params/usage scenarios.
2103 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2104 continue;
2105 }
2106
2107 // Enable redundant encoding of the specified codec. Treat any
2108 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002109#ifdef USE_WEBRTC_DEV_BRANCH
2110 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2111 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2112 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
2113#else
2114 // TODO(minyue): Remove code under #else case after new WebRTC roll.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002115 LOG(LS_INFO) << "Enabling FEC";
2116 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2117 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002118#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002119 return false;
2120 }
2121 } else {
2122 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002123 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002124 // For Opus as the send codec, we are to enable inband FEC if requested
2125 // and set maximum playback rate.
2126 if (IsOpus(*it)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002127 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
2128 &opus_max_playback_rate);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002129 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002130 }
2131 found_send_codec = true;
2132 break;
2133 }
2134
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002135 if (nack_enabled_ != nack_enabled) {
2136 SetNack(channel, nack_enabled);
2137 nack_enabled_ = nack_enabled;
2138 }
2139
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002140 if (!found_send_codec) {
2141 LOG(LS_WARNING) << "Received empty list of codecs.";
2142 return false;
2143 }
2144
2145 // Set the codec immediately, since SetVADStatus() depends on whether
2146 // the current codec is mono or stereo.
2147 if (!SetSendCodec(channel, send_codec))
2148 return false;
2149
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002150 // FEC should be enabled after SetSendCodec.
2151 if (enable_codec_fec) {
2152 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2153 << channel;
2154#ifdef USE_WEBRTC_DEV_BRANCH
2155 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2156 // Enable codec internal FEC. Treat any failure as fatal internal error.
2157 LOG_RTCERR2(SetFECStatus, channel, true);
2158 return false;
2159 }
2160#endif // USE_WEBRTC_DEV_BRANCH
2161 }
2162
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002163 // maxplaybackrate should be set after SetSendCodec.
minyue@webrtc.org26236952014-10-29 02:27:08 +00002164 // If opus_max_playback_rate <= 0, the default maximum playback rate of 48 kHz
2165 // will be used.
2166 if (opus_max_playback_rate > 0) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002167 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002168 << opus_max_playback_rate
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002169 << " Hz on channel "
2170 << channel;
2171#ifdef USE_WEBRTC_DEV_BRANCH
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002172 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
minyue@webrtc.org26236952014-10-29 02:27:08 +00002173 channel, opus_max_playback_rate) == -1) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002174 LOG(LS_WARNING) << "Could not set maximum playback rate.";
2175 }
2176#endif
2177 }
2178
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002179 // Always update the |send_codec_| to the currently set send codec.
2180 send_codec_.reset(new webrtc::CodecInst(send_codec));
2181
minyue@webrtc.org26236952014-10-29 02:27:08 +00002182 if (send_bitrate_setting_) {
2183 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002184 }
2185
2186 // Loop through the codecs list again to config the telephone-event/CN codec.
2187 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2188 it != codecs.end(); ++it) {
2189 // Ignore codecs we don't know about. The negotiation step should prevent
2190 // this, but double-check to be sure.
2191 webrtc::CodecInst voe_codec;
2192 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2193 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2194 continue;
2195 }
2196
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002197 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2198 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002199 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002200 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2201 channel, it->id) == -1) {
2202 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2203 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002204 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002205 } else if (IsCNCodec(it->name)) {
2206 // Turn voice activity detection/comfort noise on if supported.
2207 // Set the wideband CN payload type appropriately.
2208 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002209 webrtc::PayloadFrequencies cn_freq;
2210 switch (it->clockrate) {
2211 case 8000:
2212 cn_freq = webrtc::kFreq8000Hz;
2213 break;
2214 case 16000:
2215 cn_freq = webrtc::kFreq16000Hz;
2216 break;
2217 case 32000:
2218 cn_freq = webrtc::kFreq32000Hz;
2219 break;
2220 default:
2221 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2222 << " not supported.";
2223 continue;
2224 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002225 // Set the CN payloadtype and the VAD status.
2226 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2227 if (cn_freq != webrtc::kFreq8000Hz) {
2228 if (engine()->voe()->codec()->SetSendCNPayloadType(
2229 channel, it->id, cn_freq) == -1) {
2230 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2231 // TODO(ajm): This failure condition will be removed from VoE.
2232 // Restore the return here when we update to a new enough webrtc.
2233 //
2234 // Not returning false because the SetSendCNPayloadType will fail if
2235 // the channel is already sending.
2236 // This can happen if the remote description is applied twice, for
2237 // example in the case of ROAP on top of JSEP, where both side will
2238 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002239 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002240 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002241 // Only turn on VAD if we have a CN payload type that matches the
2242 // clockrate for the codec we are going to use.
2243 if (it->clockrate == send_codec.plfreq) {
2244 LOG(LS_INFO) << "Enabling VAD";
2245 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2246 LOG_RTCERR2(SetVADStatus, channel, true);
2247 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002248 }
2249 }
2250 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002251 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002252 return true;
2253}
2254
2255bool WebRtcVoiceMediaChannel::SetSendCodecs(
2256 const std::vector<AudioCodec>& codecs) {
2257 dtmf_allowed_ = false;
2258 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2259 it != codecs.end(); ++it) {
2260 // Find the DTMF telephone event "codec".
2261 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2262 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2263 dtmf_allowed_ = true;
2264 }
2265 }
2266
2267 // Cache the codecs in order to configure the channel created later.
2268 send_codecs_ = codecs;
2269 for (ChannelMap::iterator iter = send_channels_.begin();
2270 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002271 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002272 return false;
2273 }
2274 }
2275
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002276 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002277 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002278 return true;
2279}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002280
2281void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2282 bool nack_enabled) {
2283 for (ChannelMap::const_iterator it = channels.begin();
2284 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002285 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002286 }
2287}
2288
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002289void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002290 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002291 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002292 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2293 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002294 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002295 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2296 }
2297}
2298
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002299bool WebRtcVoiceMediaChannel::SetSendCodec(
2300 const webrtc::CodecInst& send_codec) {
2301 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2302 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002303 for (ChannelMap::iterator iter = send_channels_.begin();
2304 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002305 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002306 return false;
2307 }
2308
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002309 return true;
2310}
2311
2312bool WebRtcVoiceMediaChannel::SetSendCodec(
2313 int channel, const webrtc::CodecInst& send_codec) {
2314 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2315 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2316
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002317 webrtc::CodecInst current_codec;
2318 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2319 (send_codec == current_codec)) {
2320 // Codec is already configured, we can return without setting it again.
2321 return true;
2322 }
2323
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002324 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2325 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002326 return false;
2327 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002328 return true;
2329}
2330
2331bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2332 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002333 if (receive_extensions_ == extensions) {
2334 return true;
2335 }
2336
2337 // The default channel may or may not be in |receive_channels_|. Set the rtp
2338 // header extensions for default channel regardless.
2339 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2340 return false;
2341 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002342
2343 // Loop through all receive channels and enable/disable the extensions.
2344 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2345 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002346 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2347 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002348 return false;
2349 }
2350 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002351
2352 receive_extensions_ = extensions;
2353 return true;
2354}
2355
2356bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2357 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002358 const RtpHeaderExtension* audio_level_extension =
2359 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2360 if (!SetHeaderExtension(
2361 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2362 audio_level_extension)) {
2363 return false;
2364 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002365
2366 const RtpHeaderExtension* send_time_extension =
2367 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2368 if (!SetHeaderExtension(
2369 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2370 send_time_extension)) {
2371 return false;
2372 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002373 return true;
2374}
2375
2376bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2377 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002378 if (send_extensions_ == extensions) {
2379 return true;
2380 }
2381
2382 // The default channel may or may not be in |send_channels_|. Set the rtp
2383 // header extensions for default channel regardless.
2384
2385 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2386 return false;
2387 }
2388
2389 // Loop through all send channels and enable/disable the extensions.
2390 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2391 channel_it != send_channels_.end(); ++channel_it) {
2392 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2393 extensions)) {
2394 return false;
2395 }
2396 }
2397
2398 send_extensions_ = extensions;
2399 return true;
2400}
2401
2402bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2403 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002404 const RtpHeaderExtension* audio_level_extension =
2405 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002406
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002407 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002408 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002409 audio_level_extension)) {
2410 return false;
2411 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002412
2413 const RtpHeaderExtension* send_time_extension =
2414 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002415 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002416 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002417 send_time_extension)) {
2418 return false;
2419 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002420
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002421 return true;
2422}
2423
2424bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2425 desired_playout_ = playout;
2426 return ChangePlayout(desired_playout_);
2427}
2428
2429bool WebRtcVoiceMediaChannel::PausePlayout() {
2430 return ChangePlayout(false);
2431}
2432
2433bool WebRtcVoiceMediaChannel::ResumePlayout() {
2434 return ChangePlayout(desired_playout_);
2435}
2436
2437bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2438 if (playout_ == playout) {
2439 return true;
2440 }
2441
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002442 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002443 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002444 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002445 // Only toggle the default channel if we don't have any other channels.
2446 result = SetPlayout(voe_channel(), playout);
2447 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002448 for (ChannelMap::iterator it = receive_channels_.begin();
2449 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002450 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002451 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002452 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002453 result = false;
2454 }
2455 }
2456
2457 if (result) {
2458 playout_ = playout;
2459 }
2460 return result;
2461}
2462
2463bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2464 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002465 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002466 return ChangeSend(desired_send_);
2467 return true;
2468}
2469
2470bool WebRtcVoiceMediaChannel::PauseSend() {
2471 return ChangeSend(SEND_NOTHING);
2472}
2473
2474bool WebRtcVoiceMediaChannel::ResumeSend() {
2475 return ChangeSend(desired_send_);
2476}
2477
2478bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2479 if (send_ == send) {
2480 return true;
2481 }
2482
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002483 // Change the settings on each send channel.
2484 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002485 engine()->SetOptionOverrides(options_);
2486
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002487 // Change the settings on each send channel.
2488 for (ChannelMap::iterator iter = send_channels_.begin();
2489 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002490 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002491 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002492 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002493
2494 // Clear up the options after stopping sending.
2495 if (send == SEND_NOTHING)
2496 engine()->ClearOptionOverrides();
2497
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002498 send_ = send;
2499 return true;
2500}
2501
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002502bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2503 if (send == SEND_MICROPHONE) {
2504 if (engine()->voe()->base()->StartSend(channel) == -1) {
2505 LOG_RTCERR1(StartSend, channel);
2506 return false;
2507 }
2508 if (engine()->voe()->file() &&
2509 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2510 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2511 return false;
2512 }
2513 } else { // SEND_NOTHING
2514 ASSERT(send == SEND_NOTHING);
2515 if (engine()->voe()->base()->StopSend(channel) == -1) {
2516 LOG_RTCERR1(StopSend, channel);
2517 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002518 }
2519 }
2520
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002521 return true;
2522}
2523
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002524// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002525void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2526 if (engine()->voe()->network()->RegisterExternalTransport(
2527 channel, *this) == -1) {
2528 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2529 }
2530
2531 // Enable RTCP (for quality stats and feedback messages)
2532 EnableRtcp(channel);
2533
2534 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2535 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002536
2537 // Set RTP header extension for the new channel.
2538 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002539}
2540
2541bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2542 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2543 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2544 }
2545
2546 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2547 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002548 return false;
2549 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002550
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002551 return true;
2552}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002553
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002554bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2555 // If the default channel is already used for sending create a new channel
2556 // otherwise use the default channel for sending.
2557 int channel = GetSendChannelNum(sp.first_ssrc());
2558 if (channel != -1) {
2559 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2560 return false;
2561 }
2562
2563 bool default_channel_is_available = true;
2564 for (ChannelMap::const_iterator iter = send_channels_.begin();
2565 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002566 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002567 default_channel_is_available = false;
2568 break;
2569 }
2570 }
2571 if (default_channel_is_available) {
2572 channel = voe_channel();
2573 } else {
2574 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002575 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002576 if (channel == -1) {
2577 LOG_RTCERR0(CreateChannel);
2578 return false;
2579 }
2580
2581 ConfigureSendChannel(channel);
2582 }
2583
2584 // Save the channel to send_channels_, so that RemoveSendStream() can still
2585 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002586 webrtc::AudioTransport* audio_transport =
2587 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002588 send_channels_.insert(std::make_pair(
2589 sp.first_ssrc(),
2590 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002591
2592 // Set the send (local) SSRC.
2593 // If there are multiple send SSRCs, we can only set the first one here, and
2594 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2595 // (with a codec requires multiple SSRC(s)).
2596 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2597 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2598 return false;
2599 }
2600
2601 // At this point the channel's local SSRC has been updated. If the channel is
2602 // the default channel make sure that all the receive channels are updated as
2603 // well. Receive channels have to have the same SSRC as the default channel in
2604 // order to send receiver reports with this SSRC.
2605 if (IsDefaultChannel(channel)) {
2606 for (ChannelMap::const_iterator it = receive_channels_.begin();
2607 it != receive_channels_.end(); ++it) {
2608 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002609 if (!IsDefaultChannel(it->second->channel())) {
2610 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002611 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002612 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002613 return false;
2614 }
2615 }
2616 }
2617 }
2618
2619 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002620 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2621 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002622 }
2623
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002624 // Set the current codecs to be used for the new channel.
2625 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002626 return false;
2627
2628 return ChangeSend(channel, desired_send_);
2629}
2630
2631bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2632 ChannelMap::iterator it = send_channels_.find(ssrc);
2633 if (it == send_channels_.end()) {
2634 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2635 << " which doesn't exist.";
2636 return false;
2637 }
2638
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002639 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002640 ChangeSend(channel, SEND_NOTHING);
2641
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002642 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2643 // this will disconnect the audio renderer with the send channel.
2644 delete it->second;
2645 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002646
2647 if (IsDefaultChannel(channel)) {
2648 // Do not delete the default channel since the receive channels depend on
2649 // the default channel, recycle it instead.
2650 ChangeSend(channel, SEND_NOTHING);
2651 } else {
2652 // Clean up and delete the send channel.
2653 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2654 << " with VoiceEngine channel #" << channel << ".";
2655 if (!DeleteChannel(channel))
2656 return false;
2657 }
2658
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002659 if (send_channels_.empty())
2660 ChangeSend(SEND_NOTHING);
2661
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002662 return true;
2663}
2664
2665bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002666 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002667
2668 if (!VERIFY(sp.ssrcs.size() == 1))
2669 return false;
2670 uint32 ssrc = sp.first_ssrc();
2671
wu@webrtc.org78187522013-10-07 23:32:02 +00002672 if (ssrc == 0) {
2673 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2674 return false;
2675 }
2676
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002677 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2678 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002679 return false;
2680 }
2681
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002682 // Reuse default channel for recv stream in non-conference mode call
2683 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002684 webrtc::AudioTransport* audio_transport =
2685 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002686 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2687 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2688 << " reuse default channel";
2689 default_receive_ssrc_ = sp.first_ssrc();
2690 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002691 default_receive_ssrc_,
2692 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002693 if (!SetupSharedBweOnChannel(voe_channel())) {
2694 return false;
2695 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002696 return SetPlayout(voe_channel(), playout_);
2697 }
2698
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002699 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002700 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002701 if (channel == -1) {
2702 LOG_RTCERR0(CreateChannel);
2703 return false;
2704 }
2705
wu@webrtc.org78187522013-10-07 23:32:02 +00002706 if (!ConfigureRecvChannel(channel)) {
2707 DeleteChannel(channel);
2708 return false;
2709 }
2710
2711 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002712 std::make_pair(
2713 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002714
2715 LOG(LS_INFO) << "New audio stream " << ssrc
2716 << " registered to VoiceEngine channel #"
2717 << channel << ".";
2718 return true;
2719}
2720
2721bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002722 // Configure to use external transport, like our default channel.
2723 if (engine()->voe()->network()->RegisterExternalTransport(
2724 channel, *this) == -1) {
2725 LOG_RTCERR2(SetExternalTransport, channel, this);
2726 return false;
2727 }
2728
2729 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002730 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002731 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2732 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002733 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002734 return false;
2735 }
2736 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002737 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002738 return false;
2739 }
2740
2741 // Use the same recv payload types as our default channel.
2742 ResetRecvCodecs(channel);
2743 if (!recv_codecs_.empty()) {
2744 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2745 it != recv_codecs_.end(); ++it) {
2746 webrtc::CodecInst voe_codec;
2747 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2748 voe_codec.pltype = it->id;
2749 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2750 if (engine()->voe()->codec()->GetRecPayloadType(
2751 voe_channel(), voe_codec) != -1) {
2752 if (engine()->voe()->codec()->SetRecPayloadType(
2753 channel, voe_codec) == -1) {
2754 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2755 return false;
2756 }
2757 }
2758 }
2759 }
2760 }
2761
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002762 if (InConferenceMode()) {
2763 // To be in par with the video, voe_channel() is not used for receiving in
2764 // a conference call.
2765 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2766 // This is the first stream in a multi user meeting. We can now
2767 // disable playback of the default stream. This since the default
2768 // stream will probably have received some initial packets before
2769 // the new stream was added. This will mean that the CN state from
2770 // the default channel will be mixed in with the other streams
2771 // throughout the whole meeting, which might be disturbing.
2772 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2773 SetPlayout(voe_channel(), false);
2774 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002775 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002776 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002777
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002778 // Set RTP header extension for the new channel.
2779 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2780 return false;
2781 }
2782
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002783 // Set up channel to be able to forward incoming packets to video engine BWE.
2784 if (!SetupSharedBweOnChannel(channel)) {
2785 return false;
2786 }
2787
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002788 return SetPlayout(channel, playout_);
2789}
2790
2791bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002792 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002793 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002794 if (it == receive_channels_.end()) {
2795 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2796 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002797 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002798 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002799
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002800 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2801 // will disconnect the audio renderer with the receive channel.
2802 // Cache the channel before the deletion.
2803 const int channel = it->second->channel();
2804 delete it->second;
2805 receive_channels_.erase(it);
2806
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002807 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002808 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002809 // Recycle the default channel is for recv stream.
2810 if (playout_)
2811 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002812
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002813 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002814 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002815 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002816
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002817 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002818 << " with VoiceEngine channel #" << channel << ".";
2819 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002820 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002821
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002822 bool enable_default_channel_playout = false;
2823 if (receive_channels_.empty()) {
2824 // The last stream was removed. We can now enable the default
2825 // channel for new channels to be played out immediately without
2826 // waiting for AddStream messages.
2827 // We do this for both conference mode and non-conference mode.
2828 // TODO(oja): Does the default channel still have it's CN state?
2829 enable_default_channel_playout = true;
2830 }
2831 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2832 default_receive_ssrc_ != 0) {
2833 // Only the default channel is active, enable the playout on default
2834 // channel.
2835 enable_default_channel_playout = true;
2836 }
2837 if (enable_default_channel_playout && playout_) {
2838 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2839 SetPlayout(voe_channel(), true);
2840 }
2841
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002842 return true;
2843}
2844
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002845bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2846 AudioRenderer* renderer) {
2847 ChannelMap::iterator it = receive_channels_.find(ssrc);
2848 if (it == receive_channels_.end()) {
2849 if (renderer) {
2850 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002851 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002852 return false;
2853 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002854
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002855 // The channel likely has gone away, do nothing.
2856 return true;
2857 }
2858
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002859 if (renderer)
2860 it->second->Start(renderer);
2861 else
2862 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002863
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002864 return true;
2865}
2866
2867bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2868 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002869 ChannelMap::iterator it = send_channels_.find(ssrc);
2870 if (it == send_channels_.end()) {
2871 if (renderer) {
2872 // Return an error if trying to set a valid renderer with an invalid ssrc.
2873 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2874 return false;
2875 }
2876
2877 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002878 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002879 }
2880
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002881 if (renderer)
2882 it->second->Start(renderer);
2883 else
2884 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002885
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002886 return true;
2887}
2888
2889bool WebRtcVoiceMediaChannel::GetActiveStreams(
2890 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002891 // In conference mode, the default channel should not be in
2892 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002893 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002894 for (ChannelMap::iterator it = receive_channels_.begin();
2895 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002896 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002897 if (level > 0) {
2898 actives->push_back(std::make_pair(it->first, level));
2899 }
2900 }
2901 return true;
2902}
2903
2904int WebRtcVoiceMediaChannel::GetOutputLevel() {
2905 // return the highest output level of all streams
2906 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002907 for (ChannelMap::iterator it = receive_channels_.begin();
2908 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002909 int level = GetOutputLevel(it->second->channel());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002910 highest = rtc::_max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002911 }
2912 return highest;
2913}
2914
2915int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2916 int ret;
2917 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2918 // In case of error, log the info and continue
2919 LOG_RTCERR0(TimeSinceLastTyping);
2920 ret = -1;
2921 } else {
2922 ret *= 1000; // We return ms, webrtc returns seconds.
2923 }
2924 return ret;
2925}
2926
2927void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2928 int cost_per_typing, int reporting_threshold, int penalty_decay,
2929 int type_event_delay) {
2930 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2931 time_window, cost_per_typing,
2932 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2933 // In case of error, log the info and continue
2934 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2935 cost_per_typing, reporting_threshold, penalty_decay,
2936 type_event_delay);
2937 }
2938}
2939
2940bool WebRtcVoiceMediaChannel::SetOutputScaling(
2941 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002942 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002943 // Collect the channels to scale the output volume.
2944 std::vector<int> channels;
2945 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002946 // Default channel is not in receive_channels_ if it is not being used for
2947 // playout.
2948 if (default_receive_ssrc_ == 0)
2949 channels.push_back(voe_channel());
2950 for (ChannelMap::const_iterator it = receive_channels_.begin();
2951 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002952 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002953 }
2954 } else { // Collect only the channel of the specified ssrc.
2955 int channel = GetReceiveChannelNum(ssrc);
2956 if (-1 == channel) {
2957 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2958 return false;
2959 }
2960 channels.push_back(channel);
2961 }
2962
2963 // Scale the output volume for the collected channels. We first normalize to
2964 // scale the volume and then set the left and right pan.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002965 float scale = static_cast<float>(rtc::_max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002966 if (scale > 0.0001f) {
2967 left /= scale;
2968 right /= scale;
2969 }
2970 for (std::vector<int>::const_iterator it = channels.begin();
2971 it != channels.end(); ++it) {
2972 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2973 *it, scale)) {
2974 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2975 return false;
2976 }
2977 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2978 *it, static_cast<float>(left), static_cast<float>(right))) {
2979 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2980 // Do not return if fails. SetOutputVolumePan is not available for all
2981 // pltforms.
2982 }
2983 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2984 << " right=" << right * scale
2985 << " for channel " << *it << " and ssrc " << ssrc;
2986 }
2987 return true;
2988}
2989
2990bool WebRtcVoiceMediaChannel::GetOutputScaling(
2991 uint32 ssrc, double* left, double* right) {
2992 if (!left || !right) return false;
2993
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002994 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002995 // Determine which channel based on ssrc.
2996 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2997 if (channel == -1) {
2998 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2999 return false;
3000 }
3001
3002 float scaling;
3003 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
3004 channel, scaling)) {
3005 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
3006 return false;
3007 }
3008
3009 float left_pan;
3010 float right_pan;
3011 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
3012 channel, left_pan, right_pan)) {
3013 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
3014 // If GetOutputVolumePan fails, we use the default left and right pan.
3015 left_pan = 1.0f;
3016 right_pan = 1.0f;
3017 }
3018
3019 *left = scaling * left_pan;
3020 *right = scaling * right_pan;
3021 return true;
3022}
3023
3024bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
3025 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
3026 return true;
3027}
3028
3029bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
3030 bool play, bool loop) {
3031 if (!ringback_tone_) {
3032 return false;
3033 }
3034
3035 // The voe file api is not available in chrome.
3036 if (!engine()->voe()->file()) {
3037 return false;
3038 }
3039
3040 // Determine which VoiceEngine channel to play on.
3041 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
3042 if (channel == -1) {
3043 return false;
3044 }
3045
3046 // Make sure the ringtone is cued properly, and play it out.
3047 if (play) {
3048 ringback_tone_->set_loop(loop);
3049 ringback_tone_->Rewind();
3050 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
3051 ringback_tone_.get()) == -1) {
3052 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
3053 LOG(LS_ERROR) << "Unable to start ringback tone";
3054 return false;
3055 }
3056 ringback_channels_.insert(channel);
3057 LOG(LS_INFO) << "Started ringback on channel " << channel;
3058 } else {
3059 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
3060 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
3061 LOG_RTCERR1(StopPlayingFileLocally, channel);
3062 return false;
3063 }
3064 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
3065 ringback_channels_.erase(channel);
3066 }
3067
3068 return true;
3069}
3070
3071bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3072 return dtmf_allowed_;
3073}
3074
3075bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3076 int duration, int flags) {
3077 if (!dtmf_allowed_) {
3078 return false;
3079 }
3080
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003081 // Send the event.
3082 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003083 int channel = -1;
3084 if (ssrc == 0) {
3085 bool default_channel_is_inuse = false;
3086 for (ChannelMap::const_iterator iter = send_channels_.begin();
3087 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003088 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003089 default_channel_is_inuse = true;
3090 break;
3091 }
3092 }
3093 if (default_channel_is_inuse) {
3094 channel = voe_channel();
3095 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003096 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003097 }
3098 } else {
3099 channel = GetSendChannelNum(ssrc);
3100 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003101 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003102 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3103 << ssrc << " is not in use.";
3104 return false;
3105 }
3106 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003107 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3108 channel, event, true, duration) == -1) {
3109 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003110 return false;
3111 }
3112 }
3113
3114 // Play the event.
3115 if (flags & cricket::DF_PLAY) {
3116 // Play DTMF tone locally.
3117 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3118 LOG_RTCERR2(PlayDtmfTone, event, duration);
3119 return false;
3120 }
3121 }
3122
3123 return true;
3124}
3125
wu@webrtc.orga9890802013-12-13 00:21:03 +00003126void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003127 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003128 // Pick which channel to send this packet to. If this packet doesn't match
3129 // any multiplexed streams, just send it to the default channel. Otherwise,
3130 // send it to the specific decoder instance for that stream.
3131 int which_channel = GetReceiveChannelNum(
3132 ParseSsrc(packet->data(), packet->length(), false));
3133 if (which_channel == -1) {
3134 which_channel = voe_channel();
3135 }
3136
3137 // Stop any ringback that might be playing on the channel.
3138 // It's possible the ringback has already stopped, ih which case we'll just
3139 // use the opportunity to remove the channel from ringback_channels_.
3140 if (engine()->voe()->file()) {
3141 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3142 if (it != ringback_channels_.end()) {
3143 if (engine()->voe()->file()->IsPlayingFileLocally(
3144 which_channel) == 1) {
3145 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3146 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3147 << " due to incoming media";
3148 }
3149 ringback_channels_.erase(which_channel);
3150 }
3151 }
3152
3153 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003154 engine()->voe()->network()->ReceivedRTPPacket(
3155 which_channel,
3156 packet->data(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003157 static_cast<unsigned int>(packet->length()),
3158 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003159}
3160
wu@webrtc.orga9890802013-12-13 00:21:03 +00003161void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003162 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003163 // Sending channels need all RTCP packets with feedback information.
3164 // Even sender reports can contain attached report blocks.
3165 // Receiving channels need sender reports in order to create
3166 // correct receiver reports.
3167 int type = 0;
3168 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3169 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3170 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003171 }
3172
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003173 // If it is a sender report, find the channel that is listening.
3174 bool has_sent_to_default_channel = false;
3175 if (type == kRtcpTypeSR) {
3176 int which_channel = GetReceiveChannelNum(
3177 ParseSsrc(packet->data(), packet->length(), true));
3178 if (which_channel != -1) {
3179 engine()->voe()->network()->ReceivedRTCPPacket(
3180 which_channel,
3181 packet->data(),
3182 static_cast<unsigned int>(packet->length()));
3183
3184 if (IsDefaultChannel(which_channel))
3185 has_sent_to_default_channel = true;
3186 }
3187 }
3188
3189 // SR may continue RR and any RR entry may correspond to any one of the send
3190 // channels. So all RTCP packets must be forwarded all send channels. VoE
3191 // will filter out RR internally.
3192 for (ChannelMap::iterator iter = send_channels_.begin();
3193 iter != send_channels_.end(); ++iter) {
3194 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003195 if (IsDefaultChannel(iter->second->channel()) &&
3196 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003197 continue;
3198
3199 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003200 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003201 packet->data(),
3202 static_cast<unsigned int>(packet->length()));
3203 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003204}
3205
3206bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003207 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3208 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003209 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3210 return false;
3211 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003212 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3213 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003214 return false;
3215 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003216 // We set the AGC to mute state only when all the channels are muted.
3217 // This implementation is not ideal, instead we should signal the AGC when
3218 // the mic channel is muted/unmuted. We can't do it today because there
3219 // is no good way to know which stream is mapping to the mic channel.
3220 bool all_muted = muted;
3221 for (ChannelMap::const_iterator iter = send_channels_.begin();
3222 iter != send_channels_.end() && all_muted; ++iter) {
3223 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3224 all_muted)) {
3225 LOG_RTCERR1(GetInputMute, iter->second->channel());
3226 return false;
3227 }
3228 }
3229
3230 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3231 if (ap)
3232 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003233 return true;
3234}
3235
minyue@webrtc.org26236952014-10-29 02:27:08 +00003236// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3237// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003238bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003239 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003240
minyue@webrtc.org26236952014-10-29 02:27:08 +00003241 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003242}
3243
minyue@webrtc.org26236952014-10-29 02:27:08 +00003244bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3245 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003246
minyue@webrtc.org26236952014-10-29 02:27:08 +00003247 send_bitrate_setting_ = true;
3248 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003249
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003250 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003251 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003252 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003253 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003254 }
3255
minyue@webrtc.org26236952014-10-29 02:27:08 +00003256 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003257 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3258 // SetMaxSendBandwith(0), the second call removes the previous limit.
3259 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003260 return true;
3261
3262 webrtc::CodecInst codec = *send_codec_;
3263 bool is_multi_rate = IsCodecMultiRate(codec);
3264
3265 if (is_multi_rate) {
3266 // If codec is multi-rate then just set the bitrate.
3267 codec.rate = bps;
3268 if (!SetSendCodec(codec)) {
3269 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3270 << " to bitrate " << bps << " bps.";
3271 return false;
3272 }
3273 return true;
3274 } else {
3275 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3276 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3277 // fixed bitrate then ignore.
3278 if (bps < codec.rate) {
3279 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3280 << " to bitrate " << bps << " bps"
3281 << ", requires at least " << codec.rate << " bps.";
3282 return false;
3283 }
3284 return true;
3285 }
3286}
3287
3288bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003289 bool echo_metrics_on = false;
3290 // These can take on valid negative values, so use the lowest possible level
3291 // as default rather than -1.
3292 int echo_return_loss = -100;
3293 int echo_return_loss_enhancement = -100;
3294 // These can also be negative, but in practice -1 is only used to signal
3295 // insufficient data, since the resolution is limited to multiples of 4 ms.
3296 int echo_delay_median_ms = -1;
3297 int echo_delay_std_ms = -1;
3298 if (engine()->voe()->processing()->GetEcMetricsStatus(
3299 echo_metrics_on) != -1 && echo_metrics_on) {
3300 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3301 // here, but it appears to be unsuitable currently. Revisit after this is
3302 // investigated: http://b/issue?id=5666755
3303 int erl, erle, rerl, anlp;
3304 if (engine()->voe()->processing()->GetEchoMetrics(
3305 erl, erle, rerl, anlp) != -1) {
3306 echo_return_loss = erl;
3307 echo_return_loss_enhancement = erle;
3308 }
3309
3310 int median, std;
3311 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3312 echo_delay_median_ms = median;
3313 echo_delay_std_ms = std;
3314 }
3315 }
3316
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003317 webrtc::CallStatistics cs;
3318 unsigned int ssrc;
3319 webrtc::CodecInst codec;
3320 unsigned int level;
3321
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003322 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3323 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003324 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003325
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003326 // Fill in the sender info, based on what we know, and what the
3327 // remote side told us it got from its RTCP report.
3328 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003329
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003330 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3331 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3332 continue;
3333 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003334
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003335 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003336 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3337 sinfo.bytes_sent = cs.bytesSent;
3338 sinfo.packets_sent = cs.packetsSent;
3339 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3340 // returns 0 to indicate an error value.
3341 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3342
3343 // Get data from the last remote RTCP report. Use default values if no data
3344 // available.
3345 sinfo.fraction_lost = -1.0;
3346 sinfo.jitter_ms = -1;
3347 sinfo.packets_lost = -1;
3348 sinfo.ext_seqnum = -1;
3349 std::vector<webrtc::ReportBlock> receive_blocks;
3350 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3351 channel, &receive_blocks) != -1 &&
3352 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3353 std::vector<webrtc::ReportBlock>::iterator iter;
3354 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3355 ++iter) {
3356 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003357 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003358 // Convert Q8 to floating point.
3359 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3360 // Convert samples to milliseconds.
3361 if (codec.plfreq / 1000 > 0) {
3362 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3363 }
3364 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3365 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3366 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003367 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003368 }
3369 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003370
3371 // Local speech level.
3372 sinfo.audio_level = (engine()->voe()->volume()->
3373 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3374
3375 // TODO(xians): We are injecting the same APM logging to all the send
3376 // channels here because there is no good way to know which send channel
3377 // is using the APM. The correct fix is to allow the send channels to have
3378 // their own APM so that we can feed the correct APM logging to different
3379 // send channels. See issue crbug/264611 .
3380 sinfo.echo_return_loss = echo_return_loss;
3381 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3382 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3383 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003384 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3385 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003386 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003387
3388 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003389 }
3390
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003391 // Build the list of receivers, one for each receiving channel, or 1 in
3392 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003393 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003394 for (ChannelMap::const_iterator it = receive_channels_.begin();
3395 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003396 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003397 }
3398 if (channels.empty()) {
3399 channels.push_back(voe_channel());
3400 }
3401
3402 // Get the SSRC and stats for each receiver, based on our own calculations.
3403 for (std::vector<int>::const_iterator it = channels.begin();
3404 it != channels.end(); ++it) {
3405 memset(&cs, 0, sizeof(cs));
3406 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3407 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3408 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3409 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003410 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003411 rinfo.bytes_rcvd = cs.bytesReceived;
3412 rinfo.packets_rcvd = cs.packetsReceived;
3413 // The next four fields are from the most recently sent RTCP report.
3414 // Convert Q8 to floating point.
3415 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3416 rinfo.packets_lost = cs.cumulativeLost;
3417 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003418#ifdef USE_WEBRTC_DEV_BRANCH
3419 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
3420#endif
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003421 if (codec.pltype != -1) {
3422 rinfo.codec_name = codec.plname;
3423 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003424 // Convert samples to milliseconds.
3425 if (codec.plfreq / 1000 > 0) {
3426 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3427 }
3428
3429 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3430 webrtc::NetworkStatistics ns;
3431 if (engine()->voe()->neteq() &&
3432 engine()->voe()->neteq()->GetNetworkStatistics(
3433 *it, ns) != -1) {
3434 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3435 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3436 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003437 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003438 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003439
3440 webrtc::AudioDecodingCallStats ds;
3441 if (engine()->voe()->neteq() &&
3442 engine()->voe()->neteq()->GetDecodingCallStatistics(
3443 *it, &ds) != -1) {
3444 rinfo.decoding_calls_to_silence_generator =
3445 ds.calls_to_silence_generator;
3446 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3447 rinfo.decoding_normal = ds.decoded_normal;
3448 rinfo.decoding_plc = ds.decoded_plc;
3449 rinfo.decoding_cng = ds.decoded_cng;
3450 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3451 }
3452
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003453 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003454 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003455 int playout_buffer_delay_ms = 0;
3456 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003457 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3458 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3459 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003460 }
3461
3462 // Get speech level.
3463 rinfo.audio_level = (engine()->voe()->volume()->
3464 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3465 info->receivers.push_back(rinfo);
3466 }
3467 }
3468
3469 return true;
3470}
3471
3472void WebRtcVoiceMediaChannel::GetLastMediaError(
3473 uint32* ssrc, VoiceMediaChannel::Error* error) {
3474 ASSERT(ssrc != NULL);
3475 ASSERT(error != NULL);
3476 FindSsrc(voe_channel(), ssrc);
3477 *error = WebRtcErrorToChannelError(GetLastEngineError());
3478}
3479
3480bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003481 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003482 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003483 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003484 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3485 // This means the error is not limited to a specific channel. Signal the
3486 // message using ssrc=0. If the current channel is sending, use this
3487 // channel for sending the message.
3488 *ssrc = 0;
3489 return true;
3490 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003491 // Check whether this is a sending channel.
3492 for (ChannelMap::const_iterator it = send_channels_.begin();
3493 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003494 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003495 // This is a sending channel.
3496 uint32 local_ssrc = 0;
3497 if (engine()->voe()->rtp()->GetLocalSSRC(
3498 channel_num, local_ssrc) != -1) {
3499 *ssrc = local_ssrc;
3500 }
3501 return true;
3502 }
3503 }
3504
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003505 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003506 for (ChannelMap::const_iterator it = receive_channels_.begin();
3507 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003508 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003509 *ssrc = it->first;
3510 return true;
3511 }
3512 }
3513 }
3514 return false;
3515}
3516
3517void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003518 if (error == VE_TYPING_NOISE_WARNING) {
3519 typing_noise_detected_ = true;
3520 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3521 typing_noise_detected_ = false;
3522 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003523 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3524}
3525
3526int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3527 unsigned int ulevel;
3528 int ret =
3529 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3530 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3531}
3532
3533int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003534 ChannelMap::iterator it = receive_channels_.find(ssrc);
3535 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003536 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003537 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3538}
3539
3540int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003541 ChannelMap::iterator it = send_channels_.find(ssrc);
3542 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003543 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003544
3545 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003546}
3547
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003548bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
3549 webrtc::VideoEngine* vie, int vie_channel) {
3550 shared_bwe_vie_ = vie;
3551 shared_bwe_vie_channel_ = vie_channel;
3552
3553 if (!SetupSharedBweOnChannel(voe_channel())) {
3554 return false;
3555 }
3556 for (ChannelMap::iterator it = receive_channels_.begin();
3557 it != receive_channels_.end(); ++it) {
3558 if (!SetupSharedBweOnChannel(it->second->channel())) {
3559 return false;
3560 }
3561 }
3562 return true;
3563}
3564
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003565bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3566 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3567 // Get the RED encodings from the parameter with no name. This may
3568 // change based on what is discussed on the Jingle list.
3569 // The encoding parameter is of the form "a/b"; we only support where
3570 // a == b. Verify this and parse out the value into red_pt.
3571 // If the parameter value is absent (as it will be until we wire up the
3572 // signaling of this message), use the second codec specified (i.e. the
3573 // one after "red") as the encoding parameter.
3574 int red_pt = -1;
3575 std::string red_params;
3576 CodecParameterMap::const_iterator it = red_codec.params.find("");
3577 if (it != red_codec.params.end()) {
3578 red_params = it->second;
3579 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003580 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003581 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003582 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003583 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3584 return false;
3585 }
3586 } else if (red_codec.params.empty()) {
3587 LOG(LS_WARNING) << "RED params not present, using defaults";
3588 if (all_codecs.size() > 1) {
3589 red_pt = all_codecs[1].id;
3590 }
3591 }
3592
3593 // Try to find red_pt in |codecs|.
3594 std::vector<AudioCodec>::const_iterator codec;
3595 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3596 if (codec->id == red_pt)
3597 break;
3598 }
3599
3600 // If we find the right codec, that will be the codec we pass to
3601 // SetSendCodec, with the desired payload type.
3602 if (codec != all_codecs.end() &&
3603 engine()->FindWebRtcCodec(*codec, send_codec)) {
3604 } else {
3605 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3606 return false;
3607 }
3608
3609 return true;
3610}
3611
3612bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3613 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003614 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003615 return false;
3616 }
3617 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3618 // what we want to do with them.
3619 // engine()->voe().EnableVQMon(voe_channel(), true);
3620 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3621 return true;
3622}
3623
3624bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3625 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3626 for (int i = 0; i < ncodecs; ++i) {
3627 webrtc::CodecInst voe_codec;
3628 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3629 voe_codec.pltype = -1;
3630 if (engine()->voe()->codec()->SetRecPayloadType(
3631 channel, voe_codec) == -1) {
3632 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3633 return false;
3634 }
3635 }
3636 }
3637 return true;
3638}
3639
3640bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3641 if (playout) {
3642 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3643 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3644 LOG_RTCERR1(StartPlayout, channel);
3645 return false;
3646 }
3647 } else {
3648 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3649 engine()->voe()->base()->StopPlayout(channel);
3650 }
3651 return true;
3652}
3653
3654uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3655 bool rtcp) {
3656 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3657 uint32 ssrc = 0;
3658 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003659 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003660 }
3661 return ssrc;
3662}
3663
3664// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3665VoiceMediaChannel::Error
3666 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3667 switch (err_code) {
3668 case 0:
3669 return ERROR_NONE;
3670 case VE_CANNOT_START_RECORDING:
3671 case VE_MIC_VOL_ERROR:
3672 case VE_GET_MIC_VOL_ERROR:
3673 case VE_CANNOT_ACCESS_MIC_VOL:
3674 return ERROR_REC_DEVICE_OPEN_FAILED;
3675 case VE_SATURATION_WARNING:
3676 return ERROR_REC_DEVICE_SATURATION;
3677 case VE_REC_DEVICE_REMOVED:
3678 return ERROR_REC_DEVICE_REMOVED;
3679 case VE_RUNTIME_REC_WARNING:
3680 case VE_RUNTIME_REC_ERROR:
3681 return ERROR_REC_RUNTIME_ERROR;
3682 case VE_CANNOT_START_PLAYOUT:
3683 case VE_SPEAKER_VOL_ERROR:
3684 case VE_GET_SPEAKER_VOL_ERROR:
3685 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3686 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3687 case VE_RUNTIME_PLAY_WARNING:
3688 case VE_RUNTIME_PLAY_ERROR:
3689 return ERROR_PLAY_RUNTIME_ERROR;
3690 case VE_TYPING_NOISE_WARNING:
3691 return ERROR_REC_TYPING_NOISE_DETECTED;
3692 default:
3693 return VoiceMediaChannel::ERROR_OTHER;
3694 }
3695}
3696
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003697bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3698 int channel_id, const RtpHeaderExtension* extension) {
3699 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003700 int id = 0;
3701 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003702 if (extension) {
3703 enable = true;
3704 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003705 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003706 }
3707 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003708 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003709 return false;
3710 }
3711 return true;
3712}
3713
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003714bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
3715 webrtc::ViENetwork* vie_network = NULL;
3716 int vie_channel = -1;
3717 if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
3718 shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
3719 vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
3720 vie_channel = shared_bwe_vie_channel_;
3721 }
3722 if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
3723 vie_channel) == -1) {
3724 LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
3725 if (vie_network != NULL) {
3726 // Don't fail if we're tearing down.
3727 return false;
3728 }
3729 }
3730 return true;
3731}
3732
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003733int WebRtcSoundclipStream::Read(void *buf, int len) {
3734 size_t res = 0;
3735 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003736 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003737}
3738
3739int WebRtcSoundclipStream::Rewind() {
3740 mem_.Rewind();
3741 // Return -1 to keep VoiceEngine from looping.
3742 return (loop_) ? 0 : -1;
3743}
3744
3745} // namespace cricket
3746
3747#endif // HAVE_WEBRTC_VOICE