blob: 20c2e50e14e0c39cf65acbc0db00574b234788ac [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 },
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +000075 // G722 should be advertised as 8000 Hz because of the RFC "bug".
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +000076 { "G722", 8000, 1, 9, false },
henrike@webrtc.org28e20752013-07-10 00:45:36 +000077 { "ILBC", 8000, 1, 102, false },
78 { "PCMU", 8000, 1, 0, false },
79 { "PCMA", 8000, 1, 8, false },
80 { "CN", 48000, 1, 107, false },
81 { "CN", 32000, 1, 106, false },
82 { "CN", 16000, 1, 105, false },
83 { "CN", 8000, 1, 13, false },
84 { "red", 8000, 1, 127, false },
85 { "telephone-event", 8000, 1, 126, false },
86};
87
88// For Linux/Mac, using the default device is done by specifying index 0 for
89// VoE 4.0 and not -1 (which was the case for VoE 3.5).
90//
91// On Windows Vista and newer, Microsoft introduced the concept of "Default
92// Communications Device". This means that there are two types of default
93// devices (old Wave Audio style default and Default Communications Device).
94//
95// On Windows systems which only support Wave Audio style default, uses either
96// -1 or 0 to select the default device.
97//
98// On Windows systems which support both "Default Communication Device" and
99// old Wave Audio style default, use -1 for Default Communications Device and
100// -2 for Wave Audio style default, which is what we want to use for clips.
101// It's not clear yet whether the -2 index is handled properly on other OSes.
102
103#ifdef WIN32
104static const int kDefaultAudioDeviceId = -1;
105static const int kDefaultSoundclipDeviceId = -2;
106#else
107static const int kDefaultAudioDeviceId = 0;
108#endif
109
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110static const char kIsacCodecName[] = "ISAC";
111static const char kL16CodecName[] = "L16";
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000112static const char kG722CodecName[] = "G722";
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000113
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000114// Parameter used for NACK.
115// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
116static const int kNackMaxPackets = 250;
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000117
118// Codec parameters for Opus.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000119// draft-spittka-payload-rtp-opus-03
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000120
121// Recommended bitrates:
122// 8-12 kb/s for NB speech,
123// 16-20 kb/s for WB speech,
124// 28-40 kb/s for FB speech,
125// 48-64 kb/s for FB mono music, and
126// 64-128 kb/s for FB stereo music.
127// The current implementation applies the following values to mono signals,
128// and multiplies them by 2 for stereo.
129static const int kOpusBitrateNb = 12000;
130static const int kOpusBitrateWb = 20000;
131static const int kOpusBitrateFb = 32000;
132
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000133// Opus bitrate should be in the range between 6000 and 510000.
134static const int kOpusMinBitrate = 6000;
135static const int kOpusMaxBitrate = 510000;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000136
wu@webrtc.orgde305012013-10-31 15:40:38 +0000137// Default audio dscp value.
138// See http://tools.ietf.org/html/rfc2474 for details.
139// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000140static const rtc::DiffServCodePoint kAudioDscpValue = rtc::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000141
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000142// Ensure we open the file in a writeable path on ChromeOS and Android. This
143// workaround can be removed when it's possible to specify a filename for audio
144// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000145//
146// TODO(grunell): Use a string in the options instead of hardcoding it here
147// and let the embedder choose the filename (crbug.com/264223).
148//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000149// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
150// below.
151#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000152static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000153#elif defined(ANDROID)
154static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000155#else
156static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
157#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000158
159// Dumps an AudioCodec in RFC 2327-ish format.
160static std::string ToString(const AudioCodec& codec) {
161 std::stringstream ss;
162 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
163 << " (" << codec.id << ")";
164 return ss.str();
165}
166static std::string ToString(const webrtc::CodecInst& codec) {
167 std::stringstream ss;
168 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
169 << " (" << codec.pltype << ")";
170 return ss.str();
171}
172
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000173static void LogMultiline(rtc::LoggingSeverity sev, char* text) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000174 const char* delim = "\r\n";
175 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
176 LOG_V(sev) << tok;
177 }
178}
179
180// Severity is an integer because it comes is assumed to be from command line.
181static int SeverityToFilter(int severity) {
182 int filter = webrtc::kTraceNone;
183 switch (severity) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000184 case rtc::LS_VERBOSE:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000185 filter |= webrtc::kTraceAll;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000186 case rtc::LS_INFO:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000187 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000188 case rtc::LS_WARNING:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000189 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000190 case rtc::LS_ERROR:
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000191 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
192 }
193 return filter;
194}
195
196static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
197 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
198 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
199 kCodecPrefs[i].clockrate == codec.plfreq) {
200 return kCodecPrefs[i].is_multi_rate;
201 }
202 }
203 return false;
204}
205
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000206static bool IsTelephoneEventCodec(const std::string& name) {
207 return _stricmp(name.c_str(), "telephone-event") == 0;
208}
209
210static bool IsCNCodec(const std::string& name) {
211 return _stricmp(name.c_str(), "CN") == 0;
212}
213
214static bool IsRedCodec(const std::string& name) {
215 return _stricmp(name.c_str(), "red") == 0;
216}
217
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000218static bool FindCodec(const std::vector<AudioCodec>& codecs,
219 const AudioCodec& codec,
220 AudioCodec* found_codec) {
221 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
222 it != codecs.end(); ++it) {
223 if (it->Matches(codec)) {
224 if (found_codec != NULL) {
225 *found_codec = *it;
226 }
227 return true;
228 }
229 }
230 return false;
231}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000232
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000233static bool IsNackEnabled(const AudioCodec& codec) {
234 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
235 kParamValueEmpty));
236}
237
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000238// Gets the default set of options applied to the engine. Historically, these
239// were supplied as a combination of flags from the channel manager (ec, agc,
240// ns, and highpass) and the rest hardcoded in InitInternal.
241static AudioOptions GetDefaultEngineOptions() {
242 AudioOptions options;
243 options.echo_cancellation.Set(true);
244 options.auto_gain_control.Set(true);
245 options.noise_suppression.Set(true);
246 options.highpass_filter.Set(true);
247 options.stereo_swapping.Set(false);
248 options.typing_detection.Set(true);
249 options.conference_mode.Set(false);
250 options.adjust_agc_delta.Set(0);
251 options.experimental_agc.Set(false);
252 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000253 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000254 options.aec_dump.Set(false);
255 return options;
256}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000257
258class WebRtcSoundclipMedia : public SoundclipMedia {
259 public:
260 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
261 : engine_(engine), webrtc_channel_(-1) {
262 engine_->RegisterSoundclip(this);
263 }
264
265 virtual ~WebRtcSoundclipMedia() {
266 engine_->UnregisterSoundclip(this);
267 if (webrtc_channel_ != -1) {
268 // We shouldn't have to call Disable() here. DeleteChannel() should call
269 // StopPlayout() while deleting the channel. We should fix the bug
270 // inside WebRTC and remove the Disable() call bellow. This work is
271 // tracked by bug http://b/issue?id=5382855.
272 PlaySound(NULL, 0, 0);
273 Disable();
274 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
275 == -1) {
276 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
277 }
278 }
279 }
280
281 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000282 if (!engine_->voe_sc()) {
283 return false;
284 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000285 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000286 if (webrtc_channel_ == -1) {
287 LOG_RTCERR0(CreateChannel);
288 return false;
289 }
290 return true;
291 }
292
293 bool Enable() {
294 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
295 LOG_RTCERR1(StartPlayout, webrtc_channel_);
296 return false;
297 }
298 return true;
299 }
300
301 bool Disable() {
302 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
303 LOG_RTCERR1(StopPlayout, webrtc_channel_);
304 return false;
305 }
306 return true;
307 }
308
309 virtual bool PlaySound(const char *buf, int len, int flags) {
310 // The voe file api is not available in chrome.
311 if (!engine_->voe_sc()->file()) {
312 return false;
313 }
314 // Must stop playing the current sound (if any), because we are about to
315 // modify the stream.
316 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
317 == -1) {
318 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
319 return false;
320 }
321
322 if (buf) {
323 stream_.reset(new WebRtcSoundclipStream(buf, len));
324 stream_->set_loop((flags & SF_LOOP) != 0);
325 stream_->Rewind();
326
327 // Play it.
328 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
329 webrtc_channel_, stream_.get()) == -1) {
330 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
331 LOG(LS_ERROR) << "Unable to start soundclip";
332 return false;
333 }
334 } else {
335 stream_.reset();
336 }
337 return true;
338 }
339
340 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
341
342 private:
343 WebRtcVoiceEngine *engine_;
344 int webrtc_channel_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000345 rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000346};
347
348WebRtcVoiceEngine::WebRtcVoiceEngine()
349 : voe_wrapper_(new VoEWrapper()),
350 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000351 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000352 tracing_(new VoETraceWrapper()),
353 adm_(NULL),
354 adm_sc_(NULL),
355 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
356 is_dumping_aec_(false),
357 desired_local_monitor_enable_(false),
358 tx_processor_ssrc_(0),
359 rx_processor_ssrc_(0) {
360 Construct();
361}
362
363WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
364 VoEWrapper* voe_wrapper_sc,
365 VoETraceWrapper* tracing)
366 : voe_wrapper_(voe_wrapper),
367 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000368 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000369 tracing_(tracing),
370 adm_(NULL),
371 adm_sc_(NULL),
372 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
373 is_dumping_aec_(false),
374 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000375 tx_processor_ssrc_(0),
376 rx_processor_ssrc_(0) {
377 Construct();
378}
379
380void WebRtcVoiceEngine::Construct() {
381 SetTraceFilter(log_filter_);
382 initialized_ = false;
383 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
384 SetTraceOptions("");
385 if (tracing_->SetTraceCallback(this) == -1) {
386 LOG_RTCERR0(SetTraceCallback);
387 }
388 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
389 LOG_RTCERR0(RegisterVoiceEngineObserver);
390 }
391 // Clear the default agc state.
392 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
393
394 // Load our audio codec list.
395 ConstructCodecs();
396
397 // Load our RTP Header extensions.
398 rtp_header_extensions_.push_back(
399 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
400 kRtpAudioLevelHeaderExtensionDefaultId));
401 rtp_header_extensions_.push_back(
402 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
403 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
404 options_ = GetDefaultEngineOptions();
405}
406
407static bool IsOpus(const AudioCodec& codec) {
408 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
409}
410
411static bool IsIsac(const AudioCodec& codec) {
412 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
413}
414
415// True if params["stereo"] == "1"
416static bool IsOpusStereoEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000417 int value;
418 return codec.GetParam(kCodecParamStereo, &value) && value == 1;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000419}
420
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000421// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
422// otherwise. If the value (either from params or codec.bitrate) <=0, use the
423// default configuration. If the value is beyond feasible bit rate of Opus,
424// clamp it. Returns the Opus bit rate for operation.
buildbot@webrtc.org879fac82014-10-30 07:50:13 +0000425static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000426 int bitrate = 0;
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000427 bool use_param = true;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000428 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000429 bitrate = codec.bitrate;
430 use_param = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000431 }
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000432 if (bitrate <= 0) {
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000433 if (max_playback_rate <= 8000) {
434 bitrate = kOpusBitrateNb;
435 } else if (max_playback_rate <= 16000) {
436 bitrate = kOpusBitrateWb;
437 } else {
438 bitrate = kOpusBitrateFb;
439 }
440
441 if (IsOpusStereoEnabled(codec)) {
442 bitrate *= 2;
443 }
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000444 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
445 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
446 std::string rate_source =
447 use_param ? "Codec parameter \"maxaveragebitrate\"" :
448 "Supplied Opus bitrate";
449 LOG(LS_WARNING) << rate_source
450 << " is invalid and is replaced by: "
451 << bitrate;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000452 }
453 return bitrate;
454}
455
buildbot@webrtc.orgfbd13282014-06-19 19:50:55 +0000456// Return true if params[kCodecParamUseInbandFec] == "1", false
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000457// otherwise.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000458static bool IsOpusFecEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000459 int value;
460 return codec.GetParam(kCodecParamUseInbandFec, &value) && value == 1;
461}
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000462
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000463// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
464// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
465static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
466 int value;
467 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
468 return value;
469 }
470 return kOpusDefaultMaxPlaybackRate;
471}
472
473static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
474 bool* enable_codec_fec, int* max_playback_rate) {
475 *enable_codec_fec = IsOpusFecEnabled(codec);
476 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
477
478 // If OPUS, change what we send according to the "stereo" codec
479 // parameter, and not the "channels" parameter. We set
480 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000481 // the bitrate is not specified, i.e. is <= zero, we set it to the
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000482 // appropriate default value for mono or stereo Opus.
483
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000484 voe_codec->channels = IsOpusStereoEnabled(codec) ? 2 : 1;
buildbot@webrtc.org879fac82014-10-30 07:50:13 +0000485 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000486}
487
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000488// Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
489// which says that G722 should be advertised as 8 kHz although it is a 16 kHz
490// codec.
491static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
492 if (_stricmp(voe_codec->plname, kG722CodecName) == 0) {
493 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
494 // has changed, and this special case is no longer needed.
495 ASSERT(voe_codec->plfreq != new_plfreq);
496 voe_codec->plfreq = new_plfreq;
497 }
498}
499
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000500void WebRtcVoiceEngine::ConstructCodecs() {
501 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
502 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
503 for (int i = 0; i < ncodecs; ++i) {
504 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000505 if (GetVoeCodec(i, &voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000506 // Skip uncompressed formats.
507 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
508 continue;
509 }
510
511 const CodecPref* pref = NULL;
512 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
513 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
514 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
515 kCodecPrefs[j].channels == voe_codec.channels) {
516 pref = &kCodecPrefs[j];
517 break;
518 }
519 }
520
521 if (pref) {
522 // Use the payload type that we've configured in our pref table;
523 // use the offset in our pref table to determine the sort order.
524 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
525 voe_codec.rate, voe_codec.channels,
526 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
527 LOG(LS_INFO) << ToString(codec);
528 if (IsIsac(codec)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000529 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000530 codec.bitrate = 0;
531 }
532 if (IsOpus(codec)) {
533 // Only add fmtp parameters that differ from the spec.
534 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
535 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000536 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000537 }
538 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
539 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000540 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000541 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000542 codec.SetParam(kCodecParamUseInbandFec, 1);
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000543
544 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000545 // when they can be set to values other than the default.
546 }
547 codecs_.push_back(codec);
548 } else {
549 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
550 }
551 }
552 }
553 // Make sure they are in local preference order.
554 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
555}
556
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000557bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst* codec) {
558 if (voe_wrapper_->codec()->GetCodec(index, *codec) == -1) {
559 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000560 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000561 // Change the sample rate of G722 to 8000 to match SDP.
562 MaybeFixupG722(codec, 8000);
563 return true;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000564}
565
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000566WebRtcVoiceEngine::~WebRtcVoiceEngine() {
567 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
568 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
569 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
570 }
571 if (adm_) {
572 voe_wrapper_.reset();
573 adm_->Release();
574 adm_ = NULL;
575 }
576 if (adm_sc_) {
577 voe_wrapper_sc_.reset();
578 adm_sc_->Release();
579 adm_sc_ = NULL;
580 }
581
582 // Test to see if the media processor was deregistered properly
583 ASSERT(SignalRxMediaFrame.is_empty());
584 ASSERT(SignalTxMediaFrame.is_empty());
585
586 tracing_->SetTraceCallback(NULL);
587}
588
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000589bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
henrika@webrtc.org62f6e752015-02-11 08:38:35 +0000590 ASSERT(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000591 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
592 bool res = InitInternal();
593 if (res) {
594 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
595 } else {
596 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
597 Terminate();
598 }
599 return res;
600}
601
602bool WebRtcVoiceEngine::InitInternal() {
603 // Temporarily turn logging level up for the Init call
604 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000605 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000606 SetTraceFilter(extended_filter);
607 SetTraceOptions("");
608
609 // Init WebRtc VoiceEngine.
610 if (voe_wrapper_->base()->Init(adm_) == -1) {
611 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
612 SetTraceFilter(old_filter);
613 return false;
614 }
615
616 SetTraceFilter(old_filter);
617 SetTraceOptions(log_options_);
618
619 // Log the VoiceEngine version info
620 char buffer[1024] = "";
621 voe_wrapper_->base()->GetVersion(buffer);
622 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000623 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000624
625 // Save the default AGC configuration settings. This must happen before
626 // calling SetOptions or the default will be overwritten.
627 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
628 LOG_RTCERR0(GetAgcConfig);
629 return false;
630 }
631
632 // Set defaults for options, so that ApplyOptions applies them explicitly
633 // when we clear option (channel) overrides. External clients can still
634 // modify the defaults via SetOptions (on the media engine).
635 if (!SetOptions(GetDefaultEngineOptions())) {
636 return false;
637 }
638
639 // Print our codec list again for the call diagnostic log
640 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
641 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
642 it != codecs_.end(); ++it) {
643 LOG(LS_INFO) << ToString(*it);
644 }
645
646 // Disable the DTMF playout when a tone is sent.
647 // PlayDtmfTone will be used if local playout is needed.
648 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
649 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
650 }
651
652 initialized_ = true;
653 return true;
654}
655
656bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
657 if (voe_wrapper_sc_initialized_) {
658 return true;
659 }
660 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
661 // be false, so subsequent calls to EnsureSoundclipEngineInit will
662 // probably just fail again. That's acceptable behavior.
663#if defined(LINUX) && !defined(HAVE_LIBPULSE)
664 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
665#endif
666
667 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
668 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
669 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
670 return false;
671 }
672
673 // On Windows, tell it to use the default sound (not communication) devices.
674 // First check whether there is a valid sound device for playback.
675 // TODO(juberti): Clean this up when we support setting the soundclip device.
676#ifdef WIN32
677 // The SetPlayoutDevice may not be implemented in the case of external ADM.
678 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
679 // PeerConnection interface never set the adm_sc_, so need to check both
680 // in order to determine if the external adm is used.
681 if (!adm_ && !adm_sc_) {
682 int num_of_devices = 0;
683 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
684 num_of_devices > 0) {
685 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
686 == -1) {
687 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
688 voe_wrapper_sc_->error());
689 return false;
690 }
691 } else {
692 LOG(LS_WARNING) << "No valid sound playout device found.";
693 }
694 }
695#endif
696 voe_wrapper_sc_initialized_ = true;
697 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
698 return true;
699}
700
701void WebRtcVoiceEngine::Terminate() {
702 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
703 initialized_ = false;
704
705 StopAecDump();
706
707 if (voe_wrapper_sc_) {
708 voe_wrapper_sc_initialized_ = false;
709 voe_wrapper_sc_->base()->Terminate();
710 }
711 voe_wrapper_->base()->Terminate();
712 desired_local_monitor_enable_ = false;
713}
714
715int WebRtcVoiceEngine::GetCapabilities() {
716 return AUDIO_SEND | AUDIO_RECV;
717}
718
719VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
720 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
721 if (!ch->valid()) {
722 delete ch;
723 ch = NULL;
724 }
725 return ch;
726}
727
728SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
729 if (!EnsureSoundclipEngineInit()) {
730 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
731 << "initialize.";
732 return NULL;
733 }
734 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
735 if (!soundclip->Init() || !soundclip->Enable()) {
736 delete soundclip;
737 return NULL;
738 }
739 return soundclip;
740}
741
742bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
743 if (!ApplyOptions(options)) {
744 return false;
745 }
746 options_ = options;
747 return true;
748}
749
750bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
751 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
752 if (!ApplyOptions(overrides)) {
753 return false;
754 }
755 option_overrides_ = overrides;
756 return true;
757}
758
759bool WebRtcVoiceEngine::ClearOptionOverrides() {
760 LOG(LS_INFO) << "Clearing option overrides.";
761 AudioOptions options = options_;
762 // Only call ApplyOptions if |options_overrides_| contains overrided options.
763 // ApplyOptions affects NS, AGC other options that is shared between
764 // all WebRtcVoiceEngineChannels.
765 if (option_overrides_ == AudioOptions()) {
766 return true;
767 }
768
769 if (!ApplyOptions(options)) {
770 return false;
771 }
772 option_overrides_ = AudioOptions();
773 return true;
774}
775
776// AudioOptions defaults are set in InitInternal (for options with corresponding
777// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
778bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
779 AudioOptions options = options_in; // The options are modified below.
780 // kEcConference is AEC with high suppression.
781 webrtc::EcModes ec_mode = webrtc::kEcConference;
782 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
783 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
784 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
785 bool aecm_comfort_noise = false;
786 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
787 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
788 << aecm_comfort_noise << " (default is false).";
789 }
790
791#if defined(IOS)
792 // On iOS, VPIO provides built-in EC and AGC.
793 options.echo_cancellation.Set(false);
794 options.auto_gain_control.Set(false);
795#elif defined(ANDROID)
796 ec_mode = webrtc::kEcAecm;
797#endif
798
799#if defined(IOS) || defined(ANDROID)
800 // Set the AGC mode for iOS as well despite disabling it above, to avoid
801 // unsupported configuration errors from webrtc.
802 agc_mode = webrtc::kAgcFixedDigital;
803 options.typing_detection.Set(false);
804 options.experimental_agc.Set(false);
805 options.experimental_aec.Set(false);
806 options.experimental_ns.Set(false);
807#endif
808
809 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
810
811 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
812
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000813 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000814 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000815 // Check if platform supports built-in EC. Currently only supported on
816 // Android and in combination with Java based audio layer.
817 // TODO(henrika): investigate possibility to support built-in EC also
818 // in combination with Open SL ES audio.
819 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
820 if (built_in_aec) {
821 // Set mode of built-in EC according to the audio options.
822 voe_wrapper_->hw()->EnableBuiltInAEC(echo_cancellation);
823 if (echo_cancellation) {
824 // Disable internal software EC if device has its own built-in EC,
825 // i.e., replace the software EC with the built-in EC.
826 options.echo_cancellation.Set(false);
827 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
828 }
829 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000830 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
831 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
832 return false;
833 } else {
834 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
835 << " with mode " << ec_mode;
836 }
837#if !defined(ANDROID)
838 // TODO(ajm): Remove the error return on Android from webrtc.
839 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
840 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
841 return false;
842 }
843#endif
844 if (ec_mode == webrtc::kEcAecm) {
845 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
846 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
847 return false;
848 }
849 }
850 }
851
852 bool auto_gain_control;
853 if (options.auto_gain_control.Get(&auto_gain_control)) {
854 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
855 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
856 return false;
857 } else {
858 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
859 << " with mode " << agc_mode;
860 }
861 }
862
863 if (options.tx_agc_target_dbov.IsSet() ||
864 options.tx_agc_digital_compression_gain.IsSet() ||
865 options.tx_agc_limiter.IsSet()) {
866 // Override default_agc_config_. Generally, an unset option means "leave
867 // the VoE bits alone" in this function, so we want whatever is set to be
868 // stored as the new "default". If we didn't, then setting e.g.
869 // tx_agc_target_dbov would reset digital compression gain and limiter
870 // settings.
871 // Also, if we don't update default_agc_config_, then adjust_agc_delta
872 // would be an offset from the original values, and not whatever was set
873 // explicitly.
874 default_agc_config_.targetLeveldBOv =
875 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
876 default_agc_config_.targetLeveldBOv);
877 default_agc_config_.digitalCompressionGaindB =
878 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
879 default_agc_config_.digitalCompressionGaindB);
880 default_agc_config_.limiterEnable =
881 options.tx_agc_limiter.GetWithDefaultIfUnset(
882 default_agc_config_.limiterEnable);
883 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
884 LOG_RTCERR3(SetAgcConfig,
885 default_agc_config_.targetLeveldBOv,
886 default_agc_config_.digitalCompressionGaindB,
887 default_agc_config_.limiterEnable);
888 return false;
889 }
890 }
891
892 bool noise_suppression;
893 if (options.noise_suppression.Get(&noise_suppression)) {
894 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
895 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
896 return false;
897 } else {
898 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
899 << " with mode " << ns_mode;
900 }
901 }
902
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000903 bool highpass_filter;
904 if (options.highpass_filter.Get(&highpass_filter)) {
905 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
906 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
907 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
908 return false;
909 }
910 }
911
912 bool stereo_swapping;
913 if (options.stereo_swapping.Get(&stereo_swapping)) {
914 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
915 voep->EnableStereoChannelSwapping(stereo_swapping);
916 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
917 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
918 return false;
919 }
920 }
921
922 bool typing_detection;
923 if (options.typing_detection.Get(&typing_detection)) {
924 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
925 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
926 // In case of error, log the info and continue
927 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
928 }
929 }
930
931 int adjust_agc_delta;
932 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
933 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
934 if (!AdjustAgcLevel(adjust_agc_delta)) {
935 return false;
936 }
937 }
938
939 bool aec_dump;
940 if (options.aec_dump.Get(&aec_dump)) {
941 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
942 if (aec_dump)
943 StartAecDump(kAecDumpByAudioOptionFilename);
944 else
945 StopAecDump();
946 }
947
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000948 webrtc::Config config;
949
950 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000951 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000952 if (experimental_aec_.Get(&experimental_aec)) {
953 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
954 config.Set<webrtc::DelayCorrection>(
955 new webrtc::DelayCorrection(experimental_aec));
956 }
957
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000958 experimental_ns_.SetFrom(options.experimental_ns);
959 bool experimental_ns;
960 if (experimental_ns_.Get(&experimental_ns)) {
961 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
962 config.Set<webrtc::ExperimentalNs>(
963 new webrtc::ExperimentalNs(experimental_ns));
964 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000965
966 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
967 // returns NULL on audio_processing().
968 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
969 if (audioproc) {
970 audioproc->SetExtraOptions(config);
971 }
972
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000973 uint32 recording_sample_rate;
974 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
975 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
976 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
977 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
978 }
979 }
980
981 uint32 playout_sample_rate;
982 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
983 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
984 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
985 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
986 }
987 }
988
989 return true;
990}
991
992bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
993 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
994 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
995 LOG_RTCERR1(SetDelayOffsetMs, offset);
996 return false;
997 }
998
999 return true;
1000}
1001
1002struct ResumeEntry {
1003 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
1004 : channel(c),
1005 playout(p),
1006 send(s) {
1007 }
1008
1009 WebRtcVoiceMediaChannel *channel;
1010 bool playout;
1011 SendFlags send;
1012};
1013
1014// TODO(juberti): Refactor this so that the core logic can be used to set the
1015// soundclip device. At that time, reinstate the soundclip pause/resume code.
1016bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
1017 const Device* out_device) {
1018#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001019 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001020 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001021 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001022 kDefaultAudioDeviceId;
1023 // The device manager uses -1 as the default device, which was the case for
1024 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
1025#ifndef WIN32
1026 if (-1 == in_id) {
1027 in_id = kDefaultAudioDeviceId;
1028 }
1029 if (-1 == out_id) {
1030 out_id = kDefaultAudioDeviceId;
1031 }
1032#endif
1033
1034 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
1035 in_device->name : "Default device";
1036 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
1037 out_device->name : "Default device";
1038 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
1039 << ") and speaker to (id=" << out_id << ", name=" << out_name
1040 << ")";
1041
1042 // If we're running the local monitor, we need to stop it first.
1043 bool ret = true;
1044 if (!PauseLocalMonitor()) {
1045 LOG(LS_WARNING) << "Failed to pause local monitor";
1046 ret = false;
1047 }
1048
1049 // Must also pause all audio playback and capture.
1050 for (ChannelList::const_iterator i = channels_.begin();
1051 i != channels_.end(); ++i) {
1052 WebRtcVoiceMediaChannel *channel = *i;
1053 if (!channel->PausePlayout()) {
1054 LOG(LS_WARNING) << "Failed to pause playout";
1055 ret = false;
1056 }
1057 if (!channel->PauseSend()) {
1058 LOG(LS_WARNING) << "Failed to pause send";
1059 ret = false;
1060 }
1061 }
1062
1063 // Find the recording device id in VoiceEngine and set recording device.
1064 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1065 ret = false;
1066 }
1067 if (ret) {
1068 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
1069 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
1070 ret = false;
1071 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00001072 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
1073 if (ap)
1074 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001075 }
1076
1077 // Find the playout device id in VoiceEngine and set playout device.
1078 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1079 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1080 ret = false;
1081 }
1082 if (ret) {
1083 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001084 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001085 ret = false;
1086 }
1087 }
1088
1089 // Resume all audio playback and capture.
1090 for (ChannelList::const_iterator i = channels_.begin();
1091 i != channels_.end(); ++i) {
1092 WebRtcVoiceMediaChannel *channel = *i;
1093 if (!channel->ResumePlayout()) {
1094 LOG(LS_WARNING) << "Failed to resume playout";
1095 ret = false;
1096 }
1097 if (!channel->ResumeSend()) {
1098 LOG(LS_WARNING) << "Failed to resume send";
1099 ret = false;
1100 }
1101 }
1102
1103 // Resume local monitor.
1104 if (!ResumeLocalMonitor()) {
1105 LOG(LS_WARNING) << "Failed to resume local monitor";
1106 ret = false;
1107 }
1108
1109 if (ret) {
1110 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1111 << ") and speaker to (id="<< out_id << " name=" << out_name
1112 << ")";
1113 }
1114
1115 return ret;
1116#else
1117 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001118#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001119}
1120
1121bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1122 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1123 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001124#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001125 *rtc_id = dev_id;
1126 return true;
1127#else
1128 // In Windows and Mac, we need to find the VoiceEngine device id by name
1129 // unless the input dev_id is the default device id.
1130 if (kDefaultAudioDeviceId == dev_id) {
1131 *rtc_id = dev_id;
1132 return true;
1133 }
1134
1135 // Get the number of VoiceEngine audio devices.
1136 int count = 0;
1137 if (is_input) {
1138 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1139 LOG_RTCERR0(GetNumOfRecordingDevices);
1140 return false;
1141 }
1142 } else {
1143 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1144 LOG_RTCERR0(GetNumOfPlayoutDevices);
1145 return false;
1146 }
1147 }
1148
1149 for (int i = 0; i < count; ++i) {
1150 char name[128];
1151 char guid[128];
1152 if (is_input) {
1153 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1154 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1155 } else {
1156 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1157 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1158 }
1159
1160 std::string webrtc_name(name);
1161 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1162 *rtc_id = i;
1163 return true;
1164 }
1165 }
1166 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1167 return false;
1168#endif
1169}
1170
1171bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1172 unsigned int ulevel;
1173 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1174 LOG_RTCERR1(GetSpeakerVolume, level);
1175 return false;
1176 }
1177 *level = ulevel;
1178 return true;
1179}
1180
1181bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1182 ASSERT(level >= 0 && level <= 255);
1183 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1184 LOG_RTCERR1(SetSpeakerVolume, level);
1185 return false;
1186 }
1187 return true;
1188}
1189
1190int WebRtcVoiceEngine::GetInputLevel() {
1191 unsigned int ulevel;
1192 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1193 static_cast<int>(ulevel) : -1;
1194}
1195
1196bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1197 desired_local_monitor_enable_ = enable;
1198 return ChangeLocalMonitor(desired_local_monitor_enable_);
1199}
1200
1201bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1202 // The voe file api is not available in chrome.
1203 if (!voe_wrapper_->file()) {
1204 return false;
1205 }
1206 if (enable && !monitor_) {
1207 monitor_.reset(new WebRtcMonitorStream);
1208 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1209 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1210 // Must call Stop() because there are some cases where Start will report
1211 // failure but still change the state, and if we leave VE in the on state
1212 // then it could crash later when trying to invoke methods on our monitor.
1213 voe_wrapper_->file()->StopRecordingMicrophone();
1214 monitor_.reset();
1215 return false;
1216 }
1217 } else if (!enable && monitor_) {
1218 voe_wrapper_->file()->StopRecordingMicrophone();
1219 monitor_.reset();
1220 }
1221 return true;
1222}
1223
1224bool WebRtcVoiceEngine::PauseLocalMonitor() {
1225 return ChangeLocalMonitor(false);
1226}
1227
1228bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1229 return ChangeLocalMonitor(desired_local_monitor_enable_);
1230}
1231
1232const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1233 return codecs_;
1234}
1235
1236bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1237 return FindWebRtcCodec(in, NULL);
1238}
1239
1240// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1241bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1242 webrtc::CodecInst* out) {
1243 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1244 for (int i = 0; i < ncodecs; ++i) {
1245 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001246 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001247 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1248 voe_codec.rate, voe_codec.channels, 0);
1249 bool multi_rate = IsCodecMultiRate(voe_codec);
1250 // Allow arbitrary rates for ISAC to be specified.
1251 if (multi_rate) {
1252 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1253 codec.bitrate = 0;
1254 }
1255 if (codec.Matches(in)) {
1256 if (out) {
1257 // Fixup the payload type.
1258 voe_codec.pltype = in.id;
1259
1260 // Set bitrate if specified.
1261 if (multi_rate && in.bitrate != 0) {
1262 voe_codec.rate = in.bitrate;
1263 }
1264
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001265 // Reset G722 sample rate to 16000 to match WebRTC.
1266 MaybeFixupG722(&voe_codec, 16000);
1267
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001268 // Apply codec-specific settings.
1269 if (IsIsac(codec)) {
1270 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001271 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001272 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1273 }
1274 *out = voe_codec;
1275 }
1276 return true;
1277 }
1278 }
1279 }
1280 return false;
1281}
1282const std::vector<RtpHeaderExtension>&
1283WebRtcVoiceEngine::rtp_header_extensions() const {
1284 return rtp_header_extensions_;
1285}
1286
1287void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1288 // if min_sev == -1, we keep the current log level.
1289 if (min_sev >= 0) {
1290 SetTraceFilter(SeverityToFilter(min_sev));
1291 }
1292 log_options_ = filter;
1293 SetTraceOptions(initialized_ ? log_options_ : "");
1294}
1295
1296int WebRtcVoiceEngine::GetLastEngineError() {
1297 return voe_wrapper_->error();
1298}
1299
1300void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1301 log_filter_ = filter;
1302 tracing_->SetTraceFilter(filter);
1303}
1304
1305// We suppport three different logging settings for VoiceEngine:
1306// 1. Observer callback that goes into talk diagnostic logfile.
1307// Use --logfile and --loglevel
1308//
1309// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1310// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1311//
1312// 3. EC log and dump for debugging QualityEngine.
1313// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1314//
1315// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1316// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1317void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1318 // Set encrypted trace file.
1319 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001320 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001321 std::vector<std::string>::iterator tracefile =
1322 std::find(opts.begin(), opts.end(), "tracefile");
1323 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1324 // Write encrypted debug output (at same loglevel) to file
1325 // EncryptedTraceFile no longer supported.
1326 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1327 LOG_RTCERR1(SetTraceFile, *tracefile);
1328 }
1329 }
1330
wu@webrtc.org97077a32013-10-25 21:18:33 +00001331 // Allow trace options to override the trace filter. We default
1332 // it to log_filter_ (as a translation of libjingle log levels)
1333 // elsewhere, but this allows clients to explicitly set webrtc
1334 // log levels.
1335 std::vector<std::string>::iterator tracefilter =
1336 std::find(opts.begin(), opts.end(), "tracefilter");
1337 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001338 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001339 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1340 }
1341 }
1342
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001343 // Set AEC dump file
1344 std::vector<std::string>::iterator recordEC =
1345 std::find(opts.begin(), opts.end(), "recordEC");
1346 if (recordEC != opts.end()) {
1347 ++recordEC;
1348 if (recordEC != opts.end())
1349 StartAecDump(recordEC->c_str());
1350 else
1351 StopAecDump();
1352 }
1353}
1354
1355// Ignore spammy trace messages, mostly from the stats API when we haven't
1356// gotten RTCP info yet from the remote side.
1357bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1358 static const char* kTracesToIgnore[] = {
1359 "\tfailed to GetReportBlockInformation",
1360 "GetRecCodec() failed to get received codec",
1361 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1362 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1363 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1364 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1365 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1366 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1367 "SenderInfoReceived No received SR",
1368 "StatisticsRTP() no statistics available",
1369 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1370 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1371 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1372 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1373 NULL
1374 };
1375 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1376 if (trace.find(*p) != std::string::npos) {
1377 return true;
1378 }
1379 }
1380 return false;
1381}
1382
1383void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1384 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001385 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001386 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001387 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001388 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001389 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001390 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001391 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001393 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001394
1395 // Skip past boilerplate prefix text
1396 if (length < 72) {
1397 std::string msg(trace, length);
1398 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1399 LOG_V(sev) << msg;
1400 } else {
1401 std::string msg(trace + 71, length - 72);
1402 if (!ShouldIgnoreTrace(msg)) {
1403 LOG_V(sev) << "webrtc: " << msg;
1404 }
1405 }
1406}
1407
1408void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001409 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001410 WebRtcVoiceMediaChannel* channel = NULL;
1411 uint32 ssrc = 0;
1412 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1413 << channel_num << ".";
1414 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1415 ASSERT(channel != NULL);
1416 channel->OnError(ssrc, err_code);
1417 } else {
1418 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1419 << " could not be found in channel list when error reported.";
1420 }
1421}
1422
1423bool WebRtcVoiceEngine::FindChannelAndSsrc(
1424 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1425 ASSERT(channel != NULL && ssrc != NULL);
1426
1427 *channel = NULL;
1428 *ssrc = 0;
1429 // Find corresponding channel and ssrc
1430 for (ChannelList::const_iterator it = channels_.begin();
1431 it != channels_.end(); ++it) {
1432 ASSERT(*it != NULL);
1433 if ((*it)->FindSsrc(channel_num, ssrc)) {
1434 *channel = *it;
1435 return true;
1436 }
1437 }
1438
1439 return false;
1440}
1441
1442// This method will search through the WebRtcVoiceMediaChannels and
1443// obtain the voice engine's channel number.
1444bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1445 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1446 ASSERT(channel_num != NULL);
1447 ASSERT(direction == MPD_RX || direction == MPD_TX);
1448
1449 *channel_num = -1;
1450 // Find corresponding channel for ssrc.
1451 for (ChannelList::const_iterator it = channels_.begin();
1452 it != channels_.end(); ++it) {
1453 ASSERT(*it != NULL);
1454 if (direction & MPD_RX) {
1455 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1456 }
1457 if (*channel_num == -1 && (direction & MPD_TX)) {
1458 *channel_num = (*it)->GetSendChannelNum(ssrc);
1459 }
1460 if (*channel_num != -1) {
1461 return true;
1462 }
1463 }
1464 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1465 return false;
1466}
1467
1468void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001469 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001470 channels_.push_back(channel);
1471}
1472
1473void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001474 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001475 ChannelList::iterator i = std::find(channels_.begin(),
1476 channels_.end(),
1477 channel);
1478 if (i != channels_.end()) {
1479 channels_.erase(i);
1480 }
1481}
1482
1483void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1484 soundclips_.push_back(soundclip);
1485}
1486
1487void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1488 SoundclipList::iterator i = std::find(soundclips_.begin(),
1489 soundclips_.end(),
1490 soundclip);
1491 if (i != soundclips_.end()) {
1492 soundclips_.erase(i);
1493 }
1494}
1495
1496// Adjusts the default AGC target level by the specified delta.
1497// NB: If we start messing with other config fields, we'll want
1498// to save the current webrtc::AgcConfig as well.
1499bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1500 webrtc::AgcConfig config = default_agc_config_;
1501 config.targetLeveldBOv -= delta;
1502
1503 LOG(LS_INFO) << "Adjusting AGC level from default -"
1504 << default_agc_config_.targetLeveldBOv << "dB to -"
1505 << config.targetLeveldBOv << "dB";
1506
1507 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1508 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1509 return false;
1510 }
1511 return true;
1512}
1513
1514bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1515 webrtc::AudioDeviceModule* adm_sc) {
1516 if (initialized_) {
1517 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1518 return false;
1519 }
1520 if (adm_) {
1521 adm_->Release();
1522 adm_ = NULL;
1523 }
1524 if (adm) {
1525 adm_ = adm;
1526 adm_->AddRef();
1527 }
1528
1529 if (adm_sc_) {
1530 adm_sc_->Release();
1531 adm_sc_ = NULL;
1532 }
1533 if (adm_sc) {
1534 adm_sc_ = adm_sc;
1535 adm_sc_->AddRef();
1536 }
1537 return true;
1538}
1539
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001540bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1541 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001542 if (!aec_dump_file_stream) {
1543 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001544 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001545 LOG(LS_WARNING) << "Could not close file.";
1546 return false;
1547 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001548 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001549 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001550 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001551 LOG_RTCERR0(StartDebugRecording);
1552 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001553 return false;
1554 }
1555 is_dumping_aec_ = true;
1556 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001557}
1558
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001559bool WebRtcVoiceEngine::RegisterProcessor(
1560 uint32 ssrc,
1561 VoiceProcessor* voice_processor,
1562 MediaProcessorDirection direction) {
1563 bool register_with_webrtc = false;
1564 int channel_id = -1;
1565 bool success = false;
1566 uint32* processor_ssrc = NULL;
1567 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1568 if (voice_processor == NULL || !found_channel) {
1569 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1570 << " foundChannel: " << found_channel;
1571 return false;
1572 }
1573
1574 webrtc::ProcessingTypes processing_type;
1575 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001576 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001577 if (direction == MPD_RX) {
1578 processing_type = webrtc::kPlaybackAllChannelsMixed;
1579 if (SignalRxMediaFrame.is_empty()) {
1580 register_with_webrtc = true;
1581 processor_ssrc = &rx_processor_ssrc_;
1582 }
1583 SignalRxMediaFrame.connect(voice_processor,
1584 &VoiceProcessor::OnFrame);
1585 } else {
1586 processing_type = webrtc::kRecordingPerChannel;
1587 if (SignalTxMediaFrame.is_empty()) {
1588 register_with_webrtc = true;
1589 processor_ssrc = &tx_processor_ssrc_;
1590 }
1591 SignalTxMediaFrame.connect(voice_processor,
1592 &VoiceProcessor::OnFrame);
1593 }
1594 }
1595 if (register_with_webrtc) {
1596 // TODO(janahan): when registering consider instantiating a
1597 // a VoeMediaProcess object and not make the engine extend the interface.
1598 if (voe()->media() && voe()->media()->
1599 RegisterExternalMediaProcessing(channel_id,
1600 processing_type,
1601 *this) != -1) {
1602 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1603 << channel_id;
1604 *processor_ssrc = ssrc;
1605 success = true;
1606 } else {
1607 LOG_RTCERR2(RegisterExternalMediaProcessing,
1608 channel_id,
1609 processing_type);
1610 success = false;
1611 }
1612 } else {
1613 // If we don't have to register with the engine, we just needed to
1614 // connect a new processor, set success to true;
1615 success = true;
1616 }
1617 return success;
1618}
1619
1620bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1621 MediaProcessorDirection channel_direction,
1622 uint32 ssrc,
1623 VoiceProcessor* voice_processor,
1624 MediaProcessorDirection processor_direction) {
1625 bool success = true;
1626 FrameSignal* signal;
1627 webrtc::ProcessingTypes processing_type;
1628 uint32* processor_ssrc = NULL;
1629 if (channel_direction == MPD_RX) {
1630 signal = &SignalRxMediaFrame;
1631 processing_type = webrtc::kPlaybackAllChannelsMixed;
1632 processor_ssrc = &rx_processor_ssrc_;
1633 } else {
1634 signal = &SignalTxMediaFrame;
1635 processing_type = webrtc::kRecordingPerChannel;
1636 processor_ssrc = &tx_processor_ssrc_;
1637 }
1638
1639 int deregister_id = -1;
1640 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001641 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001642 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1643 signal->disconnect(voice_processor);
1644 int channel_id = -1;
1645 bool found_channel = FindChannelNumFromSsrc(ssrc,
1646 channel_direction,
1647 &channel_id);
1648 if (signal->is_empty() && found_channel) {
1649 deregister_id = channel_id;
1650 }
1651 }
1652 }
1653 if (deregister_id != -1) {
1654 if (voe()->media() &&
1655 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1656 processing_type) != -1) {
1657 *processor_ssrc = 0;
1658 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1659 << deregister_id;
1660 } else {
1661 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1662 deregister_id,
1663 processing_type);
1664 success = false;
1665 }
1666 }
1667 return success;
1668}
1669
1670bool WebRtcVoiceEngine::UnregisterProcessor(
1671 uint32 ssrc,
1672 VoiceProcessor* voice_processor,
1673 MediaProcessorDirection direction) {
1674 bool success = true;
1675 if (voice_processor == NULL) {
1676 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1677 << ssrc;
1678 return false;
1679 }
1680 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1681 success = false;
1682 }
1683 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1684 success = false;
1685 }
1686 return success;
1687}
1688
1689// Implementing method from WebRtc VoEMediaProcess interface
1690// Do not lock mux_channel_cs_ in this callback.
1691void WebRtcVoiceEngine::Process(int channel,
1692 webrtc::ProcessingTypes type,
1693 int16_t audio10ms[],
1694 int length,
1695 int sampling_freq,
1696 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001697 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001698 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1699 if (type == webrtc::kPlaybackAllChannelsMixed) {
1700 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1701 } else if (type == webrtc::kRecordingPerChannel) {
1702 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1703 } else {
1704 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1705 << " channel: " << channel << " type: " << type
1706 << " tx_ssrc: " << tx_processor_ssrc_
1707 << " rx_ssrc: " << rx_processor_ssrc_;
1708 }
1709}
1710
1711void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1712 if (!is_dumping_aec_) {
1713 // Start dumping AEC when we are not dumping.
1714 if (voe_wrapper_->processing()->StartDebugRecording(
1715 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001716 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001717 } else {
1718 is_dumping_aec_ = true;
1719 }
1720 }
1721}
1722
1723void WebRtcVoiceEngine::StopAecDump() {
1724 if (is_dumping_aec_) {
1725 // Stop dumping AEC when we are dumping.
1726 if (voe_wrapper_->processing()->StopDebugRecording() !=
1727 webrtc::AudioProcessing::kNoError) {
1728 LOG_RTCERR0(StopDebugRecording);
1729 }
1730 is_dumping_aec_ = false;
1731 }
1732}
1733
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001734int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001735 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001736}
1737
1738int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1739 return CreateVoiceChannel(voe_wrapper_.get());
1740}
1741
1742int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1743 return CreateVoiceChannel(voe_wrapper_sc_.get());
1744}
1745
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001746class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1747 : public AudioRenderer::Sink {
1748 public:
1749 WebRtcVoiceChannelRenderer(int ch,
1750 webrtc::AudioTransport* voe_audio_transport)
1751 : channel_(ch),
1752 voe_audio_transport_(voe_audio_transport),
1753 renderer_(NULL) {
1754 }
1755 virtual ~WebRtcVoiceChannelRenderer() {
1756 Stop();
1757 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001758
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001759 // Starts the rendering by setting a sink to the renderer to get data
1760 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001761 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001762 // TODO(xians): Make sure Start() is called only once.
1763 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001764 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001765 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001766 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001767 ASSERT(renderer_ == renderer);
1768 return;
1769 }
1770
1771 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1772 // in getUserMedia by default.
1773 renderer->AddChannel(channel_);
1774 renderer->SetSink(this);
1775 renderer_ = renderer;
1776 }
1777
1778 // Stops rendering by setting the sink of the renderer to NULL. No data
1779 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001780 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001781 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001782 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001783 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001784 return;
1785
1786 renderer_->RemoveChannel(channel_);
1787 renderer_->SetSink(NULL);
1788 renderer_ = NULL;
1789 }
1790
1791 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001792 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001793 void OnData(const void* audio_data,
1794 int bits_per_sample,
1795 int sample_rate,
1796 int number_of_channels,
1797 int number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001798 voe_audio_transport_->OnData(channel_,
1799 audio_data,
1800 bits_per_sample,
1801 sample_rate,
1802 number_of_channels,
1803 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001804 }
1805
1806 // Callback from the |renderer_| when it is going away. In case Start() has
1807 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001808 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001809 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001810 // Set |renderer_| to NULL to make sure no more callback will get into
1811 // the renderer.
1812 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001813 }
1814
1815 // Accessor to the VoE channel ID.
1816 int channel() const { return channel_; }
1817
1818 private:
1819 const int channel_;
1820 webrtc::AudioTransport* const voe_audio_transport_;
1821
1822 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1823 // PeerConnection will make sure invalidating the pointer before the object
1824 // goes away.
1825 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001826
1827 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001828 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001829};
1830
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001831// WebRtcVoiceMediaChannel
1832WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1833 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1834 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001835 engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001836 send_bitrate_setting_(false),
1837 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001838 options_(),
1839 dtmf_allowed_(false),
1840 desired_playout_(false),
1841 nack_enabled_(false),
1842 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001843 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001844 desired_send_(SEND_NOTHING),
1845 send_(SEND_NOTHING),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001846 shared_bwe_vie_(NULL),
1847 shared_bwe_vie_channel_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001848 default_receive_ssrc_(0) {
1849 engine->RegisterChannel(this);
1850 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1851 << voe_channel();
1852
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001853 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001854}
1855
1856WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1857 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1858 << voe_channel();
buildbot@webrtc.org6e5c7842014-09-19 06:46:37 +00001859 SetupSharedBandwidthEstimation(NULL, -1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001860
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001861 // Remove any remaining send streams, the default channel will be deleted
1862 // later.
1863 while (!send_channels_.empty())
1864 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001865
1866 // Unregister ourselves from the engine.
1867 engine()->UnregisterChannel(this);
1868 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001869 while (!receive_channels_.empty()) {
1870 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001871 }
1872
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001873 // Delete the default channel.
1874 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001875}
1876
1877bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1878 LOG(LS_INFO) << "Setting voice channel options: "
1879 << options.ToString();
1880
wu@webrtc.orgde305012013-10-31 15:40:38 +00001881 // Check if DSCP value is changed from previous.
1882 bool dscp_option_changed = (options_.dscp != options.dscp);
1883
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001884 // TODO(xians): Add support to set different options for different send
1885 // streams after we support multiple APMs.
1886
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001887 // We retain all of the existing options, and apply the given ones
1888 // on top. This means there is no way to "clear" options such that
1889 // they go back to the engine default.
1890 options_.SetAll(options);
1891
1892 if (send_ != SEND_NOTHING) {
1893 if (!engine()->SetOptionOverrides(options_)) {
1894 LOG(LS_WARNING) <<
1895 "Failed to engine SetOptionOverrides during channel SetOptions.";
1896 return false;
1897 }
1898 } else {
1899 // Will be interpreted when appropriate.
1900 }
1901
wu@webrtc.org97077a32013-10-25 21:18:33 +00001902 // Receiver-side auto gain control happens per channel, so set it here from
1903 // options. Note that, like conference mode, setting it on the engine won't
1904 // have the desired effect, since voice channels don't inherit options from
1905 // the media engine when those options are applied per-channel.
1906 bool rx_auto_gain_control;
1907 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1908 if (engine()->voe()->processing()->SetRxAgcStatus(
1909 voe_channel(), rx_auto_gain_control,
1910 webrtc::kAgcFixedDigital) == -1) {
1911 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1912 return false;
1913 } else {
1914 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1915 << " with mode " << webrtc::kAgcFixedDigital;
1916 }
1917 }
1918 if (options.rx_agc_target_dbov.IsSet() ||
1919 options.rx_agc_digital_compression_gain.IsSet() ||
1920 options.rx_agc_limiter.IsSet()) {
1921 webrtc::AgcConfig config;
1922 // If only some of the options are being overridden, get the current
1923 // settings for the channel and bail if they aren't available.
1924 if (!options.rx_agc_target_dbov.IsSet() ||
1925 !options.rx_agc_digital_compression_gain.IsSet() ||
1926 !options.rx_agc_limiter.IsSet()) {
1927 if (engine()->voe()->processing()->GetRxAgcConfig(
1928 voe_channel(), config) != 0) {
1929 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1930 << "channel " << voe_channel() << ". Since not all rx "
1931 << "agc options are specified, unable to safely set rx "
1932 << "agc options.";
1933 return false;
1934 }
1935 }
1936 config.targetLeveldBOv =
1937 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1938 config.targetLeveldBOv);
1939 config.digitalCompressionGaindB =
1940 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1941 config.digitalCompressionGaindB);
1942 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1943 config.limiterEnable);
1944 if (engine()->voe()->processing()->SetRxAgcConfig(
1945 voe_channel(), config) == -1) {
1946 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1947 config.digitalCompressionGaindB, config.limiterEnable);
1948 return false;
1949 }
1950 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001951 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001952 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001953 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001954 dscp = kAudioDscpValue;
1955 if (MediaChannel::SetDscp(dscp) != 0) {
1956 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1957 }
1958 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001959
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001960 // Force update of Video Engine BWE forwarding to reflect experiment setting.
1961 if (!SetupSharedBandwidthEstimation(shared_bwe_vie_,
1962 shared_bwe_vie_channel_)) {
1963 return false;
1964 }
1965
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001966 LOG(LS_INFO) << "Set voice channel options. Current options: "
1967 << options_.ToString();
1968 return true;
1969}
1970
1971bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1972 const std::vector<AudioCodec>& codecs) {
1973 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001974 LOG(LS_INFO) << "Setting receive voice codecs:";
1975
1976 std::vector<AudioCodec> new_codecs;
1977 // Find all new codecs. We allow adding new codecs but don't allow changing
1978 // the payload type of codecs that is already configured since we might
1979 // already be receiving packets with that payload type.
1980 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001981 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001982 AudioCodec old_codec;
1983 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1984 if (old_codec.id != it->id) {
1985 LOG(LS_ERROR) << it->name << " payload type changed.";
1986 return false;
1987 }
1988 } else {
1989 new_codecs.push_back(*it);
1990 }
1991 }
1992 if (new_codecs.empty()) {
1993 // There are no new codecs to configure. Already configured codecs are
1994 // never removed.
1995 return true;
1996 }
1997
1998 if (playout_) {
1999 // Receive codecs can not be changed while playing. So we temporarily
2000 // pause playout.
2001 PausePlayout();
2002 }
2003
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002004 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002005 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
2006 it != new_codecs.end() && ret; ++it) {
2007 webrtc::CodecInst voe_codec;
2008 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2009 LOG(LS_INFO) << ToString(*it);
2010 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002011 if (default_receive_ssrc_ == 0) {
2012 // Set the receive codecs on the default channel explicitly if the
2013 // default channel is not used by |receive_channels_|, this happens in
2014 // conference mode or in non-conference mode when there is no playout
2015 // channel.
2016 // TODO(xians): Figure out how we use the default channel in conference
2017 // mode.
2018 if (engine()->voe()->codec()->SetRecPayloadType(
2019 voe_channel(), voe_codec) == -1) {
2020 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
2021 ret = false;
2022 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002023 }
2024
2025 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002026 for (ChannelMap::iterator it = receive_channels_.begin();
2027 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002028 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002029 it->second->channel(), voe_codec) == -1) {
2030 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002031 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002032 ret = false;
2033 }
2034 }
2035 } else {
2036 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2037 ret = false;
2038 }
2039 }
2040 if (ret) {
2041 recv_codecs_ = codecs;
2042 }
2043
2044 if (desired_playout_ && !playout_) {
2045 ResumePlayout();
2046 }
2047 return ret;
2048}
2049
2050bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002051 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002052 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002053 engine()->voe()->codec()->SetVADStatus(channel, false);
2054 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002055 engine()->voe()->rtp()->SetREDStatus(channel, false);
2056 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002057
2058 // Scan through the list to figure out the codec to use for sending, along
2059 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002060 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002061 webrtc::CodecInst send_codec;
2062 memset(&send_codec, 0, sizeof(send_codec));
2063
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002064 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002065 bool enable_codec_fec = false;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002066
minyue@webrtc.org26236952014-10-29 02:27:08 +00002067 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002068
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002069 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002070 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2071 it != codecs.end(); ++it) {
2072 // Ignore codecs we don't know about. The negotiation step should prevent
2073 // this, but double-check to be sure.
2074 webrtc::CodecInst voe_codec;
2075 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002076 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002077 continue;
2078 }
2079
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002080 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2081 // Skip telephone-event/CN codec, which will be handled later.
2082 continue;
2083 }
2084
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002085 // We'll use the first codec in the list to actually send audio data.
2086 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002087 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002088 // used is specified in params.
2089 if (IsRedCodec(it->name)) {
2090 // Parse out the RED parameters. If we fail, just ignore RED;
2091 // we don't support all possible params/usage scenarios.
2092 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2093 continue;
2094 }
2095
2096 // Enable redundant encoding of the specified codec. Treat any
2097 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002098 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2099 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2100 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002101 return false;
2102 }
2103 } else {
2104 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002105 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002106 // For Opus as the send codec, we are to enable inband FEC if requested
2107 // and set maximum playback rate.
2108 if (IsOpus(*it)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002109 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
2110 &opus_max_playback_rate);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002111 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002112 }
2113 found_send_codec = true;
2114 break;
2115 }
2116
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002117 if (nack_enabled_ != nack_enabled) {
2118 SetNack(channel, nack_enabled);
2119 nack_enabled_ = nack_enabled;
2120 }
2121
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002122 if (!found_send_codec) {
2123 LOG(LS_WARNING) << "Received empty list of codecs.";
2124 return false;
2125 }
2126
2127 // Set the codec immediately, since SetVADStatus() depends on whether
2128 // the current codec is mono or stereo.
2129 if (!SetSendCodec(channel, send_codec))
2130 return false;
2131
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002132 // FEC should be enabled after SetSendCodec.
2133 if (enable_codec_fec) {
2134 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2135 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002136 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2137 // Enable codec internal FEC. Treat any failure as fatal internal error.
2138 LOG_RTCERR2(SetFECStatus, channel, true);
2139 return false;
2140 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002141 }
2142
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002143 // maxplaybackrate should be set after SetSendCodec.
minyue@webrtc.org26236952014-10-29 02:27:08 +00002144 // If opus_max_playback_rate <= 0, the default maximum playback rate of 48 kHz
2145 // will be used.
2146 if (opus_max_playback_rate > 0) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002147 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002148 << opus_max_playback_rate
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002149 << " Hz on channel "
2150 << channel;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002151 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
minyue@webrtc.org26236952014-10-29 02:27:08 +00002152 channel, opus_max_playback_rate) == -1) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002153 LOG(LS_WARNING) << "Could not set maximum playback rate.";
2154 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002155 }
2156
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002157 // Always update the |send_codec_| to the currently set send codec.
2158 send_codec_.reset(new webrtc::CodecInst(send_codec));
2159
minyue@webrtc.org26236952014-10-29 02:27:08 +00002160 if (send_bitrate_setting_) {
2161 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002162 }
2163
2164 // Loop through the codecs list again to config the telephone-event/CN codec.
2165 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2166 it != codecs.end(); ++it) {
2167 // Ignore codecs we don't know about. The negotiation step should prevent
2168 // this, but double-check to be sure.
2169 webrtc::CodecInst voe_codec;
2170 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2171 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2172 continue;
2173 }
2174
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002175 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2176 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002177 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002178 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2179 channel, it->id) == -1) {
2180 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2181 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002182 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002183 } else if (IsCNCodec(it->name)) {
2184 // Turn voice activity detection/comfort noise on if supported.
2185 // Set the wideband CN payload type appropriately.
2186 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002187 webrtc::PayloadFrequencies cn_freq;
2188 switch (it->clockrate) {
2189 case 8000:
2190 cn_freq = webrtc::kFreq8000Hz;
2191 break;
2192 case 16000:
2193 cn_freq = webrtc::kFreq16000Hz;
2194 break;
2195 case 32000:
2196 cn_freq = webrtc::kFreq32000Hz;
2197 break;
2198 default:
2199 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2200 << " not supported.";
2201 continue;
2202 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002203 // Set the CN payloadtype and the VAD status.
2204 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2205 if (cn_freq != webrtc::kFreq8000Hz) {
2206 if (engine()->voe()->codec()->SetSendCNPayloadType(
2207 channel, it->id, cn_freq) == -1) {
2208 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2209 // TODO(ajm): This failure condition will be removed from VoE.
2210 // Restore the return here when we update to a new enough webrtc.
2211 //
2212 // Not returning false because the SetSendCNPayloadType will fail if
2213 // the channel is already sending.
2214 // This can happen if the remote description is applied twice, for
2215 // example in the case of ROAP on top of JSEP, where both side will
2216 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002217 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002218 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002219 // Only turn on VAD if we have a CN payload type that matches the
2220 // clockrate for the codec we are going to use.
2221 if (it->clockrate == send_codec.plfreq) {
2222 LOG(LS_INFO) << "Enabling VAD";
2223 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2224 LOG_RTCERR2(SetVADStatus, channel, true);
2225 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002226 }
2227 }
2228 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002229 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002230 return true;
2231}
2232
2233bool WebRtcVoiceMediaChannel::SetSendCodecs(
2234 const std::vector<AudioCodec>& codecs) {
2235 dtmf_allowed_ = false;
2236 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2237 it != codecs.end(); ++it) {
2238 // Find the DTMF telephone event "codec".
2239 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2240 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2241 dtmf_allowed_ = true;
2242 }
2243 }
2244
2245 // Cache the codecs in order to configure the channel created later.
2246 send_codecs_ = codecs;
2247 for (ChannelMap::iterator iter = send_channels_.begin();
2248 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002249 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002250 return false;
2251 }
2252 }
2253
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002254 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002255 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002256 return true;
2257}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002258
2259void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2260 bool nack_enabled) {
2261 for (ChannelMap::const_iterator it = channels.begin();
2262 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002263 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002264 }
2265}
2266
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002267void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002268 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002269 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002270 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2271 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002272 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002273 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2274 }
2275}
2276
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002277bool WebRtcVoiceMediaChannel::SetSendCodec(
2278 const webrtc::CodecInst& send_codec) {
2279 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2280 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002281 for (ChannelMap::iterator iter = send_channels_.begin();
2282 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002283 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002284 return false;
2285 }
2286
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002287 return true;
2288}
2289
2290bool WebRtcVoiceMediaChannel::SetSendCodec(
2291 int channel, const webrtc::CodecInst& send_codec) {
2292 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2293 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2294
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002295 webrtc::CodecInst current_codec;
2296 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2297 (send_codec == current_codec)) {
2298 // Codec is already configured, we can return without setting it again.
2299 return true;
2300 }
2301
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002302 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2303 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002304 return false;
2305 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002306 return true;
2307}
2308
2309bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2310 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002311 if (receive_extensions_ == extensions) {
2312 return true;
2313 }
2314
2315 // The default channel may or may not be in |receive_channels_|. Set the rtp
2316 // header extensions for default channel regardless.
2317 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2318 return false;
2319 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002320
2321 // Loop through all receive channels and enable/disable the extensions.
2322 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2323 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002324 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2325 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002326 return false;
2327 }
2328 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002329
2330 receive_extensions_ = extensions;
2331 return true;
2332}
2333
2334bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2335 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002336 const RtpHeaderExtension* audio_level_extension =
2337 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2338 if (!SetHeaderExtension(
2339 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2340 audio_level_extension)) {
2341 return false;
2342 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002343
2344 const RtpHeaderExtension* send_time_extension =
2345 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2346 if (!SetHeaderExtension(
2347 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2348 send_time_extension)) {
2349 return false;
2350 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002351 return true;
2352}
2353
2354bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2355 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002356 if (send_extensions_ == extensions) {
2357 return true;
2358 }
2359
2360 // The default channel may or may not be in |send_channels_|. Set the rtp
2361 // header extensions for default channel regardless.
2362
2363 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2364 return false;
2365 }
2366
2367 // Loop through all send channels and enable/disable the extensions.
2368 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2369 channel_it != send_channels_.end(); ++channel_it) {
2370 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2371 extensions)) {
2372 return false;
2373 }
2374 }
2375
2376 send_extensions_ = extensions;
2377 return true;
2378}
2379
2380bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2381 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002382 const RtpHeaderExtension* audio_level_extension =
2383 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002384
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002385 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002386 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002387 audio_level_extension)) {
2388 return false;
2389 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002390
2391 const RtpHeaderExtension* send_time_extension =
2392 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002393 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002394 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002395 send_time_extension)) {
2396 return false;
2397 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002398
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002399 return true;
2400}
2401
2402bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2403 desired_playout_ = playout;
2404 return ChangePlayout(desired_playout_);
2405}
2406
2407bool WebRtcVoiceMediaChannel::PausePlayout() {
2408 return ChangePlayout(false);
2409}
2410
2411bool WebRtcVoiceMediaChannel::ResumePlayout() {
2412 return ChangePlayout(desired_playout_);
2413}
2414
2415bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2416 if (playout_ == playout) {
2417 return true;
2418 }
2419
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002420 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002421 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002422 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002423 // Only toggle the default channel if we don't have any other channels.
2424 result = SetPlayout(voe_channel(), playout);
2425 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002426 for (ChannelMap::iterator it = receive_channels_.begin();
2427 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002428 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002429 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002430 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002431 result = false;
2432 }
2433 }
2434
2435 if (result) {
2436 playout_ = playout;
2437 }
2438 return result;
2439}
2440
2441bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2442 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002443 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002444 return ChangeSend(desired_send_);
2445 return true;
2446}
2447
2448bool WebRtcVoiceMediaChannel::PauseSend() {
2449 return ChangeSend(SEND_NOTHING);
2450}
2451
2452bool WebRtcVoiceMediaChannel::ResumeSend() {
2453 return ChangeSend(desired_send_);
2454}
2455
2456bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2457 if (send_ == send) {
2458 return true;
2459 }
2460
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002461 // Change the settings on each send channel.
2462 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002463 engine()->SetOptionOverrides(options_);
2464
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002465 // Change the settings on each send channel.
2466 for (ChannelMap::iterator iter = send_channels_.begin();
2467 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002468 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002469 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002470 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002471
2472 // Clear up the options after stopping sending.
2473 if (send == SEND_NOTHING)
2474 engine()->ClearOptionOverrides();
2475
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002476 send_ = send;
2477 return true;
2478}
2479
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002480bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2481 if (send == SEND_MICROPHONE) {
2482 if (engine()->voe()->base()->StartSend(channel) == -1) {
2483 LOG_RTCERR1(StartSend, channel);
2484 return false;
2485 }
2486 if (engine()->voe()->file() &&
2487 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2488 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2489 return false;
2490 }
2491 } else { // SEND_NOTHING
2492 ASSERT(send == SEND_NOTHING);
2493 if (engine()->voe()->base()->StopSend(channel) == -1) {
2494 LOG_RTCERR1(StopSend, channel);
2495 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002496 }
2497 }
2498
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002499 return true;
2500}
2501
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002502// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002503void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2504 if (engine()->voe()->network()->RegisterExternalTransport(
2505 channel, *this) == -1) {
2506 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2507 }
2508
2509 // Enable RTCP (for quality stats and feedback messages)
2510 EnableRtcp(channel);
2511
2512 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2513 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002514
2515 // Set RTP header extension for the new channel.
2516 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002517}
2518
2519bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2520 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2521 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2522 }
2523
2524 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2525 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002526 return false;
2527 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002528
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002529 return true;
2530}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002531
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002532bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2533 // If the default channel is already used for sending create a new channel
2534 // otherwise use the default channel for sending.
2535 int channel = GetSendChannelNum(sp.first_ssrc());
2536 if (channel != -1) {
2537 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2538 return false;
2539 }
2540
2541 bool default_channel_is_available = true;
2542 for (ChannelMap::const_iterator iter = send_channels_.begin();
2543 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002544 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002545 default_channel_is_available = false;
2546 break;
2547 }
2548 }
2549 if (default_channel_is_available) {
2550 channel = voe_channel();
2551 } else {
2552 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002553 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002554 if (channel == -1) {
2555 LOG_RTCERR0(CreateChannel);
2556 return false;
2557 }
2558
2559 ConfigureSendChannel(channel);
2560 }
2561
2562 // Save the channel to send_channels_, so that RemoveSendStream() can still
2563 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002564 webrtc::AudioTransport* audio_transport =
2565 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002566 send_channels_.insert(std::make_pair(
2567 sp.first_ssrc(),
2568 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002569
2570 // Set the send (local) SSRC.
2571 // If there are multiple send SSRCs, we can only set the first one here, and
2572 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2573 // (with a codec requires multiple SSRC(s)).
2574 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2575 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2576 return false;
2577 }
2578
2579 // At this point the channel's local SSRC has been updated. If the channel is
2580 // the default channel make sure that all the receive channels are updated as
2581 // well. Receive channels have to have the same SSRC as the default channel in
2582 // order to send receiver reports with this SSRC.
2583 if (IsDefaultChannel(channel)) {
2584 for (ChannelMap::const_iterator it = receive_channels_.begin();
2585 it != receive_channels_.end(); ++it) {
2586 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002587 if (!IsDefaultChannel(it->second->channel())) {
2588 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002589 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002590 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002591 return false;
2592 }
2593 }
2594 }
2595 }
2596
2597 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002598 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2599 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002600 }
2601
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002602 // Set the current codecs to be used for the new channel.
2603 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002604 return false;
2605
2606 return ChangeSend(channel, desired_send_);
2607}
2608
2609bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2610 ChannelMap::iterator it = send_channels_.find(ssrc);
2611 if (it == send_channels_.end()) {
2612 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2613 << " which doesn't exist.";
2614 return false;
2615 }
2616
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002617 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002618 ChangeSend(channel, SEND_NOTHING);
2619
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002620 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2621 // this will disconnect the audio renderer with the send channel.
2622 delete it->second;
2623 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002624
2625 if (IsDefaultChannel(channel)) {
2626 // Do not delete the default channel since the receive channels depend on
2627 // the default channel, recycle it instead.
2628 ChangeSend(channel, SEND_NOTHING);
2629 } else {
2630 // Clean up and delete the send channel.
2631 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2632 << " with VoiceEngine channel #" << channel << ".";
2633 if (!DeleteChannel(channel))
2634 return false;
2635 }
2636
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002637 if (send_channels_.empty())
2638 ChangeSend(SEND_NOTHING);
2639
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002640 return true;
2641}
2642
2643bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002644 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002645
2646 if (!VERIFY(sp.ssrcs.size() == 1))
2647 return false;
2648 uint32 ssrc = sp.first_ssrc();
2649
wu@webrtc.org78187522013-10-07 23:32:02 +00002650 if (ssrc == 0) {
2651 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2652 return false;
2653 }
2654
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002655 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2656 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002657 return false;
2658 }
2659
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002660 // Reuse default channel for recv stream in non-conference mode call
2661 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002662 webrtc::AudioTransport* audio_transport =
2663 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002664 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2665 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2666 << " reuse default channel";
2667 default_receive_ssrc_ = sp.first_ssrc();
2668 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002669 default_receive_ssrc_,
2670 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002671 if (!SetupSharedBweOnChannel(voe_channel())) {
2672 return false;
2673 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002674 return SetPlayout(voe_channel(), playout_);
2675 }
2676
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002677 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002678 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002679 if (channel == -1) {
2680 LOG_RTCERR0(CreateChannel);
2681 return false;
2682 }
2683
wu@webrtc.org78187522013-10-07 23:32:02 +00002684 if (!ConfigureRecvChannel(channel)) {
2685 DeleteChannel(channel);
2686 return false;
2687 }
2688
2689 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002690 std::make_pair(
2691 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002692
2693 LOG(LS_INFO) << "New audio stream " << ssrc
2694 << " registered to VoiceEngine channel #"
2695 << channel << ".";
2696 return true;
2697}
2698
2699bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002700 // Configure to use external transport, like our default channel.
2701 if (engine()->voe()->network()->RegisterExternalTransport(
2702 channel, *this) == -1) {
2703 LOG_RTCERR2(SetExternalTransport, channel, this);
2704 return false;
2705 }
2706
2707 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002708 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002709 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2710 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002711 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002712 return false;
2713 }
2714 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002715 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002716 return false;
2717 }
2718
2719 // Use the same recv payload types as our default channel.
2720 ResetRecvCodecs(channel);
2721 if (!recv_codecs_.empty()) {
2722 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2723 it != recv_codecs_.end(); ++it) {
2724 webrtc::CodecInst voe_codec;
2725 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2726 voe_codec.pltype = it->id;
2727 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2728 if (engine()->voe()->codec()->GetRecPayloadType(
2729 voe_channel(), voe_codec) != -1) {
2730 if (engine()->voe()->codec()->SetRecPayloadType(
2731 channel, voe_codec) == -1) {
2732 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2733 return false;
2734 }
2735 }
2736 }
2737 }
2738 }
2739
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002740 if (InConferenceMode()) {
2741 // To be in par with the video, voe_channel() is not used for receiving in
2742 // a conference call.
2743 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2744 // This is the first stream in a multi user meeting. We can now
2745 // disable playback of the default stream. This since the default
2746 // stream will probably have received some initial packets before
2747 // the new stream was added. This will mean that the CN state from
2748 // the default channel will be mixed in with the other streams
2749 // throughout the whole meeting, which might be disturbing.
2750 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2751 SetPlayout(voe_channel(), false);
2752 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002753 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002754 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002755
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002756 // Set RTP header extension for the new channel.
2757 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2758 return false;
2759 }
2760
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002761 // Set up channel to be able to forward incoming packets to video engine BWE.
2762 if (!SetupSharedBweOnChannel(channel)) {
2763 return false;
2764 }
2765
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002766 return SetPlayout(channel, playout_);
2767}
2768
2769bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002770 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002771 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002772 if (it == receive_channels_.end()) {
2773 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2774 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002775 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002776 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002777
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002778 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2779 // will disconnect the audio renderer with the receive channel.
2780 // Cache the channel before the deletion.
2781 const int channel = it->second->channel();
2782 delete it->second;
2783 receive_channels_.erase(it);
2784
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002785 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002786 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002787 // Recycle the default channel is for recv stream.
2788 if (playout_)
2789 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002790
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002791 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002792 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002793 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002794
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002795 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002796 << " with VoiceEngine channel #" << channel << ".";
2797 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002798 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002799
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002800 bool enable_default_channel_playout = false;
2801 if (receive_channels_.empty()) {
2802 // The last stream was removed. We can now enable the default
2803 // channel for new channels to be played out immediately without
2804 // waiting for AddStream messages.
2805 // We do this for both conference mode and non-conference mode.
2806 // TODO(oja): Does the default channel still have it's CN state?
2807 enable_default_channel_playout = true;
2808 }
2809 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2810 default_receive_ssrc_ != 0) {
2811 // Only the default channel is active, enable the playout on default
2812 // channel.
2813 enable_default_channel_playout = true;
2814 }
2815 if (enable_default_channel_playout && playout_) {
2816 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2817 SetPlayout(voe_channel(), true);
2818 }
2819
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002820 return true;
2821}
2822
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002823bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2824 AudioRenderer* renderer) {
2825 ChannelMap::iterator it = receive_channels_.find(ssrc);
2826 if (it == receive_channels_.end()) {
2827 if (renderer) {
2828 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002829 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002830 return false;
2831 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002832
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002833 // The channel likely has gone away, do nothing.
2834 return true;
2835 }
2836
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002837 if (renderer)
2838 it->second->Start(renderer);
2839 else
2840 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002841
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002842 return true;
2843}
2844
2845bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2846 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002847 ChannelMap::iterator it = send_channels_.find(ssrc);
2848 if (it == send_channels_.end()) {
2849 if (renderer) {
2850 // Return an error if trying to set a valid renderer with an invalid ssrc.
2851 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2852 return false;
2853 }
2854
2855 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002856 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002857 }
2858
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002859 if (renderer)
2860 it->second->Start(renderer);
2861 else
2862 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002863
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002864 return true;
2865}
2866
2867bool WebRtcVoiceMediaChannel::GetActiveStreams(
2868 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002869 // In conference mode, the default channel should not be in
2870 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002871 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002872 for (ChannelMap::iterator it = receive_channels_.begin();
2873 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002874 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002875 if (level > 0) {
2876 actives->push_back(std::make_pair(it->first, level));
2877 }
2878 }
2879 return true;
2880}
2881
2882int WebRtcVoiceMediaChannel::GetOutputLevel() {
2883 // return the highest output level of all streams
2884 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002885 for (ChannelMap::iterator it = receive_channels_.begin();
2886 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002887 int level = GetOutputLevel(it->second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002888 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002889 }
2890 return highest;
2891}
2892
2893int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2894 int ret;
2895 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2896 // In case of error, log the info and continue
2897 LOG_RTCERR0(TimeSinceLastTyping);
2898 ret = -1;
2899 } else {
2900 ret *= 1000; // We return ms, webrtc returns seconds.
2901 }
2902 return ret;
2903}
2904
2905void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2906 int cost_per_typing, int reporting_threshold, int penalty_decay,
2907 int type_event_delay) {
2908 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2909 time_window, cost_per_typing,
2910 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2911 // In case of error, log the info and continue
2912 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2913 cost_per_typing, reporting_threshold, penalty_decay,
2914 type_event_delay);
2915 }
2916}
2917
2918bool WebRtcVoiceMediaChannel::SetOutputScaling(
2919 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002920 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002921 // Collect the channels to scale the output volume.
2922 std::vector<int> channels;
2923 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002924 // Default channel is not in receive_channels_ if it is not being used for
2925 // playout.
2926 if (default_receive_ssrc_ == 0)
2927 channels.push_back(voe_channel());
2928 for (ChannelMap::const_iterator it = receive_channels_.begin();
2929 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002930 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002931 }
2932 } else { // Collect only the channel of the specified ssrc.
2933 int channel = GetReceiveChannelNum(ssrc);
2934 if (-1 == channel) {
2935 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2936 return false;
2937 }
2938 channels.push_back(channel);
2939 }
2940
2941 // Scale the output volume for the collected channels. We first normalize to
2942 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002943 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002944 if (scale > 0.0001f) {
2945 left /= scale;
2946 right /= scale;
2947 }
2948 for (std::vector<int>::const_iterator it = channels.begin();
2949 it != channels.end(); ++it) {
2950 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2951 *it, scale)) {
2952 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2953 return false;
2954 }
2955 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2956 *it, static_cast<float>(left), static_cast<float>(right))) {
2957 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2958 // Do not return if fails. SetOutputVolumePan is not available for all
2959 // pltforms.
2960 }
2961 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2962 << " right=" << right * scale
2963 << " for channel " << *it << " and ssrc " << ssrc;
2964 }
2965 return true;
2966}
2967
2968bool WebRtcVoiceMediaChannel::GetOutputScaling(
2969 uint32 ssrc, double* left, double* right) {
2970 if (!left || !right) return false;
2971
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002972 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002973 // Determine which channel based on ssrc.
2974 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2975 if (channel == -1) {
2976 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2977 return false;
2978 }
2979
2980 float scaling;
2981 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2982 channel, scaling)) {
2983 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2984 return false;
2985 }
2986
2987 float left_pan;
2988 float right_pan;
2989 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2990 channel, left_pan, right_pan)) {
2991 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2992 // If GetOutputVolumePan fails, we use the default left and right pan.
2993 left_pan = 1.0f;
2994 right_pan = 1.0f;
2995 }
2996
2997 *left = scaling * left_pan;
2998 *right = scaling * right_pan;
2999 return true;
3000}
3001
3002bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
3003 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
3004 return true;
3005}
3006
3007bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
3008 bool play, bool loop) {
3009 if (!ringback_tone_) {
3010 return false;
3011 }
3012
3013 // The voe file api is not available in chrome.
3014 if (!engine()->voe()->file()) {
3015 return false;
3016 }
3017
3018 // Determine which VoiceEngine channel to play on.
3019 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
3020 if (channel == -1) {
3021 return false;
3022 }
3023
3024 // Make sure the ringtone is cued properly, and play it out.
3025 if (play) {
3026 ringback_tone_->set_loop(loop);
3027 ringback_tone_->Rewind();
3028 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
3029 ringback_tone_.get()) == -1) {
3030 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
3031 LOG(LS_ERROR) << "Unable to start ringback tone";
3032 return false;
3033 }
3034 ringback_channels_.insert(channel);
3035 LOG(LS_INFO) << "Started ringback on channel " << channel;
3036 } else {
3037 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
3038 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
3039 LOG_RTCERR1(StopPlayingFileLocally, channel);
3040 return false;
3041 }
3042 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
3043 ringback_channels_.erase(channel);
3044 }
3045
3046 return true;
3047}
3048
3049bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3050 return dtmf_allowed_;
3051}
3052
3053bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3054 int duration, int flags) {
3055 if (!dtmf_allowed_) {
3056 return false;
3057 }
3058
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003059 // Send the event.
3060 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003061 int channel = -1;
3062 if (ssrc == 0) {
3063 bool default_channel_is_inuse = false;
3064 for (ChannelMap::const_iterator iter = send_channels_.begin();
3065 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003066 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003067 default_channel_is_inuse = true;
3068 break;
3069 }
3070 }
3071 if (default_channel_is_inuse) {
3072 channel = voe_channel();
3073 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003074 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003075 }
3076 } else {
3077 channel = GetSendChannelNum(ssrc);
3078 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003079 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003080 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3081 << ssrc << " is not in use.";
3082 return false;
3083 }
3084 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003085 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3086 channel, event, true, duration) == -1) {
3087 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003088 return false;
3089 }
3090 }
3091
3092 // Play the event.
3093 if (flags & cricket::DF_PLAY) {
3094 // Play DTMF tone locally.
3095 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3096 LOG_RTCERR2(PlayDtmfTone, event, duration);
3097 return false;
3098 }
3099 }
3100
3101 return true;
3102}
3103
wu@webrtc.orga9890802013-12-13 00:21:03 +00003104void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003105 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003106 // Pick which channel to send this packet to. If this packet doesn't match
3107 // any multiplexed streams, just send it to the default channel. Otherwise,
3108 // send it to the specific decoder instance for that stream.
3109 int which_channel = GetReceiveChannelNum(
3110 ParseSsrc(packet->data(), packet->length(), false));
3111 if (which_channel == -1) {
3112 which_channel = voe_channel();
3113 }
3114
3115 // Stop any ringback that might be playing on the channel.
3116 // It's possible the ringback has already stopped, ih which case we'll just
3117 // use the opportunity to remove the channel from ringback_channels_.
3118 if (engine()->voe()->file()) {
3119 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3120 if (it != ringback_channels_.end()) {
3121 if (engine()->voe()->file()->IsPlayingFileLocally(
3122 which_channel) == 1) {
3123 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3124 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3125 << " due to incoming media";
3126 }
3127 ringback_channels_.erase(which_channel);
3128 }
3129 }
3130
3131 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003132 engine()->voe()->network()->ReceivedRTPPacket(
3133 which_channel,
3134 packet->data(),
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003135 packet->length(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003136 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003137}
3138
wu@webrtc.orga9890802013-12-13 00:21:03 +00003139void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003140 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003141 // Sending channels need all RTCP packets with feedback information.
3142 // Even sender reports can contain attached report blocks.
3143 // Receiving channels need sender reports in order to create
3144 // correct receiver reports.
3145 int type = 0;
3146 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3147 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3148 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003149 }
3150
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003151 // If it is a sender report, find the channel that is listening.
3152 bool has_sent_to_default_channel = false;
3153 if (type == kRtcpTypeSR) {
3154 int which_channel = GetReceiveChannelNum(
3155 ParseSsrc(packet->data(), packet->length(), true));
3156 if (which_channel != -1) {
3157 engine()->voe()->network()->ReceivedRTCPPacket(
3158 which_channel,
3159 packet->data(),
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003160 packet->length());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003161
3162 if (IsDefaultChannel(which_channel))
3163 has_sent_to_default_channel = true;
3164 }
3165 }
3166
3167 // SR may continue RR and any RR entry may correspond to any one of the send
3168 // channels. So all RTCP packets must be forwarded all send channels. VoE
3169 // will filter out RR internally.
3170 for (ChannelMap::iterator iter = send_channels_.begin();
3171 iter != send_channels_.end(); ++iter) {
3172 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003173 if (IsDefaultChannel(iter->second->channel()) &&
3174 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003175 continue;
3176
3177 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003178 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003179 packet->data(),
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003180 packet->length());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003181 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003182}
3183
3184bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003185 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3186 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003187 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3188 return false;
3189 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003190 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3191 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003192 return false;
3193 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003194 // We set the AGC to mute state only when all the channels are muted.
3195 // This implementation is not ideal, instead we should signal the AGC when
3196 // the mic channel is muted/unmuted. We can't do it today because there
3197 // is no good way to know which stream is mapping to the mic channel.
3198 bool all_muted = muted;
3199 for (ChannelMap::const_iterator iter = send_channels_.begin();
3200 iter != send_channels_.end() && all_muted; ++iter) {
3201 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3202 all_muted)) {
3203 LOG_RTCERR1(GetInputMute, iter->second->channel());
3204 return false;
3205 }
3206 }
3207
3208 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3209 if (ap)
3210 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003211 return true;
3212}
3213
minyue@webrtc.org26236952014-10-29 02:27:08 +00003214// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3215// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003216bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003217 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003218
minyue@webrtc.org26236952014-10-29 02:27:08 +00003219 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003220}
3221
minyue@webrtc.org26236952014-10-29 02:27:08 +00003222bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3223 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003224
minyue@webrtc.org26236952014-10-29 02:27:08 +00003225 send_bitrate_setting_ = true;
3226 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003227
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003228 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003229 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003230 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003231 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003232 }
3233
minyue@webrtc.org26236952014-10-29 02:27:08 +00003234 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003235 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3236 // SetMaxSendBandwith(0), the second call removes the previous limit.
3237 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003238 return true;
3239
3240 webrtc::CodecInst codec = *send_codec_;
3241 bool is_multi_rate = IsCodecMultiRate(codec);
3242
3243 if (is_multi_rate) {
3244 // If codec is multi-rate then just set the bitrate.
3245 codec.rate = bps;
3246 if (!SetSendCodec(codec)) {
3247 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3248 << " to bitrate " << bps << " bps.";
3249 return false;
3250 }
3251 return true;
3252 } else {
3253 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3254 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3255 // fixed bitrate then ignore.
3256 if (bps < codec.rate) {
3257 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3258 << " to bitrate " << bps << " bps"
3259 << ", requires at least " << codec.rate << " bps.";
3260 return false;
3261 }
3262 return true;
3263 }
3264}
3265
3266bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003267 bool echo_metrics_on = false;
3268 // These can take on valid negative values, so use the lowest possible level
3269 // as default rather than -1.
3270 int echo_return_loss = -100;
3271 int echo_return_loss_enhancement = -100;
3272 // These can also be negative, but in practice -1 is only used to signal
3273 // insufficient data, since the resolution is limited to multiples of 4 ms.
3274 int echo_delay_median_ms = -1;
3275 int echo_delay_std_ms = -1;
3276 if (engine()->voe()->processing()->GetEcMetricsStatus(
3277 echo_metrics_on) != -1 && echo_metrics_on) {
3278 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3279 // here, but it appears to be unsuitable currently. Revisit after this is
3280 // investigated: http://b/issue?id=5666755
3281 int erl, erle, rerl, anlp;
3282 if (engine()->voe()->processing()->GetEchoMetrics(
3283 erl, erle, rerl, anlp) != -1) {
3284 echo_return_loss = erl;
3285 echo_return_loss_enhancement = erle;
3286 }
3287
3288 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003289 float dummy;
3290 if (engine()->voe()->processing()->GetEcDelayMetrics(
3291 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003292 echo_delay_median_ms = median;
3293 echo_delay_std_ms = std;
3294 }
3295 }
3296
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003297 webrtc::CallStatistics cs;
3298 unsigned int ssrc;
3299 webrtc::CodecInst codec;
3300 unsigned int level;
3301
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003302 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3303 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003304 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003305
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003306 // Fill in the sender info, based on what we know, and what the
3307 // remote side told us it got from its RTCP report.
3308 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003309
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003310 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3311 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3312 continue;
3313 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003314
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003315 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003316 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3317 sinfo.bytes_sent = cs.bytesSent;
3318 sinfo.packets_sent = cs.packetsSent;
3319 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3320 // returns 0 to indicate an error value.
3321 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3322
3323 // Get data from the last remote RTCP report. Use default values if no data
3324 // available.
3325 sinfo.fraction_lost = -1.0;
3326 sinfo.jitter_ms = -1;
3327 sinfo.packets_lost = -1;
3328 sinfo.ext_seqnum = -1;
3329 std::vector<webrtc::ReportBlock> receive_blocks;
3330 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3331 channel, &receive_blocks) != -1 &&
3332 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3333 std::vector<webrtc::ReportBlock>::iterator iter;
3334 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3335 ++iter) {
3336 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003337 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003338 // Convert Q8 to floating point.
3339 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3340 // Convert samples to milliseconds.
3341 if (codec.plfreq / 1000 > 0) {
3342 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3343 }
3344 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3345 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3346 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003347 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003348 }
3349 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003350
3351 // Local speech level.
3352 sinfo.audio_level = (engine()->voe()->volume()->
3353 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3354
3355 // TODO(xians): We are injecting the same APM logging to all the send
3356 // channels here because there is no good way to know which send channel
3357 // is using the APM. The correct fix is to allow the send channels to have
3358 // their own APM so that we can feed the correct APM logging to different
3359 // send channels. See issue crbug/264611 .
3360 sinfo.echo_return_loss = echo_return_loss;
3361 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3362 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3363 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003364 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3365 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003366 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003367
3368 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003369 }
3370
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003371 // Build the list of receivers, one for each receiving channel, or 1 in
3372 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003373 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003374 for (ChannelMap::const_iterator it = receive_channels_.begin();
3375 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003376 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003377 }
3378 if (channels.empty()) {
3379 channels.push_back(voe_channel());
3380 }
3381
3382 // Get the SSRC and stats for each receiver, based on our own calculations.
3383 for (std::vector<int>::const_iterator it = channels.begin();
3384 it != channels.end(); ++it) {
3385 memset(&cs, 0, sizeof(cs));
3386 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3387 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3388 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3389 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003390 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003391 rinfo.bytes_rcvd = cs.bytesReceived;
3392 rinfo.packets_rcvd = cs.packetsReceived;
3393 // The next four fields are from the most recently sent RTCP report.
3394 // Convert Q8 to floating point.
3395 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3396 rinfo.packets_lost = cs.cumulativeLost;
3397 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003398 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003399 if (codec.pltype != -1) {
3400 rinfo.codec_name = codec.plname;
3401 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003402 // Convert samples to milliseconds.
3403 if (codec.plfreq / 1000 > 0) {
3404 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3405 }
3406
3407 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3408 webrtc::NetworkStatistics ns;
3409 if (engine()->voe()->neteq() &&
3410 engine()->voe()->neteq()->GetNetworkStatistics(
3411 *it, ns) != -1) {
3412 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3413 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3414 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003415 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003416 rinfo.speech_expand_rate =
3417 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3418 rinfo.secondary_decoded_rate =
3419 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003420 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003421
3422 webrtc::AudioDecodingCallStats ds;
3423 if (engine()->voe()->neteq() &&
3424 engine()->voe()->neteq()->GetDecodingCallStatistics(
3425 *it, &ds) != -1) {
3426 rinfo.decoding_calls_to_silence_generator =
3427 ds.calls_to_silence_generator;
3428 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3429 rinfo.decoding_normal = ds.decoded_normal;
3430 rinfo.decoding_plc = ds.decoded_plc;
3431 rinfo.decoding_cng = ds.decoded_cng;
3432 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3433 }
3434
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003435 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003436 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003437 int playout_buffer_delay_ms = 0;
3438 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003439 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3440 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3441 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003442 }
3443
3444 // Get speech level.
3445 rinfo.audio_level = (engine()->voe()->volume()->
3446 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3447 info->receivers.push_back(rinfo);
3448 }
3449 }
3450
3451 return true;
3452}
3453
3454void WebRtcVoiceMediaChannel::GetLastMediaError(
3455 uint32* ssrc, VoiceMediaChannel::Error* error) {
3456 ASSERT(ssrc != NULL);
3457 ASSERT(error != NULL);
3458 FindSsrc(voe_channel(), ssrc);
3459 *error = WebRtcErrorToChannelError(GetLastEngineError());
3460}
3461
3462bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003463 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003464 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003465 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003466 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3467 // This means the error is not limited to a specific channel. Signal the
3468 // message using ssrc=0. If the current channel is sending, use this
3469 // channel for sending the message.
3470 *ssrc = 0;
3471 return true;
3472 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003473 // Check whether this is a sending channel.
3474 for (ChannelMap::const_iterator it = send_channels_.begin();
3475 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003476 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003477 // This is a sending channel.
3478 uint32 local_ssrc = 0;
3479 if (engine()->voe()->rtp()->GetLocalSSRC(
3480 channel_num, local_ssrc) != -1) {
3481 *ssrc = local_ssrc;
3482 }
3483 return true;
3484 }
3485 }
3486
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003487 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003488 for (ChannelMap::const_iterator it = receive_channels_.begin();
3489 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003490 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003491 *ssrc = it->first;
3492 return true;
3493 }
3494 }
3495 }
3496 return false;
3497}
3498
3499void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003500 if (error == VE_TYPING_NOISE_WARNING) {
3501 typing_noise_detected_ = true;
3502 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3503 typing_noise_detected_ = false;
3504 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003505 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3506}
3507
3508int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3509 unsigned int ulevel;
3510 int ret =
3511 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3512 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3513}
3514
3515int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003516 ChannelMap::iterator it = receive_channels_.find(ssrc);
3517 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003518 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003519 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3520}
3521
3522int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003523 ChannelMap::iterator it = send_channels_.find(ssrc);
3524 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003525 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003526
3527 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003528}
3529
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003530bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
3531 webrtc::VideoEngine* vie, int vie_channel) {
3532 shared_bwe_vie_ = vie;
3533 shared_bwe_vie_channel_ = vie_channel;
3534
3535 if (!SetupSharedBweOnChannel(voe_channel())) {
3536 return false;
3537 }
3538 for (ChannelMap::iterator it = receive_channels_.begin();
3539 it != receive_channels_.end(); ++it) {
3540 if (!SetupSharedBweOnChannel(it->second->channel())) {
3541 return false;
3542 }
3543 }
3544 return true;
3545}
3546
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003547bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3548 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3549 // Get the RED encodings from the parameter with no name. This may
3550 // change based on what is discussed on the Jingle list.
3551 // The encoding parameter is of the form "a/b"; we only support where
3552 // a == b. Verify this and parse out the value into red_pt.
3553 // If the parameter value is absent (as it will be until we wire up the
3554 // signaling of this message), use the second codec specified (i.e. the
3555 // one after "red") as the encoding parameter.
3556 int red_pt = -1;
3557 std::string red_params;
3558 CodecParameterMap::const_iterator it = red_codec.params.find("");
3559 if (it != red_codec.params.end()) {
3560 red_params = it->second;
3561 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003562 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003563 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003564 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003565 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3566 return false;
3567 }
3568 } else if (red_codec.params.empty()) {
3569 LOG(LS_WARNING) << "RED params not present, using defaults";
3570 if (all_codecs.size() > 1) {
3571 red_pt = all_codecs[1].id;
3572 }
3573 }
3574
3575 // Try to find red_pt in |codecs|.
3576 std::vector<AudioCodec>::const_iterator codec;
3577 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3578 if (codec->id == red_pt)
3579 break;
3580 }
3581
3582 // If we find the right codec, that will be the codec we pass to
3583 // SetSendCodec, with the desired payload type.
3584 if (codec != all_codecs.end() &&
3585 engine()->FindWebRtcCodec(*codec, send_codec)) {
3586 } else {
3587 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3588 return false;
3589 }
3590
3591 return true;
3592}
3593
3594bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3595 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003596 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003597 return false;
3598 }
3599 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3600 // what we want to do with them.
3601 // engine()->voe().EnableVQMon(voe_channel(), true);
3602 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3603 return true;
3604}
3605
3606bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3607 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3608 for (int i = 0; i < ncodecs; ++i) {
3609 webrtc::CodecInst voe_codec;
3610 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3611 voe_codec.pltype = -1;
3612 if (engine()->voe()->codec()->SetRecPayloadType(
3613 channel, voe_codec) == -1) {
3614 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3615 return false;
3616 }
3617 }
3618 }
3619 return true;
3620}
3621
3622bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3623 if (playout) {
3624 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3625 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3626 LOG_RTCERR1(StartPlayout, channel);
3627 return false;
3628 }
3629 } else {
3630 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3631 engine()->voe()->base()->StopPlayout(channel);
3632 }
3633 return true;
3634}
3635
3636uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3637 bool rtcp) {
3638 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3639 uint32 ssrc = 0;
3640 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003641 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003642 }
3643 return ssrc;
3644}
3645
3646// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3647VoiceMediaChannel::Error
3648 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3649 switch (err_code) {
3650 case 0:
3651 return ERROR_NONE;
3652 case VE_CANNOT_START_RECORDING:
3653 case VE_MIC_VOL_ERROR:
3654 case VE_GET_MIC_VOL_ERROR:
3655 case VE_CANNOT_ACCESS_MIC_VOL:
3656 return ERROR_REC_DEVICE_OPEN_FAILED;
3657 case VE_SATURATION_WARNING:
3658 return ERROR_REC_DEVICE_SATURATION;
3659 case VE_REC_DEVICE_REMOVED:
3660 return ERROR_REC_DEVICE_REMOVED;
3661 case VE_RUNTIME_REC_WARNING:
3662 case VE_RUNTIME_REC_ERROR:
3663 return ERROR_REC_RUNTIME_ERROR;
3664 case VE_CANNOT_START_PLAYOUT:
3665 case VE_SPEAKER_VOL_ERROR:
3666 case VE_GET_SPEAKER_VOL_ERROR:
3667 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3668 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3669 case VE_RUNTIME_PLAY_WARNING:
3670 case VE_RUNTIME_PLAY_ERROR:
3671 return ERROR_PLAY_RUNTIME_ERROR;
3672 case VE_TYPING_NOISE_WARNING:
3673 return ERROR_REC_TYPING_NOISE_DETECTED;
3674 default:
3675 return VoiceMediaChannel::ERROR_OTHER;
3676 }
3677}
3678
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003679bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3680 int channel_id, const RtpHeaderExtension* extension) {
3681 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003682 int id = 0;
3683 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003684 if (extension) {
3685 enable = true;
3686 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003687 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003688 }
3689 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003690 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003691 return false;
3692 }
3693 return true;
3694}
3695
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003696bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
3697 webrtc::ViENetwork* vie_network = NULL;
3698 int vie_channel = -1;
3699 if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
3700 shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
3701 vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
3702 vie_channel = shared_bwe_vie_channel_;
3703 }
3704 if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
3705 vie_channel) == -1) {
3706 LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
3707 if (vie_network != NULL) {
3708 // Don't fail if we're tearing down.
3709 return false;
3710 }
3711 }
3712 return true;
3713}
3714
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003715int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003716 size_t res = 0;
3717 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003718 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003719}
3720
3721int WebRtcSoundclipStream::Rewind() {
3722 mem_.Rewind();
3723 // Return -1 to keep VoiceEngine from looping.
3724 return (loop_) ? 0 : -1;
3725}
3726
3727} // namespace cricket
3728
3729#endif // HAVE_WEBRTC_VOICE