blob: 74b31635369243b4ac43027c5c347e8caf4d0c35 [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.orgf85dbce2014-11-07 12:25:00 +000077 { "G722", 8000, 1, 9, false },
henrike@webrtc.org28e20752013-07-10 00:45:36 +000078 { "ILBC", 8000, 1, 102, false },
79 { "PCMU", 8000, 1, 0, false },
80 { "PCMA", 8000, 1, 8, false },
81 { "CN", 48000, 1, 107, false },
82 { "CN", 32000, 1, 106, false },
83 { "CN", 16000, 1, 105, false },
84 { "CN", 8000, 1, 13, false },
85 { "red", 8000, 1, 127, false },
86 { "telephone-event", 8000, 1, 126, false },
87};
88
89// For Linux/Mac, using the default device is done by specifying index 0 for
90// VoE 4.0 and not -1 (which was the case for VoE 3.5).
91//
92// On Windows Vista and newer, Microsoft introduced the concept of "Default
93// Communications Device". This means that there are two types of default
94// devices (old Wave Audio style default and Default Communications Device).
95//
96// On Windows systems which only support Wave Audio style default, uses either
97// -1 or 0 to select the default device.
98//
99// On Windows systems which support both "Default Communication Device" and
100// old Wave Audio style default, use -1 for Default Communications Device and
101// -2 for Wave Audio style default, which is what we want to use for clips.
102// It's not clear yet whether the -2 index is handled properly on other OSes.
103
104#ifdef WIN32
105static const int kDefaultAudioDeviceId = -1;
106static const int kDefaultSoundclipDeviceId = -2;
107#else
108static const int kDefaultAudioDeviceId = 0;
109#endif
110
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111static const char kIsacCodecName[] = "ISAC";
112static const char kL16CodecName[] = "L16";
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000113static const char kG722CodecName[] = "G722";
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000114
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000115// Parameter used for NACK.
116// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
117static const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000118
119// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000120// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000121
122// Recommended bitrates:
123// 8-12 kb/s for NB speech,
124// 16-20 kb/s for WB speech,
125// 28-40 kb/s for FB speech,
126// 48-64 kb/s for FB mono music, and
127// 64-128 kb/s for FB stereo music.
128// The current implementation applies the following values to mono signals,
129// and multiplies them by 2 for stereo.
130static const int kOpusBitrateNb = 12000;
131static const int kOpusBitrateWb = 20000;
132static const int kOpusBitrateFb = 32000;
133
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000134// Opus bitrate should be in the range between 6000 and 510000.
135static const int kOpusMinBitrate = 6000;
136static const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000137
wu@webrtc.orgde305012013-10-31 15:40:38 +0000138// Default audio dscp value.
139// See http://tools.ietf.org/html/rfc2474 for details.
140// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000141static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000142
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000143// Ensure we open the file in a writeable path on ChromeOS and Android. This
144// workaround can be removed when it's possible to specify a filename for audio
145// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000146//
147// TODO(grunell): Use a string in the options instead of hardcoding it here
148// and let the embedder choose the filename (crbug.com/264223).
149//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000150// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
151// below.
152#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000153static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000154#elif defined(ANDROID)
155static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000156#else
157static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
158#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000159
160// Dumps an AudioCodec in RFC 2327-ish format.
161static std::string ToString(const AudioCodec& codec) {
162 std::stringstream ss;
163 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
164 << " (" << codec.id << ")";
165 return ss.str();
166}
167static std::string ToString(const webrtc::CodecInst& codec) {
168 std::stringstream ss;
169 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
170 << " (" << codec.pltype << ")";
171 return ss.str();
172}
173
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000174static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000175 const char* delim = "\r\n";
176 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
177 LOG_V(sev) << tok;
178 }
179}
180
181// Severity is an integer because it comes is assumed to be from command line.
182static int SeverityToFilter(int severity) {
183 int filter = webrtc::kTraceNone;
184 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000185 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000186 filter |= webrtc::kTraceAll;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000187 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000188 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000189 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000190 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000191 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000192 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
193 }
194 return filter;
195}
196
197static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
198 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
199 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
200 kCodecPrefs[i].clockrate == codec.plfreq) {
201 return kCodecPrefs[i].is_multi_rate;
202 }
203 }
204 return false;
205}
206
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000207static bool IsTelephoneEventCodec(const std::string& name) {
208 return _stricmp(name.c_str(), "telephone-event") == 0;
209}
210
211static bool IsCNCodec(const std::string& name) {
212 return _stricmp(name.c_str(), "CN") == 0;
213}
214
215static bool IsRedCodec(const std::string& name) {
216 return _stricmp(name.c_str(), "red") == 0;
217}
218
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000219static bool FindCodec(const std::vector<AudioCodec>& codecs,
220 const AudioCodec& codec,
221 AudioCodec* found_codec) {
222 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
223 it != codecs.end(); ++it) {
224 if (it->Matches(codec)) {
225 if (found_codec != NULL) {
226 *found_codec = *it;
227 }
228 return true;
229 }
230 }
231 return false;
232}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000233
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000234static bool IsNackEnabled(const AudioCodec& codec) {
235 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
236 kParamValueEmpty));
237}
238
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000239// Gets the default set of options applied to the engine. Historically, these
240// were supplied as a combination of flags from the channel manager (ec, agc,
241// ns, and highpass) and the rest hardcoded in InitInternal.
242static AudioOptions GetDefaultEngineOptions() {
243 AudioOptions options;
244 options.echo_cancellation.Set(true);
245 options.auto_gain_control.Set(true);
246 options.noise_suppression.Set(true);
247 options.highpass_filter.Set(true);
248 options.stereo_swapping.Set(false);
249 options.typing_detection.Set(true);
250 options.conference_mode.Set(false);
251 options.adjust_agc_delta.Set(0);
252 options.experimental_agc.Set(false);
253 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000254 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000255 options.aec_dump.Set(false);
256 return options;
257}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000258
259class WebRtcSoundclipMedia : public SoundclipMedia {
260 public:
261 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
262 : engine_(engine), webrtc_channel_(-1) {
263 engine_->RegisterSoundclip(this);
264 }
265
266 virtual ~WebRtcSoundclipMedia() {
267 engine_->UnregisterSoundclip(this);
268 if (webrtc_channel_ != -1) {
269 // We shouldn't have to call Disable() here. DeleteChannel() should call
270 // StopPlayout() while deleting the channel. We should fix the bug
271 // inside WebRTC and remove the Disable() call bellow. This work is
272 // tracked by bug http://b/issue?id=5382855.
273 PlaySound(NULL, 0, 0);
274 Disable();
275 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
276 == -1) {
277 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
278 }
279 }
280 }
281
282 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000283 if (!engine_->voe_sc()) {
284 return false;
285 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000286 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000287 if (webrtc_channel_ == -1) {
288 LOG_RTCERR0(CreateChannel);
289 return false;
290 }
291 return true;
292 }
293
294 bool Enable() {
295 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
296 LOG_RTCERR1(StartPlayout, webrtc_channel_);
297 return false;
298 }
299 return true;
300 }
301
302 bool Disable() {
303 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
304 LOG_RTCERR1(StopPlayout, webrtc_channel_);
305 return false;
306 }
307 return true;
308 }
309
310 virtual bool PlaySound(const char *buf, int len, int flags) {
311 // The voe file api is not available in chrome.
312 if (!engine_->voe_sc()->file()) {
313 return false;
314 }
315 // Must stop playing the current sound (if any), because we are about to
316 // modify the stream.
317 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
318 == -1) {
319 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
320 return false;
321 }
322
323 if (buf) {
324 stream_.reset(new WebRtcSoundclipStream(buf, len));
325 stream_->set_loop((flags & SF_LOOP) != 0);
326 stream_->Rewind();
327
328 // Play it.
329 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
330 webrtc_channel_, stream_.get()) == -1) {
331 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
332 LOG(LS_ERROR) << "Unable to start soundclip";
333 return false;
334 }
335 } else {
336 stream_.reset();
337 }
338 return true;
339 }
340
341 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
342
343 private:
344 WebRtcVoiceEngine *engine_;
345 int webrtc_channel_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000346 rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000347};
348
349WebRtcVoiceEngine::WebRtcVoiceEngine()
350 : voe_wrapper_(new VoEWrapper()),
351 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000352 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000353 tracing_(new VoETraceWrapper()),
354 adm_(NULL),
355 adm_sc_(NULL),
356 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
357 is_dumping_aec_(false),
358 desired_local_monitor_enable_(false),
359 tx_processor_ssrc_(0),
360 rx_processor_ssrc_(0) {
361 Construct();
362}
363
364WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
365 VoEWrapper* voe_wrapper_sc,
366 VoETraceWrapper* tracing)
367 : voe_wrapper_(voe_wrapper),
368 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000369 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000370 tracing_(tracing),
371 adm_(NULL),
372 adm_sc_(NULL),
373 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
374 is_dumping_aec_(false),
375 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000376 tx_processor_ssrc_(0),
377 rx_processor_ssrc_(0) {
378 Construct();
379}
380
381void WebRtcVoiceEngine::Construct() {
382 SetTraceFilter(log_filter_);
383 initialized_ = false;
384 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
385 SetTraceOptions("");
386 if (tracing_->SetTraceCallback(this) == -1) {
387 LOG_RTCERR0(SetTraceCallback);
388 }
389 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
390 LOG_RTCERR0(RegisterVoiceEngineObserver);
391 }
392 // Clear the default agc state.
393 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
394
395 // Load our audio codec list.
396 ConstructCodecs();
397
398 // Load our RTP Header extensions.
399 rtp_header_extensions_.push_back(
400 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
401 kRtpAudioLevelHeaderExtensionDefaultId));
402 rtp_header_extensions_.push_back(
403 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
404 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
405 options_ = GetDefaultEngineOptions();
406}
407
408static bool IsOpus(const AudioCodec& codec) {
409 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
410}
411
412static bool IsIsac(const AudioCodec& codec) {
413 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
414}
415
416// True if params["stereo"] == "1"
417static bool IsOpusStereoEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000418 int value;
419 return codec.GetParam(kCodecParamStereo, &value) && value == 1;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000420}
421
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000422// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
423// otherwise. If the value (either from params or codec.bitrate) <=0, use the
424// default configuration. If the value is beyond feasible bit rate of Opus,
425// clamp it. Returns the Opus bit rate for operation.
buildbot@webrtc.org879fac82014-10-30 07:50:13 +0000426static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000427 int bitrate = 0;
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000428 bool use_param = true;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000429 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000430 bitrate = codec.bitrate;
431 use_param = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000432 }
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000433 if (bitrate <= 0) {
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000434 if (max_playback_rate <= 8000) {
435 bitrate = kOpusBitrateNb;
436 } else if (max_playback_rate <= 16000) {
437 bitrate = kOpusBitrateWb;
438 } else {
439 bitrate = kOpusBitrateFb;
440 }
441
442 if (IsOpusStereoEnabled(codec)) {
443 bitrate *= 2;
444 }
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000445 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
446 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
447 std::string rate_source =
448 use_param ? "Codec parameter \"maxaveragebitrate\"" :
449 "Supplied Opus bitrate";
450 LOG(LS_WARNING) << rate_source
451 << " is invalid and is replaced by: "
452 << bitrate;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000453 }
454 return bitrate;
455}
456
buildbot@webrtc.orgfbd13282014-06-19 19:50:55 +0000457// Return true if params[kCodecParamUseInbandFec] == "1", false
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000458// otherwise.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000459static bool IsOpusFecEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000460 int value;
461 return codec.GetParam(kCodecParamUseInbandFec, &value) && value == 1;
462}
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000463
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000464// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
465// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
466static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
467 int value;
468 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
469 return value;
470 }
471 return kOpusDefaultMaxPlaybackRate;
472}
473
474static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
475 bool* enable_codec_fec, int* max_playback_rate) {
476 *enable_codec_fec = IsOpusFecEnabled(codec);
477 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
478
479 // If OPUS, change what we send according to the "stereo" codec
480 // parameter, and not the "channels" parameter. We set
481 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000482 // the bitrate is not specified, i.e. is <= zero, we set it to the
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000483 // appropriate default value for mono or stereo Opus.
484
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000485 voe_codec->channels = IsOpusStereoEnabled(codec) ? 2 : 1;
buildbot@webrtc.org879fac82014-10-30 07:50:13 +0000486 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000487}
488
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000489// Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
490// which says that G722 should be advertised as 8 kHz although it is a 16 kHz
491// codec.
492static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
493 if (_stricmp(voe_codec->plname, kG722CodecName) == 0) {
494 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
495 // has changed, and this special case is no longer needed.
496 ASSERT(voe_codec->plfreq != new_plfreq);
497 voe_codec->plfreq = new_plfreq;
498 }
499}
500
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000501void WebRtcVoiceEngine::ConstructCodecs() {
502 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
503 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
504 for (int i = 0; i < ncodecs; ++i) {
505 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000506 if (GetVoeCodec(i, voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000507 // Skip uncompressed formats.
508 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
509 continue;
510 }
511
512 const CodecPref* pref = NULL;
513 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
514 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
515 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
516 kCodecPrefs[j].channels == voe_codec.channels) {
517 pref = &kCodecPrefs[j];
518 break;
519 }
520 }
521
522 if (pref) {
523 // Use the payload type that we've configured in our pref table;
524 // use the offset in our pref table to determine the sort order.
525 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
526 voe_codec.rate, voe_codec.channels,
527 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
528 LOG(LS_INFO) << ToString(codec);
529 if (IsIsac(codec)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000530 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000531 codec.bitrate = 0;
532 }
533 if (IsOpus(codec)) {
534 // Only add fmtp parameters that differ from the spec.
535 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
536 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000537 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000538 }
539 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
540 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000541 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000542 }
543 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
544 // when they can be set to values other than the default.
545 }
546 codecs_.push_back(codec);
547 } else {
548 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
549 }
550 }
551 }
552 // Make sure they are in local preference order.
553 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
554}
555
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000556bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst& codec) {
557 if (voe_wrapper_->codec()->GetCodec(index, codec) != -1) {
558 // Change the sample rate of G722 to 8000 to match SDP.
559 MaybeFixupG722(&codec, 8000);
560 return true;
561 }
562 return false;
563}
564
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000565WebRtcVoiceEngine::~WebRtcVoiceEngine() {
566 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
567 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
568 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
569 }
570 if (adm_) {
571 voe_wrapper_.reset();
572 adm_->Release();
573 adm_ = NULL;
574 }
575 if (adm_sc_) {
576 voe_wrapper_sc_.reset();
577 adm_sc_->Release();
578 adm_sc_ = NULL;
579 }
580
581 // Test to see if the media processor was deregistered properly
582 ASSERT(SignalRxMediaFrame.is_empty());
583 ASSERT(SignalTxMediaFrame.is_empty());
584
585 tracing_->SetTraceCallback(NULL);
586}
587
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000588bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000589 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
590 bool res = InitInternal();
591 if (res) {
592 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
593 } else {
594 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
595 Terminate();
596 }
597 return res;
598}
599
600bool WebRtcVoiceEngine::InitInternal() {
601 // Temporarily turn logging level up for the Init call
602 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000603 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000604 SetTraceFilter(extended_filter);
605 SetTraceOptions("");
606
607 // Init WebRtc VoiceEngine.
608 if (voe_wrapper_->base()->Init(adm_) == -1) {
609 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
610 SetTraceFilter(old_filter);
611 return false;
612 }
613
614 SetTraceFilter(old_filter);
615 SetTraceOptions(log_options_);
616
617 // Log the VoiceEngine version info
618 char buffer[1024] = "";
619 voe_wrapper_->base()->GetVersion(buffer);
620 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000621 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000622
623 // Save the default AGC configuration settings. This must happen before
624 // calling SetOptions or the default will be overwritten.
625 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
626 LOG_RTCERR0(GetAgcConfig);
627 return false;
628 }
629
630 // Set defaults for options, so that ApplyOptions applies them explicitly
631 // when we clear option (channel) overrides. External clients can still
632 // modify the defaults via SetOptions (on the media engine).
633 if (!SetOptions(GetDefaultEngineOptions())) {
634 return false;
635 }
636
637 // Print our codec list again for the call diagnostic log
638 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
639 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
640 it != codecs_.end(); ++it) {
641 LOG(LS_INFO) << ToString(*it);
642 }
643
644 // Disable the DTMF playout when a tone is sent.
645 // PlayDtmfTone will be used if local playout is needed.
646 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
647 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
648 }
649
650 initialized_ = true;
651 return true;
652}
653
654bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
655 if (voe_wrapper_sc_initialized_) {
656 return true;
657 }
658 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
659 // be false, so subsequent calls to EnsureSoundclipEngineInit will
660 // probably just fail again. That's acceptable behavior.
661#if defined(LINUX) && !defined(HAVE_LIBPULSE)
662 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
663#endif
664
665 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
666 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
667 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
668 return false;
669 }
670
671 // On Windows, tell it to use the default sound (not communication) devices.
672 // First check whether there is a valid sound device for playback.
673 // TODO(juberti): Clean this up when we support setting the soundclip device.
674#ifdef WIN32
675 // The SetPlayoutDevice may not be implemented in the case of external ADM.
676 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
677 // PeerConnection interface never set the adm_sc_, so need to check both
678 // in order to determine if the external adm is used.
679 if (!adm_ && !adm_sc_) {
680 int num_of_devices = 0;
681 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
682 num_of_devices > 0) {
683 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
684 == -1) {
685 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
686 voe_wrapper_sc_->error());
687 return false;
688 }
689 } else {
690 LOG(LS_WARNING) << "No valid sound playout device found.";
691 }
692 }
693#endif
694 voe_wrapper_sc_initialized_ = true;
695 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
696 return true;
697}
698
699void WebRtcVoiceEngine::Terminate() {
700 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
701 initialized_ = false;
702
703 StopAecDump();
704
705 if (voe_wrapper_sc_) {
706 voe_wrapper_sc_initialized_ = false;
707 voe_wrapper_sc_->base()->Terminate();
708 }
709 voe_wrapper_->base()->Terminate();
710 desired_local_monitor_enable_ = false;
711}
712
713int WebRtcVoiceEngine::GetCapabilities() {
714 return AUDIO_SEND | AUDIO_RECV;
715}
716
717VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
718 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
719 if (!ch->valid()) {
720 delete ch;
721 ch = NULL;
722 }
723 return ch;
724}
725
726SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
727 if (!EnsureSoundclipEngineInit()) {
728 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
729 << "initialize.";
730 return NULL;
731 }
732 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
733 if (!soundclip->Init() || !soundclip->Enable()) {
734 delete soundclip;
735 return NULL;
736 }
737 return soundclip;
738}
739
740bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
741 if (!ApplyOptions(options)) {
742 return false;
743 }
744 options_ = options;
745 return true;
746}
747
748bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
749 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
750 if (!ApplyOptions(overrides)) {
751 return false;
752 }
753 option_overrides_ = overrides;
754 return true;
755}
756
757bool WebRtcVoiceEngine::ClearOptionOverrides() {
758 LOG(LS_INFO) << "Clearing option overrides.";
759 AudioOptions options = options_;
760 // Only call ApplyOptions if |options_overrides_| contains overrided options.
761 // ApplyOptions affects NS, AGC other options that is shared between
762 // all WebRtcVoiceEngineChannels.
763 if (option_overrides_ == AudioOptions()) {
764 return true;
765 }
766
767 if (!ApplyOptions(options)) {
768 return false;
769 }
770 option_overrides_ = AudioOptions();
771 return true;
772}
773
774// AudioOptions defaults are set in InitInternal (for options with corresponding
775// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
776bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
777 AudioOptions options = options_in; // The options are modified below.
778 // kEcConference is AEC with high suppression.
779 webrtc::EcModes ec_mode = webrtc::kEcConference;
780 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
781 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
782 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
783 bool aecm_comfort_noise = false;
784 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
785 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
786 << aecm_comfort_noise << " (default is false).";
787 }
788
789#if defined(IOS)
790 // On iOS, VPIO provides built-in EC and AGC.
791 options.echo_cancellation.Set(false);
792 options.auto_gain_control.Set(false);
793#elif defined(ANDROID)
794 ec_mode = webrtc::kEcAecm;
795#endif
796
797#if defined(IOS) || defined(ANDROID)
798 // Set the AGC mode for iOS as well despite disabling it above, to avoid
799 // unsupported configuration errors from webrtc.
800 agc_mode = webrtc::kAgcFixedDigital;
801 options.typing_detection.Set(false);
802 options.experimental_agc.Set(false);
803 options.experimental_aec.Set(false);
804 options.experimental_ns.Set(false);
805#endif
806
807 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
808
809 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
810
811 bool echo_cancellation;
812 if (options.echo_cancellation.Get(&echo_cancellation)) {
813 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
814 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
815 return false;
816 } else {
817 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
818 << " with mode " << ec_mode;
819 }
820#if !defined(ANDROID)
821 // TODO(ajm): Remove the error return on Android from webrtc.
822 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
823 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
824 return false;
825 }
826#endif
827 if (ec_mode == webrtc::kEcAecm) {
828 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
829 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
830 return false;
831 }
832 }
833 }
834
835 bool auto_gain_control;
836 if (options.auto_gain_control.Get(&auto_gain_control)) {
837 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
838 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
839 return false;
840 } else {
841 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
842 << " with mode " << agc_mode;
843 }
844 }
845
846 if (options.tx_agc_target_dbov.IsSet() ||
847 options.tx_agc_digital_compression_gain.IsSet() ||
848 options.tx_agc_limiter.IsSet()) {
849 // Override default_agc_config_. Generally, an unset option means "leave
850 // the VoE bits alone" in this function, so we want whatever is set to be
851 // stored as the new "default". If we didn't, then setting e.g.
852 // tx_agc_target_dbov would reset digital compression gain and limiter
853 // settings.
854 // Also, if we don't update default_agc_config_, then adjust_agc_delta
855 // would be an offset from the original values, and not whatever was set
856 // explicitly.
857 default_agc_config_.targetLeveldBOv =
858 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
859 default_agc_config_.targetLeveldBOv);
860 default_agc_config_.digitalCompressionGaindB =
861 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
862 default_agc_config_.digitalCompressionGaindB);
863 default_agc_config_.limiterEnable =
864 options.tx_agc_limiter.GetWithDefaultIfUnset(
865 default_agc_config_.limiterEnable);
866 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
867 LOG_RTCERR3(SetAgcConfig,
868 default_agc_config_.targetLeveldBOv,
869 default_agc_config_.digitalCompressionGaindB,
870 default_agc_config_.limiterEnable);
871 return false;
872 }
873 }
874
875 bool noise_suppression;
876 if (options.noise_suppression.Get(&noise_suppression)) {
877 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
878 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
879 return false;
880 } else {
881 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
882 << " with mode " << ns_mode;
883 }
884 }
885
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000886 bool highpass_filter;
887 if (options.highpass_filter.Get(&highpass_filter)) {
888 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
889 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
890 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
891 return false;
892 }
893 }
894
895 bool stereo_swapping;
896 if (options.stereo_swapping.Get(&stereo_swapping)) {
897 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
898 voep->EnableStereoChannelSwapping(stereo_swapping);
899 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
900 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
901 return false;
902 }
903 }
904
905 bool typing_detection;
906 if (options.typing_detection.Get(&typing_detection)) {
907 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
908 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
909 // In case of error, log the info and continue
910 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
911 }
912 }
913
914 int adjust_agc_delta;
915 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
916 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
917 if (!AdjustAgcLevel(adjust_agc_delta)) {
918 return false;
919 }
920 }
921
922 bool aec_dump;
923 if (options.aec_dump.Get(&aec_dump)) {
924 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
925 if (aec_dump)
926 StartAecDump(kAecDumpByAudioOptionFilename);
927 else
928 StopAecDump();
929 }
930
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000931 webrtc::Config config;
932
933 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000934 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000935 if (experimental_aec_.Get(&experimental_aec)) {
936 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
937 config.Set<webrtc::DelayCorrection>(
938 new webrtc::DelayCorrection(experimental_aec));
939 }
940
941#ifdef USE_WEBRTC_DEV_BRANCH
942 experimental_ns_.SetFrom(options.experimental_ns);
943 bool experimental_ns;
944 if (experimental_ns_.Get(&experimental_ns)) {
945 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
946 config.Set<webrtc::ExperimentalNs>(
947 new webrtc::ExperimentalNs(experimental_ns));
948 }
949#endif
950
951 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
952 // returns NULL on audio_processing().
953 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
954 if (audioproc) {
955 audioproc->SetExtraOptions(config);
956 }
957
958#ifndef USE_WEBRTC_DEV_BRANCH
959 bool experimental_ns;
960 if (options.experimental_ns.Get(&experimental_ns)) {
961 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000962 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
963 // returns NULL on audio_processing().
964 if (audioproc) {
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000965 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
966 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
967 return false;
968 }
969 } else {
970 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
971 << experimental_ns;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000972 }
973 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000974#endif
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000975
976 uint32 recording_sample_rate;
977 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
978 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
979 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
980 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
981 }
982 }
983
984 uint32 playout_sample_rate;
985 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
986 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
987 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
988 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
989 }
990 }
991
992 return true;
993}
994
995bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
996 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
997 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
998 LOG_RTCERR1(SetDelayOffsetMs, offset);
999 return false;
1000 }
1001
1002 return true;
1003}
1004
1005struct ResumeEntry {
1006 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
1007 : channel(c),
1008 playout(p),
1009 send(s) {
1010 }
1011
1012 WebRtcVoiceMediaChannel *channel;
1013 bool playout;
1014 SendFlags send;
1015};
1016
1017// TODO(juberti): Refactor this so that the core logic can be used to set the
1018// soundclip device. At that time, reinstate the soundclip pause/resume code.
1019bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
1020 const Device* out_device) {
1021#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001022 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001023 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001024 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001025 kDefaultAudioDeviceId;
1026 // The device manager uses -1 as the default device, which was the case for
1027 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
1028#ifndef WIN32
1029 if (-1 == in_id) {
1030 in_id = kDefaultAudioDeviceId;
1031 }
1032 if (-1 == out_id) {
1033 out_id = kDefaultAudioDeviceId;
1034 }
1035#endif
1036
1037 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
1038 in_device->name : "Default device";
1039 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
1040 out_device->name : "Default device";
1041 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
1042 << ") and speaker to (id=" << out_id << ", name=" << out_name
1043 << ")";
1044
1045 // If we're running the local monitor, we need to stop it first.
1046 bool ret = true;
1047 if (!PauseLocalMonitor()) {
1048 LOG(LS_WARNING) << "Failed to pause local monitor";
1049 ret = false;
1050 }
1051
1052 // Must also pause all audio playback and capture.
1053 for (ChannelList::const_iterator i = channels_.begin();
1054 i != channels_.end(); ++i) {
1055 WebRtcVoiceMediaChannel *channel = *i;
1056 if (!channel->PausePlayout()) {
1057 LOG(LS_WARNING) << "Failed to pause playout";
1058 ret = false;
1059 }
1060 if (!channel->PauseSend()) {
1061 LOG(LS_WARNING) << "Failed to pause send";
1062 ret = false;
1063 }
1064 }
1065
1066 // Find the recording device id in VoiceEngine and set recording device.
1067 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1068 ret = false;
1069 }
1070 if (ret) {
1071 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
1072 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
1073 ret = false;
1074 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00001075 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
1076 if (ap)
1077 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001078 }
1079
1080 // Find the playout device id in VoiceEngine and set playout device.
1081 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1082 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1083 ret = false;
1084 }
1085 if (ret) {
1086 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001087 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001088 ret = false;
1089 }
1090 }
1091
1092 // Resume all audio playback and capture.
1093 for (ChannelList::const_iterator i = channels_.begin();
1094 i != channels_.end(); ++i) {
1095 WebRtcVoiceMediaChannel *channel = *i;
1096 if (!channel->ResumePlayout()) {
1097 LOG(LS_WARNING) << "Failed to resume playout";
1098 ret = false;
1099 }
1100 if (!channel->ResumeSend()) {
1101 LOG(LS_WARNING) << "Failed to resume send";
1102 ret = false;
1103 }
1104 }
1105
1106 // Resume local monitor.
1107 if (!ResumeLocalMonitor()) {
1108 LOG(LS_WARNING) << "Failed to resume local monitor";
1109 ret = false;
1110 }
1111
1112 if (ret) {
1113 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1114 << ") and speaker to (id="<< out_id << " name=" << out_name
1115 << ")";
1116 }
1117
1118 return ret;
1119#else
1120 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001121#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001122}
1123
1124bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1125 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1126 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001127#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001128 *rtc_id = dev_id;
1129 return true;
1130#else
1131 // In Windows and Mac, we need to find the VoiceEngine device id by name
1132 // unless the input dev_id is the default device id.
1133 if (kDefaultAudioDeviceId == dev_id) {
1134 *rtc_id = dev_id;
1135 return true;
1136 }
1137
1138 // Get the number of VoiceEngine audio devices.
1139 int count = 0;
1140 if (is_input) {
1141 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1142 LOG_RTCERR0(GetNumOfRecordingDevices);
1143 return false;
1144 }
1145 } else {
1146 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1147 LOG_RTCERR0(GetNumOfPlayoutDevices);
1148 return false;
1149 }
1150 }
1151
1152 for (int i = 0; i < count; ++i) {
1153 char name[128];
1154 char guid[128];
1155 if (is_input) {
1156 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1157 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1158 } else {
1159 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1160 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1161 }
1162
1163 std::string webrtc_name(name);
1164 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1165 *rtc_id = i;
1166 return true;
1167 }
1168 }
1169 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1170 return false;
1171#endif
1172}
1173
1174bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1175 unsigned int ulevel;
1176 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1177 LOG_RTCERR1(GetSpeakerVolume, level);
1178 return false;
1179 }
1180 *level = ulevel;
1181 return true;
1182}
1183
1184bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1185 ASSERT(level >= 0 && level <= 255);
1186 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1187 LOG_RTCERR1(SetSpeakerVolume, level);
1188 return false;
1189 }
1190 return true;
1191}
1192
1193int WebRtcVoiceEngine::GetInputLevel() {
1194 unsigned int ulevel;
1195 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1196 static_cast<int>(ulevel) : -1;
1197}
1198
1199bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1200 desired_local_monitor_enable_ = enable;
1201 return ChangeLocalMonitor(desired_local_monitor_enable_);
1202}
1203
1204bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1205 // The voe file api is not available in chrome.
1206 if (!voe_wrapper_->file()) {
1207 return false;
1208 }
1209 if (enable && !monitor_) {
1210 monitor_.reset(new WebRtcMonitorStream);
1211 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1212 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1213 // Must call Stop() because there are some cases where Start will report
1214 // failure but still change the state, and if we leave VE in the on state
1215 // then it could crash later when trying to invoke methods on our monitor.
1216 voe_wrapper_->file()->StopRecordingMicrophone();
1217 monitor_.reset();
1218 return false;
1219 }
1220 } else if (!enable && monitor_) {
1221 voe_wrapper_->file()->StopRecordingMicrophone();
1222 monitor_.reset();
1223 }
1224 return true;
1225}
1226
1227bool WebRtcVoiceEngine::PauseLocalMonitor() {
1228 return ChangeLocalMonitor(false);
1229}
1230
1231bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1232 return ChangeLocalMonitor(desired_local_monitor_enable_);
1233}
1234
1235const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1236 return codecs_;
1237}
1238
1239bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1240 return FindWebRtcCodec(in, NULL);
1241}
1242
1243// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1244bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1245 webrtc::CodecInst* out) {
1246 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1247 for (int i = 0; i < ncodecs; ++i) {
1248 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001249 if (GetVoeCodec(i, voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001250 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1251 voe_codec.rate, voe_codec.channels, 0);
1252 bool multi_rate = IsCodecMultiRate(voe_codec);
1253 // Allow arbitrary rates for ISAC to be specified.
1254 if (multi_rate) {
1255 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1256 codec.bitrate = 0;
1257 }
1258 if (codec.Matches(in)) {
1259 if (out) {
1260 // Fixup the payload type.
1261 voe_codec.pltype = in.id;
1262
1263 // Set bitrate if specified.
1264 if (multi_rate && in.bitrate != 0) {
1265 voe_codec.rate = in.bitrate;
1266 }
1267
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001268 // Reset G722 sample rate to 16000 to match WebRTC.
1269 MaybeFixupG722(&voe_codec, 16000);
1270
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001271 // Apply codec-specific settings.
1272 if (IsIsac(codec)) {
1273 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001274 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001275 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1276 }
1277 *out = voe_codec;
1278 }
1279 return true;
1280 }
1281 }
1282 }
1283 return false;
1284}
1285const std::vector<RtpHeaderExtension>&
1286WebRtcVoiceEngine::rtp_header_extensions() const {
1287 return rtp_header_extensions_;
1288}
1289
1290void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1291 // if min_sev == -1, we keep the current log level.
1292 if (min_sev >= 0) {
1293 SetTraceFilter(SeverityToFilter(min_sev));
1294 }
1295 log_options_ = filter;
1296 SetTraceOptions(initialized_ ? log_options_ : "");
1297}
1298
1299int WebRtcVoiceEngine::GetLastEngineError() {
1300 return voe_wrapper_->error();
1301}
1302
1303void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1304 log_filter_ = filter;
1305 tracing_->SetTraceFilter(filter);
1306}
1307
1308// We suppport three different logging settings for VoiceEngine:
1309// 1. Observer callback that goes into talk diagnostic logfile.
1310// Use --logfile and --loglevel
1311//
1312// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1313// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1314//
1315// 3. EC log and dump for debugging QualityEngine.
1316// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1317//
1318// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1319// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1320void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1321 // Set encrypted trace file.
1322 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001323 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001324 std::vector<std::string>::iterator tracefile =
1325 std::find(opts.begin(), opts.end(), "tracefile");
1326 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1327 // Write encrypted debug output (at same loglevel) to file
1328 // EncryptedTraceFile no longer supported.
1329 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1330 LOG_RTCERR1(SetTraceFile, *tracefile);
1331 }
1332 }
1333
wu@webrtc.org97077a32013-10-25 21:18:33 +00001334 // Allow trace options to override the trace filter. We default
1335 // it to log_filter_ (as a translation of libjingle log levels)
1336 // elsewhere, but this allows clients to explicitly set webrtc
1337 // log levels.
1338 std::vector<std::string>::iterator tracefilter =
1339 std::find(opts.begin(), opts.end(), "tracefilter");
1340 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001341 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001342 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1343 }
1344 }
1345
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001346 // Set AEC dump file
1347 std::vector<std::string>::iterator recordEC =
1348 std::find(opts.begin(), opts.end(), "recordEC");
1349 if (recordEC != opts.end()) {
1350 ++recordEC;
1351 if (recordEC != opts.end())
1352 StartAecDump(recordEC->c_str());
1353 else
1354 StopAecDump();
1355 }
1356}
1357
1358// Ignore spammy trace messages, mostly from the stats API when we haven't
1359// gotten RTCP info yet from the remote side.
1360bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1361 static const char* kTracesToIgnore[] = {
1362 "\tfailed to GetReportBlockInformation",
1363 "GetRecCodec() failed to get received codec",
1364 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1365 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1366 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1367 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1368 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1369 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1370 "SenderInfoReceived No received SR",
1371 "StatisticsRTP() no statistics available",
1372 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1373 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1374 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1375 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1376 NULL
1377 };
1378 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1379 if (trace.find(*p) != std::string::npos) {
1380 return true;
1381 }
1382 }
1383 return false;
1384}
1385
1386void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1387 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001388 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001389 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001390 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001391 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001392 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001393 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001394 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001395 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001396 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001397
1398 // Skip past boilerplate prefix text
1399 if (length < 72) {
1400 std::string msg(trace, length);
1401 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1402 LOG_V(sev) << msg;
1403 } else {
1404 std::string msg(trace + 71, length - 72);
1405 if (!ShouldIgnoreTrace(msg)) {
1406 LOG_V(sev) << "webrtc: " << msg;
1407 }
1408 }
1409}
1410
1411void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001412 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001413 WebRtcVoiceMediaChannel* channel = NULL;
1414 uint32 ssrc = 0;
1415 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1416 << channel_num << ".";
1417 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1418 ASSERT(channel != NULL);
1419 channel->OnError(ssrc, err_code);
1420 } else {
1421 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1422 << " could not be found in channel list when error reported.";
1423 }
1424}
1425
1426bool WebRtcVoiceEngine::FindChannelAndSsrc(
1427 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1428 ASSERT(channel != NULL && ssrc != NULL);
1429
1430 *channel = NULL;
1431 *ssrc = 0;
1432 // Find corresponding channel and ssrc
1433 for (ChannelList::const_iterator it = channels_.begin();
1434 it != channels_.end(); ++it) {
1435 ASSERT(*it != NULL);
1436 if ((*it)->FindSsrc(channel_num, ssrc)) {
1437 *channel = *it;
1438 return true;
1439 }
1440 }
1441
1442 return false;
1443}
1444
1445// This method will search through the WebRtcVoiceMediaChannels and
1446// obtain the voice engine's channel number.
1447bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1448 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1449 ASSERT(channel_num != NULL);
1450 ASSERT(direction == MPD_RX || direction == MPD_TX);
1451
1452 *channel_num = -1;
1453 // Find corresponding channel for ssrc.
1454 for (ChannelList::const_iterator it = channels_.begin();
1455 it != channels_.end(); ++it) {
1456 ASSERT(*it != NULL);
1457 if (direction & MPD_RX) {
1458 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1459 }
1460 if (*channel_num == -1 && (direction & MPD_TX)) {
1461 *channel_num = (*it)->GetSendChannelNum(ssrc);
1462 }
1463 if (*channel_num != -1) {
1464 return true;
1465 }
1466 }
1467 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1468 return false;
1469}
1470
1471void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001472 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001473 channels_.push_back(channel);
1474}
1475
1476void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001477 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001478 ChannelList::iterator i = std::find(channels_.begin(),
1479 channels_.end(),
1480 channel);
1481 if (i != channels_.end()) {
1482 channels_.erase(i);
1483 }
1484}
1485
1486void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1487 soundclips_.push_back(soundclip);
1488}
1489
1490void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1491 SoundclipList::iterator i = std::find(soundclips_.begin(),
1492 soundclips_.end(),
1493 soundclip);
1494 if (i != soundclips_.end()) {
1495 soundclips_.erase(i);
1496 }
1497}
1498
1499// Adjusts the default AGC target level by the specified delta.
1500// NB: If we start messing with other config fields, we'll want
1501// to save the current webrtc::AgcConfig as well.
1502bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1503 webrtc::AgcConfig config = default_agc_config_;
1504 config.targetLeveldBOv -= delta;
1505
1506 LOG(LS_INFO) << "Adjusting AGC level from default -"
1507 << default_agc_config_.targetLeveldBOv << "dB to -"
1508 << config.targetLeveldBOv << "dB";
1509
1510 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1511 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1512 return false;
1513 }
1514 return true;
1515}
1516
1517bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1518 webrtc::AudioDeviceModule* adm_sc) {
1519 if (initialized_) {
1520 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1521 return false;
1522 }
1523 if (adm_) {
1524 adm_->Release();
1525 adm_ = NULL;
1526 }
1527 if (adm) {
1528 adm_ = adm;
1529 adm_->AddRef();
1530 }
1531
1532 if (adm_sc_) {
1533 adm_sc_->Release();
1534 adm_sc_ = NULL;
1535 }
1536 if (adm_sc) {
1537 adm_sc_ = adm_sc;
1538 adm_sc_->AddRef();
1539 }
1540 return true;
1541}
1542
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001543bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1544 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001545 if (!aec_dump_file_stream) {
1546 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001547 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001548 LOG(LS_WARNING) << "Could not close file.";
1549 return false;
1550 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001551 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001552 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001553 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001554 LOG_RTCERR0(StartDebugRecording);
1555 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001556 return false;
1557 }
1558 is_dumping_aec_ = true;
1559 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001560}
1561
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001562bool WebRtcVoiceEngine::RegisterProcessor(
1563 uint32 ssrc,
1564 VoiceProcessor* voice_processor,
1565 MediaProcessorDirection direction) {
1566 bool register_with_webrtc = false;
1567 int channel_id = -1;
1568 bool success = false;
1569 uint32* processor_ssrc = NULL;
1570 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1571 if (voice_processor == NULL || !found_channel) {
1572 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1573 << " foundChannel: " << found_channel;
1574 return false;
1575 }
1576
1577 webrtc::ProcessingTypes processing_type;
1578 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001579 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001580 if (direction == MPD_RX) {
1581 processing_type = webrtc::kPlaybackAllChannelsMixed;
1582 if (SignalRxMediaFrame.is_empty()) {
1583 register_with_webrtc = true;
1584 processor_ssrc = &rx_processor_ssrc_;
1585 }
1586 SignalRxMediaFrame.connect(voice_processor,
1587 &VoiceProcessor::OnFrame);
1588 } else {
1589 processing_type = webrtc::kRecordingPerChannel;
1590 if (SignalTxMediaFrame.is_empty()) {
1591 register_with_webrtc = true;
1592 processor_ssrc = &tx_processor_ssrc_;
1593 }
1594 SignalTxMediaFrame.connect(voice_processor,
1595 &VoiceProcessor::OnFrame);
1596 }
1597 }
1598 if (register_with_webrtc) {
1599 // TODO(janahan): when registering consider instantiating a
1600 // a VoeMediaProcess object and not make the engine extend the interface.
1601 if (voe()->media() && voe()->media()->
1602 RegisterExternalMediaProcessing(channel_id,
1603 processing_type,
1604 *this) != -1) {
1605 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1606 << channel_id;
1607 *processor_ssrc = ssrc;
1608 success = true;
1609 } else {
1610 LOG_RTCERR2(RegisterExternalMediaProcessing,
1611 channel_id,
1612 processing_type);
1613 success = false;
1614 }
1615 } else {
1616 // If we don't have to register with the engine, we just needed to
1617 // connect a new processor, set success to true;
1618 success = true;
1619 }
1620 return success;
1621}
1622
1623bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1624 MediaProcessorDirection channel_direction,
1625 uint32 ssrc,
1626 VoiceProcessor* voice_processor,
1627 MediaProcessorDirection processor_direction) {
1628 bool success = true;
1629 FrameSignal* signal;
1630 webrtc::ProcessingTypes processing_type;
1631 uint32* processor_ssrc = NULL;
1632 if (channel_direction == MPD_RX) {
1633 signal = &SignalRxMediaFrame;
1634 processing_type = webrtc::kPlaybackAllChannelsMixed;
1635 processor_ssrc = &rx_processor_ssrc_;
1636 } else {
1637 signal = &SignalTxMediaFrame;
1638 processing_type = webrtc::kRecordingPerChannel;
1639 processor_ssrc = &tx_processor_ssrc_;
1640 }
1641
1642 int deregister_id = -1;
1643 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001644 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001645 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1646 signal->disconnect(voice_processor);
1647 int channel_id = -1;
1648 bool found_channel = FindChannelNumFromSsrc(ssrc,
1649 channel_direction,
1650 &channel_id);
1651 if (signal->is_empty() && found_channel) {
1652 deregister_id = channel_id;
1653 }
1654 }
1655 }
1656 if (deregister_id != -1) {
1657 if (voe()->media() &&
1658 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1659 processing_type) != -1) {
1660 *processor_ssrc = 0;
1661 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1662 << deregister_id;
1663 } else {
1664 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1665 deregister_id,
1666 processing_type);
1667 success = false;
1668 }
1669 }
1670 return success;
1671}
1672
1673bool WebRtcVoiceEngine::UnregisterProcessor(
1674 uint32 ssrc,
1675 VoiceProcessor* voice_processor,
1676 MediaProcessorDirection direction) {
1677 bool success = true;
1678 if (voice_processor == NULL) {
1679 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1680 << ssrc;
1681 return false;
1682 }
1683 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1684 success = false;
1685 }
1686 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1687 success = false;
1688 }
1689 return success;
1690}
1691
1692// Implementing method from WebRtc VoEMediaProcess interface
1693// Do not lock mux_channel_cs_ in this callback.
1694void WebRtcVoiceEngine::Process(int channel,
1695 webrtc::ProcessingTypes type,
1696 int16_t audio10ms[],
1697 int length,
1698 int sampling_freq,
1699 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001700 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001701 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1702 if (type == webrtc::kPlaybackAllChannelsMixed) {
1703 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1704 } else if (type == webrtc::kRecordingPerChannel) {
1705 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1706 } else {
1707 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1708 << " channel: " << channel << " type: " << type
1709 << " tx_ssrc: " << tx_processor_ssrc_
1710 << " rx_ssrc: " << rx_processor_ssrc_;
1711 }
1712}
1713
1714void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1715 if (!is_dumping_aec_) {
1716 // Start dumping AEC when we are not dumping.
1717 if (voe_wrapper_->processing()->StartDebugRecording(
1718 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001719 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001720 } else {
1721 is_dumping_aec_ = true;
1722 }
1723 }
1724}
1725
1726void WebRtcVoiceEngine::StopAecDump() {
1727 if (is_dumping_aec_) {
1728 // Stop dumping AEC when we are dumping.
1729 if (voe_wrapper_->processing()->StopDebugRecording() !=
1730 webrtc::AudioProcessing::kNoError) {
1731 LOG_RTCERR0(StopDebugRecording);
1732 }
1733 is_dumping_aec_ = false;
1734 }
1735}
1736
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001737int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001738 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001739}
1740
1741int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1742 return CreateVoiceChannel(voe_wrapper_.get());
1743}
1744
1745int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1746 return CreateVoiceChannel(voe_wrapper_sc_.get());
1747}
1748
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001749class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1750 : public AudioRenderer::Sink {
1751 public:
1752 WebRtcVoiceChannelRenderer(int ch,
1753 webrtc::AudioTransport* voe_audio_transport)
1754 : channel_(ch),
1755 voe_audio_transport_(voe_audio_transport),
1756 renderer_(NULL) {
1757 }
1758 virtual ~WebRtcVoiceChannelRenderer() {
1759 Stop();
1760 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001761
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001762 // Starts the rendering by setting a sink to the renderer to get data
1763 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001764 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001765 // TODO(xians): Make sure Start() is called only once.
1766 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001767 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001768 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001769 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001770 ASSERT(renderer_ == renderer);
1771 return;
1772 }
1773
1774 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1775 // in getUserMedia by default.
1776 renderer->AddChannel(channel_);
1777 renderer->SetSink(this);
1778 renderer_ = renderer;
1779 }
1780
1781 // Stops rendering by setting the sink of the renderer to NULL. No data
1782 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001783 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001784 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001785 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001786 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001787 return;
1788
1789 renderer_->RemoveChannel(channel_);
1790 renderer_->SetSink(NULL);
1791 renderer_ = NULL;
1792 }
1793
1794 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001795 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001796 virtual void OnData(const void* audio_data,
1797 int bits_per_sample,
1798 int sample_rate,
1799 int number_of_channels,
1800 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001801 voe_audio_transport_->OnData(channel_,
1802 audio_data,
1803 bits_per_sample,
1804 sample_rate,
1805 number_of_channels,
1806 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001807 }
1808
1809 // Callback from the |renderer_| when it is going away. In case Start() has
1810 // never been called, this callback won't be triggered.
1811 virtual void OnClose() OVERRIDE {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001812 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001813 // Set |renderer_| to NULL to make sure no more callback will get into
1814 // the renderer.
1815 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001816 }
1817
1818 // Accessor to the VoE channel ID.
1819 int channel() const { return channel_; }
1820
1821 private:
1822 const int channel_;
1823 webrtc::AudioTransport* const voe_audio_transport_;
1824
1825 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1826 // PeerConnection will make sure invalidating the pointer before the object
1827 // goes away.
1828 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001829
1830 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001831 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001832};
1833
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001834// WebRtcVoiceMediaChannel
1835WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1836 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1837 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001838 engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001839 send_bitrate_setting_(false),
1840 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001841 options_(),
1842 dtmf_allowed_(false),
1843 desired_playout_(false),
1844 nack_enabled_(false),
1845 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001846 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001847 desired_send_(SEND_NOTHING),
1848 send_(SEND_NOTHING),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001849 shared_bwe_vie_(NULL),
1850 shared_bwe_vie_channel_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001851 default_receive_ssrc_(0) {
1852 engine->RegisterChannel(this);
1853 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1854 << voe_channel();
1855
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001856 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001857}
1858
1859WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1860 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1861 << voe_channel();
buildbot@webrtc.org6e5c7842014-09-19 06:46:37 +00001862 SetupSharedBandwidthEstimation(NULL, -1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001863
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001864 // Remove any remaining send streams, the default channel will be deleted
1865 // later.
1866 while (!send_channels_.empty())
1867 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001868
1869 // Unregister ourselves from the engine.
1870 engine()->UnregisterChannel(this);
1871 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001872 while (!receive_channels_.empty()) {
1873 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001874 }
1875
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001876 // Delete the default channel.
1877 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001878}
1879
1880bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1881 LOG(LS_INFO) << "Setting voice channel options: "
1882 << options.ToString();
1883
wu@webrtc.orgde305012013-10-31 15:40:38 +00001884 // Check if DSCP value is changed from previous.
1885 bool dscp_option_changed = (options_.dscp != options.dscp);
1886
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001887 // TODO(xians): Add support to set different options for different send
1888 // streams after we support multiple APMs.
1889
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001890 // We retain all of the existing options, and apply the given ones
1891 // on top. This means there is no way to "clear" options such that
1892 // they go back to the engine default.
1893 options_.SetAll(options);
1894
1895 if (send_ != SEND_NOTHING) {
1896 if (!engine()->SetOptionOverrides(options_)) {
1897 LOG(LS_WARNING) <<
1898 "Failed to engine SetOptionOverrides during channel SetOptions.";
1899 return false;
1900 }
1901 } else {
1902 // Will be interpreted when appropriate.
1903 }
1904
wu@webrtc.org97077a32013-10-25 21:18:33 +00001905 // Receiver-side auto gain control happens per channel, so set it here from
1906 // options. Note that, like conference mode, setting it on the engine won't
1907 // have the desired effect, since voice channels don't inherit options from
1908 // the media engine when those options are applied per-channel.
1909 bool rx_auto_gain_control;
1910 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1911 if (engine()->voe()->processing()->SetRxAgcStatus(
1912 voe_channel(), rx_auto_gain_control,
1913 webrtc::kAgcFixedDigital) == -1) {
1914 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1915 return false;
1916 } else {
1917 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1918 << " with mode " << webrtc::kAgcFixedDigital;
1919 }
1920 }
1921 if (options.rx_agc_target_dbov.IsSet() ||
1922 options.rx_agc_digital_compression_gain.IsSet() ||
1923 options.rx_agc_limiter.IsSet()) {
1924 webrtc::AgcConfig config;
1925 // If only some of the options are being overridden, get the current
1926 // settings for the channel and bail if they aren't available.
1927 if (!options.rx_agc_target_dbov.IsSet() ||
1928 !options.rx_agc_digital_compression_gain.IsSet() ||
1929 !options.rx_agc_limiter.IsSet()) {
1930 if (engine()->voe()->processing()->GetRxAgcConfig(
1931 voe_channel(), config) != 0) {
1932 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1933 << "channel " << voe_channel() << ". Since not all rx "
1934 << "agc options are specified, unable to safely set rx "
1935 << "agc options.";
1936 return false;
1937 }
1938 }
1939 config.targetLeveldBOv =
1940 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1941 config.targetLeveldBOv);
1942 config.digitalCompressionGaindB =
1943 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1944 config.digitalCompressionGaindB);
1945 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1946 config.limiterEnable);
1947 if (engine()->voe()->processing()->SetRxAgcConfig(
1948 voe_channel(), config) == -1) {
1949 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1950 config.digitalCompressionGaindB, config.limiterEnable);
1951 return false;
1952 }
1953 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001954 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001955 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001956 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001957 dscp = kAudioDscpValue;
1958 if (MediaChannel::SetDscp(dscp) != 0) {
1959 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1960 }
1961 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001962
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001963 // Force update of Video Engine BWE forwarding to reflect experiment setting.
1964 if (!SetupSharedBandwidthEstimation(shared_bwe_vie_,
1965 shared_bwe_vie_channel_)) {
1966 return false;
1967 }
1968
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001969 LOG(LS_INFO) << "Set voice channel options. Current options: "
1970 << options_.ToString();
1971 return true;
1972}
1973
1974bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1975 const std::vector<AudioCodec>& codecs) {
1976 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001977 LOG(LS_INFO) << "Setting receive voice codecs:";
1978
1979 std::vector<AudioCodec> new_codecs;
1980 // Find all new codecs. We allow adding new codecs but don't allow changing
1981 // the payload type of codecs that is already configured since we might
1982 // already be receiving packets with that payload type.
1983 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001984 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001985 AudioCodec old_codec;
1986 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1987 if (old_codec.id != it->id) {
1988 LOG(LS_ERROR) << it->name << " payload type changed.";
1989 return false;
1990 }
1991 } else {
1992 new_codecs.push_back(*it);
1993 }
1994 }
1995 if (new_codecs.empty()) {
1996 // There are no new codecs to configure. Already configured codecs are
1997 // never removed.
1998 return true;
1999 }
2000
2001 if (playout_) {
2002 // Receive codecs can not be changed while playing. So we temporarily
2003 // pause playout.
2004 PausePlayout();
2005 }
2006
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002007 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002008 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
2009 it != new_codecs.end() && ret; ++it) {
2010 webrtc::CodecInst voe_codec;
2011 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2012 LOG(LS_INFO) << ToString(*it);
2013 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002014 if (default_receive_ssrc_ == 0) {
2015 // Set the receive codecs on the default channel explicitly if the
2016 // default channel is not used by |receive_channels_|, this happens in
2017 // conference mode or in non-conference mode when there is no playout
2018 // channel.
2019 // TODO(xians): Figure out how we use the default channel in conference
2020 // mode.
2021 if (engine()->voe()->codec()->SetRecPayloadType(
2022 voe_channel(), voe_codec) == -1) {
2023 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
2024 ret = false;
2025 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002026 }
2027
2028 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002029 for (ChannelMap::iterator it = receive_channels_.begin();
2030 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002031 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002032 it->second->channel(), voe_codec) == -1) {
2033 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002034 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002035 ret = false;
2036 }
2037 }
2038 } else {
2039 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2040 ret = false;
2041 }
2042 }
2043 if (ret) {
2044 recv_codecs_ = codecs;
2045 }
2046
2047 if (desired_playout_ && !playout_) {
2048 ResumePlayout();
2049 }
2050 return ret;
2051}
2052
2053bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002054 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002055 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002056 engine()->voe()->codec()->SetVADStatus(channel, false);
2057 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002058#ifdef USE_WEBRTC_DEV_BRANCH
2059 engine()->voe()->rtp()->SetREDStatus(channel, false);
2060 engine()->voe()->codec()->SetFECStatus(channel, false);
2061#else
2062 // TODO(minyue): Remove code under #else case after new WebRTC roll.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002063 engine()->voe()->rtp()->SetFECStatus(channel, false);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002064#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002065
2066 // Scan through the list to figure out the codec to use for sending, along
2067 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002068 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002069 webrtc::CodecInst send_codec;
2070 memset(&send_codec, 0, sizeof(send_codec));
2071
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002072 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002073 bool enable_codec_fec = false;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002074
minyue@webrtc.org26236952014-10-29 02:27:08 +00002075 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002076
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002077 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002078 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2079 it != codecs.end(); ++it) {
2080 // Ignore codecs we don't know about. The negotiation step should prevent
2081 // this, but double-check to be sure.
2082 webrtc::CodecInst voe_codec;
2083 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002084 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002085 continue;
2086 }
2087
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002088 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2089 // Skip telephone-event/CN codec, which will be handled later.
2090 continue;
2091 }
2092
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002093 // We'll use the first codec in the list to actually send audio data.
2094 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002095 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002096 // used is specified in params.
2097 if (IsRedCodec(it->name)) {
2098 // Parse out the RED parameters. If we fail, just ignore RED;
2099 // we don't support all possible params/usage scenarios.
2100 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2101 continue;
2102 }
2103
2104 // Enable redundant encoding of the specified codec. Treat any
2105 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002106#ifdef USE_WEBRTC_DEV_BRANCH
2107 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2108 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2109 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
2110#else
2111 // TODO(minyue): Remove code under #else case after new WebRTC roll.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002112 LOG(LS_INFO) << "Enabling FEC";
2113 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2114 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002115#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002116 return false;
2117 }
2118 } else {
2119 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002120 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002121 // For Opus as the send codec, we are to enable inband FEC if requested
2122 // and set maximum playback rate.
2123 if (IsOpus(*it)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002124 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
2125 &opus_max_playback_rate);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002126 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002127 }
2128 found_send_codec = true;
2129 break;
2130 }
2131
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002132 if (nack_enabled_ != nack_enabled) {
2133 SetNack(channel, nack_enabled);
2134 nack_enabled_ = nack_enabled;
2135 }
2136
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002137 if (!found_send_codec) {
2138 LOG(LS_WARNING) << "Received empty list of codecs.";
2139 return false;
2140 }
2141
2142 // Set the codec immediately, since SetVADStatus() depends on whether
2143 // the current codec is mono or stereo.
2144 if (!SetSendCodec(channel, send_codec))
2145 return false;
2146
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002147 // FEC should be enabled after SetSendCodec.
2148 if (enable_codec_fec) {
2149 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2150 << channel;
2151#ifdef USE_WEBRTC_DEV_BRANCH
2152 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2153 // Enable codec internal FEC. Treat any failure as fatal internal error.
2154 LOG_RTCERR2(SetFECStatus, channel, true);
2155 return false;
2156 }
2157#endif // USE_WEBRTC_DEV_BRANCH
2158 }
2159
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002160 // maxplaybackrate should be set after SetSendCodec.
minyue@webrtc.org26236952014-10-29 02:27:08 +00002161 // If opus_max_playback_rate <= 0, the default maximum playback rate of 48 kHz
2162 // will be used.
2163 if (opus_max_playback_rate > 0) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002164 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002165 << opus_max_playback_rate
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002166 << " Hz on channel "
2167 << channel;
2168#ifdef USE_WEBRTC_DEV_BRANCH
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002169 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
minyue@webrtc.org26236952014-10-29 02:27:08 +00002170 channel, opus_max_playback_rate) == -1) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002171 LOG(LS_WARNING) << "Could not set maximum playback rate.";
2172 }
2173#endif
2174 }
2175
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002176 // Always update the |send_codec_| to the currently set send codec.
2177 send_codec_.reset(new webrtc::CodecInst(send_codec));
2178
minyue@webrtc.org26236952014-10-29 02:27:08 +00002179 if (send_bitrate_setting_) {
2180 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002181 }
2182
2183 // Loop through the codecs list again to config the telephone-event/CN codec.
2184 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2185 it != codecs.end(); ++it) {
2186 // Ignore codecs we don't know about. The negotiation step should prevent
2187 // this, but double-check to be sure.
2188 webrtc::CodecInst voe_codec;
2189 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2190 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2191 continue;
2192 }
2193
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002194 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2195 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002196 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002197 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2198 channel, it->id) == -1) {
2199 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2200 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002201 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002202 } else if (IsCNCodec(it->name)) {
2203 // Turn voice activity detection/comfort noise on if supported.
2204 // Set the wideband CN payload type appropriately.
2205 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002206 webrtc::PayloadFrequencies cn_freq;
2207 switch (it->clockrate) {
2208 case 8000:
2209 cn_freq = webrtc::kFreq8000Hz;
2210 break;
2211 case 16000:
2212 cn_freq = webrtc::kFreq16000Hz;
2213 break;
2214 case 32000:
2215 cn_freq = webrtc::kFreq32000Hz;
2216 break;
2217 default:
2218 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2219 << " not supported.";
2220 continue;
2221 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002222 // Set the CN payloadtype and the VAD status.
2223 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2224 if (cn_freq != webrtc::kFreq8000Hz) {
2225 if (engine()->voe()->codec()->SetSendCNPayloadType(
2226 channel, it->id, cn_freq) == -1) {
2227 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2228 // TODO(ajm): This failure condition will be removed from VoE.
2229 // Restore the return here when we update to a new enough webrtc.
2230 //
2231 // Not returning false because the SetSendCNPayloadType will fail if
2232 // the channel is already sending.
2233 // This can happen if the remote description is applied twice, for
2234 // example in the case of ROAP on top of JSEP, where both side will
2235 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002236 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002237 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002238 // Only turn on VAD if we have a CN payload type that matches the
2239 // clockrate for the codec we are going to use.
2240 if (it->clockrate == send_codec.plfreq) {
2241 LOG(LS_INFO) << "Enabling VAD";
2242 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2243 LOG_RTCERR2(SetVADStatus, channel, true);
2244 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002245 }
2246 }
2247 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002248 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002249 return true;
2250}
2251
2252bool WebRtcVoiceMediaChannel::SetSendCodecs(
2253 const std::vector<AudioCodec>& codecs) {
2254 dtmf_allowed_ = false;
2255 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2256 it != codecs.end(); ++it) {
2257 // Find the DTMF telephone event "codec".
2258 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2259 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2260 dtmf_allowed_ = true;
2261 }
2262 }
2263
2264 // Cache the codecs in order to configure the channel created later.
2265 send_codecs_ = codecs;
2266 for (ChannelMap::iterator iter = send_channels_.begin();
2267 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002268 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002269 return false;
2270 }
2271 }
2272
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002273 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002274 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002275 return true;
2276}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002277
2278void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2279 bool nack_enabled) {
2280 for (ChannelMap::const_iterator it = channels.begin();
2281 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002282 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002283 }
2284}
2285
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002286void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002287 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002288 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002289 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2290 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002291 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002292 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2293 }
2294}
2295
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002296bool WebRtcVoiceMediaChannel::SetSendCodec(
2297 const webrtc::CodecInst& send_codec) {
2298 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2299 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002300 for (ChannelMap::iterator iter = send_channels_.begin();
2301 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002302 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002303 return false;
2304 }
2305
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002306 return true;
2307}
2308
2309bool WebRtcVoiceMediaChannel::SetSendCodec(
2310 int channel, const webrtc::CodecInst& send_codec) {
2311 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2312 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2313
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002314 webrtc::CodecInst current_codec;
2315 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2316 (send_codec == current_codec)) {
2317 // Codec is already configured, we can return without setting it again.
2318 return true;
2319 }
2320
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002321 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2322 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002323 return false;
2324 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002325 return true;
2326}
2327
2328bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2329 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002330 if (receive_extensions_ == extensions) {
2331 return true;
2332 }
2333
2334 // The default channel may or may not be in |receive_channels_|. Set the rtp
2335 // header extensions for default channel regardless.
2336 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2337 return false;
2338 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002339
2340 // Loop through all receive channels and enable/disable the extensions.
2341 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2342 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002343 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2344 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002345 return false;
2346 }
2347 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002348
2349 receive_extensions_ = extensions;
2350 return true;
2351}
2352
2353bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2354 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002355 const RtpHeaderExtension* audio_level_extension =
2356 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2357 if (!SetHeaderExtension(
2358 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2359 audio_level_extension)) {
2360 return false;
2361 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002362
2363 const RtpHeaderExtension* send_time_extension =
2364 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2365 if (!SetHeaderExtension(
2366 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2367 send_time_extension)) {
2368 return false;
2369 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002370 return true;
2371}
2372
2373bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2374 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002375 if (send_extensions_ == extensions) {
2376 return true;
2377 }
2378
2379 // The default channel may or may not be in |send_channels_|. Set the rtp
2380 // header extensions for default channel regardless.
2381
2382 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2383 return false;
2384 }
2385
2386 // Loop through all send channels and enable/disable the extensions.
2387 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2388 channel_it != send_channels_.end(); ++channel_it) {
2389 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2390 extensions)) {
2391 return false;
2392 }
2393 }
2394
2395 send_extensions_ = extensions;
2396 return true;
2397}
2398
2399bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2400 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002401 const RtpHeaderExtension* audio_level_extension =
2402 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002403
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002404 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002405 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002406 audio_level_extension)) {
2407 return false;
2408 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002409
2410 const RtpHeaderExtension* send_time_extension =
2411 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002412 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002413 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002414 send_time_extension)) {
2415 return false;
2416 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002417
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002418 return true;
2419}
2420
2421bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2422 desired_playout_ = playout;
2423 return ChangePlayout(desired_playout_);
2424}
2425
2426bool WebRtcVoiceMediaChannel::PausePlayout() {
2427 return ChangePlayout(false);
2428}
2429
2430bool WebRtcVoiceMediaChannel::ResumePlayout() {
2431 return ChangePlayout(desired_playout_);
2432}
2433
2434bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2435 if (playout_ == playout) {
2436 return true;
2437 }
2438
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002439 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002440 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002441 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002442 // Only toggle the default channel if we don't have any other channels.
2443 result = SetPlayout(voe_channel(), playout);
2444 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002445 for (ChannelMap::iterator it = receive_channels_.begin();
2446 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002447 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002448 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002449 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002450 result = false;
2451 }
2452 }
2453
2454 if (result) {
2455 playout_ = playout;
2456 }
2457 return result;
2458}
2459
2460bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2461 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002462 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002463 return ChangeSend(desired_send_);
2464 return true;
2465}
2466
2467bool WebRtcVoiceMediaChannel::PauseSend() {
2468 return ChangeSend(SEND_NOTHING);
2469}
2470
2471bool WebRtcVoiceMediaChannel::ResumeSend() {
2472 return ChangeSend(desired_send_);
2473}
2474
2475bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2476 if (send_ == send) {
2477 return true;
2478 }
2479
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002480 // Change the settings on each send channel.
2481 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002482 engine()->SetOptionOverrides(options_);
2483
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002484 // Change the settings on each send channel.
2485 for (ChannelMap::iterator iter = send_channels_.begin();
2486 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002487 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002488 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002489 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002490
2491 // Clear up the options after stopping sending.
2492 if (send == SEND_NOTHING)
2493 engine()->ClearOptionOverrides();
2494
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002495 send_ = send;
2496 return true;
2497}
2498
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002499bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2500 if (send == SEND_MICROPHONE) {
2501 if (engine()->voe()->base()->StartSend(channel) == -1) {
2502 LOG_RTCERR1(StartSend, channel);
2503 return false;
2504 }
2505 if (engine()->voe()->file() &&
2506 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2507 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2508 return false;
2509 }
2510 } else { // SEND_NOTHING
2511 ASSERT(send == SEND_NOTHING);
2512 if (engine()->voe()->base()->StopSend(channel) == -1) {
2513 LOG_RTCERR1(StopSend, channel);
2514 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002515 }
2516 }
2517
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002518 return true;
2519}
2520
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002521// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002522void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2523 if (engine()->voe()->network()->RegisterExternalTransport(
2524 channel, *this) == -1) {
2525 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2526 }
2527
2528 // Enable RTCP (for quality stats and feedback messages)
2529 EnableRtcp(channel);
2530
2531 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2532 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002533
2534 // Set RTP header extension for the new channel.
2535 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002536}
2537
2538bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2539 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2540 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2541 }
2542
2543 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2544 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002545 return false;
2546 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002547
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002548 return true;
2549}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002550
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002551bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2552 // If the default channel is already used for sending create a new channel
2553 // otherwise use the default channel for sending.
2554 int channel = GetSendChannelNum(sp.first_ssrc());
2555 if (channel != -1) {
2556 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2557 return false;
2558 }
2559
2560 bool default_channel_is_available = true;
2561 for (ChannelMap::const_iterator iter = send_channels_.begin();
2562 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002563 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002564 default_channel_is_available = false;
2565 break;
2566 }
2567 }
2568 if (default_channel_is_available) {
2569 channel = voe_channel();
2570 } else {
2571 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002572 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002573 if (channel == -1) {
2574 LOG_RTCERR0(CreateChannel);
2575 return false;
2576 }
2577
2578 ConfigureSendChannel(channel);
2579 }
2580
2581 // Save the channel to send_channels_, so that RemoveSendStream() can still
2582 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002583 webrtc::AudioTransport* audio_transport =
2584 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002585 send_channels_.insert(std::make_pair(
2586 sp.first_ssrc(),
2587 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002588
2589 // Set the send (local) SSRC.
2590 // If there are multiple send SSRCs, we can only set the first one here, and
2591 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2592 // (with a codec requires multiple SSRC(s)).
2593 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2594 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2595 return false;
2596 }
2597
2598 // At this point the channel's local SSRC has been updated. If the channel is
2599 // the default channel make sure that all the receive channels are updated as
2600 // well. Receive channels have to have the same SSRC as the default channel in
2601 // order to send receiver reports with this SSRC.
2602 if (IsDefaultChannel(channel)) {
2603 for (ChannelMap::const_iterator it = receive_channels_.begin();
2604 it != receive_channels_.end(); ++it) {
2605 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002606 if (!IsDefaultChannel(it->second->channel())) {
2607 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002608 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002609 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002610 return false;
2611 }
2612 }
2613 }
2614 }
2615
2616 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002617 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2618 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002619 }
2620
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002621 // Set the current codecs to be used for the new channel.
2622 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002623 return false;
2624
2625 return ChangeSend(channel, desired_send_);
2626}
2627
2628bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2629 ChannelMap::iterator it = send_channels_.find(ssrc);
2630 if (it == send_channels_.end()) {
2631 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2632 << " which doesn't exist.";
2633 return false;
2634 }
2635
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002636 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002637 ChangeSend(channel, SEND_NOTHING);
2638
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002639 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2640 // this will disconnect the audio renderer with the send channel.
2641 delete it->second;
2642 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002643
2644 if (IsDefaultChannel(channel)) {
2645 // Do not delete the default channel since the receive channels depend on
2646 // the default channel, recycle it instead.
2647 ChangeSend(channel, SEND_NOTHING);
2648 } else {
2649 // Clean up and delete the send channel.
2650 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2651 << " with VoiceEngine channel #" << channel << ".";
2652 if (!DeleteChannel(channel))
2653 return false;
2654 }
2655
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002656 if (send_channels_.empty())
2657 ChangeSend(SEND_NOTHING);
2658
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002659 return true;
2660}
2661
2662bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002663 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002664
2665 if (!VERIFY(sp.ssrcs.size() == 1))
2666 return false;
2667 uint32 ssrc = sp.first_ssrc();
2668
wu@webrtc.org78187522013-10-07 23:32:02 +00002669 if (ssrc == 0) {
2670 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2671 return false;
2672 }
2673
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002674 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2675 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002676 return false;
2677 }
2678
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002679 // Reuse default channel for recv stream in non-conference mode call
2680 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002681 webrtc::AudioTransport* audio_transport =
2682 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002683 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2684 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2685 << " reuse default channel";
2686 default_receive_ssrc_ = sp.first_ssrc();
2687 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002688 default_receive_ssrc_,
2689 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002690 if (!SetupSharedBweOnChannel(voe_channel())) {
2691 return false;
2692 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002693 return SetPlayout(voe_channel(), playout_);
2694 }
2695
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002696 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002697 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002698 if (channel == -1) {
2699 LOG_RTCERR0(CreateChannel);
2700 return false;
2701 }
2702
wu@webrtc.org78187522013-10-07 23:32:02 +00002703 if (!ConfigureRecvChannel(channel)) {
2704 DeleteChannel(channel);
2705 return false;
2706 }
2707
2708 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002709 std::make_pair(
2710 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002711
2712 LOG(LS_INFO) << "New audio stream " << ssrc
2713 << " registered to VoiceEngine channel #"
2714 << channel << ".";
2715 return true;
2716}
2717
2718bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002719 // Configure to use external transport, like our default channel.
2720 if (engine()->voe()->network()->RegisterExternalTransport(
2721 channel, *this) == -1) {
2722 LOG_RTCERR2(SetExternalTransport, channel, this);
2723 return false;
2724 }
2725
2726 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002727 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002728 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2729 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002730 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002731 return false;
2732 }
2733 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002734 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002735 return false;
2736 }
2737
2738 // Use the same recv payload types as our default channel.
2739 ResetRecvCodecs(channel);
2740 if (!recv_codecs_.empty()) {
2741 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2742 it != recv_codecs_.end(); ++it) {
2743 webrtc::CodecInst voe_codec;
2744 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2745 voe_codec.pltype = it->id;
2746 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2747 if (engine()->voe()->codec()->GetRecPayloadType(
2748 voe_channel(), voe_codec) != -1) {
2749 if (engine()->voe()->codec()->SetRecPayloadType(
2750 channel, voe_codec) == -1) {
2751 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2752 return false;
2753 }
2754 }
2755 }
2756 }
2757 }
2758
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002759 if (InConferenceMode()) {
2760 // To be in par with the video, voe_channel() is not used for receiving in
2761 // a conference call.
2762 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2763 // This is the first stream in a multi user meeting. We can now
2764 // disable playback of the default stream. This since the default
2765 // stream will probably have received some initial packets before
2766 // the new stream was added. This will mean that the CN state from
2767 // the default channel will be mixed in with the other streams
2768 // throughout the whole meeting, which might be disturbing.
2769 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2770 SetPlayout(voe_channel(), false);
2771 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002772 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002773 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002774
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002775 // Set RTP header extension for the new channel.
2776 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2777 return false;
2778 }
2779
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002780 // Set up channel to be able to forward incoming packets to video engine BWE.
2781 if (!SetupSharedBweOnChannel(channel)) {
2782 return false;
2783 }
2784
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002785 return SetPlayout(channel, playout_);
2786}
2787
2788bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002789 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002790 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002791 if (it == receive_channels_.end()) {
2792 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2793 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002794 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002795 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002796
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002797 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2798 // will disconnect the audio renderer with the receive channel.
2799 // Cache the channel before the deletion.
2800 const int channel = it->second->channel();
2801 delete it->second;
2802 receive_channels_.erase(it);
2803
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002804 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002805 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002806 // Recycle the default channel is for recv stream.
2807 if (playout_)
2808 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002809
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002810 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002811 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002812 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002813
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002814 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002815 << " with VoiceEngine channel #" << channel << ".";
2816 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002817 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002818
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002819 bool enable_default_channel_playout = false;
2820 if (receive_channels_.empty()) {
2821 // The last stream was removed. We can now enable the default
2822 // channel for new channels to be played out immediately without
2823 // waiting for AddStream messages.
2824 // We do this for both conference mode and non-conference mode.
2825 // TODO(oja): Does the default channel still have it's CN state?
2826 enable_default_channel_playout = true;
2827 }
2828 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2829 default_receive_ssrc_ != 0) {
2830 // Only the default channel is active, enable the playout on default
2831 // channel.
2832 enable_default_channel_playout = true;
2833 }
2834 if (enable_default_channel_playout && playout_) {
2835 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2836 SetPlayout(voe_channel(), true);
2837 }
2838
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002839 return true;
2840}
2841
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002842bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2843 AudioRenderer* renderer) {
2844 ChannelMap::iterator it = receive_channels_.find(ssrc);
2845 if (it == receive_channels_.end()) {
2846 if (renderer) {
2847 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002848 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002849 return false;
2850 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002851
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002852 // The channel likely has gone away, do nothing.
2853 return true;
2854 }
2855
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002856 if (renderer)
2857 it->second->Start(renderer);
2858 else
2859 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002860
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002861 return true;
2862}
2863
2864bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2865 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002866 ChannelMap::iterator it = send_channels_.find(ssrc);
2867 if (it == send_channels_.end()) {
2868 if (renderer) {
2869 // Return an error if trying to set a valid renderer with an invalid ssrc.
2870 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2871 return false;
2872 }
2873
2874 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002875 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002876 }
2877
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002878 if (renderer)
2879 it->second->Start(renderer);
2880 else
2881 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002882
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002883 return true;
2884}
2885
2886bool WebRtcVoiceMediaChannel::GetActiveStreams(
2887 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002888 // In conference mode, the default channel should not be in
2889 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002890 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002891 for (ChannelMap::iterator it = receive_channels_.begin();
2892 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002893 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002894 if (level > 0) {
2895 actives->push_back(std::make_pair(it->first, level));
2896 }
2897 }
2898 return true;
2899}
2900
2901int WebRtcVoiceMediaChannel::GetOutputLevel() {
2902 // return the highest output level of all streams
2903 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002904 for (ChannelMap::iterator it = receive_channels_.begin();
2905 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002906 int level = GetOutputLevel(it->second->channel());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002907 highest = rtc::_max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002908 }
2909 return highest;
2910}
2911
2912int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2913 int ret;
2914 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2915 // In case of error, log the info and continue
2916 LOG_RTCERR0(TimeSinceLastTyping);
2917 ret = -1;
2918 } else {
2919 ret *= 1000; // We return ms, webrtc returns seconds.
2920 }
2921 return ret;
2922}
2923
2924void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2925 int cost_per_typing, int reporting_threshold, int penalty_decay,
2926 int type_event_delay) {
2927 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2928 time_window, cost_per_typing,
2929 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2930 // In case of error, log the info and continue
2931 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2932 cost_per_typing, reporting_threshold, penalty_decay,
2933 type_event_delay);
2934 }
2935}
2936
2937bool WebRtcVoiceMediaChannel::SetOutputScaling(
2938 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002939 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002940 // Collect the channels to scale the output volume.
2941 std::vector<int> channels;
2942 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002943 // Default channel is not in receive_channels_ if it is not being used for
2944 // playout.
2945 if (default_receive_ssrc_ == 0)
2946 channels.push_back(voe_channel());
2947 for (ChannelMap::const_iterator it = receive_channels_.begin();
2948 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002949 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002950 }
2951 } else { // Collect only the channel of the specified ssrc.
2952 int channel = GetReceiveChannelNum(ssrc);
2953 if (-1 == channel) {
2954 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2955 return false;
2956 }
2957 channels.push_back(channel);
2958 }
2959
2960 // Scale the output volume for the collected channels. We first normalize to
2961 // scale the volume and then set the left and right pan.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002962 float scale = static_cast<float>(rtc::_max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002963 if (scale > 0.0001f) {
2964 left /= scale;
2965 right /= scale;
2966 }
2967 for (std::vector<int>::const_iterator it = channels.begin();
2968 it != channels.end(); ++it) {
2969 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2970 *it, scale)) {
2971 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2972 return false;
2973 }
2974 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2975 *it, static_cast<float>(left), static_cast<float>(right))) {
2976 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2977 // Do not return if fails. SetOutputVolumePan is not available for all
2978 // pltforms.
2979 }
2980 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2981 << " right=" << right * scale
2982 << " for channel " << *it << " and ssrc " << ssrc;
2983 }
2984 return true;
2985}
2986
2987bool WebRtcVoiceMediaChannel::GetOutputScaling(
2988 uint32 ssrc, double* left, double* right) {
2989 if (!left || !right) return false;
2990
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002991 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002992 // Determine which channel based on ssrc.
2993 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2994 if (channel == -1) {
2995 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2996 return false;
2997 }
2998
2999 float scaling;
3000 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
3001 channel, scaling)) {
3002 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
3003 return false;
3004 }
3005
3006 float left_pan;
3007 float right_pan;
3008 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
3009 channel, left_pan, right_pan)) {
3010 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
3011 // If GetOutputVolumePan fails, we use the default left and right pan.
3012 left_pan = 1.0f;
3013 right_pan = 1.0f;
3014 }
3015
3016 *left = scaling * left_pan;
3017 *right = scaling * right_pan;
3018 return true;
3019}
3020
3021bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
3022 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
3023 return true;
3024}
3025
3026bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
3027 bool play, bool loop) {
3028 if (!ringback_tone_) {
3029 return false;
3030 }
3031
3032 // The voe file api is not available in chrome.
3033 if (!engine()->voe()->file()) {
3034 return false;
3035 }
3036
3037 // Determine which VoiceEngine channel to play on.
3038 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
3039 if (channel == -1) {
3040 return false;
3041 }
3042
3043 // Make sure the ringtone is cued properly, and play it out.
3044 if (play) {
3045 ringback_tone_->set_loop(loop);
3046 ringback_tone_->Rewind();
3047 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
3048 ringback_tone_.get()) == -1) {
3049 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
3050 LOG(LS_ERROR) << "Unable to start ringback tone";
3051 return false;
3052 }
3053 ringback_channels_.insert(channel);
3054 LOG(LS_INFO) << "Started ringback on channel " << channel;
3055 } else {
3056 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
3057 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
3058 LOG_RTCERR1(StopPlayingFileLocally, channel);
3059 return false;
3060 }
3061 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
3062 ringback_channels_.erase(channel);
3063 }
3064
3065 return true;
3066}
3067
3068bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3069 return dtmf_allowed_;
3070}
3071
3072bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3073 int duration, int flags) {
3074 if (!dtmf_allowed_) {
3075 return false;
3076 }
3077
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003078 // Send the event.
3079 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003080 int channel = -1;
3081 if (ssrc == 0) {
3082 bool default_channel_is_inuse = false;
3083 for (ChannelMap::const_iterator iter = send_channels_.begin();
3084 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003085 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003086 default_channel_is_inuse = true;
3087 break;
3088 }
3089 }
3090 if (default_channel_is_inuse) {
3091 channel = voe_channel();
3092 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003093 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003094 }
3095 } else {
3096 channel = GetSendChannelNum(ssrc);
3097 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003098 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003099 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3100 << ssrc << " is not in use.";
3101 return false;
3102 }
3103 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003104 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3105 channel, event, true, duration) == -1) {
3106 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003107 return false;
3108 }
3109 }
3110
3111 // Play the event.
3112 if (flags & cricket::DF_PLAY) {
3113 // Play DTMF tone locally.
3114 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3115 LOG_RTCERR2(PlayDtmfTone, event, duration);
3116 return false;
3117 }
3118 }
3119
3120 return true;
3121}
3122
wu@webrtc.orga9890802013-12-13 00:21:03 +00003123void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003124 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003125 // Pick which channel to send this packet to. If this packet doesn't match
3126 // any multiplexed streams, just send it to the default channel. Otherwise,
3127 // send it to the specific decoder instance for that stream.
3128 int which_channel = GetReceiveChannelNum(
3129 ParseSsrc(packet->data(), packet->length(), false));
3130 if (which_channel == -1) {
3131 which_channel = voe_channel();
3132 }
3133
3134 // Stop any ringback that might be playing on the channel.
3135 // It's possible the ringback has already stopped, ih which case we'll just
3136 // use the opportunity to remove the channel from ringback_channels_.
3137 if (engine()->voe()->file()) {
3138 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3139 if (it != ringback_channels_.end()) {
3140 if (engine()->voe()->file()->IsPlayingFileLocally(
3141 which_channel) == 1) {
3142 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3143 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3144 << " due to incoming media";
3145 }
3146 ringback_channels_.erase(which_channel);
3147 }
3148 }
3149
3150 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003151 engine()->voe()->network()->ReceivedRTPPacket(
3152 which_channel,
3153 packet->data(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003154 static_cast<unsigned int>(packet->length()),
3155 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003156}
3157
wu@webrtc.orga9890802013-12-13 00:21:03 +00003158void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003159 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003160 // Sending channels need all RTCP packets with feedback information.
3161 // Even sender reports can contain attached report blocks.
3162 // Receiving channels need sender reports in order to create
3163 // correct receiver reports.
3164 int type = 0;
3165 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3166 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3167 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003168 }
3169
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003170 // If it is a sender report, find the channel that is listening.
3171 bool has_sent_to_default_channel = false;
3172 if (type == kRtcpTypeSR) {
3173 int which_channel = GetReceiveChannelNum(
3174 ParseSsrc(packet->data(), packet->length(), true));
3175 if (which_channel != -1) {
3176 engine()->voe()->network()->ReceivedRTCPPacket(
3177 which_channel,
3178 packet->data(),
3179 static_cast<unsigned int>(packet->length()));
3180
3181 if (IsDefaultChannel(which_channel))
3182 has_sent_to_default_channel = true;
3183 }
3184 }
3185
3186 // SR may continue RR and any RR entry may correspond to any one of the send
3187 // channels. So all RTCP packets must be forwarded all send channels. VoE
3188 // will filter out RR internally.
3189 for (ChannelMap::iterator iter = send_channels_.begin();
3190 iter != send_channels_.end(); ++iter) {
3191 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003192 if (IsDefaultChannel(iter->second->channel()) &&
3193 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003194 continue;
3195
3196 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003197 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003198 packet->data(),
3199 static_cast<unsigned int>(packet->length()));
3200 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003201}
3202
3203bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003204 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3205 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003206 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3207 return false;
3208 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003209 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3210 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003211 return false;
3212 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003213 // We set the AGC to mute state only when all the channels are muted.
3214 // This implementation is not ideal, instead we should signal the AGC when
3215 // the mic channel is muted/unmuted. We can't do it today because there
3216 // is no good way to know which stream is mapping to the mic channel.
3217 bool all_muted = muted;
3218 for (ChannelMap::const_iterator iter = send_channels_.begin();
3219 iter != send_channels_.end() && all_muted; ++iter) {
3220 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3221 all_muted)) {
3222 LOG_RTCERR1(GetInputMute, iter->second->channel());
3223 return false;
3224 }
3225 }
3226
3227 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3228 if (ap)
3229 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003230 return true;
3231}
3232
minyue@webrtc.org26236952014-10-29 02:27:08 +00003233// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3234// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003235bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003236 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003237
minyue@webrtc.org26236952014-10-29 02:27:08 +00003238 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003239}
3240
minyue@webrtc.org26236952014-10-29 02:27:08 +00003241bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3242 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003243
minyue@webrtc.org26236952014-10-29 02:27:08 +00003244 send_bitrate_setting_ = true;
3245 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003246
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003247 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003248 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003249 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003250 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003251 }
3252
minyue@webrtc.org26236952014-10-29 02:27:08 +00003253 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003254 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3255 // SetMaxSendBandwith(0), the second call removes the previous limit.
3256 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003257 return true;
3258
3259 webrtc::CodecInst codec = *send_codec_;
3260 bool is_multi_rate = IsCodecMultiRate(codec);
3261
3262 if (is_multi_rate) {
3263 // If codec is multi-rate then just set the bitrate.
3264 codec.rate = bps;
3265 if (!SetSendCodec(codec)) {
3266 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3267 << " to bitrate " << bps << " bps.";
3268 return false;
3269 }
3270 return true;
3271 } else {
3272 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3273 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3274 // fixed bitrate then ignore.
3275 if (bps < codec.rate) {
3276 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3277 << " to bitrate " << bps << " bps"
3278 << ", requires at least " << codec.rate << " bps.";
3279 return false;
3280 }
3281 return true;
3282 }
3283}
3284
3285bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003286 bool echo_metrics_on = false;
3287 // These can take on valid negative values, so use the lowest possible level
3288 // as default rather than -1.
3289 int echo_return_loss = -100;
3290 int echo_return_loss_enhancement = -100;
3291 // These can also be negative, but in practice -1 is only used to signal
3292 // insufficient data, since the resolution is limited to multiples of 4 ms.
3293 int echo_delay_median_ms = -1;
3294 int echo_delay_std_ms = -1;
3295 if (engine()->voe()->processing()->GetEcMetricsStatus(
3296 echo_metrics_on) != -1 && echo_metrics_on) {
3297 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3298 // here, but it appears to be unsuitable currently. Revisit after this is
3299 // investigated: http://b/issue?id=5666755
3300 int erl, erle, rerl, anlp;
3301 if (engine()->voe()->processing()->GetEchoMetrics(
3302 erl, erle, rerl, anlp) != -1) {
3303 echo_return_loss = erl;
3304 echo_return_loss_enhancement = erle;
3305 }
3306
3307 int median, std;
3308 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3309 echo_delay_median_ms = median;
3310 echo_delay_std_ms = std;
3311 }
3312 }
3313
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003314 webrtc::CallStatistics cs;
3315 unsigned int ssrc;
3316 webrtc::CodecInst codec;
3317 unsigned int level;
3318
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003319 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3320 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003321 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003322
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003323 // Fill in the sender info, based on what we know, and what the
3324 // remote side told us it got from its RTCP report.
3325 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003326
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003327 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3328 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3329 continue;
3330 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003331
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003332 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003333 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3334 sinfo.bytes_sent = cs.bytesSent;
3335 sinfo.packets_sent = cs.packetsSent;
3336 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3337 // returns 0 to indicate an error value.
3338 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3339
3340 // Get data from the last remote RTCP report. Use default values if no data
3341 // available.
3342 sinfo.fraction_lost = -1.0;
3343 sinfo.jitter_ms = -1;
3344 sinfo.packets_lost = -1;
3345 sinfo.ext_seqnum = -1;
3346 std::vector<webrtc::ReportBlock> receive_blocks;
3347 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3348 channel, &receive_blocks) != -1 &&
3349 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3350 std::vector<webrtc::ReportBlock>::iterator iter;
3351 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3352 ++iter) {
3353 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003354 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003355 // Convert Q8 to floating point.
3356 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3357 // Convert samples to milliseconds.
3358 if (codec.plfreq / 1000 > 0) {
3359 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3360 }
3361 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3362 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3363 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003364 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003365 }
3366 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003367
3368 // Local speech level.
3369 sinfo.audio_level = (engine()->voe()->volume()->
3370 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3371
3372 // TODO(xians): We are injecting the same APM logging to all the send
3373 // channels here because there is no good way to know which send channel
3374 // is using the APM. The correct fix is to allow the send channels to have
3375 // their own APM so that we can feed the correct APM logging to different
3376 // send channels. See issue crbug/264611 .
3377 sinfo.echo_return_loss = echo_return_loss;
3378 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3379 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3380 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003381 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3382 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003383 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003384
3385 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003386 }
3387
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003388 // Build the list of receivers, one for each receiving channel, or 1 in
3389 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003390 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003391 for (ChannelMap::const_iterator it = receive_channels_.begin();
3392 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003393 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003394 }
3395 if (channels.empty()) {
3396 channels.push_back(voe_channel());
3397 }
3398
3399 // Get the SSRC and stats for each receiver, based on our own calculations.
3400 for (std::vector<int>::const_iterator it = channels.begin();
3401 it != channels.end(); ++it) {
3402 memset(&cs, 0, sizeof(cs));
3403 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3404 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3405 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3406 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003407 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003408 rinfo.bytes_rcvd = cs.bytesReceived;
3409 rinfo.packets_rcvd = cs.packetsReceived;
3410 // The next four fields are from the most recently sent RTCP report.
3411 // Convert Q8 to floating point.
3412 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3413 rinfo.packets_lost = cs.cumulativeLost;
3414 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003415#ifdef USE_WEBRTC_DEV_BRANCH
3416 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
3417#endif
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003418 if (codec.pltype != -1) {
3419 rinfo.codec_name = codec.plname;
3420 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003421 // Convert samples to milliseconds.
3422 if (codec.plfreq / 1000 > 0) {
3423 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3424 }
3425
3426 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3427 webrtc::NetworkStatistics ns;
3428 if (engine()->voe()->neteq() &&
3429 engine()->voe()->neteq()->GetNetworkStatistics(
3430 *it, ns) != -1) {
3431 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3432 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3433 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003434 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003435 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003436
3437 webrtc::AudioDecodingCallStats ds;
3438 if (engine()->voe()->neteq() &&
3439 engine()->voe()->neteq()->GetDecodingCallStatistics(
3440 *it, &ds) != -1) {
3441 rinfo.decoding_calls_to_silence_generator =
3442 ds.calls_to_silence_generator;
3443 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3444 rinfo.decoding_normal = ds.decoded_normal;
3445 rinfo.decoding_plc = ds.decoded_plc;
3446 rinfo.decoding_cng = ds.decoded_cng;
3447 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3448 }
3449
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003450 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003451 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003452 int playout_buffer_delay_ms = 0;
3453 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003454 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3455 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3456 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003457 }
3458
3459 // Get speech level.
3460 rinfo.audio_level = (engine()->voe()->volume()->
3461 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3462 info->receivers.push_back(rinfo);
3463 }
3464 }
3465
3466 return true;
3467}
3468
3469void WebRtcVoiceMediaChannel::GetLastMediaError(
3470 uint32* ssrc, VoiceMediaChannel::Error* error) {
3471 ASSERT(ssrc != NULL);
3472 ASSERT(error != NULL);
3473 FindSsrc(voe_channel(), ssrc);
3474 *error = WebRtcErrorToChannelError(GetLastEngineError());
3475}
3476
3477bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003478 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003479 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003480 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003481 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3482 // This means the error is not limited to a specific channel. Signal the
3483 // message using ssrc=0. If the current channel is sending, use this
3484 // channel for sending the message.
3485 *ssrc = 0;
3486 return true;
3487 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003488 // Check whether this is a sending channel.
3489 for (ChannelMap::const_iterator it = send_channels_.begin();
3490 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003491 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003492 // This is a sending channel.
3493 uint32 local_ssrc = 0;
3494 if (engine()->voe()->rtp()->GetLocalSSRC(
3495 channel_num, local_ssrc) != -1) {
3496 *ssrc = local_ssrc;
3497 }
3498 return true;
3499 }
3500 }
3501
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003502 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003503 for (ChannelMap::const_iterator it = receive_channels_.begin();
3504 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003505 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003506 *ssrc = it->first;
3507 return true;
3508 }
3509 }
3510 }
3511 return false;
3512}
3513
3514void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003515 if (error == VE_TYPING_NOISE_WARNING) {
3516 typing_noise_detected_ = true;
3517 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3518 typing_noise_detected_ = false;
3519 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003520 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3521}
3522
3523int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3524 unsigned int ulevel;
3525 int ret =
3526 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3527 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3528}
3529
3530int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003531 ChannelMap::iterator it = receive_channels_.find(ssrc);
3532 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003533 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003534 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3535}
3536
3537int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003538 ChannelMap::iterator it = send_channels_.find(ssrc);
3539 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003540 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003541
3542 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003543}
3544
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003545bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
3546 webrtc::VideoEngine* vie, int vie_channel) {
3547 shared_bwe_vie_ = vie;
3548 shared_bwe_vie_channel_ = vie_channel;
3549
3550 if (!SetupSharedBweOnChannel(voe_channel())) {
3551 return false;
3552 }
3553 for (ChannelMap::iterator it = receive_channels_.begin();
3554 it != receive_channels_.end(); ++it) {
3555 if (!SetupSharedBweOnChannel(it->second->channel())) {
3556 return false;
3557 }
3558 }
3559 return true;
3560}
3561
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003562bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3563 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3564 // Get the RED encodings from the parameter with no name. This may
3565 // change based on what is discussed on the Jingle list.
3566 // The encoding parameter is of the form "a/b"; we only support where
3567 // a == b. Verify this and parse out the value into red_pt.
3568 // If the parameter value is absent (as it will be until we wire up the
3569 // signaling of this message), use the second codec specified (i.e. the
3570 // one after "red") as the encoding parameter.
3571 int red_pt = -1;
3572 std::string red_params;
3573 CodecParameterMap::const_iterator it = red_codec.params.find("");
3574 if (it != red_codec.params.end()) {
3575 red_params = it->second;
3576 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003577 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003578 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003579 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003580 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3581 return false;
3582 }
3583 } else if (red_codec.params.empty()) {
3584 LOG(LS_WARNING) << "RED params not present, using defaults";
3585 if (all_codecs.size() > 1) {
3586 red_pt = all_codecs[1].id;
3587 }
3588 }
3589
3590 // Try to find red_pt in |codecs|.
3591 std::vector<AudioCodec>::const_iterator codec;
3592 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3593 if (codec->id == red_pt)
3594 break;
3595 }
3596
3597 // If we find the right codec, that will be the codec we pass to
3598 // SetSendCodec, with the desired payload type.
3599 if (codec != all_codecs.end() &&
3600 engine()->FindWebRtcCodec(*codec, send_codec)) {
3601 } else {
3602 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3603 return false;
3604 }
3605
3606 return true;
3607}
3608
3609bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3610 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003611 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003612 return false;
3613 }
3614 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3615 // what we want to do with them.
3616 // engine()->voe().EnableVQMon(voe_channel(), true);
3617 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3618 return true;
3619}
3620
3621bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3622 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3623 for (int i = 0; i < ncodecs; ++i) {
3624 webrtc::CodecInst voe_codec;
3625 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3626 voe_codec.pltype = -1;
3627 if (engine()->voe()->codec()->SetRecPayloadType(
3628 channel, voe_codec) == -1) {
3629 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3630 return false;
3631 }
3632 }
3633 }
3634 return true;
3635}
3636
3637bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3638 if (playout) {
3639 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3640 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3641 LOG_RTCERR1(StartPlayout, channel);
3642 return false;
3643 }
3644 } else {
3645 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3646 engine()->voe()->base()->StopPlayout(channel);
3647 }
3648 return true;
3649}
3650
3651uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3652 bool rtcp) {
3653 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3654 uint32 ssrc = 0;
3655 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003656 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003657 }
3658 return ssrc;
3659}
3660
3661// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3662VoiceMediaChannel::Error
3663 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3664 switch (err_code) {
3665 case 0:
3666 return ERROR_NONE;
3667 case VE_CANNOT_START_RECORDING:
3668 case VE_MIC_VOL_ERROR:
3669 case VE_GET_MIC_VOL_ERROR:
3670 case VE_CANNOT_ACCESS_MIC_VOL:
3671 return ERROR_REC_DEVICE_OPEN_FAILED;
3672 case VE_SATURATION_WARNING:
3673 return ERROR_REC_DEVICE_SATURATION;
3674 case VE_REC_DEVICE_REMOVED:
3675 return ERROR_REC_DEVICE_REMOVED;
3676 case VE_RUNTIME_REC_WARNING:
3677 case VE_RUNTIME_REC_ERROR:
3678 return ERROR_REC_RUNTIME_ERROR;
3679 case VE_CANNOT_START_PLAYOUT:
3680 case VE_SPEAKER_VOL_ERROR:
3681 case VE_GET_SPEAKER_VOL_ERROR:
3682 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3683 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3684 case VE_RUNTIME_PLAY_WARNING:
3685 case VE_RUNTIME_PLAY_ERROR:
3686 return ERROR_PLAY_RUNTIME_ERROR;
3687 case VE_TYPING_NOISE_WARNING:
3688 return ERROR_REC_TYPING_NOISE_DETECTED;
3689 default:
3690 return VoiceMediaChannel::ERROR_OTHER;
3691 }
3692}
3693
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003694bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3695 int channel_id, const RtpHeaderExtension* extension) {
3696 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003697 int id = 0;
3698 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003699 if (extension) {
3700 enable = true;
3701 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003702 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003703 }
3704 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003705 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003706 return false;
3707 }
3708 return true;
3709}
3710
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003711bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
3712 webrtc::ViENetwork* vie_network = NULL;
3713 int vie_channel = -1;
3714 if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
3715 shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
3716 vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
3717 vie_channel = shared_bwe_vie_channel_;
3718 }
3719 if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
3720 vie_channel) == -1) {
3721 LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
3722 if (vie_network != NULL) {
3723 // Don't fail if we're tearing down.
3724 return false;
3725 }
3726 }
3727 return true;
3728}
3729
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003730int WebRtcSoundclipStream::Read(void *buf, int len) {
3731 size_t res = 0;
3732 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003733 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003734}
3735
3736int WebRtcSoundclipStream::Rewind() {
3737 mem_.Rewind();
3738 // Return -1 to keep VoiceEngine from looping.
3739 return (loop_) ? 0 : -1;
3740}
3741
3742} // namespace cricket
3743
3744#endif // HAVE_WEBRTC_VOICE