blob: df07cd5280514fe87c0767954688b2c066bad4ee [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#ifdef HAVE_CONFIG_H
29#include <config.h>
30#endif
31
32#ifdef HAVE_WEBRTC_VOICE
33
34#include "talk/media/webrtc/webrtcvoiceengine.h"
35
36#include <algorithm>
37#include <cstdio>
38#include <string>
39#include <vector>
40
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000041#include "talk/media/base/audiorenderer.h"
42#include "talk/media/base/constants.h"
43#include "talk/media/base/streamparams.h"
44#include "talk/media/base/voiceprocessor.h"
45#include "talk/media/webrtc/webrtcvoe.h"
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000046#include "webrtc/base/base64.h"
47#include "webrtc/base/byteorder.h"
48#include "webrtc/base/common.h"
49#include "webrtc/base/helpers.h"
50#include "webrtc/base/logging.h"
51#include "webrtc/base/stringencode.h"
52#include "webrtc/base/stringutils.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000053#include "webrtc/common.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054#include "webrtc/modules/audio_processing/include/audio_processing.h"
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +000055#include "webrtc/video_engine/include/vie_network.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056
57#ifdef WIN32
58#include <objbase.h> // NOLINT
59#endif
60
61namespace cricket {
62
63struct CodecPref {
64 const char* name;
65 int clockrate;
66 int channels;
67 int payload_type;
68 bool is_multi_rate;
69};
70
71static const CodecPref kCodecPrefs[] = {
72 { "OPUS", 48000, 2, 111, true },
73 { "ISAC", 16000, 1, 103, true },
74 { "ISAC", 32000, 1, 104, true },
75 { "CELT", 32000, 1, 109, true },
76 { "CELT", 32000, 2, 110, true },
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +000077 // G722 should be advertised as 8000 Hz because of the RFC "bug".
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +000078 { "G722", 8000, 1, 9, false },
henrike@webrtc.org28e20752013-07-10 00:45:36 +000079 { "ILBC", 8000, 1, 102, false },
80 { "PCMU", 8000, 1, 0, false },
81 { "PCMA", 8000, 1, 8, false },
82 { "CN", 48000, 1, 107, false },
83 { "CN", 32000, 1, 106, false },
84 { "CN", 16000, 1, 105, false },
85 { "CN", 8000, 1, 13, false },
86 { "red", 8000, 1, 127, false },
87 { "telephone-event", 8000, 1, 126, false },
88};
89
90// For Linux/Mac, using the default device is done by specifying index 0 for
91// VoE 4.0 and not -1 (which was the case for VoE 3.5).
92//
93// On Windows Vista and newer, Microsoft introduced the concept of "Default
94// Communications Device". This means that there are two types of default
95// devices (old Wave Audio style default and Default Communications Device).
96//
97// On Windows systems which only support Wave Audio style default, uses either
98// -1 or 0 to select the default device.
99//
100// On Windows systems which support both "Default Communication Device" and
101// old Wave Audio style default, use -1 for Default Communications Device and
102// -2 for Wave Audio style default, which is what we want to use for clips.
103// It's not clear yet whether the -2 index is handled properly on other OSes.
104
105#ifdef WIN32
106static const int kDefaultAudioDeviceId = -1;
107static const int kDefaultSoundclipDeviceId = -2;
108#else
109static const int kDefaultAudioDeviceId = 0;
110#endif
111
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112static const char kIsacCodecName[] = "ISAC";
113static const char kL16CodecName[] = "L16";
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000114static const char kG722CodecName[] = "G722";
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000115
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000116// Parameter used for NACK.
117// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
118static const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000119
120// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000121// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000122
123// Recommended bitrates:
124// 8-12 kb/s for NB speech,
125// 16-20 kb/s for WB speech,
126// 28-40 kb/s for FB speech,
127// 48-64 kb/s for FB mono music, and
128// 64-128 kb/s for FB stereo music.
129// The current implementation applies the following values to mono signals,
130// and multiplies them by 2 for stereo.
131static const int kOpusBitrateNb = 12000;
132static const int kOpusBitrateWb = 20000;
133static const int kOpusBitrateFb = 32000;
134
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000135// Opus bitrate should be in the range between 6000 and 510000.
136static const int kOpusMinBitrate = 6000;
137static const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000138
wu@webrtc.orgde305012013-10-31 15:40:38 +0000139// Default audio dscp value.
140// See http://tools.ietf.org/html/rfc2474 for details.
141// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000142static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000143
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000144// Ensure we open the file in a writeable path on ChromeOS and Android. This
145// workaround can be removed when it's possible to specify a filename for audio
146// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000147//
148// TODO(grunell): Use a string in the options instead of hardcoding it here
149// and let the embedder choose the filename (crbug.com/264223).
150//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000151// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
152// below.
153#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000154static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000155#elif defined(ANDROID)
156static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000157#else
158static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
159#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000160
161// Dumps an AudioCodec in RFC 2327-ish format.
162static std::string ToString(const AudioCodec& codec) {
163 std::stringstream ss;
164 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
165 << " (" << codec.id << ")";
166 return ss.str();
167}
168static std::string ToString(const webrtc::CodecInst& codec) {
169 std::stringstream ss;
170 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
171 << " (" << codec.pltype << ")";
172 return ss.str();
173}
174
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000175static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000176 const char* delim = "\r\n";
177 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
178 LOG_V(sev) << tok;
179 }
180}
181
182// Severity is an integer because it comes is assumed to be from command line.
183static int SeverityToFilter(int severity) {
184 int filter = webrtc::kTraceNone;
185 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000186 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000187 filter |= webrtc::kTraceAll;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000188 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000189 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000190 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000191 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000192 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000193 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
194 }
195 return filter;
196}
197
198static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
199 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
200 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
201 kCodecPrefs[i].clockrate == codec.plfreq) {
202 return kCodecPrefs[i].is_multi_rate;
203 }
204 }
205 return false;
206}
207
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000208static bool IsTelephoneEventCodec(const std::string& name) {
209 return _stricmp(name.c_str(), "telephone-event") == 0;
210}
211
212static bool IsCNCodec(const std::string& name) {
213 return _stricmp(name.c_str(), "CN") == 0;
214}
215
216static bool IsRedCodec(const std::string& name) {
217 return _stricmp(name.c_str(), "red") == 0;
218}
219
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000220static bool FindCodec(const std::vector<AudioCodec>& codecs,
221 const AudioCodec& codec,
222 AudioCodec* found_codec) {
223 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
224 it != codecs.end(); ++it) {
225 if (it->Matches(codec)) {
226 if (found_codec != NULL) {
227 *found_codec = *it;
228 }
229 return true;
230 }
231 }
232 return false;
233}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000234
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000235static bool IsNackEnabled(const AudioCodec& codec) {
236 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
237 kParamValueEmpty));
238}
239
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000240// Gets the default set of options applied to the engine. Historically, these
241// were supplied as a combination of flags from the channel manager (ec, agc,
242// ns, and highpass) and the rest hardcoded in InitInternal.
243static AudioOptions GetDefaultEngineOptions() {
244 AudioOptions options;
245 options.echo_cancellation.Set(true);
246 options.auto_gain_control.Set(true);
247 options.noise_suppression.Set(true);
248 options.highpass_filter.Set(true);
249 options.stereo_swapping.Set(false);
250 options.typing_detection.Set(true);
251 options.conference_mode.Set(false);
252 options.adjust_agc_delta.Set(0);
253 options.experimental_agc.Set(false);
254 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000255 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000256 options.aec_dump.Set(false);
257 return options;
258}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000259
260class WebRtcSoundclipMedia : public SoundclipMedia {
261 public:
262 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
263 : engine_(engine), webrtc_channel_(-1) {
264 engine_->RegisterSoundclip(this);
265 }
266
267 virtual ~WebRtcSoundclipMedia() {
268 engine_->UnregisterSoundclip(this);
269 if (webrtc_channel_ != -1) {
270 // We shouldn't have to call Disable() here. DeleteChannel() should call
271 // StopPlayout() while deleting the channel. We should fix the bug
272 // inside WebRTC and remove the Disable() call bellow. This work is
273 // tracked by bug http://b/issue?id=5382855.
274 PlaySound(NULL, 0, 0);
275 Disable();
276 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
277 == -1) {
278 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
279 }
280 }
281 }
282
283 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000284 if (!engine_->voe_sc()) {
285 return false;
286 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000287 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000288 if (webrtc_channel_ == -1) {
289 LOG_RTCERR0(CreateChannel);
290 return false;
291 }
292 return true;
293 }
294
295 bool Enable() {
296 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
297 LOG_RTCERR1(StartPlayout, webrtc_channel_);
298 return false;
299 }
300 return true;
301 }
302
303 bool Disable() {
304 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
305 LOG_RTCERR1(StopPlayout, webrtc_channel_);
306 return false;
307 }
308 return true;
309 }
310
311 virtual bool PlaySound(const char *buf, int len, int flags) {
312 // The voe file api is not available in chrome.
313 if (!engine_->voe_sc()->file()) {
314 return false;
315 }
316 // Must stop playing the current sound (if any), because we are about to
317 // modify the stream.
318 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
319 == -1) {
320 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
321 return false;
322 }
323
324 if (buf) {
325 stream_.reset(new WebRtcSoundclipStream(buf, len));
326 stream_->set_loop((flags & SF_LOOP) != 0);
327 stream_->Rewind();
328
329 // Play it.
330 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
331 webrtc_channel_, stream_.get()) == -1) {
332 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
333 LOG(LS_ERROR) << "Unable to start soundclip";
334 return false;
335 }
336 } else {
337 stream_.reset();
338 }
339 return true;
340 }
341
342 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
343
344 private:
345 WebRtcVoiceEngine *engine_;
346 int webrtc_channel_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000347 rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000348};
349
350WebRtcVoiceEngine::WebRtcVoiceEngine()
351 : voe_wrapper_(new VoEWrapper()),
352 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000353 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000354 tracing_(new VoETraceWrapper()),
355 adm_(NULL),
356 adm_sc_(NULL),
357 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
358 is_dumping_aec_(false),
359 desired_local_monitor_enable_(false),
360 tx_processor_ssrc_(0),
361 rx_processor_ssrc_(0) {
362 Construct();
363}
364
365WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
366 VoEWrapper* voe_wrapper_sc,
367 VoETraceWrapper* tracing)
368 : voe_wrapper_(voe_wrapper),
369 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000370 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000371 tracing_(tracing),
372 adm_(NULL),
373 adm_sc_(NULL),
374 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
375 is_dumping_aec_(false),
376 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000377 tx_processor_ssrc_(0),
378 rx_processor_ssrc_(0) {
379 Construct();
380}
381
382void WebRtcVoiceEngine::Construct() {
383 SetTraceFilter(log_filter_);
384 initialized_ = false;
385 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
386 SetTraceOptions("");
387 if (tracing_->SetTraceCallback(this) == -1) {
388 LOG_RTCERR0(SetTraceCallback);
389 }
390 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
391 LOG_RTCERR0(RegisterVoiceEngineObserver);
392 }
393 // Clear the default agc state.
394 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
395
396 // Load our audio codec list.
397 ConstructCodecs();
398
399 // Load our RTP Header extensions.
400 rtp_header_extensions_.push_back(
401 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
402 kRtpAudioLevelHeaderExtensionDefaultId));
403 rtp_header_extensions_.push_back(
404 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
405 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
406 options_ = GetDefaultEngineOptions();
407}
408
409static bool IsOpus(const AudioCodec& codec) {
410 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
411}
412
413static bool IsIsac(const AudioCodec& codec) {
414 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
415}
416
417// True if params["stereo"] == "1"
418static bool IsOpusStereoEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000419 int value;
420 return codec.GetParam(kCodecParamStereo, &value) && value == 1;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000421}
422
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000423// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
424// otherwise. If the value (either from params or codec.bitrate) <=0, use the
425// default configuration. If the value is beyond feasible bit rate of Opus,
426// clamp it. Returns the Opus bit rate for operation.
buildbot@webrtc.org879fac82014-10-30 07:50:13 +0000427static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000428 int bitrate = 0;
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000429 bool use_param = true;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000430 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000431 bitrate = codec.bitrate;
432 use_param = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000433 }
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000434 if (bitrate <= 0) {
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000435 if (max_playback_rate <= 8000) {
436 bitrate = kOpusBitrateNb;
437 } else if (max_playback_rate <= 16000) {
438 bitrate = kOpusBitrateWb;
439 } else {
440 bitrate = kOpusBitrateFb;
441 }
442
443 if (IsOpusStereoEnabled(codec)) {
444 bitrate *= 2;
445 }
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000446 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
447 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
448 std::string rate_source =
449 use_param ? "Codec parameter \"maxaveragebitrate\"" :
450 "Supplied Opus bitrate";
451 LOG(LS_WARNING) << rate_source
452 << " is invalid and is replaced by: "
453 << bitrate;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000454 }
455 return bitrate;
456}
457
buildbot@webrtc.orgfbd13282014-06-19 19:50:55 +0000458// Return true if params[kCodecParamUseInbandFec] == "1", false
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000459// otherwise.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000460static bool IsOpusFecEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000461 int value;
462 return codec.GetParam(kCodecParamUseInbandFec, &value) && value == 1;
463}
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000464
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000465// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
466// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
467static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
468 int value;
469 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
470 return value;
471 }
472 return kOpusDefaultMaxPlaybackRate;
473}
474
475static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
476 bool* enable_codec_fec, int* max_playback_rate) {
477 *enable_codec_fec = IsOpusFecEnabled(codec);
478 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
479
480 // If OPUS, change what we send according to the "stereo" codec
481 // parameter, and not the "channels" parameter. We set
482 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000483 // the bitrate is not specified, i.e. is <= zero, we set it to the
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000484 // appropriate default value for mono or stereo Opus.
485
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000486 voe_codec->channels = IsOpusStereoEnabled(codec) ? 2 : 1;
buildbot@webrtc.org879fac82014-10-30 07:50:13 +0000487 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000488}
489
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000490// Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
491// which says that G722 should be advertised as 8 kHz although it is a 16 kHz
492// codec.
493static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
494 if (_stricmp(voe_codec->plname, kG722CodecName) == 0) {
495 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
496 // has changed, and this special case is no longer needed.
497 ASSERT(voe_codec->plfreq != new_plfreq);
498 voe_codec->plfreq = new_plfreq;
499 }
500}
501
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000502void WebRtcVoiceEngine::ConstructCodecs() {
503 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
504 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
505 for (int i = 0; i < ncodecs; ++i) {
506 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000507 if (GetVoeCodec(i, &voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000508 // Skip uncompressed formats.
509 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
510 continue;
511 }
512
513 const CodecPref* pref = NULL;
514 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
515 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
516 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
517 kCodecPrefs[j].channels == voe_codec.channels) {
518 pref = &kCodecPrefs[j];
519 break;
520 }
521 }
522
523 if (pref) {
524 // Use the payload type that we've configured in our pref table;
525 // use the offset in our pref table to determine the sort order.
526 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
527 voe_codec.rate, voe_codec.channels,
528 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
529 LOG(LS_INFO) << ToString(codec);
530 if (IsIsac(codec)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000531 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000532 codec.bitrate = 0;
533 }
534 if (IsOpus(codec)) {
535 // Only add fmtp parameters that differ from the spec.
536 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
537 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000538 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000539 }
540 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
541 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000542 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000543 }
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000544 codec.SetParam(kCodecParamUseInbandFec, "1");
545
546 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000547 // when they can be set to values other than the default.
548 }
549 codecs_.push_back(codec);
550 } else {
551 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
552 }
553 }
554 }
555 // Make sure they are in local preference order.
556 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
557}
558
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000559bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst* codec) {
560 if (voe_wrapper_->codec()->GetCodec(index, *codec) == -1) {
561 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000562 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000563 // Change the sample rate of G722 to 8000 to match SDP.
564 MaybeFixupG722(codec, 8000);
565 return true;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000566}
567
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000568WebRtcVoiceEngine::~WebRtcVoiceEngine() {
569 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
570 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
571 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
572 }
573 if (adm_) {
574 voe_wrapper_.reset();
575 adm_->Release();
576 adm_ = NULL;
577 }
578 if (adm_sc_) {
579 voe_wrapper_sc_.reset();
580 adm_sc_->Release();
581 adm_sc_ = NULL;
582 }
583
584 // Test to see if the media processor was deregistered properly
585 ASSERT(SignalRxMediaFrame.is_empty());
586 ASSERT(SignalTxMediaFrame.is_empty());
587
588 tracing_->SetTraceCallback(NULL);
589}
590
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000591bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
henrika@webrtc.org62f6e752015-02-11 08:38:35 +0000592 ASSERT(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000593 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
594 bool res = InitInternal();
595 if (res) {
596 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
597 } else {
598 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
599 Terminate();
600 }
601 return res;
602}
603
604bool WebRtcVoiceEngine::InitInternal() {
605 // Temporarily turn logging level up for the Init call
606 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000607 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000608 SetTraceFilter(extended_filter);
609 SetTraceOptions("");
610
611 // Init WebRtc VoiceEngine.
612 if (voe_wrapper_->base()->Init(adm_) == -1) {
613 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
614 SetTraceFilter(old_filter);
615 return false;
616 }
617
618 SetTraceFilter(old_filter);
619 SetTraceOptions(log_options_);
620
621 // Log the VoiceEngine version info
622 char buffer[1024] = "";
623 voe_wrapper_->base()->GetVersion(buffer);
624 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000625 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000626
627 // Save the default AGC configuration settings. This must happen before
628 // calling SetOptions or the default will be overwritten.
629 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
630 LOG_RTCERR0(GetAgcConfig);
631 return false;
632 }
633
634 // Set defaults for options, so that ApplyOptions applies them explicitly
635 // when we clear option (channel) overrides. External clients can still
636 // modify the defaults via SetOptions (on the media engine).
637 if (!SetOptions(GetDefaultEngineOptions())) {
638 return false;
639 }
640
641 // Print our codec list again for the call diagnostic log
642 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
643 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
644 it != codecs_.end(); ++it) {
645 LOG(LS_INFO) << ToString(*it);
646 }
647
648 // Disable the DTMF playout when a tone is sent.
649 // PlayDtmfTone will be used if local playout is needed.
650 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
651 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
652 }
653
654 initialized_ = true;
655 return true;
656}
657
658bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
659 if (voe_wrapper_sc_initialized_) {
660 return true;
661 }
662 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
663 // be false, so subsequent calls to EnsureSoundclipEngineInit will
664 // probably just fail again. That's acceptable behavior.
665#if defined(LINUX) && !defined(HAVE_LIBPULSE)
666 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
667#endif
668
669 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
670 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
671 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
672 return false;
673 }
674
675 // On Windows, tell it to use the default sound (not communication) devices.
676 // First check whether there is a valid sound device for playback.
677 // TODO(juberti): Clean this up when we support setting the soundclip device.
678#ifdef WIN32
679 // The SetPlayoutDevice may not be implemented in the case of external ADM.
680 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
681 // PeerConnection interface never set the adm_sc_, so need to check both
682 // in order to determine if the external adm is used.
683 if (!adm_ && !adm_sc_) {
684 int num_of_devices = 0;
685 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
686 num_of_devices > 0) {
687 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
688 == -1) {
689 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
690 voe_wrapper_sc_->error());
691 return false;
692 }
693 } else {
694 LOG(LS_WARNING) << "No valid sound playout device found.";
695 }
696 }
697#endif
698 voe_wrapper_sc_initialized_ = true;
699 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
700 return true;
701}
702
703void WebRtcVoiceEngine::Terminate() {
704 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
705 initialized_ = false;
706
707 StopAecDump();
708
709 if (voe_wrapper_sc_) {
710 voe_wrapper_sc_initialized_ = false;
711 voe_wrapper_sc_->base()->Terminate();
712 }
713 voe_wrapper_->base()->Terminate();
714 desired_local_monitor_enable_ = false;
715}
716
717int WebRtcVoiceEngine::GetCapabilities() {
718 return AUDIO_SEND | AUDIO_RECV;
719}
720
721VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
722 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
723 if (!ch->valid()) {
724 delete ch;
725 ch = NULL;
726 }
727 return ch;
728}
729
730SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
731 if (!EnsureSoundclipEngineInit()) {
732 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
733 << "initialize.";
734 return NULL;
735 }
736 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
737 if (!soundclip->Init() || !soundclip->Enable()) {
738 delete soundclip;
739 return NULL;
740 }
741 return soundclip;
742}
743
744bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
745 if (!ApplyOptions(options)) {
746 return false;
747 }
748 options_ = options;
749 return true;
750}
751
752bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
753 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
754 if (!ApplyOptions(overrides)) {
755 return false;
756 }
757 option_overrides_ = overrides;
758 return true;
759}
760
761bool WebRtcVoiceEngine::ClearOptionOverrides() {
762 LOG(LS_INFO) << "Clearing option overrides.";
763 AudioOptions options = options_;
764 // Only call ApplyOptions if |options_overrides_| contains overrided options.
765 // ApplyOptions affects NS, AGC other options that is shared between
766 // all WebRtcVoiceEngineChannels.
767 if (option_overrides_ == AudioOptions()) {
768 return true;
769 }
770
771 if (!ApplyOptions(options)) {
772 return false;
773 }
774 option_overrides_ = AudioOptions();
775 return true;
776}
777
778// AudioOptions defaults are set in InitInternal (for options with corresponding
779// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
780bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
781 AudioOptions options = options_in; // The options are modified below.
782 // kEcConference is AEC with high suppression.
783 webrtc::EcModes ec_mode = webrtc::kEcConference;
784 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
785 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
786 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
787 bool aecm_comfort_noise = false;
788 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
789 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
790 << aecm_comfort_noise << " (default is false).";
791 }
792
793#if defined(IOS)
794 // On iOS, VPIO provides built-in EC and AGC.
795 options.echo_cancellation.Set(false);
796 options.auto_gain_control.Set(false);
797#elif defined(ANDROID)
798 ec_mode = webrtc::kEcAecm;
799#endif
800
801#if defined(IOS) || defined(ANDROID)
802 // Set the AGC mode for iOS as well despite disabling it above, to avoid
803 // unsupported configuration errors from webrtc.
804 agc_mode = webrtc::kAgcFixedDigital;
805 options.typing_detection.Set(false);
806 options.experimental_agc.Set(false);
807 options.experimental_aec.Set(false);
808 options.experimental_ns.Set(false);
809#endif
810
811 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
812
813 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
814
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000815 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000816 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000817 // Check if platform supports built-in EC. Currently only supported on
818 // Android and in combination with Java based audio layer.
819 // TODO(henrika): investigate possibility to support built-in EC also
820 // in combination with Open SL ES audio.
821 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
822 if (built_in_aec) {
823 // Set mode of built-in EC according to the audio options.
824 voe_wrapper_->hw()->EnableBuiltInAEC(echo_cancellation);
825 if (echo_cancellation) {
826 // Disable internal software EC if device has its own built-in EC,
827 // i.e., replace the software EC with the built-in EC.
828 options.echo_cancellation.Set(false);
829 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
830 }
831 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000832 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
833 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
834 return false;
835 } else {
836 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
837 << " with mode " << ec_mode;
838 }
839#if !defined(ANDROID)
840 // TODO(ajm): Remove the error return on Android from webrtc.
841 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
842 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
843 return false;
844 }
845#endif
846 if (ec_mode == webrtc::kEcAecm) {
847 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
848 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
849 return false;
850 }
851 }
852 }
853
854 bool auto_gain_control;
855 if (options.auto_gain_control.Get(&auto_gain_control)) {
856 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
857 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
858 return false;
859 } else {
860 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
861 << " with mode " << agc_mode;
862 }
863 }
864
865 if (options.tx_agc_target_dbov.IsSet() ||
866 options.tx_agc_digital_compression_gain.IsSet() ||
867 options.tx_agc_limiter.IsSet()) {
868 // Override default_agc_config_. Generally, an unset option means "leave
869 // the VoE bits alone" in this function, so we want whatever is set to be
870 // stored as the new "default". If we didn't, then setting e.g.
871 // tx_agc_target_dbov would reset digital compression gain and limiter
872 // settings.
873 // Also, if we don't update default_agc_config_, then adjust_agc_delta
874 // would be an offset from the original values, and not whatever was set
875 // explicitly.
876 default_agc_config_.targetLeveldBOv =
877 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
878 default_agc_config_.targetLeveldBOv);
879 default_agc_config_.digitalCompressionGaindB =
880 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
881 default_agc_config_.digitalCompressionGaindB);
882 default_agc_config_.limiterEnable =
883 options.tx_agc_limiter.GetWithDefaultIfUnset(
884 default_agc_config_.limiterEnable);
885 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
886 LOG_RTCERR3(SetAgcConfig,
887 default_agc_config_.targetLeveldBOv,
888 default_agc_config_.digitalCompressionGaindB,
889 default_agc_config_.limiterEnable);
890 return false;
891 }
892 }
893
894 bool noise_suppression;
895 if (options.noise_suppression.Get(&noise_suppression)) {
896 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
897 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
898 return false;
899 } else {
900 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
901 << " with mode " << ns_mode;
902 }
903 }
904
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000905 bool highpass_filter;
906 if (options.highpass_filter.Get(&highpass_filter)) {
907 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
908 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
909 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
910 return false;
911 }
912 }
913
914 bool stereo_swapping;
915 if (options.stereo_swapping.Get(&stereo_swapping)) {
916 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
917 voep->EnableStereoChannelSwapping(stereo_swapping);
918 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
919 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
920 return false;
921 }
922 }
923
924 bool typing_detection;
925 if (options.typing_detection.Get(&typing_detection)) {
926 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
927 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
928 // In case of error, log the info and continue
929 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
930 }
931 }
932
933 int adjust_agc_delta;
934 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
935 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
936 if (!AdjustAgcLevel(adjust_agc_delta)) {
937 return false;
938 }
939 }
940
941 bool aec_dump;
942 if (options.aec_dump.Get(&aec_dump)) {
943 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
944 if (aec_dump)
945 StartAecDump(kAecDumpByAudioOptionFilename);
946 else
947 StopAecDump();
948 }
949
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000950 webrtc::Config config;
951
952 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000953 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000954 if (experimental_aec_.Get(&experimental_aec)) {
955 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
956 config.Set<webrtc::DelayCorrection>(
957 new webrtc::DelayCorrection(experimental_aec));
958 }
959
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000960 experimental_ns_.SetFrom(options.experimental_ns);
961 bool experimental_ns;
962 if (experimental_ns_.Get(&experimental_ns)) {
963 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
964 config.Set<webrtc::ExperimentalNs>(
965 new webrtc::ExperimentalNs(experimental_ns));
966 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000967
968 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
969 // returns NULL on audio_processing().
970 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
971 if (audioproc) {
972 audioproc->SetExtraOptions(config);
973 }
974
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000975 uint32 recording_sample_rate;
976 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
977 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
978 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
979 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
980 }
981 }
982
983 uint32 playout_sample_rate;
984 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
985 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
986 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
987 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
988 }
989 }
990
991 return true;
992}
993
994bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
995 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
996 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
997 LOG_RTCERR1(SetDelayOffsetMs, offset);
998 return false;
999 }
1000
1001 return true;
1002}
1003
1004struct ResumeEntry {
1005 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
1006 : channel(c),
1007 playout(p),
1008 send(s) {
1009 }
1010
1011 WebRtcVoiceMediaChannel *channel;
1012 bool playout;
1013 SendFlags send;
1014};
1015
1016// TODO(juberti): Refactor this so that the core logic can be used to set the
1017// soundclip device. At that time, reinstate the soundclip pause/resume code.
1018bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
1019 const Device* out_device) {
1020#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001021 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001022 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001023 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001024 kDefaultAudioDeviceId;
1025 // The device manager uses -1 as the default device, which was the case for
1026 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
1027#ifndef WIN32
1028 if (-1 == in_id) {
1029 in_id = kDefaultAudioDeviceId;
1030 }
1031 if (-1 == out_id) {
1032 out_id = kDefaultAudioDeviceId;
1033 }
1034#endif
1035
1036 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
1037 in_device->name : "Default device";
1038 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
1039 out_device->name : "Default device";
1040 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
1041 << ") and speaker to (id=" << out_id << ", name=" << out_name
1042 << ")";
1043
1044 // If we're running the local monitor, we need to stop it first.
1045 bool ret = true;
1046 if (!PauseLocalMonitor()) {
1047 LOG(LS_WARNING) << "Failed to pause local monitor";
1048 ret = false;
1049 }
1050
1051 // Must also pause all audio playback and capture.
1052 for (ChannelList::const_iterator i = channels_.begin();
1053 i != channels_.end(); ++i) {
1054 WebRtcVoiceMediaChannel *channel = *i;
1055 if (!channel->PausePlayout()) {
1056 LOG(LS_WARNING) << "Failed to pause playout";
1057 ret = false;
1058 }
1059 if (!channel->PauseSend()) {
1060 LOG(LS_WARNING) << "Failed to pause send";
1061 ret = false;
1062 }
1063 }
1064
1065 // Find the recording device id in VoiceEngine and set recording device.
1066 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1067 ret = false;
1068 }
1069 if (ret) {
1070 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
1071 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
1072 ret = false;
1073 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00001074 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
1075 if (ap)
1076 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001077 }
1078
1079 // Find the playout device id in VoiceEngine and set playout device.
1080 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1081 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1082 ret = false;
1083 }
1084 if (ret) {
1085 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001086 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001087 ret = false;
1088 }
1089 }
1090
1091 // Resume all audio playback and capture.
1092 for (ChannelList::const_iterator i = channels_.begin();
1093 i != channels_.end(); ++i) {
1094 WebRtcVoiceMediaChannel *channel = *i;
1095 if (!channel->ResumePlayout()) {
1096 LOG(LS_WARNING) << "Failed to resume playout";
1097 ret = false;
1098 }
1099 if (!channel->ResumeSend()) {
1100 LOG(LS_WARNING) << "Failed to resume send";
1101 ret = false;
1102 }
1103 }
1104
1105 // Resume local monitor.
1106 if (!ResumeLocalMonitor()) {
1107 LOG(LS_WARNING) << "Failed to resume local monitor";
1108 ret = false;
1109 }
1110
1111 if (ret) {
1112 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1113 << ") and speaker to (id="<< out_id << " name=" << out_name
1114 << ")";
1115 }
1116
1117 return ret;
1118#else
1119 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001120#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001121}
1122
1123bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1124 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1125 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001126#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001127 *rtc_id = dev_id;
1128 return true;
1129#else
1130 // In Windows and Mac, we need to find the VoiceEngine device id by name
1131 // unless the input dev_id is the default device id.
1132 if (kDefaultAudioDeviceId == dev_id) {
1133 *rtc_id = dev_id;
1134 return true;
1135 }
1136
1137 // Get the number of VoiceEngine audio devices.
1138 int count = 0;
1139 if (is_input) {
1140 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1141 LOG_RTCERR0(GetNumOfRecordingDevices);
1142 return false;
1143 }
1144 } else {
1145 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1146 LOG_RTCERR0(GetNumOfPlayoutDevices);
1147 return false;
1148 }
1149 }
1150
1151 for (int i = 0; i < count; ++i) {
1152 char name[128];
1153 char guid[128];
1154 if (is_input) {
1155 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1156 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1157 } else {
1158 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1159 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1160 }
1161
1162 std::string webrtc_name(name);
1163 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1164 *rtc_id = i;
1165 return true;
1166 }
1167 }
1168 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1169 return false;
1170#endif
1171}
1172
1173bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1174 unsigned int ulevel;
1175 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1176 LOG_RTCERR1(GetSpeakerVolume, level);
1177 return false;
1178 }
1179 *level = ulevel;
1180 return true;
1181}
1182
1183bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1184 ASSERT(level >= 0 && level <= 255);
1185 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1186 LOG_RTCERR1(SetSpeakerVolume, level);
1187 return false;
1188 }
1189 return true;
1190}
1191
1192int WebRtcVoiceEngine::GetInputLevel() {
1193 unsigned int ulevel;
1194 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1195 static_cast<int>(ulevel) : -1;
1196}
1197
1198bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1199 desired_local_monitor_enable_ = enable;
1200 return ChangeLocalMonitor(desired_local_monitor_enable_);
1201}
1202
1203bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1204 // The voe file api is not available in chrome.
1205 if (!voe_wrapper_->file()) {
1206 return false;
1207 }
1208 if (enable && !monitor_) {
1209 monitor_.reset(new WebRtcMonitorStream);
1210 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1211 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1212 // Must call Stop() because there are some cases where Start will report
1213 // failure but still change the state, and if we leave VE in the on state
1214 // then it could crash later when trying to invoke methods on our monitor.
1215 voe_wrapper_->file()->StopRecordingMicrophone();
1216 monitor_.reset();
1217 return false;
1218 }
1219 } else if (!enable && monitor_) {
1220 voe_wrapper_->file()->StopRecordingMicrophone();
1221 monitor_.reset();
1222 }
1223 return true;
1224}
1225
1226bool WebRtcVoiceEngine::PauseLocalMonitor() {
1227 return ChangeLocalMonitor(false);
1228}
1229
1230bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1231 return ChangeLocalMonitor(desired_local_monitor_enable_);
1232}
1233
1234const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1235 return codecs_;
1236}
1237
1238bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1239 return FindWebRtcCodec(in, NULL);
1240}
1241
1242// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1243bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1244 webrtc::CodecInst* out) {
1245 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1246 for (int i = 0; i < ncodecs; ++i) {
1247 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001248 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001249 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1250 voe_codec.rate, voe_codec.channels, 0);
1251 bool multi_rate = IsCodecMultiRate(voe_codec);
1252 // Allow arbitrary rates for ISAC to be specified.
1253 if (multi_rate) {
1254 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1255 codec.bitrate = 0;
1256 }
1257 if (codec.Matches(in)) {
1258 if (out) {
1259 // Fixup the payload type.
1260 voe_codec.pltype = in.id;
1261
1262 // Set bitrate if specified.
1263 if (multi_rate && in.bitrate != 0) {
1264 voe_codec.rate = in.bitrate;
1265 }
1266
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001267 // Reset G722 sample rate to 16000 to match WebRTC.
1268 MaybeFixupG722(&voe_codec, 16000);
1269
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001270 // Apply codec-specific settings.
1271 if (IsIsac(codec)) {
1272 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001273 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001274 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1275 }
1276 *out = voe_codec;
1277 }
1278 return true;
1279 }
1280 }
1281 }
1282 return false;
1283}
1284const std::vector<RtpHeaderExtension>&
1285WebRtcVoiceEngine::rtp_header_extensions() const {
1286 return rtp_header_extensions_;
1287}
1288
1289void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1290 // if min_sev == -1, we keep the current log level.
1291 if (min_sev >= 0) {
1292 SetTraceFilter(SeverityToFilter(min_sev));
1293 }
1294 log_options_ = filter;
1295 SetTraceOptions(initialized_ ? log_options_ : "");
1296}
1297
1298int WebRtcVoiceEngine::GetLastEngineError() {
1299 return voe_wrapper_->error();
1300}
1301
1302void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1303 log_filter_ = filter;
1304 tracing_->SetTraceFilter(filter);
1305}
1306
1307// We suppport three different logging settings for VoiceEngine:
1308// 1. Observer callback that goes into talk diagnostic logfile.
1309// Use --logfile and --loglevel
1310//
1311// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1312// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1313//
1314// 3. EC log and dump for debugging QualityEngine.
1315// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1316//
1317// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1318// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1319void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1320 // Set encrypted trace file.
1321 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001322 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001323 std::vector<std::string>::iterator tracefile =
1324 std::find(opts.begin(), opts.end(), "tracefile");
1325 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1326 // Write encrypted debug output (at same loglevel) to file
1327 // EncryptedTraceFile no longer supported.
1328 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1329 LOG_RTCERR1(SetTraceFile, *tracefile);
1330 }
1331 }
1332
wu@webrtc.org97077a32013-10-25 21:18:33 +00001333 // Allow trace options to override the trace filter. We default
1334 // it to log_filter_ (as a translation of libjingle log levels)
1335 // elsewhere, but this allows clients to explicitly set webrtc
1336 // log levels.
1337 std::vector<std::string>::iterator tracefilter =
1338 std::find(opts.begin(), opts.end(), "tracefilter");
1339 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001340 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001341 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1342 }
1343 }
1344
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001345 // Set AEC dump file
1346 std::vector<std::string>::iterator recordEC =
1347 std::find(opts.begin(), opts.end(), "recordEC");
1348 if (recordEC != opts.end()) {
1349 ++recordEC;
1350 if (recordEC != opts.end())
1351 StartAecDump(recordEC->c_str());
1352 else
1353 StopAecDump();
1354 }
1355}
1356
1357// Ignore spammy trace messages, mostly from the stats API when we haven't
1358// gotten RTCP info yet from the remote side.
1359bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1360 static const char* kTracesToIgnore[] = {
1361 "\tfailed to GetReportBlockInformation",
1362 "GetRecCodec() failed to get received codec",
1363 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1364 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1365 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1366 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1367 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1368 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1369 "SenderInfoReceived No received SR",
1370 "StatisticsRTP() no statistics available",
1371 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1372 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1373 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1374 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1375 NULL
1376 };
1377 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1378 if (trace.find(*p) != std::string::npos) {
1379 return true;
1380 }
1381 }
1382 return false;
1383}
1384
1385void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1386 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001387 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001388 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001389 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001390 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001391 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001393 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001394 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001395 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001396
1397 // Skip past boilerplate prefix text
1398 if (length < 72) {
1399 std::string msg(trace, length);
1400 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1401 LOG_V(sev) << msg;
1402 } else {
1403 std::string msg(trace + 71, length - 72);
1404 if (!ShouldIgnoreTrace(msg)) {
1405 LOG_V(sev) << "webrtc: " << msg;
1406 }
1407 }
1408}
1409
1410void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001411 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001412 WebRtcVoiceMediaChannel* channel = NULL;
1413 uint32 ssrc = 0;
1414 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1415 << channel_num << ".";
1416 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1417 ASSERT(channel != NULL);
1418 channel->OnError(ssrc, err_code);
1419 } else {
1420 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1421 << " could not be found in channel list when error reported.";
1422 }
1423}
1424
1425bool WebRtcVoiceEngine::FindChannelAndSsrc(
1426 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1427 ASSERT(channel != NULL && ssrc != NULL);
1428
1429 *channel = NULL;
1430 *ssrc = 0;
1431 // Find corresponding channel and ssrc
1432 for (ChannelList::const_iterator it = channels_.begin();
1433 it != channels_.end(); ++it) {
1434 ASSERT(*it != NULL);
1435 if ((*it)->FindSsrc(channel_num, ssrc)) {
1436 *channel = *it;
1437 return true;
1438 }
1439 }
1440
1441 return false;
1442}
1443
1444// This method will search through the WebRtcVoiceMediaChannels and
1445// obtain the voice engine's channel number.
1446bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1447 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1448 ASSERT(channel_num != NULL);
1449 ASSERT(direction == MPD_RX || direction == MPD_TX);
1450
1451 *channel_num = -1;
1452 // Find corresponding channel for ssrc.
1453 for (ChannelList::const_iterator it = channels_.begin();
1454 it != channels_.end(); ++it) {
1455 ASSERT(*it != NULL);
1456 if (direction & MPD_RX) {
1457 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1458 }
1459 if (*channel_num == -1 && (direction & MPD_TX)) {
1460 *channel_num = (*it)->GetSendChannelNum(ssrc);
1461 }
1462 if (*channel_num != -1) {
1463 return true;
1464 }
1465 }
1466 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1467 return false;
1468}
1469
1470void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001471 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001472 channels_.push_back(channel);
1473}
1474
1475void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001476 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001477 ChannelList::iterator i = std::find(channels_.begin(),
1478 channels_.end(),
1479 channel);
1480 if (i != channels_.end()) {
1481 channels_.erase(i);
1482 }
1483}
1484
1485void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1486 soundclips_.push_back(soundclip);
1487}
1488
1489void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1490 SoundclipList::iterator i = std::find(soundclips_.begin(),
1491 soundclips_.end(),
1492 soundclip);
1493 if (i != soundclips_.end()) {
1494 soundclips_.erase(i);
1495 }
1496}
1497
1498// Adjusts the default AGC target level by the specified delta.
1499// NB: If we start messing with other config fields, we'll want
1500// to save the current webrtc::AgcConfig as well.
1501bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1502 webrtc::AgcConfig config = default_agc_config_;
1503 config.targetLeveldBOv -= delta;
1504
1505 LOG(LS_INFO) << "Adjusting AGC level from default -"
1506 << default_agc_config_.targetLeveldBOv << "dB to -"
1507 << config.targetLeveldBOv << "dB";
1508
1509 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1510 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1511 return false;
1512 }
1513 return true;
1514}
1515
1516bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1517 webrtc::AudioDeviceModule* adm_sc) {
1518 if (initialized_) {
1519 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1520 return false;
1521 }
1522 if (adm_) {
1523 adm_->Release();
1524 adm_ = NULL;
1525 }
1526 if (adm) {
1527 adm_ = adm;
1528 adm_->AddRef();
1529 }
1530
1531 if (adm_sc_) {
1532 adm_sc_->Release();
1533 adm_sc_ = NULL;
1534 }
1535 if (adm_sc) {
1536 adm_sc_ = adm_sc;
1537 adm_sc_->AddRef();
1538 }
1539 return true;
1540}
1541
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001542bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1543 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001544 if (!aec_dump_file_stream) {
1545 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001546 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001547 LOG(LS_WARNING) << "Could not close file.";
1548 return false;
1549 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001550 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001551 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001552 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001553 LOG_RTCERR0(StartDebugRecording);
1554 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001555 return false;
1556 }
1557 is_dumping_aec_ = true;
1558 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001559}
1560
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001561bool WebRtcVoiceEngine::RegisterProcessor(
1562 uint32 ssrc,
1563 VoiceProcessor* voice_processor,
1564 MediaProcessorDirection direction) {
1565 bool register_with_webrtc = false;
1566 int channel_id = -1;
1567 bool success = false;
1568 uint32* processor_ssrc = NULL;
1569 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1570 if (voice_processor == NULL || !found_channel) {
1571 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1572 << " foundChannel: " << found_channel;
1573 return false;
1574 }
1575
1576 webrtc::ProcessingTypes processing_type;
1577 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001578 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001579 if (direction == MPD_RX) {
1580 processing_type = webrtc::kPlaybackAllChannelsMixed;
1581 if (SignalRxMediaFrame.is_empty()) {
1582 register_with_webrtc = true;
1583 processor_ssrc = &rx_processor_ssrc_;
1584 }
1585 SignalRxMediaFrame.connect(voice_processor,
1586 &VoiceProcessor::OnFrame);
1587 } else {
1588 processing_type = webrtc::kRecordingPerChannel;
1589 if (SignalTxMediaFrame.is_empty()) {
1590 register_with_webrtc = true;
1591 processor_ssrc = &tx_processor_ssrc_;
1592 }
1593 SignalTxMediaFrame.connect(voice_processor,
1594 &VoiceProcessor::OnFrame);
1595 }
1596 }
1597 if (register_with_webrtc) {
1598 // TODO(janahan): when registering consider instantiating a
1599 // a VoeMediaProcess object and not make the engine extend the interface.
1600 if (voe()->media() && voe()->media()->
1601 RegisterExternalMediaProcessing(channel_id,
1602 processing_type,
1603 *this) != -1) {
1604 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1605 << channel_id;
1606 *processor_ssrc = ssrc;
1607 success = true;
1608 } else {
1609 LOG_RTCERR2(RegisterExternalMediaProcessing,
1610 channel_id,
1611 processing_type);
1612 success = false;
1613 }
1614 } else {
1615 // If we don't have to register with the engine, we just needed to
1616 // connect a new processor, set success to true;
1617 success = true;
1618 }
1619 return success;
1620}
1621
1622bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1623 MediaProcessorDirection channel_direction,
1624 uint32 ssrc,
1625 VoiceProcessor* voice_processor,
1626 MediaProcessorDirection processor_direction) {
1627 bool success = true;
1628 FrameSignal* signal;
1629 webrtc::ProcessingTypes processing_type;
1630 uint32* processor_ssrc = NULL;
1631 if (channel_direction == MPD_RX) {
1632 signal = &SignalRxMediaFrame;
1633 processing_type = webrtc::kPlaybackAllChannelsMixed;
1634 processor_ssrc = &rx_processor_ssrc_;
1635 } else {
1636 signal = &SignalTxMediaFrame;
1637 processing_type = webrtc::kRecordingPerChannel;
1638 processor_ssrc = &tx_processor_ssrc_;
1639 }
1640
1641 int deregister_id = -1;
1642 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001643 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001644 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1645 signal->disconnect(voice_processor);
1646 int channel_id = -1;
1647 bool found_channel = FindChannelNumFromSsrc(ssrc,
1648 channel_direction,
1649 &channel_id);
1650 if (signal->is_empty() && found_channel) {
1651 deregister_id = channel_id;
1652 }
1653 }
1654 }
1655 if (deregister_id != -1) {
1656 if (voe()->media() &&
1657 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1658 processing_type) != -1) {
1659 *processor_ssrc = 0;
1660 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1661 << deregister_id;
1662 } else {
1663 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1664 deregister_id,
1665 processing_type);
1666 success = false;
1667 }
1668 }
1669 return success;
1670}
1671
1672bool WebRtcVoiceEngine::UnregisterProcessor(
1673 uint32 ssrc,
1674 VoiceProcessor* voice_processor,
1675 MediaProcessorDirection direction) {
1676 bool success = true;
1677 if (voice_processor == NULL) {
1678 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1679 << ssrc;
1680 return false;
1681 }
1682 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1683 success = false;
1684 }
1685 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1686 success = false;
1687 }
1688 return success;
1689}
1690
1691// Implementing method from WebRtc VoEMediaProcess interface
1692// Do not lock mux_channel_cs_ in this callback.
1693void WebRtcVoiceEngine::Process(int channel,
1694 webrtc::ProcessingTypes type,
1695 int16_t audio10ms[],
1696 int length,
1697 int sampling_freq,
1698 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001699 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001700 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1701 if (type == webrtc::kPlaybackAllChannelsMixed) {
1702 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1703 } else if (type == webrtc::kRecordingPerChannel) {
1704 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1705 } else {
1706 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1707 << " channel: " << channel << " type: " << type
1708 << " tx_ssrc: " << tx_processor_ssrc_
1709 << " rx_ssrc: " << rx_processor_ssrc_;
1710 }
1711}
1712
1713void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1714 if (!is_dumping_aec_) {
1715 // Start dumping AEC when we are not dumping.
1716 if (voe_wrapper_->processing()->StartDebugRecording(
1717 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001718 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001719 } else {
1720 is_dumping_aec_ = true;
1721 }
1722 }
1723}
1724
1725void WebRtcVoiceEngine::StopAecDump() {
1726 if (is_dumping_aec_) {
1727 // Stop dumping AEC when we are dumping.
1728 if (voe_wrapper_->processing()->StopDebugRecording() !=
1729 webrtc::AudioProcessing::kNoError) {
1730 LOG_RTCERR0(StopDebugRecording);
1731 }
1732 is_dumping_aec_ = false;
1733 }
1734}
1735
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001736int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001737 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001738}
1739
1740int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1741 return CreateVoiceChannel(voe_wrapper_.get());
1742}
1743
1744int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1745 return CreateVoiceChannel(voe_wrapper_sc_.get());
1746}
1747
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001748class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1749 : public AudioRenderer::Sink {
1750 public:
1751 WebRtcVoiceChannelRenderer(int ch,
1752 webrtc::AudioTransport* voe_audio_transport)
1753 : channel_(ch),
1754 voe_audio_transport_(voe_audio_transport),
1755 renderer_(NULL) {
1756 }
1757 virtual ~WebRtcVoiceChannelRenderer() {
1758 Stop();
1759 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001760
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001761 // Starts the rendering by setting a sink to the renderer to get data
1762 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001763 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001764 // TODO(xians): Make sure Start() is called only once.
1765 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001766 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001767 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001768 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001769 ASSERT(renderer_ == renderer);
1770 return;
1771 }
1772
1773 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1774 // in getUserMedia by default.
1775 renderer->AddChannel(channel_);
1776 renderer->SetSink(this);
1777 renderer_ = renderer;
1778 }
1779
1780 // Stops rendering by setting the sink of the renderer to NULL. No data
1781 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001782 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001783 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001784 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001785 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001786 return;
1787
1788 renderer_->RemoveChannel(channel_);
1789 renderer_->SetSink(NULL);
1790 renderer_ = NULL;
1791 }
1792
1793 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001794 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001795 virtual void OnData(const void* audio_data,
1796 int bits_per_sample,
1797 int sample_rate,
1798 int number_of_channels,
1799 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001800 voe_audio_transport_->OnData(channel_,
1801 audio_data,
1802 bits_per_sample,
1803 sample_rate,
1804 number_of_channels,
1805 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001806 }
1807
1808 // Callback from the |renderer_| when it is going away. In case Start() has
1809 // never been called, this callback won't be triggered.
1810 virtual void OnClose() OVERRIDE {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001811 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001812 // Set |renderer_| to NULL to make sure no more callback will get into
1813 // the renderer.
1814 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001815 }
1816
1817 // Accessor to the VoE channel ID.
1818 int channel() const { return channel_; }
1819
1820 private:
1821 const int channel_;
1822 webrtc::AudioTransport* const voe_audio_transport_;
1823
1824 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1825 // PeerConnection will make sure invalidating the pointer before the object
1826 // goes away.
1827 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001828
1829 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001830 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001831};
1832
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001833// WebRtcVoiceMediaChannel
1834WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1835 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1836 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001837 engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001838 send_bitrate_setting_(false),
1839 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001840 options_(),
1841 dtmf_allowed_(false),
1842 desired_playout_(false),
1843 nack_enabled_(false),
1844 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001845 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001846 desired_send_(SEND_NOTHING),
1847 send_(SEND_NOTHING),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001848 shared_bwe_vie_(NULL),
1849 shared_bwe_vie_channel_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001850 default_receive_ssrc_(0) {
1851 engine->RegisterChannel(this);
1852 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1853 << voe_channel();
1854
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001855 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001856}
1857
1858WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1859 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1860 << voe_channel();
buildbot@webrtc.org6e5c7842014-09-19 06:46:37 +00001861 SetupSharedBandwidthEstimation(NULL, -1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001862
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001863 // Remove any remaining send streams, the default channel will be deleted
1864 // later.
1865 while (!send_channels_.empty())
1866 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001867
1868 // Unregister ourselves from the engine.
1869 engine()->UnregisterChannel(this);
1870 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001871 while (!receive_channels_.empty()) {
1872 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001873 }
1874
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001875 // Delete the default channel.
1876 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001877}
1878
1879bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1880 LOG(LS_INFO) << "Setting voice channel options: "
1881 << options.ToString();
1882
wu@webrtc.orgde305012013-10-31 15:40:38 +00001883 // Check if DSCP value is changed from previous.
1884 bool dscp_option_changed = (options_.dscp != options.dscp);
1885
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001886 // TODO(xians): Add support to set different options for different send
1887 // streams after we support multiple APMs.
1888
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001889 // We retain all of the existing options, and apply the given ones
1890 // on top. This means there is no way to "clear" options such that
1891 // they go back to the engine default.
1892 options_.SetAll(options);
1893
1894 if (send_ != SEND_NOTHING) {
1895 if (!engine()->SetOptionOverrides(options_)) {
1896 LOG(LS_WARNING) <<
1897 "Failed to engine SetOptionOverrides during channel SetOptions.";
1898 return false;
1899 }
1900 } else {
1901 // Will be interpreted when appropriate.
1902 }
1903
wu@webrtc.org97077a32013-10-25 21:18:33 +00001904 // Receiver-side auto gain control happens per channel, so set it here from
1905 // options. Note that, like conference mode, setting it on the engine won't
1906 // have the desired effect, since voice channels don't inherit options from
1907 // the media engine when those options are applied per-channel.
1908 bool rx_auto_gain_control;
1909 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1910 if (engine()->voe()->processing()->SetRxAgcStatus(
1911 voe_channel(), rx_auto_gain_control,
1912 webrtc::kAgcFixedDigital) == -1) {
1913 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1914 return false;
1915 } else {
1916 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1917 << " with mode " << webrtc::kAgcFixedDigital;
1918 }
1919 }
1920 if (options.rx_agc_target_dbov.IsSet() ||
1921 options.rx_agc_digital_compression_gain.IsSet() ||
1922 options.rx_agc_limiter.IsSet()) {
1923 webrtc::AgcConfig config;
1924 // If only some of the options are being overridden, get the current
1925 // settings for the channel and bail if they aren't available.
1926 if (!options.rx_agc_target_dbov.IsSet() ||
1927 !options.rx_agc_digital_compression_gain.IsSet() ||
1928 !options.rx_agc_limiter.IsSet()) {
1929 if (engine()->voe()->processing()->GetRxAgcConfig(
1930 voe_channel(), config) != 0) {
1931 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1932 << "channel " << voe_channel() << ". Since not all rx "
1933 << "agc options are specified, unable to safely set rx "
1934 << "agc options.";
1935 return false;
1936 }
1937 }
1938 config.targetLeveldBOv =
1939 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1940 config.targetLeveldBOv);
1941 config.digitalCompressionGaindB =
1942 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1943 config.digitalCompressionGaindB);
1944 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1945 config.limiterEnable);
1946 if (engine()->voe()->processing()->SetRxAgcConfig(
1947 voe_channel(), config) == -1) {
1948 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1949 config.digitalCompressionGaindB, config.limiterEnable);
1950 return false;
1951 }
1952 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001953 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001954 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001955 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001956 dscp = kAudioDscpValue;
1957 if (MediaChannel::SetDscp(dscp) != 0) {
1958 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1959 }
1960 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001961
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001962 // Force update of Video Engine BWE forwarding to reflect experiment setting.
1963 if (!SetupSharedBandwidthEstimation(shared_bwe_vie_,
1964 shared_bwe_vie_channel_)) {
1965 return false;
1966 }
1967
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001968 LOG(LS_INFO) << "Set voice channel options. Current options: "
1969 << options_.ToString();
1970 return true;
1971}
1972
1973bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1974 const std::vector<AudioCodec>& codecs) {
1975 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001976 LOG(LS_INFO) << "Setting receive voice codecs:";
1977
1978 std::vector<AudioCodec> new_codecs;
1979 // Find all new codecs. We allow adding new codecs but don't allow changing
1980 // the payload type of codecs that is already configured since we might
1981 // already be receiving packets with that payload type.
1982 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001983 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001984 AudioCodec old_codec;
1985 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1986 if (old_codec.id != it->id) {
1987 LOG(LS_ERROR) << it->name << " payload type changed.";
1988 return false;
1989 }
1990 } else {
1991 new_codecs.push_back(*it);
1992 }
1993 }
1994 if (new_codecs.empty()) {
1995 // There are no new codecs to configure. Already configured codecs are
1996 // never removed.
1997 return true;
1998 }
1999
2000 if (playout_) {
2001 // Receive codecs can not be changed while playing. So we temporarily
2002 // pause playout.
2003 PausePlayout();
2004 }
2005
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002006 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002007 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
2008 it != new_codecs.end() && ret; ++it) {
2009 webrtc::CodecInst voe_codec;
2010 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2011 LOG(LS_INFO) << ToString(*it);
2012 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002013 if (default_receive_ssrc_ == 0) {
2014 // Set the receive codecs on the default channel explicitly if the
2015 // default channel is not used by |receive_channels_|, this happens in
2016 // conference mode or in non-conference mode when there is no playout
2017 // channel.
2018 // TODO(xians): Figure out how we use the default channel in conference
2019 // mode.
2020 if (engine()->voe()->codec()->SetRecPayloadType(
2021 voe_channel(), voe_codec) == -1) {
2022 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
2023 ret = false;
2024 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002025 }
2026
2027 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002028 for (ChannelMap::iterator it = receive_channels_.begin();
2029 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002030 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002031 it->second->channel(), voe_codec) == -1) {
2032 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002033 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002034 ret = false;
2035 }
2036 }
2037 } else {
2038 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2039 ret = false;
2040 }
2041 }
2042 if (ret) {
2043 recv_codecs_ = codecs;
2044 }
2045
2046 if (desired_playout_ && !playout_) {
2047 ResumePlayout();
2048 }
2049 return ret;
2050}
2051
2052bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002053 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002054 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002055 engine()->voe()->codec()->SetVADStatus(channel, false);
2056 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002057 engine()->voe()->rtp()->SetREDStatus(channel, false);
2058 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002059
2060 // Scan through the list to figure out the codec to use for sending, along
2061 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002062 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002063 webrtc::CodecInst send_codec;
2064 memset(&send_codec, 0, sizeof(send_codec));
2065
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002066 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002067 bool enable_codec_fec = false;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002068
minyue@webrtc.org26236952014-10-29 02:27:08 +00002069 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002070
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002071 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002072 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2073 it != codecs.end(); ++it) {
2074 // Ignore codecs we don't know about. The negotiation step should prevent
2075 // this, but double-check to be sure.
2076 webrtc::CodecInst voe_codec;
2077 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002078 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002079 continue;
2080 }
2081
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002082 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2083 // Skip telephone-event/CN codec, which will be handled later.
2084 continue;
2085 }
2086
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002087 // We'll use the first codec in the list to actually send audio data.
2088 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002089 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002090 // used is specified in params.
2091 if (IsRedCodec(it->name)) {
2092 // Parse out the RED parameters. If we fail, just ignore RED;
2093 // we don't support all possible params/usage scenarios.
2094 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2095 continue;
2096 }
2097
2098 // Enable redundant encoding of the specified codec. Treat any
2099 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002100 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2101 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2102 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002103 return false;
2104 }
2105 } else {
2106 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002107 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002108 // For Opus as the send codec, we are to enable inband FEC if requested
2109 // and set maximum playback rate.
2110 if (IsOpus(*it)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002111 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
2112 &opus_max_playback_rate);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002113 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002114 }
2115 found_send_codec = true;
2116 break;
2117 }
2118
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002119 if (nack_enabled_ != nack_enabled) {
2120 SetNack(channel, nack_enabled);
2121 nack_enabled_ = nack_enabled;
2122 }
2123
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002124 if (!found_send_codec) {
2125 LOG(LS_WARNING) << "Received empty list of codecs.";
2126 return false;
2127 }
2128
2129 // Set the codec immediately, since SetVADStatus() depends on whether
2130 // the current codec is mono or stereo.
2131 if (!SetSendCodec(channel, send_codec))
2132 return false;
2133
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002134 // FEC should be enabled after SetSendCodec.
2135 if (enable_codec_fec) {
2136 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2137 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002138 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2139 // Enable codec internal FEC. Treat any failure as fatal internal error.
2140 LOG_RTCERR2(SetFECStatus, channel, true);
2141 return false;
2142 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002143 }
2144
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002145 // maxplaybackrate should be set after SetSendCodec.
minyue@webrtc.org26236952014-10-29 02:27:08 +00002146 // If opus_max_playback_rate <= 0, the default maximum playback rate of 48 kHz
2147 // will be used.
2148 if (opus_max_playback_rate > 0) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002149 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002150 << opus_max_playback_rate
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002151 << " Hz on channel "
2152 << channel;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002153 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
minyue@webrtc.org26236952014-10-29 02:27:08 +00002154 channel, opus_max_playback_rate) == -1) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002155 LOG(LS_WARNING) << "Could not set maximum playback rate.";
2156 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002157 }
2158
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002159 // Always update the |send_codec_| to the currently set send codec.
2160 send_codec_.reset(new webrtc::CodecInst(send_codec));
2161
minyue@webrtc.org26236952014-10-29 02:27:08 +00002162 if (send_bitrate_setting_) {
2163 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002164 }
2165
2166 // Loop through the codecs list again to config the telephone-event/CN codec.
2167 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2168 it != codecs.end(); ++it) {
2169 // Ignore codecs we don't know about. The negotiation step should prevent
2170 // this, but double-check to be sure.
2171 webrtc::CodecInst voe_codec;
2172 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2173 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2174 continue;
2175 }
2176
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002177 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2178 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002179 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002180 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2181 channel, it->id) == -1) {
2182 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2183 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002184 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002185 } else if (IsCNCodec(it->name)) {
2186 // Turn voice activity detection/comfort noise on if supported.
2187 // Set the wideband CN payload type appropriately.
2188 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002189 webrtc::PayloadFrequencies cn_freq;
2190 switch (it->clockrate) {
2191 case 8000:
2192 cn_freq = webrtc::kFreq8000Hz;
2193 break;
2194 case 16000:
2195 cn_freq = webrtc::kFreq16000Hz;
2196 break;
2197 case 32000:
2198 cn_freq = webrtc::kFreq32000Hz;
2199 break;
2200 default:
2201 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2202 << " not supported.";
2203 continue;
2204 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002205 // Set the CN payloadtype and the VAD status.
2206 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2207 if (cn_freq != webrtc::kFreq8000Hz) {
2208 if (engine()->voe()->codec()->SetSendCNPayloadType(
2209 channel, it->id, cn_freq) == -1) {
2210 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2211 // TODO(ajm): This failure condition will be removed from VoE.
2212 // Restore the return here when we update to a new enough webrtc.
2213 //
2214 // Not returning false because the SetSendCNPayloadType will fail if
2215 // the channel is already sending.
2216 // This can happen if the remote description is applied twice, for
2217 // example in the case of ROAP on top of JSEP, where both side will
2218 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002219 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002220 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002221 // Only turn on VAD if we have a CN payload type that matches the
2222 // clockrate for the codec we are going to use.
2223 if (it->clockrate == send_codec.plfreq) {
2224 LOG(LS_INFO) << "Enabling VAD";
2225 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2226 LOG_RTCERR2(SetVADStatus, channel, true);
2227 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002228 }
2229 }
2230 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002231 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002232 return true;
2233}
2234
2235bool WebRtcVoiceMediaChannel::SetSendCodecs(
2236 const std::vector<AudioCodec>& codecs) {
2237 dtmf_allowed_ = false;
2238 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2239 it != codecs.end(); ++it) {
2240 // Find the DTMF telephone event "codec".
2241 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2242 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2243 dtmf_allowed_ = true;
2244 }
2245 }
2246
2247 // Cache the codecs in order to configure the channel created later.
2248 send_codecs_ = codecs;
2249 for (ChannelMap::iterator iter = send_channels_.begin();
2250 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002251 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002252 return false;
2253 }
2254 }
2255
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002256 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002257 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002258 return true;
2259}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002260
2261void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2262 bool nack_enabled) {
2263 for (ChannelMap::const_iterator it = channels.begin();
2264 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002265 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002266 }
2267}
2268
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002269void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002270 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002271 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002272 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2273 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002274 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002275 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2276 }
2277}
2278
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002279bool WebRtcVoiceMediaChannel::SetSendCodec(
2280 const webrtc::CodecInst& send_codec) {
2281 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2282 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002283 for (ChannelMap::iterator iter = send_channels_.begin();
2284 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002285 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002286 return false;
2287 }
2288
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002289 return true;
2290}
2291
2292bool WebRtcVoiceMediaChannel::SetSendCodec(
2293 int channel, const webrtc::CodecInst& send_codec) {
2294 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2295 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2296
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002297 webrtc::CodecInst current_codec;
2298 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2299 (send_codec == current_codec)) {
2300 // Codec is already configured, we can return without setting it again.
2301 return true;
2302 }
2303
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002304 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2305 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002306 return false;
2307 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002308 return true;
2309}
2310
2311bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2312 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002313 if (receive_extensions_ == extensions) {
2314 return true;
2315 }
2316
2317 // The default channel may or may not be in |receive_channels_|. Set the rtp
2318 // header extensions for default channel regardless.
2319 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2320 return false;
2321 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002322
2323 // Loop through all receive channels and enable/disable the extensions.
2324 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2325 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002326 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2327 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002328 return false;
2329 }
2330 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002331
2332 receive_extensions_ = extensions;
2333 return true;
2334}
2335
2336bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2337 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002338 const RtpHeaderExtension* audio_level_extension =
2339 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2340 if (!SetHeaderExtension(
2341 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2342 audio_level_extension)) {
2343 return false;
2344 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002345
2346 const RtpHeaderExtension* send_time_extension =
2347 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2348 if (!SetHeaderExtension(
2349 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2350 send_time_extension)) {
2351 return false;
2352 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002353 return true;
2354}
2355
2356bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2357 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002358 if (send_extensions_ == extensions) {
2359 return true;
2360 }
2361
2362 // The default channel may or may not be in |send_channels_|. Set the rtp
2363 // header extensions for default channel regardless.
2364
2365 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2366 return false;
2367 }
2368
2369 // Loop through all send channels and enable/disable the extensions.
2370 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2371 channel_it != send_channels_.end(); ++channel_it) {
2372 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2373 extensions)) {
2374 return false;
2375 }
2376 }
2377
2378 send_extensions_ = extensions;
2379 return true;
2380}
2381
2382bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2383 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002384 const RtpHeaderExtension* audio_level_extension =
2385 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002386
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002387 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002388 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002389 audio_level_extension)) {
2390 return false;
2391 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002392
2393 const RtpHeaderExtension* send_time_extension =
2394 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002395 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002396 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002397 send_time_extension)) {
2398 return false;
2399 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002400
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002401 return true;
2402}
2403
2404bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2405 desired_playout_ = playout;
2406 return ChangePlayout(desired_playout_);
2407}
2408
2409bool WebRtcVoiceMediaChannel::PausePlayout() {
2410 return ChangePlayout(false);
2411}
2412
2413bool WebRtcVoiceMediaChannel::ResumePlayout() {
2414 return ChangePlayout(desired_playout_);
2415}
2416
2417bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2418 if (playout_ == playout) {
2419 return true;
2420 }
2421
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002422 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002423 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002424 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002425 // Only toggle the default channel if we don't have any other channels.
2426 result = SetPlayout(voe_channel(), playout);
2427 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002428 for (ChannelMap::iterator it = receive_channels_.begin();
2429 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002430 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002431 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002432 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002433 result = false;
2434 }
2435 }
2436
2437 if (result) {
2438 playout_ = playout;
2439 }
2440 return result;
2441}
2442
2443bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2444 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002445 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002446 return ChangeSend(desired_send_);
2447 return true;
2448}
2449
2450bool WebRtcVoiceMediaChannel::PauseSend() {
2451 return ChangeSend(SEND_NOTHING);
2452}
2453
2454bool WebRtcVoiceMediaChannel::ResumeSend() {
2455 return ChangeSend(desired_send_);
2456}
2457
2458bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2459 if (send_ == send) {
2460 return true;
2461 }
2462
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002463 // Change the settings on each send channel.
2464 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002465 engine()->SetOptionOverrides(options_);
2466
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002467 // Change the settings on each send channel.
2468 for (ChannelMap::iterator iter = send_channels_.begin();
2469 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002470 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002471 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002472 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002473
2474 // Clear up the options after stopping sending.
2475 if (send == SEND_NOTHING)
2476 engine()->ClearOptionOverrides();
2477
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002478 send_ = send;
2479 return true;
2480}
2481
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002482bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2483 if (send == SEND_MICROPHONE) {
2484 if (engine()->voe()->base()->StartSend(channel) == -1) {
2485 LOG_RTCERR1(StartSend, channel);
2486 return false;
2487 }
2488 if (engine()->voe()->file() &&
2489 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2490 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2491 return false;
2492 }
2493 } else { // SEND_NOTHING
2494 ASSERT(send == SEND_NOTHING);
2495 if (engine()->voe()->base()->StopSend(channel) == -1) {
2496 LOG_RTCERR1(StopSend, channel);
2497 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002498 }
2499 }
2500
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002501 return true;
2502}
2503
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002504// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002505void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2506 if (engine()->voe()->network()->RegisterExternalTransport(
2507 channel, *this) == -1) {
2508 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2509 }
2510
2511 // Enable RTCP (for quality stats and feedback messages)
2512 EnableRtcp(channel);
2513
2514 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2515 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002516
2517 // Set RTP header extension for the new channel.
2518 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002519}
2520
2521bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2522 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2523 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2524 }
2525
2526 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2527 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002528 return false;
2529 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002530
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002531 return true;
2532}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002533
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002534bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2535 // If the default channel is already used for sending create a new channel
2536 // otherwise use the default channel for sending.
2537 int channel = GetSendChannelNum(sp.first_ssrc());
2538 if (channel != -1) {
2539 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2540 return false;
2541 }
2542
2543 bool default_channel_is_available = true;
2544 for (ChannelMap::const_iterator iter = send_channels_.begin();
2545 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002546 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002547 default_channel_is_available = false;
2548 break;
2549 }
2550 }
2551 if (default_channel_is_available) {
2552 channel = voe_channel();
2553 } else {
2554 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002555 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002556 if (channel == -1) {
2557 LOG_RTCERR0(CreateChannel);
2558 return false;
2559 }
2560
2561 ConfigureSendChannel(channel);
2562 }
2563
2564 // Save the channel to send_channels_, so that RemoveSendStream() can still
2565 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002566 webrtc::AudioTransport* audio_transport =
2567 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002568 send_channels_.insert(std::make_pair(
2569 sp.first_ssrc(),
2570 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002571
2572 // Set the send (local) SSRC.
2573 // If there are multiple send SSRCs, we can only set the first one here, and
2574 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2575 // (with a codec requires multiple SSRC(s)).
2576 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2577 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2578 return false;
2579 }
2580
2581 // At this point the channel's local SSRC has been updated. If the channel is
2582 // the default channel make sure that all the receive channels are updated as
2583 // well. Receive channels have to have the same SSRC as the default channel in
2584 // order to send receiver reports with this SSRC.
2585 if (IsDefaultChannel(channel)) {
2586 for (ChannelMap::const_iterator it = receive_channels_.begin();
2587 it != receive_channels_.end(); ++it) {
2588 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002589 if (!IsDefaultChannel(it->second->channel())) {
2590 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002591 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002592 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002593 return false;
2594 }
2595 }
2596 }
2597 }
2598
2599 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002600 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2601 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002602 }
2603
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002604 // Set the current codecs to be used for the new channel.
2605 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002606 return false;
2607
2608 return ChangeSend(channel, desired_send_);
2609}
2610
2611bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2612 ChannelMap::iterator it = send_channels_.find(ssrc);
2613 if (it == send_channels_.end()) {
2614 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2615 << " which doesn't exist.";
2616 return false;
2617 }
2618
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002619 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002620 ChangeSend(channel, SEND_NOTHING);
2621
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002622 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2623 // this will disconnect the audio renderer with the send channel.
2624 delete it->second;
2625 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002626
2627 if (IsDefaultChannel(channel)) {
2628 // Do not delete the default channel since the receive channels depend on
2629 // the default channel, recycle it instead.
2630 ChangeSend(channel, SEND_NOTHING);
2631 } else {
2632 // Clean up and delete the send channel.
2633 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2634 << " with VoiceEngine channel #" << channel << ".";
2635 if (!DeleteChannel(channel))
2636 return false;
2637 }
2638
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002639 if (send_channels_.empty())
2640 ChangeSend(SEND_NOTHING);
2641
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002642 return true;
2643}
2644
2645bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002646 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002647
2648 if (!VERIFY(sp.ssrcs.size() == 1))
2649 return false;
2650 uint32 ssrc = sp.first_ssrc();
2651
wu@webrtc.org78187522013-10-07 23:32:02 +00002652 if (ssrc == 0) {
2653 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2654 return false;
2655 }
2656
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002657 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2658 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002659 return false;
2660 }
2661
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002662 // Reuse default channel for recv stream in non-conference mode call
2663 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002664 webrtc::AudioTransport* audio_transport =
2665 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002666 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2667 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2668 << " reuse default channel";
2669 default_receive_ssrc_ = sp.first_ssrc();
2670 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002671 default_receive_ssrc_,
2672 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002673 if (!SetupSharedBweOnChannel(voe_channel())) {
2674 return false;
2675 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002676 return SetPlayout(voe_channel(), playout_);
2677 }
2678
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002679 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002680 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002681 if (channel == -1) {
2682 LOG_RTCERR0(CreateChannel);
2683 return false;
2684 }
2685
wu@webrtc.org78187522013-10-07 23:32:02 +00002686 if (!ConfigureRecvChannel(channel)) {
2687 DeleteChannel(channel);
2688 return false;
2689 }
2690
2691 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002692 std::make_pair(
2693 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002694
2695 LOG(LS_INFO) << "New audio stream " << ssrc
2696 << " registered to VoiceEngine channel #"
2697 << channel << ".";
2698 return true;
2699}
2700
2701bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002702 // Configure to use external transport, like our default channel.
2703 if (engine()->voe()->network()->RegisterExternalTransport(
2704 channel, *this) == -1) {
2705 LOG_RTCERR2(SetExternalTransport, channel, this);
2706 return false;
2707 }
2708
2709 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002710 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002711 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2712 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002713 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002714 return false;
2715 }
2716 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002717 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002718 return false;
2719 }
2720
2721 // Use the same recv payload types as our default channel.
2722 ResetRecvCodecs(channel);
2723 if (!recv_codecs_.empty()) {
2724 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2725 it != recv_codecs_.end(); ++it) {
2726 webrtc::CodecInst voe_codec;
2727 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2728 voe_codec.pltype = it->id;
2729 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2730 if (engine()->voe()->codec()->GetRecPayloadType(
2731 voe_channel(), voe_codec) != -1) {
2732 if (engine()->voe()->codec()->SetRecPayloadType(
2733 channel, voe_codec) == -1) {
2734 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2735 return false;
2736 }
2737 }
2738 }
2739 }
2740 }
2741
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002742 if (InConferenceMode()) {
2743 // To be in par with the video, voe_channel() is not used for receiving in
2744 // a conference call.
2745 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2746 // This is the first stream in a multi user meeting. We can now
2747 // disable playback of the default stream. This since the default
2748 // stream will probably have received some initial packets before
2749 // the new stream was added. This will mean that the CN state from
2750 // the default channel will be mixed in with the other streams
2751 // throughout the whole meeting, which might be disturbing.
2752 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2753 SetPlayout(voe_channel(), false);
2754 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002755 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002756 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002757
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002758 // Set RTP header extension for the new channel.
2759 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2760 return false;
2761 }
2762
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002763 // Set up channel to be able to forward incoming packets to video engine BWE.
2764 if (!SetupSharedBweOnChannel(channel)) {
2765 return false;
2766 }
2767
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002768 return SetPlayout(channel, playout_);
2769}
2770
2771bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002772 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002773 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002774 if (it == receive_channels_.end()) {
2775 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2776 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002777 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002778 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002779
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002780 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2781 // will disconnect the audio renderer with the receive channel.
2782 // Cache the channel before the deletion.
2783 const int channel = it->second->channel();
2784 delete it->second;
2785 receive_channels_.erase(it);
2786
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002787 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002788 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002789 // Recycle the default channel is for recv stream.
2790 if (playout_)
2791 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002792
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002793 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002794 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002795 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002796
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002797 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002798 << " with VoiceEngine channel #" << channel << ".";
2799 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002800 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002801
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002802 bool enable_default_channel_playout = false;
2803 if (receive_channels_.empty()) {
2804 // The last stream was removed. We can now enable the default
2805 // channel for new channels to be played out immediately without
2806 // waiting for AddStream messages.
2807 // We do this for both conference mode and non-conference mode.
2808 // TODO(oja): Does the default channel still have it's CN state?
2809 enable_default_channel_playout = true;
2810 }
2811 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2812 default_receive_ssrc_ != 0) {
2813 // Only the default channel is active, enable the playout on default
2814 // channel.
2815 enable_default_channel_playout = true;
2816 }
2817 if (enable_default_channel_playout && playout_) {
2818 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2819 SetPlayout(voe_channel(), true);
2820 }
2821
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002822 return true;
2823}
2824
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002825bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2826 AudioRenderer* renderer) {
2827 ChannelMap::iterator it = receive_channels_.find(ssrc);
2828 if (it == receive_channels_.end()) {
2829 if (renderer) {
2830 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002831 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002832 return false;
2833 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002834
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002835 // The channel likely has gone away, do nothing.
2836 return true;
2837 }
2838
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002839 if (renderer)
2840 it->second->Start(renderer);
2841 else
2842 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002843
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002844 return true;
2845}
2846
2847bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2848 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002849 ChannelMap::iterator it = send_channels_.find(ssrc);
2850 if (it == send_channels_.end()) {
2851 if (renderer) {
2852 // Return an error if trying to set a valid renderer with an invalid ssrc.
2853 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2854 return false;
2855 }
2856
2857 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002858 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002859 }
2860
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002861 if (renderer)
2862 it->second->Start(renderer);
2863 else
2864 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002865
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002866 return true;
2867}
2868
2869bool WebRtcVoiceMediaChannel::GetActiveStreams(
2870 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002871 // In conference mode, the default channel should not be in
2872 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002873 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002874 for (ChannelMap::iterator it = receive_channels_.begin();
2875 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002876 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002877 if (level > 0) {
2878 actives->push_back(std::make_pair(it->first, level));
2879 }
2880 }
2881 return true;
2882}
2883
2884int WebRtcVoiceMediaChannel::GetOutputLevel() {
2885 // return the highest output level of all streams
2886 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002887 for (ChannelMap::iterator it = receive_channels_.begin();
2888 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002889 int level = GetOutputLevel(it->second->channel());
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002890 highest = rtc::_max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002891 }
2892 return highest;
2893}
2894
2895int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2896 int ret;
2897 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2898 // In case of error, log the info and continue
2899 LOG_RTCERR0(TimeSinceLastTyping);
2900 ret = -1;
2901 } else {
2902 ret *= 1000; // We return ms, webrtc returns seconds.
2903 }
2904 return ret;
2905}
2906
2907void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2908 int cost_per_typing, int reporting_threshold, int penalty_decay,
2909 int type_event_delay) {
2910 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2911 time_window, cost_per_typing,
2912 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2913 // In case of error, log the info and continue
2914 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2915 cost_per_typing, reporting_threshold, penalty_decay,
2916 type_event_delay);
2917 }
2918}
2919
2920bool WebRtcVoiceMediaChannel::SetOutputScaling(
2921 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002922 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002923 // Collect the channels to scale the output volume.
2924 std::vector<int> channels;
2925 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002926 // Default channel is not in receive_channels_ if it is not being used for
2927 // playout.
2928 if (default_receive_ssrc_ == 0)
2929 channels.push_back(voe_channel());
2930 for (ChannelMap::const_iterator it = receive_channels_.begin();
2931 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002932 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002933 }
2934 } else { // Collect only the channel of the specified ssrc.
2935 int channel = GetReceiveChannelNum(ssrc);
2936 if (-1 == channel) {
2937 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2938 return false;
2939 }
2940 channels.push_back(channel);
2941 }
2942
2943 // Scale the output volume for the collected channels. We first normalize to
2944 // scale the volume and then set the left and right pan.
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002945 float scale = static_cast<float>(rtc::_max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002946 if (scale > 0.0001f) {
2947 left /= scale;
2948 right /= scale;
2949 }
2950 for (std::vector<int>::const_iterator it = channels.begin();
2951 it != channels.end(); ++it) {
2952 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2953 *it, scale)) {
2954 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2955 return false;
2956 }
2957 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2958 *it, static_cast<float>(left), static_cast<float>(right))) {
2959 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2960 // Do not return if fails. SetOutputVolumePan is not available for all
2961 // pltforms.
2962 }
2963 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2964 << " right=" << right * scale
2965 << " for channel " << *it << " and ssrc " << ssrc;
2966 }
2967 return true;
2968}
2969
2970bool WebRtcVoiceMediaChannel::GetOutputScaling(
2971 uint32 ssrc, double* left, double* right) {
2972 if (!left || !right) return false;
2973
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002974 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002975 // Determine which channel based on ssrc.
2976 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2977 if (channel == -1) {
2978 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2979 return false;
2980 }
2981
2982 float scaling;
2983 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2984 channel, scaling)) {
2985 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2986 return false;
2987 }
2988
2989 float left_pan;
2990 float right_pan;
2991 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2992 channel, left_pan, right_pan)) {
2993 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2994 // If GetOutputVolumePan fails, we use the default left and right pan.
2995 left_pan = 1.0f;
2996 right_pan = 1.0f;
2997 }
2998
2999 *left = scaling * left_pan;
3000 *right = scaling * right_pan;
3001 return true;
3002}
3003
3004bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
3005 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
3006 return true;
3007}
3008
3009bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
3010 bool play, bool loop) {
3011 if (!ringback_tone_) {
3012 return false;
3013 }
3014
3015 // The voe file api is not available in chrome.
3016 if (!engine()->voe()->file()) {
3017 return false;
3018 }
3019
3020 // Determine which VoiceEngine channel to play on.
3021 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
3022 if (channel == -1) {
3023 return false;
3024 }
3025
3026 // Make sure the ringtone is cued properly, and play it out.
3027 if (play) {
3028 ringback_tone_->set_loop(loop);
3029 ringback_tone_->Rewind();
3030 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
3031 ringback_tone_.get()) == -1) {
3032 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
3033 LOG(LS_ERROR) << "Unable to start ringback tone";
3034 return false;
3035 }
3036 ringback_channels_.insert(channel);
3037 LOG(LS_INFO) << "Started ringback on channel " << channel;
3038 } else {
3039 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
3040 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
3041 LOG_RTCERR1(StopPlayingFileLocally, channel);
3042 return false;
3043 }
3044 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
3045 ringback_channels_.erase(channel);
3046 }
3047
3048 return true;
3049}
3050
3051bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3052 return dtmf_allowed_;
3053}
3054
3055bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3056 int duration, int flags) {
3057 if (!dtmf_allowed_) {
3058 return false;
3059 }
3060
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003061 // Send the event.
3062 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003063 int channel = -1;
3064 if (ssrc == 0) {
3065 bool default_channel_is_inuse = false;
3066 for (ChannelMap::const_iterator iter = send_channels_.begin();
3067 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003068 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003069 default_channel_is_inuse = true;
3070 break;
3071 }
3072 }
3073 if (default_channel_is_inuse) {
3074 channel = voe_channel();
3075 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003076 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003077 }
3078 } else {
3079 channel = GetSendChannelNum(ssrc);
3080 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003081 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003082 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3083 << ssrc << " is not in use.";
3084 return false;
3085 }
3086 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003087 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3088 channel, event, true, duration) == -1) {
3089 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003090 return false;
3091 }
3092 }
3093
3094 // Play the event.
3095 if (flags & cricket::DF_PLAY) {
3096 // Play DTMF tone locally.
3097 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3098 LOG_RTCERR2(PlayDtmfTone, event, duration);
3099 return false;
3100 }
3101 }
3102
3103 return true;
3104}
3105
wu@webrtc.orga9890802013-12-13 00:21:03 +00003106void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003107 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003108 // Pick which channel to send this packet to. If this packet doesn't match
3109 // any multiplexed streams, just send it to the default channel. Otherwise,
3110 // send it to the specific decoder instance for that stream.
3111 int which_channel = GetReceiveChannelNum(
3112 ParseSsrc(packet->data(), packet->length(), false));
3113 if (which_channel == -1) {
3114 which_channel = voe_channel();
3115 }
3116
3117 // Stop any ringback that might be playing on the channel.
3118 // It's possible the ringback has already stopped, ih which case we'll just
3119 // use the opportunity to remove the channel from ringback_channels_.
3120 if (engine()->voe()->file()) {
3121 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3122 if (it != ringback_channels_.end()) {
3123 if (engine()->voe()->file()->IsPlayingFileLocally(
3124 which_channel) == 1) {
3125 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3126 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3127 << " due to incoming media";
3128 }
3129 ringback_channels_.erase(which_channel);
3130 }
3131 }
3132
3133 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003134 engine()->voe()->network()->ReceivedRTPPacket(
3135 which_channel,
3136 packet->data(),
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003137 packet->length(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003138 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003139}
3140
wu@webrtc.orga9890802013-12-13 00:21:03 +00003141void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003142 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003143 // Sending channels need all RTCP packets with feedback information.
3144 // Even sender reports can contain attached report blocks.
3145 // Receiving channels need sender reports in order to create
3146 // correct receiver reports.
3147 int type = 0;
3148 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3149 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3150 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003151 }
3152
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003153 // If it is a sender report, find the channel that is listening.
3154 bool has_sent_to_default_channel = false;
3155 if (type == kRtcpTypeSR) {
3156 int which_channel = GetReceiveChannelNum(
3157 ParseSsrc(packet->data(), packet->length(), true));
3158 if (which_channel != -1) {
3159 engine()->voe()->network()->ReceivedRTCPPacket(
3160 which_channel,
3161 packet->data(),
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003162 packet->length());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003163
3164 if (IsDefaultChannel(which_channel))
3165 has_sent_to_default_channel = true;
3166 }
3167 }
3168
3169 // SR may continue RR and any RR entry may correspond to any one of the send
3170 // channels. So all RTCP packets must be forwarded all send channels. VoE
3171 // will filter out RR internally.
3172 for (ChannelMap::iterator iter = send_channels_.begin();
3173 iter != send_channels_.end(); ++iter) {
3174 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003175 if (IsDefaultChannel(iter->second->channel()) &&
3176 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003177 continue;
3178
3179 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003180 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003181 packet->data(),
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003182 packet->length());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003183 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003184}
3185
3186bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003187 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3188 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003189 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3190 return false;
3191 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003192 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3193 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003194 return false;
3195 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003196 // We set the AGC to mute state only when all the channels are muted.
3197 // This implementation is not ideal, instead we should signal the AGC when
3198 // the mic channel is muted/unmuted. We can't do it today because there
3199 // is no good way to know which stream is mapping to the mic channel.
3200 bool all_muted = muted;
3201 for (ChannelMap::const_iterator iter = send_channels_.begin();
3202 iter != send_channels_.end() && all_muted; ++iter) {
3203 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3204 all_muted)) {
3205 LOG_RTCERR1(GetInputMute, iter->second->channel());
3206 return false;
3207 }
3208 }
3209
3210 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3211 if (ap)
3212 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003213 return true;
3214}
3215
minyue@webrtc.org26236952014-10-29 02:27:08 +00003216// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3217// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003218bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003219 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003220
minyue@webrtc.org26236952014-10-29 02:27:08 +00003221 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003222}
3223
minyue@webrtc.org26236952014-10-29 02:27:08 +00003224bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3225 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003226
minyue@webrtc.org26236952014-10-29 02:27:08 +00003227 send_bitrate_setting_ = true;
3228 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003229
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003230 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003231 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003232 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003233 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003234 }
3235
minyue@webrtc.org26236952014-10-29 02:27:08 +00003236 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003237 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3238 // SetMaxSendBandwith(0), the second call removes the previous limit.
3239 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003240 return true;
3241
3242 webrtc::CodecInst codec = *send_codec_;
3243 bool is_multi_rate = IsCodecMultiRate(codec);
3244
3245 if (is_multi_rate) {
3246 // If codec is multi-rate then just set the bitrate.
3247 codec.rate = bps;
3248 if (!SetSendCodec(codec)) {
3249 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3250 << " to bitrate " << bps << " bps.";
3251 return false;
3252 }
3253 return true;
3254 } else {
3255 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3256 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3257 // fixed bitrate then ignore.
3258 if (bps < codec.rate) {
3259 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3260 << " to bitrate " << bps << " bps"
3261 << ", requires at least " << codec.rate << " bps.";
3262 return false;
3263 }
3264 return true;
3265 }
3266}
3267
3268bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003269 bool echo_metrics_on = false;
3270 // These can take on valid negative values, so use the lowest possible level
3271 // as default rather than -1.
3272 int echo_return_loss = -100;
3273 int echo_return_loss_enhancement = -100;
3274 // These can also be negative, but in practice -1 is only used to signal
3275 // insufficient data, since the resolution is limited to multiples of 4 ms.
3276 int echo_delay_median_ms = -1;
3277 int echo_delay_std_ms = -1;
3278 if (engine()->voe()->processing()->GetEcMetricsStatus(
3279 echo_metrics_on) != -1 && echo_metrics_on) {
3280 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3281 // here, but it appears to be unsuitable currently. Revisit after this is
3282 // investigated: http://b/issue?id=5666755
3283 int erl, erle, rerl, anlp;
3284 if (engine()->voe()->processing()->GetEchoMetrics(
3285 erl, erle, rerl, anlp) != -1) {
3286 echo_return_loss = erl;
3287 echo_return_loss_enhancement = erle;
3288 }
3289
3290 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003291 float dummy;
3292 if (engine()->voe()->processing()->GetEcDelayMetrics(
3293 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003294 echo_delay_median_ms = median;
3295 echo_delay_std_ms = std;
3296 }
3297 }
3298
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003299 webrtc::CallStatistics cs;
3300 unsigned int ssrc;
3301 webrtc::CodecInst codec;
3302 unsigned int level;
3303
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003304 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3305 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003306 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003307
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003308 // Fill in the sender info, based on what we know, and what the
3309 // remote side told us it got from its RTCP report.
3310 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003311
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003312 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3313 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3314 continue;
3315 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003316
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003317 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003318 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3319 sinfo.bytes_sent = cs.bytesSent;
3320 sinfo.packets_sent = cs.packetsSent;
3321 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3322 // returns 0 to indicate an error value.
3323 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3324
3325 // Get data from the last remote RTCP report. Use default values if no data
3326 // available.
3327 sinfo.fraction_lost = -1.0;
3328 sinfo.jitter_ms = -1;
3329 sinfo.packets_lost = -1;
3330 sinfo.ext_seqnum = -1;
3331 std::vector<webrtc::ReportBlock> receive_blocks;
3332 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3333 channel, &receive_blocks) != -1 &&
3334 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3335 std::vector<webrtc::ReportBlock>::iterator iter;
3336 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3337 ++iter) {
3338 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003339 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003340 // Convert Q8 to floating point.
3341 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3342 // Convert samples to milliseconds.
3343 if (codec.plfreq / 1000 > 0) {
3344 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3345 }
3346 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3347 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3348 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003349 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003350 }
3351 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003352
3353 // Local speech level.
3354 sinfo.audio_level = (engine()->voe()->volume()->
3355 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3356
3357 // TODO(xians): We are injecting the same APM logging to all the send
3358 // channels here because there is no good way to know which send channel
3359 // is using the APM. The correct fix is to allow the send channels to have
3360 // their own APM so that we can feed the correct APM logging to different
3361 // send channels. See issue crbug/264611 .
3362 sinfo.echo_return_loss = echo_return_loss;
3363 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3364 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3365 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003366 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3367 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003368 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003369
3370 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003371 }
3372
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003373 // Build the list of receivers, one for each receiving channel, or 1 in
3374 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003375 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003376 for (ChannelMap::const_iterator it = receive_channels_.begin();
3377 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003378 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003379 }
3380 if (channels.empty()) {
3381 channels.push_back(voe_channel());
3382 }
3383
3384 // Get the SSRC and stats for each receiver, based on our own calculations.
3385 for (std::vector<int>::const_iterator it = channels.begin();
3386 it != channels.end(); ++it) {
3387 memset(&cs, 0, sizeof(cs));
3388 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3389 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3390 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3391 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003392 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003393 rinfo.bytes_rcvd = cs.bytesReceived;
3394 rinfo.packets_rcvd = cs.packetsReceived;
3395 // The next four fields are from the most recently sent RTCP report.
3396 // Convert Q8 to floating point.
3397 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3398 rinfo.packets_lost = cs.cumulativeLost;
3399 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003400 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003401 if (codec.pltype != -1) {
3402 rinfo.codec_name = codec.plname;
3403 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003404 // Convert samples to milliseconds.
3405 if (codec.plfreq / 1000 > 0) {
3406 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3407 }
3408
3409 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3410 webrtc::NetworkStatistics ns;
3411 if (engine()->voe()->neteq() &&
3412 engine()->voe()->neteq()->GetNetworkStatistics(
3413 *it, ns) != -1) {
3414 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3415 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3416 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003417 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003418 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003419
3420 webrtc::AudioDecodingCallStats ds;
3421 if (engine()->voe()->neteq() &&
3422 engine()->voe()->neteq()->GetDecodingCallStatistics(
3423 *it, &ds) != -1) {
3424 rinfo.decoding_calls_to_silence_generator =
3425 ds.calls_to_silence_generator;
3426 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3427 rinfo.decoding_normal = ds.decoded_normal;
3428 rinfo.decoding_plc = ds.decoded_plc;
3429 rinfo.decoding_cng = ds.decoded_cng;
3430 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3431 }
3432
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003433 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003434 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003435 int playout_buffer_delay_ms = 0;
3436 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003437 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3438 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3439 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003440 }
3441
3442 // Get speech level.
3443 rinfo.audio_level = (engine()->voe()->volume()->
3444 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3445 info->receivers.push_back(rinfo);
3446 }
3447 }
3448
3449 return true;
3450}
3451
3452void WebRtcVoiceMediaChannel::GetLastMediaError(
3453 uint32* ssrc, VoiceMediaChannel::Error* error) {
3454 ASSERT(ssrc != NULL);
3455 ASSERT(error != NULL);
3456 FindSsrc(voe_channel(), ssrc);
3457 *error = WebRtcErrorToChannelError(GetLastEngineError());
3458}
3459
3460bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003461 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003462 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003463 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003464 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3465 // This means the error is not limited to a specific channel. Signal the
3466 // message using ssrc=0. If the current channel is sending, use this
3467 // channel for sending the message.
3468 *ssrc = 0;
3469 return true;
3470 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003471 // Check whether this is a sending channel.
3472 for (ChannelMap::const_iterator it = send_channels_.begin();
3473 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003474 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003475 // This is a sending channel.
3476 uint32 local_ssrc = 0;
3477 if (engine()->voe()->rtp()->GetLocalSSRC(
3478 channel_num, local_ssrc) != -1) {
3479 *ssrc = local_ssrc;
3480 }
3481 return true;
3482 }
3483 }
3484
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003485 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003486 for (ChannelMap::const_iterator it = receive_channels_.begin();
3487 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003488 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003489 *ssrc = it->first;
3490 return true;
3491 }
3492 }
3493 }
3494 return false;
3495}
3496
3497void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003498 if (error == VE_TYPING_NOISE_WARNING) {
3499 typing_noise_detected_ = true;
3500 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3501 typing_noise_detected_ = false;
3502 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003503 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3504}
3505
3506int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3507 unsigned int ulevel;
3508 int ret =
3509 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3510 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3511}
3512
3513int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003514 ChannelMap::iterator it = receive_channels_.find(ssrc);
3515 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003516 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003517 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3518}
3519
3520int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003521 ChannelMap::iterator it = send_channels_.find(ssrc);
3522 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003523 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003524
3525 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003526}
3527
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003528bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
3529 webrtc::VideoEngine* vie, int vie_channel) {
3530 shared_bwe_vie_ = vie;
3531 shared_bwe_vie_channel_ = vie_channel;
3532
3533 if (!SetupSharedBweOnChannel(voe_channel())) {
3534 return false;
3535 }
3536 for (ChannelMap::iterator it = receive_channels_.begin();
3537 it != receive_channels_.end(); ++it) {
3538 if (!SetupSharedBweOnChannel(it->second->channel())) {
3539 return false;
3540 }
3541 }
3542 return true;
3543}
3544
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003545bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3546 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3547 // Get the RED encodings from the parameter with no name. This may
3548 // change based on what is discussed on the Jingle list.
3549 // The encoding parameter is of the form "a/b"; we only support where
3550 // a == b. Verify this and parse out the value into red_pt.
3551 // If the parameter value is absent (as it will be until we wire up the
3552 // signaling of this message), use the second codec specified (i.e. the
3553 // one after "red") as the encoding parameter.
3554 int red_pt = -1;
3555 std::string red_params;
3556 CodecParameterMap::const_iterator it = red_codec.params.find("");
3557 if (it != red_codec.params.end()) {
3558 red_params = it->second;
3559 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003560 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003561 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003562 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003563 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3564 return false;
3565 }
3566 } else if (red_codec.params.empty()) {
3567 LOG(LS_WARNING) << "RED params not present, using defaults";
3568 if (all_codecs.size() > 1) {
3569 red_pt = all_codecs[1].id;
3570 }
3571 }
3572
3573 // Try to find red_pt in |codecs|.
3574 std::vector<AudioCodec>::const_iterator codec;
3575 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3576 if (codec->id == red_pt)
3577 break;
3578 }
3579
3580 // If we find the right codec, that will be the codec we pass to
3581 // SetSendCodec, with the desired payload type.
3582 if (codec != all_codecs.end() &&
3583 engine()->FindWebRtcCodec(*codec, send_codec)) {
3584 } else {
3585 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3586 return false;
3587 }
3588
3589 return true;
3590}
3591
3592bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3593 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003594 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003595 return false;
3596 }
3597 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3598 // what we want to do with them.
3599 // engine()->voe().EnableVQMon(voe_channel(), true);
3600 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3601 return true;
3602}
3603
3604bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3605 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3606 for (int i = 0; i < ncodecs; ++i) {
3607 webrtc::CodecInst voe_codec;
3608 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3609 voe_codec.pltype = -1;
3610 if (engine()->voe()->codec()->SetRecPayloadType(
3611 channel, voe_codec) == -1) {
3612 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3613 return false;
3614 }
3615 }
3616 }
3617 return true;
3618}
3619
3620bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3621 if (playout) {
3622 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3623 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3624 LOG_RTCERR1(StartPlayout, channel);
3625 return false;
3626 }
3627 } else {
3628 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3629 engine()->voe()->base()->StopPlayout(channel);
3630 }
3631 return true;
3632}
3633
3634uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3635 bool rtcp) {
3636 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3637 uint32 ssrc = 0;
3638 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003639 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003640 }
3641 return ssrc;
3642}
3643
3644// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3645VoiceMediaChannel::Error
3646 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3647 switch (err_code) {
3648 case 0:
3649 return ERROR_NONE;
3650 case VE_CANNOT_START_RECORDING:
3651 case VE_MIC_VOL_ERROR:
3652 case VE_GET_MIC_VOL_ERROR:
3653 case VE_CANNOT_ACCESS_MIC_VOL:
3654 return ERROR_REC_DEVICE_OPEN_FAILED;
3655 case VE_SATURATION_WARNING:
3656 return ERROR_REC_DEVICE_SATURATION;
3657 case VE_REC_DEVICE_REMOVED:
3658 return ERROR_REC_DEVICE_REMOVED;
3659 case VE_RUNTIME_REC_WARNING:
3660 case VE_RUNTIME_REC_ERROR:
3661 return ERROR_REC_RUNTIME_ERROR;
3662 case VE_CANNOT_START_PLAYOUT:
3663 case VE_SPEAKER_VOL_ERROR:
3664 case VE_GET_SPEAKER_VOL_ERROR:
3665 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3666 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3667 case VE_RUNTIME_PLAY_WARNING:
3668 case VE_RUNTIME_PLAY_ERROR:
3669 return ERROR_PLAY_RUNTIME_ERROR;
3670 case VE_TYPING_NOISE_WARNING:
3671 return ERROR_REC_TYPING_NOISE_DETECTED;
3672 default:
3673 return VoiceMediaChannel::ERROR_OTHER;
3674 }
3675}
3676
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003677bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3678 int channel_id, const RtpHeaderExtension* extension) {
3679 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003680 int id = 0;
3681 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003682 if (extension) {
3683 enable = true;
3684 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003685 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003686 }
3687 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003688 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003689 return false;
3690 }
3691 return true;
3692}
3693
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003694bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
3695 webrtc::ViENetwork* vie_network = NULL;
3696 int vie_channel = -1;
3697 if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
3698 shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
3699 vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
3700 vie_channel = shared_bwe_vie_channel_;
3701 }
3702 if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
3703 vie_channel) == -1) {
3704 LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
3705 if (vie_network != NULL) {
3706 // Don't fail if we're tearing down.
3707 return false;
3708 }
3709 }
3710 return true;
3711}
3712
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003713int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003714 size_t res = 0;
3715 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003716 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003717}
3718
3719int WebRtcSoundclipStream::Rewind() {
3720 mem_.Rewind();
3721 // Return -1 to keep VoiceEngine from looping.
3722 return (loop_) ? 0 : -1;
3723}
3724
3725} // namespace cricket
3726
3727#endif // HAVE_WEBRTC_VOICE