blob: 282c0334ce03fb514b9ab9752da7e117a0ed4274 [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);
bjornv@webrtc.org3f118232015-03-16 14:22:03 +0000827 echo_cancellation = false;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000828 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
829 }
830 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000831 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
832 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
833 return false;
834 } else {
835 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
836 << " with mode " << ec_mode;
837 }
838#if !defined(ANDROID)
839 // TODO(ajm): Remove the error return on Android from webrtc.
840 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
841 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
842 return false;
843 }
844#endif
845 if (ec_mode == webrtc::kEcAecm) {
846 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
847 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
848 return false;
849 }
850 }
851 }
852
853 bool auto_gain_control;
854 if (options.auto_gain_control.Get(&auto_gain_control)) {
855 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
856 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
857 return false;
858 } else {
859 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
860 << " with mode " << agc_mode;
861 }
862 }
863
864 if (options.tx_agc_target_dbov.IsSet() ||
865 options.tx_agc_digital_compression_gain.IsSet() ||
866 options.tx_agc_limiter.IsSet()) {
867 // Override default_agc_config_. Generally, an unset option means "leave
868 // the VoE bits alone" in this function, so we want whatever is set to be
869 // stored as the new "default". If we didn't, then setting e.g.
870 // tx_agc_target_dbov would reset digital compression gain and limiter
871 // settings.
872 // Also, if we don't update default_agc_config_, then adjust_agc_delta
873 // would be an offset from the original values, and not whatever was set
874 // explicitly.
875 default_agc_config_.targetLeveldBOv =
876 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
877 default_agc_config_.targetLeveldBOv);
878 default_agc_config_.digitalCompressionGaindB =
879 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
880 default_agc_config_.digitalCompressionGaindB);
881 default_agc_config_.limiterEnable =
882 options.tx_agc_limiter.GetWithDefaultIfUnset(
883 default_agc_config_.limiterEnable);
884 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
885 LOG_RTCERR3(SetAgcConfig,
886 default_agc_config_.targetLeveldBOv,
887 default_agc_config_.digitalCompressionGaindB,
888 default_agc_config_.limiterEnable);
889 return false;
890 }
891 }
892
893 bool noise_suppression;
894 if (options.noise_suppression.Get(&noise_suppression)) {
895 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
896 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
897 return false;
898 } else {
899 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
900 << " with mode " << ns_mode;
901 }
902 }
903
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000904 bool highpass_filter;
905 if (options.highpass_filter.Get(&highpass_filter)) {
906 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
907 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
908 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
909 return false;
910 }
911 }
912
913 bool stereo_swapping;
914 if (options.stereo_swapping.Get(&stereo_swapping)) {
915 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
916 voep->EnableStereoChannelSwapping(stereo_swapping);
917 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
918 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
919 return false;
920 }
921 }
922
923 bool typing_detection;
924 if (options.typing_detection.Get(&typing_detection)) {
925 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
926 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
927 // In case of error, log the info and continue
928 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
929 }
930 }
931
932 int adjust_agc_delta;
933 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
934 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
935 if (!AdjustAgcLevel(adjust_agc_delta)) {
936 return false;
937 }
938 }
939
940 bool aec_dump;
941 if (options.aec_dump.Get(&aec_dump)) {
942 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
943 if (aec_dump)
944 StartAecDump(kAecDumpByAudioOptionFilename);
945 else
946 StopAecDump();
947 }
948
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000949 webrtc::Config config;
950
951 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000952 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000953 if (experimental_aec_.Get(&experimental_aec)) {
954 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
955 config.Set<webrtc::DelayCorrection>(
956 new webrtc::DelayCorrection(experimental_aec));
957 }
958
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000959 experimental_ns_.SetFrom(options.experimental_ns);
960 bool experimental_ns;
961 if (experimental_ns_.Get(&experimental_ns)) {
962 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
963 config.Set<webrtc::ExperimentalNs>(
964 new webrtc::ExperimentalNs(experimental_ns));
965 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000966
967 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
968 // returns NULL on audio_processing().
969 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
970 if (audioproc) {
971 audioproc->SetExtraOptions(config);
972 }
973
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000974 uint32 recording_sample_rate;
975 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
976 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
977 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
978 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
979 }
980 }
981
982 uint32 playout_sample_rate;
983 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
984 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
985 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
986 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
987 }
988 }
989
990 return true;
991}
992
993bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
994 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
995 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
996 LOG_RTCERR1(SetDelayOffsetMs, offset);
997 return false;
998 }
999
1000 return true;
1001}
1002
1003struct ResumeEntry {
1004 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
1005 : channel(c),
1006 playout(p),
1007 send(s) {
1008 }
1009
1010 WebRtcVoiceMediaChannel *channel;
1011 bool playout;
1012 SendFlags send;
1013};
1014
1015// TODO(juberti): Refactor this so that the core logic can be used to set the
1016// soundclip device. At that time, reinstate the soundclip pause/resume code.
1017bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
1018 const Device* out_device) {
1019#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001020 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001021 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001022 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001023 kDefaultAudioDeviceId;
1024 // The device manager uses -1 as the default device, which was the case for
1025 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
1026#ifndef WIN32
1027 if (-1 == in_id) {
1028 in_id = kDefaultAudioDeviceId;
1029 }
1030 if (-1 == out_id) {
1031 out_id = kDefaultAudioDeviceId;
1032 }
1033#endif
1034
1035 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
1036 in_device->name : "Default device";
1037 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
1038 out_device->name : "Default device";
1039 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
1040 << ") and speaker to (id=" << out_id << ", name=" << out_name
1041 << ")";
1042
1043 // If we're running the local monitor, we need to stop it first.
1044 bool ret = true;
1045 if (!PauseLocalMonitor()) {
1046 LOG(LS_WARNING) << "Failed to pause local monitor";
1047 ret = false;
1048 }
1049
1050 // Must also pause all audio playback and capture.
1051 for (ChannelList::const_iterator i = channels_.begin();
1052 i != channels_.end(); ++i) {
1053 WebRtcVoiceMediaChannel *channel = *i;
1054 if (!channel->PausePlayout()) {
1055 LOG(LS_WARNING) << "Failed to pause playout";
1056 ret = false;
1057 }
1058 if (!channel->PauseSend()) {
1059 LOG(LS_WARNING) << "Failed to pause send";
1060 ret = false;
1061 }
1062 }
1063
1064 // Find the recording device id in VoiceEngine and set recording device.
1065 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1066 ret = false;
1067 }
1068 if (ret) {
1069 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
1070 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
1071 ret = false;
1072 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00001073 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
1074 if (ap)
1075 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001076 }
1077
1078 // Find the playout device id in VoiceEngine and set playout device.
1079 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1080 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1081 ret = false;
1082 }
1083 if (ret) {
1084 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001085 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001086 ret = false;
1087 }
1088 }
1089
1090 // Resume all audio playback and capture.
1091 for (ChannelList::const_iterator i = channels_.begin();
1092 i != channels_.end(); ++i) {
1093 WebRtcVoiceMediaChannel *channel = *i;
1094 if (!channel->ResumePlayout()) {
1095 LOG(LS_WARNING) << "Failed to resume playout";
1096 ret = false;
1097 }
1098 if (!channel->ResumeSend()) {
1099 LOG(LS_WARNING) << "Failed to resume send";
1100 ret = false;
1101 }
1102 }
1103
1104 // Resume local monitor.
1105 if (!ResumeLocalMonitor()) {
1106 LOG(LS_WARNING) << "Failed to resume local monitor";
1107 ret = false;
1108 }
1109
1110 if (ret) {
1111 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1112 << ") and speaker to (id="<< out_id << " name=" << out_name
1113 << ")";
1114 }
1115
1116 return ret;
1117#else
1118 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001119#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001120}
1121
1122bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1123 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1124 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001125#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001126 *rtc_id = dev_id;
1127 return true;
1128#else
1129 // In Windows and Mac, we need to find the VoiceEngine device id by name
1130 // unless the input dev_id is the default device id.
1131 if (kDefaultAudioDeviceId == dev_id) {
1132 *rtc_id = dev_id;
1133 return true;
1134 }
1135
1136 // Get the number of VoiceEngine audio devices.
1137 int count = 0;
1138 if (is_input) {
1139 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1140 LOG_RTCERR0(GetNumOfRecordingDevices);
1141 return false;
1142 }
1143 } else {
1144 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1145 LOG_RTCERR0(GetNumOfPlayoutDevices);
1146 return false;
1147 }
1148 }
1149
1150 for (int i = 0; i < count; ++i) {
1151 char name[128];
1152 char guid[128];
1153 if (is_input) {
1154 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1155 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1156 } else {
1157 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1158 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1159 }
1160
1161 std::string webrtc_name(name);
1162 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1163 *rtc_id = i;
1164 return true;
1165 }
1166 }
1167 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1168 return false;
1169#endif
1170}
1171
1172bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1173 unsigned int ulevel;
1174 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1175 LOG_RTCERR1(GetSpeakerVolume, level);
1176 return false;
1177 }
1178 *level = ulevel;
1179 return true;
1180}
1181
1182bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1183 ASSERT(level >= 0 && level <= 255);
1184 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1185 LOG_RTCERR1(SetSpeakerVolume, level);
1186 return false;
1187 }
1188 return true;
1189}
1190
1191int WebRtcVoiceEngine::GetInputLevel() {
1192 unsigned int ulevel;
1193 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1194 static_cast<int>(ulevel) : -1;
1195}
1196
1197bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1198 desired_local_monitor_enable_ = enable;
1199 return ChangeLocalMonitor(desired_local_monitor_enable_);
1200}
1201
1202bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1203 // The voe file api is not available in chrome.
1204 if (!voe_wrapper_->file()) {
1205 return false;
1206 }
1207 if (enable && !monitor_) {
1208 monitor_.reset(new WebRtcMonitorStream);
1209 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1210 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1211 // Must call Stop() because there are some cases where Start will report
1212 // failure but still change the state, and if we leave VE in the on state
1213 // then it could crash later when trying to invoke methods on our monitor.
1214 voe_wrapper_->file()->StopRecordingMicrophone();
1215 monitor_.reset();
1216 return false;
1217 }
1218 } else if (!enable && monitor_) {
1219 voe_wrapper_->file()->StopRecordingMicrophone();
1220 monitor_.reset();
1221 }
1222 return true;
1223}
1224
1225bool WebRtcVoiceEngine::PauseLocalMonitor() {
1226 return ChangeLocalMonitor(false);
1227}
1228
1229bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1230 return ChangeLocalMonitor(desired_local_monitor_enable_);
1231}
1232
1233const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1234 return codecs_;
1235}
1236
1237bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1238 return FindWebRtcCodec(in, NULL);
1239}
1240
1241// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1242bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1243 webrtc::CodecInst* out) {
1244 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1245 for (int i = 0; i < ncodecs; ++i) {
1246 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001247 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001248 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1249 voe_codec.rate, voe_codec.channels, 0);
1250 bool multi_rate = IsCodecMultiRate(voe_codec);
1251 // Allow arbitrary rates for ISAC to be specified.
1252 if (multi_rate) {
1253 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1254 codec.bitrate = 0;
1255 }
1256 if (codec.Matches(in)) {
1257 if (out) {
1258 // Fixup the payload type.
1259 voe_codec.pltype = in.id;
1260
1261 // Set bitrate if specified.
1262 if (multi_rate && in.bitrate != 0) {
1263 voe_codec.rate = in.bitrate;
1264 }
1265
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001266 // Reset G722 sample rate to 16000 to match WebRTC.
1267 MaybeFixupG722(&voe_codec, 16000);
1268
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001269 // Apply codec-specific settings.
1270 if (IsIsac(codec)) {
1271 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001272 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001273 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1274 }
1275 *out = voe_codec;
1276 }
1277 return true;
1278 }
1279 }
1280 }
1281 return false;
1282}
1283const std::vector<RtpHeaderExtension>&
1284WebRtcVoiceEngine::rtp_header_extensions() const {
1285 return rtp_header_extensions_;
1286}
1287
1288void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1289 // if min_sev == -1, we keep the current log level.
1290 if (min_sev >= 0) {
1291 SetTraceFilter(SeverityToFilter(min_sev));
1292 }
1293 log_options_ = filter;
1294 SetTraceOptions(initialized_ ? log_options_ : "");
1295}
1296
1297int WebRtcVoiceEngine::GetLastEngineError() {
1298 return voe_wrapper_->error();
1299}
1300
1301void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1302 log_filter_ = filter;
1303 tracing_->SetTraceFilter(filter);
1304}
1305
1306// We suppport three different logging settings for VoiceEngine:
1307// 1. Observer callback that goes into talk diagnostic logfile.
1308// Use --logfile and --loglevel
1309//
1310// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1311// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1312//
1313// 3. EC log and dump for debugging QualityEngine.
1314// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1315//
1316// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1317// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1318void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1319 // Set encrypted trace file.
1320 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001321 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001322 std::vector<std::string>::iterator tracefile =
1323 std::find(opts.begin(), opts.end(), "tracefile");
1324 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1325 // Write encrypted debug output (at same loglevel) to file
1326 // EncryptedTraceFile no longer supported.
1327 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1328 LOG_RTCERR1(SetTraceFile, *tracefile);
1329 }
1330 }
1331
wu@webrtc.org97077a32013-10-25 21:18:33 +00001332 // Allow trace options to override the trace filter. We default
1333 // it to log_filter_ (as a translation of libjingle log levels)
1334 // elsewhere, but this allows clients to explicitly set webrtc
1335 // log levels.
1336 std::vector<std::string>::iterator tracefilter =
1337 std::find(opts.begin(), opts.end(), "tracefilter");
1338 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001339 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001340 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1341 }
1342 }
1343
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001344 // Set AEC dump file
1345 std::vector<std::string>::iterator recordEC =
1346 std::find(opts.begin(), opts.end(), "recordEC");
1347 if (recordEC != opts.end()) {
1348 ++recordEC;
1349 if (recordEC != opts.end())
1350 StartAecDump(recordEC->c_str());
1351 else
1352 StopAecDump();
1353 }
1354}
1355
1356// Ignore spammy trace messages, mostly from the stats API when we haven't
1357// gotten RTCP info yet from the remote side.
1358bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1359 static const char* kTracesToIgnore[] = {
1360 "\tfailed to GetReportBlockInformation",
1361 "GetRecCodec() failed to get received codec",
1362 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1363 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1364 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1365 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1366 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1367 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1368 "SenderInfoReceived No received SR",
1369 "StatisticsRTP() no statistics available",
1370 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1371 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1372 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1373 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1374 NULL
1375 };
1376 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1377 if (trace.find(*p) != std::string::npos) {
1378 return true;
1379 }
1380 }
1381 return false;
1382}
1383
1384void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1385 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001386 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001387 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001388 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001389 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001390 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001391 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001392 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001393 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001394 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001395
1396 // Skip past boilerplate prefix text
1397 if (length < 72) {
1398 std::string msg(trace, length);
1399 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1400 LOG_V(sev) << msg;
1401 } else {
1402 std::string msg(trace + 71, length - 72);
1403 if (!ShouldIgnoreTrace(msg)) {
1404 LOG_V(sev) << "webrtc: " << msg;
1405 }
1406 }
1407}
1408
1409void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001410 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001411 WebRtcVoiceMediaChannel* channel = NULL;
1412 uint32 ssrc = 0;
1413 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1414 << channel_num << ".";
1415 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1416 ASSERT(channel != NULL);
1417 channel->OnError(ssrc, err_code);
1418 } else {
1419 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1420 << " could not be found in channel list when error reported.";
1421 }
1422}
1423
1424bool WebRtcVoiceEngine::FindChannelAndSsrc(
1425 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1426 ASSERT(channel != NULL && ssrc != NULL);
1427
1428 *channel = NULL;
1429 *ssrc = 0;
1430 // Find corresponding channel and ssrc
1431 for (ChannelList::const_iterator it = channels_.begin();
1432 it != channels_.end(); ++it) {
1433 ASSERT(*it != NULL);
1434 if ((*it)->FindSsrc(channel_num, ssrc)) {
1435 *channel = *it;
1436 return true;
1437 }
1438 }
1439
1440 return false;
1441}
1442
1443// This method will search through the WebRtcVoiceMediaChannels and
1444// obtain the voice engine's channel number.
1445bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1446 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1447 ASSERT(channel_num != NULL);
1448 ASSERT(direction == MPD_RX || direction == MPD_TX);
1449
1450 *channel_num = -1;
1451 // Find corresponding channel for ssrc.
1452 for (ChannelList::const_iterator it = channels_.begin();
1453 it != channels_.end(); ++it) {
1454 ASSERT(*it != NULL);
1455 if (direction & MPD_RX) {
1456 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1457 }
1458 if (*channel_num == -1 && (direction & MPD_TX)) {
1459 *channel_num = (*it)->GetSendChannelNum(ssrc);
1460 }
1461 if (*channel_num != -1) {
1462 return true;
1463 }
1464 }
1465 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1466 return false;
1467}
1468
1469void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001470 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471 channels_.push_back(channel);
1472}
1473
1474void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001475 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001476 ChannelList::iterator i = std::find(channels_.begin(),
1477 channels_.end(),
1478 channel);
1479 if (i != channels_.end()) {
1480 channels_.erase(i);
1481 }
1482}
1483
1484void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1485 soundclips_.push_back(soundclip);
1486}
1487
1488void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1489 SoundclipList::iterator i = std::find(soundclips_.begin(),
1490 soundclips_.end(),
1491 soundclip);
1492 if (i != soundclips_.end()) {
1493 soundclips_.erase(i);
1494 }
1495}
1496
1497// Adjusts the default AGC target level by the specified delta.
1498// NB: If we start messing with other config fields, we'll want
1499// to save the current webrtc::AgcConfig as well.
1500bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1501 webrtc::AgcConfig config = default_agc_config_;
1502 config.targetLeveldBOv -= delta;
1503
1504 LOG(LS_INFO) << "Adjusting AGC level from default -"
1505 << default_agc_config_.targetLeveldBOv << "dB to -"
1506 << config.targetLeveldBOv << "dB";
1507
1508 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1509 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1510 return false;
1511 }
1512 return true;
1513}
1514
1515bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1516 webrtc::AudioDeviceModule* adm_sc) {
1517 if (initialized_) {
1518 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1519 return false;
1520 }
1521 if (adm_) {
1522 adm_->Release();
1523 adm_ = NULL;
1524 }
1525 if (adm) {
1526 adm_ = adm;
1527 adm_->AddRef();
1528 }
1529
1530 if (adm_sc_) {
1531 adm_sc_->Release();
1532 adm_sc_ = NULL;
1533 }
1534 if (adm_sc) {
1535 adm_sc_ = adm_sc;
1536 adm_sc_->AddRef();
1537 }
1538 return true;
1539}
1540
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001541bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1542 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001543 if (!aec_dump_file_stream) {
1544 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001545 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001546 LOG(LS_WARNING) << "Could not close file.";
1547 return false;
1548 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001549 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001550 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001551 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001552 LOG_RTCERR0(StartDebugRecording);
1553 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001554 return false;
1555 }
1556 is_dumping_aec_ = true;
1557 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001558}
1559
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001560bool WebRtcVoiceEngine::RegisterProcessor(
1561 uint32 ssrc,
1562 VoiceProcessor* voice_processor,
1563 MediaProcessorDirection direction) {
1564 bool register_with_webrtc = false;
1565 int channel_id = -1;
1566 bool success = false;
1567 uint32* processor_ssrc = NULL;
1568 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1569 if (voice_processor == NULL || !found_channel) {
1570 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1571 << " foundChannel: " << found_channel;
1572 return false;
1573 }
1574
1575 webrtc::ProcessingTypes processing_type;
1576 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001577 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001578 if (direction == MPD_RX) {
1579 processing_type = webrtc::kPlaybackAllChannelsMixed;
1580 if (SignalRxMediaFrame.is_empty()) {
1581 register_with_webrtc = true;
1582 processor_ssrc = &rx_processor_ssrc_;
1583 }
1584 SignalRxMediaFrame.connect(voice_processor,
1585 &VoiceProcessor::OnFrame);
1586 } else {
1587 processing_type = webrtc::kRecordingPerChannel;
1588 if (SignalTxMediaFrame.is_empty()) {
1589 register_with_webrtc = true;
1590 processor_ssrc = &tx_processor_ssrc_;
1591 }
1592 SignalTxMediaFrame.connect(voice_processor,
1593 &VoiceProcessor::OnFrame);
1594 }
1595 }
1596 if (register_with_webrtc) {
1597 // TODO(janahan): when registering consider instantiating a
1598 // a VoeMediaProcess object and not make the engine extend the interface.
1599 if (voe()->media() && voe()->media()->
1600 RegisterExternalMediaProcessing(channel_id,
1601 processing_type,
1602 *this) != -1) {
1603 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1604 << channel_id;
1605 *processor_ssrc = ssrc;
1606 success = true;
1607 } else {
1608 LOG_RTCERR2(RegisterExternalMediaProcessing,
1609 channel_id,
1610 processing_type);
1611 success = false;
1612 }
1613 } else {
1614 // If we don't have to register with the engine, we just needed to
1615 // connect a new processor, set success to true;
1616 success = true;
1617 }
1618 return success;
1619}
1620
1621bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1622 MediaProcessorDirection channel_direction,
1623 uint32 ssrc,
1624 VoiceProcessor* voice_processor,
1625 MediaProcessorDirection processor_direction) {
1626 bool success = true;
1627 FrameSignal* signal;
1628 webrtc::ProcessingTypes processing_type;
1629 uint32* processor_ssrc = NULL;
1630 if (channel_direction == MPD_RX) {
1631 signal = &SignalRxMediaFrame;
1632 processing_type = webrtc::kPlaybackAllChannelsMixed;
1633 processor_ssrc = &rx_processor_ssrc_;
1634 } else {
1635 signal = &SignalTxMediaFrame;
1636 processing_type = webrtc::kRecordingPerChannel;
1637 processor_ssrc = &tx_processor_ssrc_;
1638 }
1639
1640 int deregister_id = -1;
1641 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001642 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001643 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1644 signal->disconnect(voice_processor);
1645 int channel_id = -1;
1646 bool found_channel = FindChannelNumFromSsrc(ssrc,
1647 channel_direction,
1648 &channel_id);
1649 if (signal->is_empty() && found_channel) {
1650 deregister_id = channel_id;
1651 }
1652 }
1653 }
1654 if (deregister_id != -1) {
1655 if (voe()->media() &&
1656 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1657 processing_type) != -1) {
1658 *processor_ssrc = 0;
1659 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1660 << deregister_id;
1661 } else {
1662 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1663 deregister_id,
1664 processing_type);
1665 success = false;
1666 }
1667 }
1668 return success;
1669}
1670
1671bool WebRtcVoiceEngine::UnregisterProcessor(
1672 uint32 ssrc,
1673 VoiceProcessor* voice_processor,
1674 MediaProcessorDirection direction) {
1675 bool success = true;
1676 if (voice_processor == NULL) {
1677 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1678 << ssrc;
1679 return false;
1680 }
1681 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1682 success = false;
1683 }
1684 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1685 success = false;
1686 }
1687 return success;
1688}
1689
1690// Implementing method from WebRtc VoEMediaProcess interface
1691// Do not lock mux_channel_cs_ in this callback.
1692void WebRtcVoiceEngine::Process(int channel,
1693 webrtc::ProcessingTypes type,
1694 int16_t audio10ms[],
1695 int length,
1696 int sampling_freq,
1697 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001698 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001699 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1700 if (type == webrtc::kPlaybackAllChannelsMixed) {
1701 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1702 } else if (type == webrtc::kRecordingPerChannel) {
1703 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1704 } else {
1705 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1706 << " channel: " << channel << " type: " << type
1707 << " tx_ssrc: " << tx_processor_ssrc_
1708 << " rx_ssrc: " << rx_processor_ssrc_;
1709 }
1710}
1711
1712void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1713 if (!is_dumping_aec_) {
1714 // Start dumping AEC when we are not dumping.
1715 if (voe_wrapper_->processing()->StartDebugRecording(
1716 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001717 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001718 } else {
1719 is_dumping_aec_ = true;
1720 }
1721 }
1722}
1723
1724void WebRtcVoiceEngine::StopAecDump() {
1725 if (is_dumping_aec_) {
1726 // Stop dumping AEC when we are dumping.
1727 if (voe_wrapper_->processing()->StopDebugRecording() !=
1728 webrtc::AudioProcessing::kNoError) {
1729 LOG_RTCERR0(StopDebugRecording);
1730 }
1731 is_dumping_aec_ = false;
1732 }
1733}
1734
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001735int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001736 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001737}
1738
1739int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1740 return CreateVoiceChannel(voe_wrapper_.get());
1741}
1742
1743int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1744 return CreateVoiceChannel(voe_wrapper_sc_.get());
1745}
1746
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001747class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1748 : public AudioRenderer::Sink {
1749 public:
1750 WebRtcVoiceChannelRenderer(int ch,
1751 webrtc::AudioTransport* voe_audio_transport)
1752 : channel_(ch),
1753 voe_audio_transport_(voe_audio_transport),
1754 renderer_(NULL) {
1755 }
1756 virtual ~WebRtcVoiceChannelRenderer() {
1757 Stop();
1758 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001759
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001760 // Starts the rendering by setting a sink to the renderer to get data
1761 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001762 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001763 // TODO(xians): Make sure Start() is called only once.
1764 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001765 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001766 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001767 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001768 ASSERT(renderer_ == renderer);
1769 return;
1770 }
1771
1772 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1773 // in getUserMedia by default.
1774 renderer->AddChannel(channel_);
1775 renderer->SetSink(this);
1776 renderer_ = renderer;
1777 }
1778
1779 // Stops rendering by setting the sink of the renderer to NULL. No data
1780 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001781 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001782 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001783 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001784 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001785 return;
1786
1787 renderer_->RemoveChannel(channel_);
1788 renderer_->SetSink(NULL);
1789 renderer_ = NULL;
1790 }
1791
1792 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001793 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001794 void OnData(const void* audio_data,
1795 int bits_per_sample,
1796 int sample_rate,
1797 int number_of_channels,
1798 int number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001799 voe_audio_transport_->OnData(channel_,
1800 audio_data,
1801 bits_per_sample,
1802 sample_rate,
1803 number_of_channels,
1804 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001805 }
1806
1807 // Callback from the |renderer_| when it is going away. In case Start() has
1808 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001809 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001810 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001811 // Set |renderer_| to NULL to make sure no more callback will get into
1812 // the renderer.
1813 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001814 }
1815
1816 // Accessor to the VoE channel ID.
1817 int channel() const { return channel_; }
1818
1819 private:
1820 const int channel_;
1821 webrtc::AudioTransport* const voe_audio_transport_;
1822
1823 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1824 // PeerConnection will make sure invalidating the pointer before the object
1825 // goes away.
1826 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001827
1828 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001829 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001830};
1831
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001832// WebRtcVoiceMediaChannel
1833WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1834 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1835 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001836 engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001837 send_bitrate_setting_(false),
1838 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001839 options_(),
1840 dtmf_allowed_(false),
1841 desired_playout_(false),
1842 nack_enabled_(false),
1843 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001844 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001845 desired_send_(SEND_NOTHING),
1846 send_(SEND_NOTHING),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001847 shared_bwe_vie_(NULL),
1848 shared_bwe_vie_channel_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001849 default_receive_ssrc_(0) {
1850 engine->RegisterChannel(this);
1851 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1852 << voe_channel();
1853
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001854 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001855}
1856
1857WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1858 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1859 << voe_channel();
buildbot@webrtc.org6e5c7842014-09-19 06:46:37 +00001860 SetupSharedBandwidthEstimation(NULL, -1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001861
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001862 // Remove any remaining send streams, the default channel will be deleted
1863 // later.
1864 while (!send_channels_.empty())
1865 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001866
1867 // Unregister ourselves from the engine.
1868 engine()->UnregisterChannel(this);
1869 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001870 while (!receive_channels_.empty()) {
1871 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001872 }
1873
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001874 // Delete the default channel.
1875 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001876}
1877
1878bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1879 LOG(LS_INFO) << "Setting voice channel options: "
1880 << options.ToString();
1881
wu@webrtc.orgde305012013-10-31 15:40:38 +00001882 // Check if DSCP value is changed from previous.
1883 bool dscp_option_changed = (options_.dscp != options.dscp);
1884
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001885 // TODO(xians): Add support to set different options for different send
1886 // streams after we support multiple APMs.
1887
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001888 // We retain all of the existing options, and apply the given ones
1889 // on top. This means there is no way to "clear" options such that
1890 // they go back to the engine default.
1891 options_.SetAll(options);
1892
1893 if (send_ != SEND_NOTHING) {
1894 if (!engine()->SetOptionOverrides(options_)) {
1895 LOG(LS_WARNING) <<
1896 "Failed to engine SetOptionOverrides during channel SetOptions.";
1897 return false;
1898 }
1899 } else {
1900 // Will be interpreted when appropriate.
1901 }
1902
wu@webrtc.org97077a32013-10-25 21:18:33 +00001903 // Receiver-side auto gain control happens per channel, so set it here from
1904 // options. Note that, like conference mode, setting it on the engine won't
1905 // have the desired effect, since voice channels don't inherit options from
1906 // the media engine when those options are applied per-channel.
1907 bool rx_auto_gain_control;
1908 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1909 if (engine()->voe()->processing()->SetRxAgcStatus(
1910 voe_channel(), rx_auto_gain_control,
1911 webrtc::kAgcFixedDigital) == -1) {
1912 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1913 return false;
1914 } else {
1915 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1916 << " with mode " << webrtc::kAgcFixedDigital;
1917 }
1918 }
1919 if (options.rx_agc_target_dbov.IsSet() ||
1920 options.rx_agc_digital_compression_gain.IsSet() ||
1921 options.rx_agc_limiter.IsSet()) {
1922 webrtc::AgcConfig config;
1923 // If only some of the options are being overridden, get the current
1924 // settings for the channel and bail if they aren't available.
1925 if (!options.rx_agc_target_dbov.IsSet() ||
1926 !options.rx_agc_digital_compression_gain.IsSet() ||
1927 !options.rx_agc_limiter.IsSet()) {
1928 if (engine()->voe()->processing()->GetRxAgcConfig(
1929 voe_channel(), config) != 0) {
1930 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1931 << "channel " << voe_channel() << ". Since not all rx "
1932 << "agc options are specified, unable to safely set rx "
1933 << "agc options.";
1934 return false;
1935 }
1936 }
1937 config.targetLeveldBOv =
1938 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1939 config.targetLeveldBOv);
1940 config.digitalCompressionGaindB =
1941 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1942 config.digitalCompressionGaindB);
1943 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1944 config.limiterEnable);
1945 if (engine()->voe()->processing()->SetRxAgcConfig(
1946 voe_channel(), config) == -1) {
1947 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1948 config.digitalCompressionGaindB, config.limiterEnable);
1949 return false;
1950 }
1951 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001952 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001953 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001954 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001955 dscp = kAudioDscpValue;
1956 if (MediaChannel::SetDscp(dscp) != 0) {
1957 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1958 }
1959 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001960
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001961 // Force update of Video Engine BWE forwarding to reflect experiment setting.
1962 if (!SetupSharedBandwidthEstimation(shared_bwe_vie_,
1963 shared_bwe_vie_channel_)) {
1964 return false;
1965 }
1966
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001967 LOG(LS_INFO) << "Set voice channel options. Current options: "
1968 << options_.ToString();
1969 return true;
1970}
1971
1972bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1973 const std::vector<AudioCodec>& codecs) {
1974 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001975 LOG(LS_INFO) << "Setting receive voice codecs:";
1976
1977 std::vector<AudioCodec> new_codecs;
1978 // Find all new codecs. We allow adding new codecs but don't allow changing
1979 // the payload type of codecs that is already configured since we might
1980 // already be receiving packets with that payload type.
1981 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001982 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001983 AudioCodec old_codec;
1984 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1985 if (old_codec.id != it->id) {
1986 LOG(LS_ERROR) << it->name << " payload type changed.";
1987 return false;
1988 }
1989 } else {
1990 new_codecs.push_back(*it);
1991 }
1992 }
1993 if (new_codecs.empty()) {
1994 // There are no new codecs to configure. Already configured codecs are
1995 // never removed.
1996 return true;
1997 }
1998
1999 if (playout_) {
2000 // Receive codecs can not be changed while playing. So we temporarily
2001 // pause playout.
2002 PausePlayout();
2003 }
2004
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002005 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002006 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
2007 it != new_codecs.end() && ret; ++it) {
2008 webrtc::CodecInst voe_codec;
2009 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2010 LOG(LS_INFO) << ToString(*it);
2011 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002012 if (default_receive_ssrc_ == 0) {
2013 // Set the receive codecs on the default channel explicitly if the
2014 // default channel is not used by |receive_channels_|, this happens in
2015 // conference mode or in non-conference mode when there is no playout
2016 // channel.
2017 // TODO(xians): Figure out how we use the default channel in conference
2018 // mode.
2019 if (engine()->voe()->codec()->SetRecPayloadType(
2020 voe_channel(), voe_codec) == -1) {
2021 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
2022 ret = false;
2023 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002024 }
2025
2026 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002027 for (ChannelMap::iterator it = receive_channels_.begin();
2028 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002029 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002030 it->second->channel(), voe_codec) == -1) {
2031 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002032 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002033 ret = false;
2034 }
2035 }
2036 } else {
2037 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2038 ret = false;
2039 }
2040 }
2041 if (ret) {
2042 recv_codecs_ = codecs;
2043 }
2044
2045 if (desired_playout_ && !playout_) {
2046 ResumePlayout();
2047 }
2048 return ret;
2049}
2050
2051bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002052 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002053 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002054 engine()->voe()->codec()->SetVADStatus(channel, false);
2055 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002056 engine()->voe()->rtp()->SetREDStatus(channel, false);
2057 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002058
2059 // Scan through the list to figure out the codec to use for sending, along
2060 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002061 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002062 webrtc::CodecInst send_codec;
2063 memset(&send_codec, 0, sizeof(send_codec));
2064
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002065 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002066 bool enable_codec_fec = false;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002067
minyue@webrtc.org26236952014-10-29 02:27:08 +00002068 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002069
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002070 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002071 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2072 it != codecs.end(); ++it) {
2073 // Ignore codecs we don't know about. The negotiation step should prevent
2074 // this, but double-check to be sure.
2075 webrtc::CodecInst voe_codec;
2076 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002077 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002078 continue;
2079 }
2080
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002081 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2082 // Skip telephone-event/CN codec, which will be handled later.
2083 continue;
2084 }
2085
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002086 // We'll use the first codec in the list to actually send audio data.
2087 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002088 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002089 // used is specified in params.
2090 if (IsRedCodec(it->name)) {
2091 // Parse out the RED parameters. If we fail, just ignore RED;
2092 // we don't support all possible params/usage scenarios.
2093 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2094 continue;
2095 }
2096
2097 // Enable redundant encoding of the specified codec. Treat any
2098 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002099 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2100 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2101 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002102 return false;
2103 }
2104 } else {
2105 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002106 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002107 // For Opus as the send codec, we are to enable inband FEC if requested
2108 // and set maximum playback rate.
2109 if (IsOpus(*it)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002110 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
2111 &opus_max_playback_rate);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002112 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002113 }
2114 found_send_codec = true;
2115 break;
2116 }
2117
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002118 if (nack_enabled_ != nack_enabled) {
2119 SetNack(channel, nack_enabled);
2120 nack_enabled_ = nack_enabled;
2121 }
2122
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002123 if (!found_send_codec) {
2124 LOG(LS_WARNING) << "Received empty list of codecs.";
2125 return false;
2126 }
2127
2128 // Set the codec immediately, since SetVADStatus() depends on whether
2129 // the current codec is mono or stereo.
2130 if (!SetSendCodec(channel, send_codec))
2131 return false;
2132
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002133 // FEC should be enabled after SetSendCodec.
2134 if (enable_codec_fec) {
2135 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2136 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002137 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2138 // Enable codec internal FEC. Treat any failure as fatal internal error.
2139 LOG_RTCERR2(SetFECStatus, channel, true);
2140 return false;
2141 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002142 }
2143
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002144 // maxplaybackrate should be set after SetSendCodec.
minyue@webrtc.org26236952014-10-29 02:27:08 +00002145 // If opus_max_playback_rate <= 0, the default maximum playback rate of 48 kHz
2146 // will be used.
2147 if (opus_max_playback_rate > 0) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002148 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002149 << opus_max_playback_rate
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002150 << " Hz on channel "
2151 << channel;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002152 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
minyue@webrtc.org26236952014-10-29 02:27:08 +00002153 channel, opus_max_playback_rate) == -1) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002154 LOG(LS_WARNING) << "Could not set maximum playback rate.";
2155 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002156 }
2157
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002158 // Always update the |send_codec_| to the currently set send codec.
2159 send_codec_.reset(new webrtc::CodecInst(send_codec));
2160
minyue@webrtc.org26236952014-10-29 02:27:08 +00002161 if (send_bitrate_setting_) {
2162 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002163 }
2164
2165 // Loop through the codecs list again to config the telephone-event/CN codec.
2166 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2167 it != codecs.end(); ++it) {
2168 // Ignore codecs we don't know about. The negotiation step should prevent
2169 // this, but double-check to be sure.
2170 webrtc::CodecInst voe_codec;
2171 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2172 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2173 continue;
2174 }
2175
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002176 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2177 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002178 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002179 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2180 channel, it->id) == -1) {
2181 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2182 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002183 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002184 } else if (IsCNCodec(it->name)) {
2185 // Turn voice activity detection/comfort noise on if supported.
2186 // Set the wideband CN payload type appropriately.
2187 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002188 webrtc::PayloadFrequencies cn_freq;
2189 switch (it->clockrate) {
2190 case 8000:
2191 cn_freq = webrtc::kFreq8000Hz;
2192 break;
2193 case 16000:
2194 cn_freq = webrtc::kFreq16000Hz;
2195 break;
2196 case 32000:
2197 cn_freq = webrtc::kFreq32000Hz;
2198 break;
2199 default:
2200 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2201 << " not supported.";
2202 continue;
2203 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002204 // Set the CN payloadtype and the VAD status.
2205 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2206 if (cn_freq != webrtc::kFreq8000Hz) {
2207 if (engine()->voe()->codec()->SetSendCNPayloadType(
2208 channel, it->id, cn_freq) == -1) {
2209 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2210 // TODO(ajm): This failure condition will be removed from VoE.
2211 // Restore the return here when we update to a new enough webrtc.
2212 //
2213 // Not returning false because the SetSendCNPayloadType will fail if
2214 // the channel is already sending.
2215 // This can happen if the remote description is applied twice, for
2216 // example in the case of ROAP on top of JSEP, where both side will
2217 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002218 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002219 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002220 // Only turn on VAD if we have a CN payload type that matches the
2221 // clockrate for the codec we are going to use.
2222 if (it->clockrate == send_codec.plfreq) {
2223 LOG(LS_INFO) << "Enabling VAD";
2224 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2225 LOG_RTCERR2(SetVADStatus, channel, true);
2226 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002227 }
2228 }
2229 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002230 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002231 return true;
2232}
2233
2234bool WebRtcVoiceMediaChannel::SetSendCodecs(
2235 const std::vector<AudioCodec>& codecs) {
2236 dtmf_allowed_ = false;
2237 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2238 it != codecs.end(); ++it) {
2239 // Find the DTMF telephone event "codec".
2240 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2241 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2242 dtmf_allowed_ = true;
2243 }
2244 }
2245
2246 // Cache the codecs in order to configure the channel created later.
2247 send_codecs_ = codecs;
2248 for (ChannelMap::iterator iter = send_channels_.begin();
2249 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002250 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002251 return false;
2252 }
2253 }
2254
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002255 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002256 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002257 return true;
2258}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002259
2260void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2261 bool nack_enabled) {
2262 for (ChannelMap::const_iterator it = channels.begin();
2263 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002264 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002265 }
2266}
2267
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002268void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002269 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002270 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002271 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2272 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002273 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002274 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2275 }
2276}
2277
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002278bool WebRtcVoiceMediaChannel::SetSendCodec(
2279 const webrtc::CodecInst& send_codec) {
2280 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2281 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002282 for (ChannelMap::iterator iter = send_channels_.begin();
2283 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002284 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002285 return false;
2286 }
2287
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002288 return true;
2289}
2290
2291bool WebRtcVoiceMediaChannel::SetSendCodec(
2292 int channel, const webrtc::CodecInst& send_codec) {
2293 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2294 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2295
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002296 webrtc::CodecInst current_codec;
2297 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2298 (send_codec == current_codec)) {
2299 // Codec is already configured, we can return without setting it again.
2300 return true;
2301 }
2302
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002303 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2304 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002305 return false;
2306 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002307 return true;
2308}
2309
2310bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2311 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002312 if (receive_extensions_ == extensions) {
2313 return true;
2314 }
2315
2316 // The default channel may or may not be in |receive_channels_|. Set the rtp
2317 // header extensions for default channel regardless.
2318 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2319 return false;
2320 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002321
2322 // Loop through all receive channels and enable/disable the extensions.
2323 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2324 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002325 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2326 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002327 return false;
2328 }
2329 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002330
2331 receive_extensions_ = extensions;
2332 return true;
2333}
2334
2335bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2336 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002337 const RtpHeaderExtension* audio_level_extension =
2338 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2339 if (!SetHeaderExtension(
2340 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2341 audio_level_extension)) {
2342 return false;
2343 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002344
2345 const RtpHeaderExtension* send_time_extension =
2346 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2347 if (!SetHeaderExtension(
2348 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2349 send_time_extension)) {
2350 return false;
2351 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002352 return true;
2353}
2354
2355bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2356 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002357 if (send_extensions_ == extensions) {
2358 return true;
2359 }
2360
2361 // The default channel may or may not be in |send_channels_|. Set the rtp
2362 // header extensions for default channel regardless.
2363
2364 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2365 return false;
2366 }
2367
2368 // Loop through all send channels and enable/disable the extensions.
2369 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2370 channel_it != send_channels_.end(); ++channel_it) {
2371 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2372 extensions)) {
2373 return false;
2374 }
2375 }
2376
2377 send_extensions_ = extensions;
2378 return true;
2379}
2380
2381bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2382 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002383 const RtpHeaderExtension* audio_level_extension =
2384 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002385
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002386 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002387 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002388 audio_level_extension)) {
2389 return false;
2390 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002391
2392 const RtpHeaderExtension* send_time_extension =
2393 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002394 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002395 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002396 send_time_extension)) {
2397 return false;
2398 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002399
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002400 return true;
2401}
2402
2403bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2404 desired_playout_ = playout;
2405 return ChangePlayout(desired_playout_);
2406}
2407
2408bool WebRtcVoiceMediaChannel::PausePlayout() {
2409 return ChangePlayout(false);
2410}
2411
2412bool WebRtcVoiceMediaChannel::ResumePlayout() {
2413 return ChangePlayout(desired_playout_);
2414}
2415
2416bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2417 if (playout_ == playout) {
2418 return true;
2419 }
2420
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002421 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002422 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002423 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002424 // Only toggle the default channel if we don't have any other channels.
2425 result = SetPlayout(voe_channel(), playout);
2426 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002427 for (ChannelMap::iterator it = receive_channels_.begin();
2428 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002429 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002430 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002431 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002432 result = false;
2433 }
2434 }
2435
2436 if (result) {
2437 playout_ = playout;
2438 }
2439 return result;
2440}
2441
2442bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2443 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002444 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002445 return ChangeSend(desired_send_);
2446 return true;
2447}
2448
2449bool WebRtcVoiceMediaChannel::PauseSend() {
2450 return ChangeSend(SEND_NOTHING);
2451}
2452
2453bool WebRtcVoiceMediaChannel::ResumeSend() {
2454 return ChangeSend(desired_send_);
2455}
2456
2457bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2458 if (send_ == send) {
2459 return true;
2460 }
2461
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002462 // Change the settings on each send channel.
2463 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002464 engine()->SetOptionOverrides(options_);
2465
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002466 // Change the settings on each send channel.
2467 for (ChannelMap::iterator iter = send_channels_.begin();
2468 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002469 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002470 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002471 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002472
2473 // Clear up the options after stopping sending.
2474 if (send == SEND_NOTHING)
2475 engine()->ClearOptionOverrides();
2476
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002477 send_ = send;
2478 return true;
2479}
2480
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002481bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2482 if (send == SEND_MICROPHONE) {
2483 if (engine()->voe()->base()->StartSend(channel) == -1) {
2484 LOG_RTCERR1(StartSend, channel);
2485 return false;
2486 }
2487 if (engine()->voe()->file() &&
2488 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2489 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2490 return false;
2491 }
2492 } else { // SEND_NOTHING
2493 ASSERT(send == SEND_NOTHING);
2494 if (engine()->voe()->base()->StopSend(channel) == -1) {
2495 LOG_RTCERR1(StopSend, channel);
2496 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002497 }
2498 }
2499
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002500 return true;
2501}
2502
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002503// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002504void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2505 if (engine()->voe()->network()->RegisterExternalTransport(
2506 channel, *this) == -1) {
2507 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2508 }
2509
2510 // Enable RTCP (for quality stats and feedback messages)
2511 EnableRtcp(channel);
2512
2513 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2514 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002515
2516 // Set RTP header extension for the new channel.
2517 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002518}
2519
2520bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2521 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2522 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2523 }
2524
2525 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2526 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002527 return false;
2528 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002529
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002530 return true;
2531}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002532
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002533bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2534 // If the default channel is already used for sending create a new channel
2535 // otherwise use the default channel for sending.
2536 int channel = GetSendChannelNum(sp.first_ssrc());
2537 if (channel != -1) {
2538 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2539 return false;
2540 }
2541
2542 bool default_channel_is_available = true;
2543 for (ChannelMap::const_iterator iter = send_channels_.begin();
2544 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002545 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002546 default_channel_is_available = false;
2547 break;
2548 }
2549 }
2550 if (default_channel_is_available) {
2551 channel = voe_channel();
2552 } else {
2553 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002554 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002555 if (channel == -1) {
2556 LOG_RTCERR0(CreateChannel);
2557 return false;
2558 }
2559
2560 ConfigureSendChannel(channel);
2561 }
2562
2563 // Save the channel to send_channels_, so that RemoveSendStream() can still
2564 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002565 webrtc::AudioTransport* audio_transport =
2566 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002567 send_channels_.insert(std::make_pair(
2568 sp.first_ssrc(),
2569 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002570
2571 // Set the send (local) SSRC.
2572 // If there are multiple send SSRCs, we can only set the first one here, and
2573 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2574 // (with a codec requires multiple SSRC(s)).
2575 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2576 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2577 return false;
2578 }
2579
2580 // At this point the channel's local SSRC has been updated. If the channel is
2581 // the default channel make sure that all the receive channels are updated as
2582 // well. Receive channels have to have the same SSRC as the default channel in
2583 // order to send receiver reports with this SSRC.
2584 if (IsDefaultChannel(channel)) {
2585 for (ChannelMap::const_iterator it = receive_channels_.begin();
2586 it != receive_channels_.end(); ++it) {
2587 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002588 if (!IsDefaultChannel(it->second->channel())) {
2589 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002590 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002591 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002592 return false;
2593 }
2594 }
2595 }
2596 }
2597
2598 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002599 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2600 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002601 }
2602
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002603 // Set the current codecs to be used for the new channel.
2604 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002605 return false;
2606
2607 return ChangeSend(channel, desired_send_);
2608}
2609
2610bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2611 ChannelMap::iterator it = send_channels_.find(ssrc);
2612 if (it == send_channels_.end()) {
2613 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2614 << " which doesn't exist.";
2615 return false;
2616 }
2617
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002618 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002619 ChangeSend(channel, SEND_NOTHING);
2620
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002621 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2622 // this will disconnect the audio renderer with the send channel.
2623 delete it->second;
2624 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002625
2626 if (IsDefaultChannel(channel)) {
2627 // Do not delete the default channel since the receive channels depend on
2628 // the default channel, recycle it instead.
2629 ChangeSend(channel, SEND_NOTHING);
2630 } else {
2631 // Clean up and delete the send channel.
2632 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2633 << " with VoiceEngine channel #" << channel << ".";
2634 if (!DeleteChannel(channel))
2635 return false;
2636 }
2637
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002638 if (send_channels_.empty())
2639 ChangeSend(SEND_NOTHING);
2640
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002641 return true;
2642}
2643
2644bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002645 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002646
2647 if (!VERIFY(sp.ssrcs.size() == 1))
2648 return false;
2649 uint32 ssrc = sp.first_ssrc();
2650
wu@webrtc.org78187522013-10-07 23:32:02 +00002651 if (ssrc == 0) {
2652 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2653 return false;
2654 }
2655
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002656 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2657 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002658 return false;
2659 }
2660
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002661 // Reuse default channel for recv stream in non-conference mode call
2662 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002663 webrtc::AudioTransport* audio_transport =
2664 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002665 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2666 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2667 << " reuse default channel";
2668 default_receive_ssrc_ = sp.first_ssrc();
2669 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002670 default_receive_ssrc_,
2671 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002672 if (!SetupSharedBweOnChannel(voe_channel())) {
2673 return false;
2674 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002675 return SetPlayout(voe_channel(), playout_);
2676 }
2677
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002678 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002679 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002680 if (channel == -1) {
2681 LOG_RTCERR0(CreateChannel);
2682 return false;
2683 }
2684
wu@webrtc.org78187522013-10-07 23:32:02 +00002685 if (!ConfigureRecvChannel(channel)) {
2686 DeleteChannel(channel);
2687 return false;
2688 }
2689
2690 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002691 std::make_pair(
2692 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002693
2694 LOG(LS_INFO) << "New audio stream " << ssrc
2695 << " registered to VoiceEngine channel #"
2696 << channel << ".";
2697 return true;
2698}
2699
2700bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002701 // Configure to use external transport, like our default channel.
2702 if (engine()->voe()->network()->RegisterExternalTransport(
2703 channel, *this) == -1) {
2704 LOG_RTCERR2(SetExternalTransport, channel, this);
2705 return false;
2706 }
2707
2708 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002709 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002710 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2711 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002712 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002713 return false;
2714 }
2715 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002716 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002717 return false;
2718 }
2719
2720 // Use the same recv payload types as our default channel.
2721 ResetRecvCodecs(channel);
2722 if (!recv_codecs_.empty()) {
2723 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2724 it != recv_codecs_.end(); ++it) {
2725 webrtc::CodecInst voe_codec;
2726 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2727 voe_codec.pltype = it->id;
2728 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2729 if (engine()->voe()->codec()->GetRecPayloadType(
2730 voe_channel(), voe_codec) != -1) {
2731 if (engine()->voe()->codec()->SetRecPayloadType(
2732 channel, voe_codec) == -1) {
2733 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2734 return false;
2735 }
2736 }
2737 }
2738 }
2739 }
2740
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002741 if (InConferenceMode()) {
2742 // To be in par with the video, voe_channel() is not used for receiving in
2743 // a conference call.
2744 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2745 // This is the first stream in a multi user meeting. We can now
2746 // disable playback of the default stream. This since the default
2747 // stream will probably have received some initial packets before
2748 // the new stream was added. This will mean that the CN state from
2749 // the default channel will be mixed in with the other streams
2750 // throughout the whole meeting, which might be disturbing.
2751 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2752 SetPlayout(voe_channel(), false);
2753 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002754 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002755 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002756
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002757 // Set RTP header extension for the new channel.
2758 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2759 return false;
2760 }
2761
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002762 // Set up channel to be able to forward incoming packets to video engine BWE.
2763 if (!SetupSharedBweOnChannel(channel)) {
2764 return false;
2765 }
2766
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002767 return SetPlayout(channel, playout_);
2768}
2769
2770bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002771 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002772 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002773 if (it == receive_channels_.end()) {
2774 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2775 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002776 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002777 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002778
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002779 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2780 // will disconnect the audio renderer with the receive channel.
2781 // Cache the channel before the deletion.
2782 const int channel = it->second->channel();
2783 delete it->second;
2784 receive_channels_.erase(it);
2785
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002786 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002787 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002788 // Recycle the default channel is for recv stream.
2789 if (playout_)
2790 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002791
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002792 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002793 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002794 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002795
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002796 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002797 << " with VoiceEngine channel #" << channel << ".";
2798 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002799 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002800
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002801 bool enable_default_channel_playout = false;
2802 if (receive_channels_.empty()) {
2803 // The last stream was removed. We can now enable the default
2804 // channel for new channels to be played out immediately without
2805 // waiting for AddStream messages.
2806 // We do this for both conference mode and non-conference mode.
2807 // TODO(oja): Does the default channel still have it's CN state?
2808 enable_default_channel_playout = true;
2809 }
2810 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2811 default_receive_ssrc_ != 0) {
2812 // Only the default channel is active, enable the playout on default
2813 // channel.
2814 enable_default_channel_playout = true;
2815 }
2816 if (enable_default_channel_playout && playout_) {
2817 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2818 SetPlayout(voe_channel(), true);
2819 }
2820
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002821 return true;
2822}
2823
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002824bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2825 AudioRenderer* renderer) {
2826 ChannelMap::iterator it = receive_channels_.find(ssrc);
2827 if (it == receive_channels_.end()) {
2828 if (renderer) {
2829 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002830 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002831 return false;
2832 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002833
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002834 // The channel likely has gone away, do nothing.
2835 return true;
2836 }
2837
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002838 if (renderer)
2839 it->second->Start(renderer);
2840 else
2841 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002842
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002843 return true;
2844}
2845
2846bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2847 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002848 ChannelMap::iterator it = send_channels_.find(ssrc);
2849 if (it == send_channels_.end()) {
2850 if (renderer) {
2851 // Return an error if trying to set a valid renderer with an invalid ssrc.
2852 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2853 return false;
2854 }
2855
2856 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002857 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002858 }
2859
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002860 if (renderer)
2861 it->second->Start(renderer);
2862 else
2863 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002864
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002865 return true;
2866}
2867
2868bool WebRtcVoiceMediaChannel::GetActiveStreams(
2869 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002870 // In conference mode, the default channel should not be in
2871 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002872 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002873 for (ChannelMap::iterator it = receive_channels_.begin();
2874 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002875 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002876 if (level > 0) {
2877 actives->push_back(std::make_pair(it->first, level));
2878 }
2879 }
2880 return true;
2881}
2882
2883int WebRtcVoiceMediaChannel::GetOutputLevel() {
2884 // return the highest output level of all streams
2885 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002886 for (ChannelMap::iterator it = receive_channels_.begin();
2887 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002888 int level = GetOutputLevel(it->second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002889 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002890 }
2891 return highest;
2892}
2893
2894int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2895 int ret;
2896 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2897 // In case of error, log the info and continue
2898 LOG_RTCERR0(TimeSinceLastTyping);
2899 ret = -1;
2900 } else {
2901 ret *= 1000; // We return ms, webrtc returns seconds.
2902 }
2903 return ret;
2904}
2905
2906void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2907 int cost_per_typing, int reporting_threshold, int penalty_decay,
2908 int type_event_delay) {
2909 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2910 time_window, cost_per_typing,
2911 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2912 // In case of error, log the info and continue
2913 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2914 cost_per_typing, reporting_threshold, penalty_decay,
2915 type_event_delay);
2916 }
2917}
2918
2919bool WebRtcVoiceMediaChannel::SetOutputScaling(
2920 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002921 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002922 // Collect the channels to scale the output volume.
2923 std::vector<int> channels;
2924 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002925 // Default channel is not in receive_channels_ if it is not being used for
2926 // playout.
2927 if (default_receive_ssrc_ == 0)
2928 channels.push_back(voe_channel());
2929 for (ChannelMap::const_iterator it = receive_channels_.begin();
2930 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002931 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002932 }
2933 } else { // Collect only the channel of the specified ssrc.
2934 int channel = GetReceiveChannelNum(ssrc);
2935 if (-1 == channel) {
2936 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2937 return false;
2938 }
2939 channels.push_back(channel);
2940 }
2941
2942 // Scale the output volume for the collected channels. We first normalize to
2943 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002944 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002945 if (scale > 0.0001f) {
2946 left /= scale;
2947 right /= scale;
2948 }
2949 for (std::vector<int>::const_iterator it = channels.begin();
2950 it != channels.end(); ++it) {
2951 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2952 *it, scale)) {
2953 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2954 return false;
2955 }
2956 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2957 *it, static_cast<float>(left), static_cast<float>(right))) {
2958 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2959 // Do not return if fails. SetOutputVolumePan is not available for all
2960 // pltforms.
2961 }
2962 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2963 << " right=" << right * scale
2964 << " for channel " << *it << " and ssrc " << ssrc;
2965 }
2966 return true;
2967}
2968
2969bool WebRtcVoiceMediaChannel::GetOutputScaling(
2970 uint32 ssrc, double* left, double* right) {
2971 if (!left || !right) return false;
2972
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002973 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002974 // Determine which channel based on ssrc.
2975 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2976 if (channel == -1) {
2977 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2978 return false;
2979 }
2980
2981 float scaling;
2982 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2983 channel, scaling)) {
2984 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2985 return false;
2986 }
2987
2988 float left_pan;
2989 float right_pan;
2990 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2991 channel, left_pan, right_pan)) {
2992 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2993 // If GetOutputVolumePan fails, we use the default left and right pan.
2994 left_pan = 1.0f;
2995 right_pan = 1.0f;
2996 }
2997
2998 *left = scaling * left_pan;
2999 *right = scaling * right_pan;
3000 return true;
3001}
3002
3003bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
3004 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
3005 return true;
3006}
3007
3008bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
3009 bool play, bool loop) {
3010 if (!ringback_tone_) {
3011 return false;
3012 }
3013
3014 // The voe file api is not available in chrome.
3015 if (!engine()->voe()->file()) {
3016 return false;
3017 }
3018
3019 // Determine which VoiceEngine channel to play on.
3020 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
3021 if (channel == -1) {
3022 return false;
3023 }
3024
3025 // Make sure the ringtone is cued properly, and play it out.
3026 if (play) {
3027 ringback_tone_->set_loop(loop);
3028 ringback_tone_->Rewind();
3029 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
3030 ringback_tone_.get()) == -1) {
3031 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
3032 LOG(LS_ERROR) << "Unable to start ringback tone";
3033 return false;
3034 }
3035 ringback_channels_.insert(channel);
3036 LOG(LS_INFO) << "Started ringback on channel " << channel;
3037 } else {
3038 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
3039 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
3040 LOG_RTCERR1(StopPlayingFileLocally, channel);
3041 return false;
3042 }
3043 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
3044 ringback_channels_.erase(channel);
3045 }
3046
3047 return true;
3048}
3049
3050bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3051 return dtmf_allowed_;
3052}
3053
3054bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3055 int duration, int flags) {
3056 if (!dtmf_allowed_) {
3057 return false;
3058 }
3059
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003060 // Send the event.
3061 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003062 int channel = -1;
3063 if (ssrc == 0) {
3064 bool default_channel_is_inuse = false;
3065 for (ChannelMap::const_iterator iter = send_channels_.begin();
3066 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003067 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003068 default_channel_is_inuse = true;
3069 break;
3070 }
3071 }
3072 if (default_channel_is_inuse) {
3073 channel = voe_channel();
3074 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003075 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003076 }
3077 } else {
3078 channel = GetSendChannelNum(ssrc);
3079 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003080 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003081 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3082 << ssrc << " is not in use.";
3083 return false;
3084 }
3085 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003086 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3087 channel, event, true, duration) == -1) {
3088 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003089 return false;
3090 }
3091 }
3092
3093 // Play the event.
3094 if (flags & cricket::DF_PLAY) {
3095 // Play DTMF tone locally.
3096 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3097 LOG_RTCERR2(PlayDtmfTone, event, duration);
3098 return false;
3099 }
3100 }
3101
3102 return true;
3103}
3104
wu@webrtc.orga9890802013-12-13 00:21:03 +00003105void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003106 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003107 // Pick which channel to send this packet to. If this packet doesn't match
3108 // any multiplexed streams, just send it to the default channel. Otherwise,
3109 // send it to the specific decoder instance for that stream.
3110 int which_channel = GetReceiveChannelNum(
3111 ParseSsrc(packet->data(), packet->length(), false));
3112 if (which_channel == -1) {
3113 which_channel = voe_channel();
3114 }
3115
3116 // Stop any ringback that might be playing on the channel.
3117 // It's possible the ringback has already stopped, ih which case we'll just
3118 // use the opportunity to remove the channel from ringback_channels_.
3119 if (engine()->voe()->file()) {
3120 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3121 if (it != ringback_channels_.end()) {
3122 if (engine()->voe()->file()->IsPlayingFileLocally(
3123 which_channel) == 1) {
3124 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3125 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3126 << " due to incoming media";
3127 }
3128 ringback_channels_.erase(which_channel);
3129 }
3130 }
3131
3132 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003133 engine()->voe()->network()->ReceivedRTPPacket(
3134 which_channel,
3135 packet->data(),
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003136 packet->length(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003137 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003138}
3139
wu@webrtc.orga9890802013-12-13 00:21:03 +00003140void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003141 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003142 // Sending channels need all RTCP packets with feedback information.
3143 // Even sender reports can contain attached report blocks.
3144 // Receiving channels need sender reports in order to create
3145 // correct receiver reports.
3146 int type = 0;
3147 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3148 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3149 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003150 }
3151
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003152 // If it is a sender report, find the channel that is listening.
3153 bool has_sent_to_default_channel = false;
3154 if (type == kRtcpTypeSR) {
3155 int which_channel = GetReceiveChannelNum(
3156 ParseSsrc(packet->data(), packet->length(), true));
3157 if (which_channel != -1) {
3158 engine()->voe()->network()->ReceivedRTCPPacket(
3159 which_channel,
3160 packet->data(),
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003161 packet->length());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003162
3163 if (IsDefaultChannel(which_channel))
3164 has_sent_to_default_channel = true;
3165 }
3166 }
3167
3168 // SR may continue RR and any RR entry may correspond to any one of the send
3169 // channels. So all RTCP packets must be forwarded all send channels. VoE
3170 // will filter out RR internally.
3171 for (ChannelMap::iterator iter = send_channels_.begin();
3172 iter != send_channels_.end(); ++iter) {
3173 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003174 if (IsDefaultChannel(iter->second->channel()) &&
3175 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003176 continue;
3177
3178 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003179 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003180 packet->data(),
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003181 packet->length());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003182 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003183}
3184
3185bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003186 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3187 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003188 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3189 return false;
3190 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003191 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3192 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003193 return false;
3194 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003195 // We set the AGC to mute state only when all the channels are muted.
3196 // This implementation is not ideal, instead we should signal the AGC when
3197 // the mic channel is muted/unmuted. We can't do it today because there
3198 // is no good way to know which stream is mapping to the mic channel.
3199 bool all_muted = muted;
3200 for (ChannelMap::const_iterator iter = send_channels_.begin();
3201 iter != send_channels_.end() && all_muted; ++iter) {
3202 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3203 all_muted)) {
3204 LOG_RTCERR1(GetInputMute, iter->second->channel());
3205 return false;
3206 }
3207 }
3208
3209 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3210 if (ap)
3211 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003212 return true;
3213}
3214
minyue@webrtc.org26236952014-10-29 02:27:08 +00003215// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3216// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003217bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003218 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003219
minyue@webrtc.org26236952014-10-29 02:27:08 +00003220 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003221}
3222
minyue@webrtc.org26236952014-10-29 02:27:08 +00003223bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3224 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003225
minyue@webrtc.org26236952014-10-29 02:27:08 +00003226 send_bitrate_setting_ = true;
3227 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003228
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003229 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003230 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003231 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003232 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003233 }
3234
minyue@webrtc.org26236952014-10-29 02:27:08 +00003235 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003236 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3237 // SetMaxSendBandwith(0), the second call removes the previous limit.
3238 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003239 return true;
3240
3241 webrtc::CodecInst codec = *send_codec_;
3242 bool is_multi_rate = IsCodecMultiRate(codec);
3243
3244 if (is_multi_rate) {
3245 // If codec is multi-rate then just set the bitrate.
3246 codec.rate = bps;
3247 if (!SetSendCodec(codec)) {
3248 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3249 << " to bitrate " << bps << " bps.";
3250 return false;
3251 }
3252 return true;
3253 } else {
3254 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3255 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3256 // fixed bitrate then ignore.
3257 if (bps < codec.rate) {
3258 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3259 << " to bitrate " << bps << " bps"
3260 << ", requires at least " << codec.rate << " bps.";
3261 return false;
3262 }
3263 return true;
3264 }
3265}
3266
3267bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003268 bool echo_metrics_on = false;
3269 // These can take on valid negative values, so use the lowest possible level
3270 // as default rather than -1.
3271 int echo_return_loss = -100;
3272 int echo_return_loss_enhancement = -100;
3273 // These can also be negative, but in practice -1 is only used to signal
3274 // insufficient data, since the resolution is limited to multiples of 4 ms.
3275 int echo_delay_median_ms = -1;
3276 int echo_delay_std_ms = -1;
3277 if (engine()->voe()->processing()->GetEcMetricsStatus(
3278 echo_metrics_on) != -1 && echo_metrics_on) {
3279 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3280 // here, but it appears to be unsuitable currently. Revisit after this is
3281 // investigated: http://b/issue?id=5666755
3282 int erl, erle, rerl, anlp;
3283 if (engine()->voe()->processing()->GetEchoMetrics(
3284 erl, erle, rerl, anlp) != -1) {
3285 echo_return_loss = erl;
3286 echo_return_loss_enhancement = erle;
3287 }
3288
3289 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003290 float dummy;
3291 if (engine()->voe()->processing()->GetEcDelayMetrics(
3292 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003293 echo_delay_median_ms = median;
3294 echo_delay_std_ms = std;
3295 }
3296 }
3297
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003298 webrtc::CallStatistics cs;
3299 unsigned int ssrc;
3300 webrtc::CodecInst codec;
3301 unsigned int level;
3302
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003303 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3304 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003305 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003306
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003307 // Fill in the sender info, based on what we know, and what the
3308 // remote side told us it got from its RTCP report.
3309 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003310
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003311 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3312 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3313 continue;
3314 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003315
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003316 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003317 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3318 sinfo.bytes_sent = cs.bytesSent;
3319 sinfo.packets_sent = cs.packetsSent;
3320 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3321 // returns 0 to indicate an error value.
3322 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3323
3324 // Get data from the last remote RTCP report. Use default values if no data
3325 // available.
3326 sinfo.fraction_lost = -1.0;
3327 sinfo.jitter_ms = -1;
3328 sinfo.packets_lost = -1;
3329 sinfo.ext_seqnum = -1;
3330 std::vector<webrtc::ReportBlock> receive_blocks;
3331 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3332 channel, &receive_blocks) != -1 &&
3333 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3334 std::vector<webrtc::ReportBlock>::iterator iter;
3335 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3336 ++iter) {
3337 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003338 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003339 // Convert Q8 to floating point.
3340 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3341 // Convert samples to milliseconds.
3342 if (codec.plfreq / 1000 > 0) {
3343 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3344 }
3345 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3346 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3347 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003348 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003349 }
3350 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003351
3352 // Local speech level.
3353 sinfo.audio_level = (engine()->voe()->volume()->
3354 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3355
3356 // TODO(xians): We are injecting the same APM logging to all the send
3357 // channels here because there is no good way to know which send channel
3358 // is using the APM. The correct fix is to allow the send channels to have
3359 // their own APM so that we can feed the correct APM logging to different
3360 // send channels. See issue crbug/264611 .
3361 sinfo.echo_return_loss = echo_return_loss;
3362 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3363 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3364 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003365 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3366 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003367 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003368
3369 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003370 }
3371
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003372 // Build the list of receivers, one for each receiving channel, or 1 in
3373 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003374 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003375 for (ChannelMap::const_iterator it = receive_channels_.begin();
3376 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003377 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003378 }
3379 if (channels.empty()) {
3380 channels.push_back(voe_channel());
3381 }
3382
3383 // Get the SSRC and stats for each receiver, based on our own calculations.
3384 for (std::vector<int>::const_iterator it = channels.begin();
3385 it != channels.end(); ++it) {
3386 memset(&cs, 0, sizeof(cs));
3387 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3388 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3389 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3390 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003391 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003392 rinfo.bytes_rcvd = cs.bytesReceived;
3393 rinfo.packets_rcvd = cs.packetsReceived;
3394 // The next four fields are from the most recently sent RTCP report.
3395 // Convert Q8 to floating point.
3396 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3397 rinfo.packets_lost = cs.cumulativeLost;
3398 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003399 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003400 if (codec.pltype != -1) {
3401 rinfo.codec_name = codec.plname;
3402 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003403 // Convert samples to milliseconds.
3404 if (codec.plfreq / 1000 > 0) {
3405 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3406 }
3407
3408 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3409 webrtc::NetworkStatistics ns;
3410 if (engine()->voe()->neteq() &&
3411 engine()->voe()->neteq()->GetNetworkStatistics(
3412 *it, ns) != -1) {
3413 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3414 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3415 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003416 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003417 rinfo.speech_expand_rate =
3418 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3419 rinfo.secondary_decoded_rate =
3420 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003421 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003422
3423 webrtc::AudioDecodingCallStats ds;
3424 if (engine()->voe()->neteq() &&
3425 engine()->voe()->neteq()->GetDecodingCallStatistics(
3426 *it, &ds) != -1) {
3427 rinfo.decoding_calls_to_silence_generator =
3428 ds.calls_to_silence_generator;
3429 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3430 rinfo.decoding_normal = ds.decoded_normal;
3431 rinfo.decoding_plc = ds.decoded_plc;
3432 rinfo.decoding_cng = ds.decoded_cng;
3433 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3434 }
3435
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003436 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003437 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003438 int playout_buffer_delay_ms = 0;
3439 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003440 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3441 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3442 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003443 }
3444
3445 // Get speech level.
3446 rinfo.audio_level = (engine()->voe()->volume()->
3447 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3448 info->receivers.push_back(rinfo);
3449 }
3450 }
3451
3452 return true;
3453}
3454
3455void WebRtcVoiceMediaChannel::GetLastMediaError(
3456 uint32* ssrc, VoiceMediaChannel::Error* error) {
3457 ASSERT(ssrc != NULL);
3458 ASSERT(error != NULL);
3459 FindSsrc(voe_channel(), ssrc);
3460 *error = WebRtcErrorToChannelError(GetLastEngineError());
3461}
3462
3463bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003464 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003465 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003466 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003467 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3468 // This means the error is not limited to a specific channel. Signal the
3469 // message using ssrc=0. If the current channel is sending, use this
3470 // channel for sending the message.
3471 *ssrc = 0;
3472 return true;
3473 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003474 // Check whether this is a sending channel.
3475 for (ChannelMap::const_iterator it = send_channels_.begin();
3476 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003477 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003478 // This is a sending channel.
3479 uint32 local_ssrc = 0;
3480 if (engine()->voe()->rtp()->GetLocalSSRC(
3481 channel_num, local_ssrc) != -1) {
3482 *ssrc = local_ssrc;
3483 }
3484 return true;
3485 }
3486 }
3487
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003488 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003489 for (ChannelMap::const_iterator it = receive_channels_.begin();
3490 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003491 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003492 *ssrc = it->first;
3493 return true;
3494 }
3495 }
3496 }
3497 return false;
3498}
3499
3500void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003501 if (error == VE_TYPING_NOISE_WARNING) {
3502 typing_noise_detected_ = true;
3503 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3504 typing_noise_detected_ = false;
3505 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003506 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3507}
3508
3509int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3510 unsigned int ulevel;
3511 int ret =
3512 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3513 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3514}
3515
3516int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003517 ChannelMap::iterator it = receive_channels_.find(ssrc);
3518 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003519 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003520 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3521}
3522
3523int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003524 ChannelMap::iterator it = send_channels_.find(ssrc);
3525 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003526 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003527
3528 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003529}
3530
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003531bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
3532 webrtc::VideoEngine* vie, int vie_channel) {
3533 shared_bwe_vie_ = vie;
3534 shared_bwe_vie_channel_ = vie_channel;
3535
3536 if (!SetupSharedBweOnChannel(voe_channel())) {
3537 return false;
3538 }
3539 for (ChannelMap::iterator it = receive_channels_.begin();
3540 it != receive_channels_.end(); ++it) {
3541 if (!SetupSharedBweOnChannel(it->second->channel())) {
3542 return false;
3543 }
3544 }
3545 return true;
3546}
3547
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003548bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3549 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3550 // Get the RED encodings from the parameter with no name. This may
3551 // change based on what is discussed on the Jingle list.
3552 // The encoding parameter is of the form "a/b"; we only support where
3553 // a == b. Verify this and parse out the value into red_pt.
3554 // If the parameter value is absent (as it will be until we wire up the
3555 // signaling of this message), use the second codec specified (i.e. the
3556 // one after "red") as the encoding parameter.
3557 int red_pt = -1;
3558 std::string red_params;
3559 CodecParameterMap::const_iterator it = red_codec.params.find("");
3560 if (it != red_codec.params.end()) {
3561 red_params = it->second;
3562 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003563 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003564 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003565 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003566 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3567 return false;
3568 }
3569 } else if (red_codec.params.empty()) {
3570 LOG(LS_WARNING) << "RED params not present, using defaults";
3571 if (all_codecs.size() > 1) {
3572 red_pt = all_codecs[1].id;
3573 }
3574 }
3575
3576 // Try to find red_pt in |codecs|.
3577 std::vector<AudioCodec>::const_iterator codec;
3578 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3579 if (codec->id == red_pt)
3580 break;
3581 }
3582
3583 // If we find the right codec, that will be the codec we pass to
3584 // SetSendCodec, with the desired payload type.
3585 if (codec != all_codecs.end() &&
3586 engine()->FindWebRtcCodec(*codec, send_codec)) {
3587 } else {
3588 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3589 return false;
3590 }
3591
3592 return true;
3593}
3594
3595bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3596 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003597 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003598 return false;
3599 }
3600 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3601 // what we want to do with them.
3602 // engine()->voe().EnableVQMon(voe_channel(), true);
3603 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3604 return true;
3605}
3606
3607bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3608 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3609 for (int i = 0; i < ncodecs; ++i) {
3610 webrtc::CodecInst voe_codec;
3611 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3612 voe_codec.pltype = -1;
3613 if (engine()->voe()->codec()->SetRecPayloadType(
3614 channel, voe_codec) == -1) {
3615 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3616 return false;
3617 }
3618 }
3619 }
3620 return true;
3621}
3622
3623bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3624 if (playout) {
3625 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3626 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3627 LOG_RTCERR1(StartPlayout, channel);
3628 return false;
3629 }
3630 } else {
3631 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3632 engine()->voe()->base()->StopPlayout(channel);
3633 }
3634 return true;
3635}
3636
3637uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3638 bool rtcp) {
3639 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3640 uint32 ssrc = 0;
3641 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003642 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003643 }
3644 return ssrc;
3645}
3646
3647// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3648VoiceMediaChannel::Error
3649 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3650 switch (err_code) {
3651 case 0:
3652 return ERROR_NONE;
3653 case VE_CANNOT_START_RECORDING:
3654 case VE_MIC_VOL_ERROR:
3655 case VE_GET_MIC_VOL_ERROR:
3656 case VE_CANNOT_ACCESS_MIC_VOL:
3657 return ERROR_REC_DEVICE_OPEN_FAILED;
3658 case VE_SATURATION_WARNING:
3659 return ERROR_REC_DEVICE_SATURATION;
3660 case VE_REC_DEVICE_REMOVED:
3661 return ERROR_REC_DEVICE_REMOVED;
3662 case VE_RUNTIME_REC_WARNING:
3663 case VE_RUNTIME_REC_ERROR:
3664 return ERROR_REC_RUNTIME_ERROR;
3665 case VE_CANNOT_START_PLAYOUT:
3666 case VE_SPEAKER_VOL_ERROR:
3667 case VE_GET_SPEAKER_VOL_ERROR:
3668 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3669 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3670 case VE_RUNTIME_PLAY_WARNING:
3671 case VE_RUNTIME_PLAY_ERROR:
3672 return ERROR_PLAY_RUNTIME_ERROR;
3673 case VE_TYPING_NOISE_WARNING:
3674 return ERROR_REC_TYPING_NOISE_DETECTED;
3675 default:
3676 return VoiceMediaChannel::ERROR_OTHER;
3677 }
3678}
3679
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003680bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3681 int channel_id, const RtpHeaderExtension* extension) {
3682 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003683 int id = 0;
3684 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003685 if (extension) {
3686 enable = true;
3687 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003688 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003689 }
3690 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003691 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003692 return false;
3693 }
3694 return true;
3695}
3696
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003697bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
3698 webrtc::ViENetwork* vie_network = NULL;
3699 int vie_channel = -1;
3700 if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
3701 shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
3702 vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
3703 vie_channel = shared_bwe_vie_channel_;
3704 }
3705 if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
3706 vie_channel) == -1) {
3707 LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
3708 if (vie_network != NULL) {
3709 // Don't fail if we're tearing down.
3710 return false;
3711 }
3712 }
3713 return true;
3714}
3715
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003716int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003717 size_t res = 0;
3718 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003719 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003720}
3721
3722int WebRtcSoundclipStream::Rewind() {
3723 mem_.Rewind();
3724 // Return -1 to keep VoiceEngine from looping.
3725 return (loop_) ? 0 : -1;
3726}
3727
3728} // namespace cricket
3729
3730#endif // HAVE_WEBRTC_VOICE