blob: 888776cf72b77bfea2e456818ae54a1b1ef9ba1b [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);
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100253 options.delay_agnostic_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000254 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000255 options.aec_dump.Set(false);
256 return options;
257}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000258
259class WebRtcSoundclipMedia : public SoundclipMedia {
260 public:
261 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
262 : engine_(engine), webrtc_channel_(-1) {
263 engine_->RegisterSoundclip(this);
264 }
265
266 virtual ~WebRtcSoundclipMedia() {
267 engine_->UnregisterSoundclip(this);
268 if (webrtc_channel_ != -1) {
269 // We shouldn't have to call Disable() here. DeleteChannel() should call
270 // StopPlayout() while deleting the channel. We should fix the bug
271 // inside WebRTC and remove the Disable() call bellow. This work is
272 // tracked by bug http://b/issue?id=5382855.
273 PlaySound(NULL, 0, 0);
274 Disable();
275 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
276 == -1) {
277 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
278 }
279 }
280 }
281
282 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000283 if (!engine_->voe_sc()) {
284 return false;
285 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000286 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000287 if (webrtc_channel_ == -1) {
288 LOG_RTCERR0(CreateChannel);
289 return false;
290 }
291 return true;
292 }
293
294 bool Enable() {
295 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
296 LOG_RTCERR1(StartPlayout, webrtc_channel_);
297 return false;
298 }
299 return true;
300 }
301
302 bool Disable() {
303 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
304 LOG_RTCERR1(StopPlayout, webrtc_channel_);
305 return false;
306 }
307 return true;
308 }
309
310 virtual bool PlaySound(const char *buf, int len, int flags) {
311 // The voe file api is not available in chrome.
312 if (!engine_->voe_sc()->file()) {
313 return false;
314 }
315 // Must stop playing the current sound (if any), because we are about to
316 // modify the stream.
317 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
318 == -1) {
319 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
320 return false;
321 }
322
323 if (buf) {
324 stream_.reset(new WebRtcSoundclipStream(buf, len));
325 stream_->set_loop((flags & SF_LOOP) != 0);
326 stream_->Rewind();
327
328 // Play it.
329 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
330 webrtc_channel_, stream_.get()) == -1) {
331 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
332 LOG(LS_ERROR) << "Unable to start soundclip";
333 return false;
334 }
335 } else {
336 stream_.reset();
337 }
338 return true;
339 }
340
341 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
342
343 private:
344 WebRtcVoiceEngine *engine_;
345 int webrtc_channel_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000346 rtc::scoped_ptr<WebRtcSoundclipStream> stream_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000347};
348
349WebRtcVoiceEngine::WebRtcVoiceEngine()
350 : voe_wrapper_(new VoEWrapper()),
351 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000352 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000353 tracing_(new VoETraceWrapper()),
354 adm_(NULL),
355 adm_sc_(NULL),
356 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
357 is_dumping_aec_(false),
358 desired_local_monitor_enable_(false),
359 tx_processor_ssrc_(0),
360 rx_processor_ssrc_(0) {
361 Construct();
362}
363
364WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
365 VoEWrapper* voe_wrapper_sc,
366 VoETraceWrapper* tracing)
367 : voe_wrapper_(voe_wrapper),
368 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000369 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000370 tracing_(tracing),
371 adm_(NULL),
372 adm_sc_(NULL),
373 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
374 is_dumping_aec_(false),
375 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000376 tx_processor_ssrc_(0),
377 rx_processor_ssrc_(0) {
378 Construct();
379}
380
381void WebRtcVoiceEngine::Construct() {
382 SetTraceFilter(log_filter_);
383 initialized_ = false;
384 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
385 SetTraceOptions("");
386 if (tracing_->SetTraceCallback(this) == -1) {
387 LOG_RTCERR0(SetTraceCallback);
388 }
389 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
390 LOG_RTCERR0(RegisterVoiceEngineObserver);
391 }
392 // Clear the default agc state.
393 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
394
395 // Load our audio codec list.
396 ConstructCodecs();
397
398 // Load our RTP Header extensions.
399 rtp_header_extensions_.push_back(
400 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
401 kRtpAudioLevelHeaderExtensionDefaultId));
402 rtp_header_extensions_.push_back(
403 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
404 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
405 options_ = GetDefaultEngineOptions();
406}
407
408static bool IsOpus(const AudioCodec& codec) {
409 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
410}
411
412static bool IsIsac(const AudioCodec& codec) {
413 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
414}
415
416// True if params["stereo"] == "1"
417static bool IsOpusStereoEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000418 int value;
419 return codec.GetParam(kCodecParamStereo, &value) && value == 1;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000420}
421
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000422// Use params[kCodecParamMaxAverageBitrate] if it is defined, use codec.bitrate
423// otherwise. If the value (either from params or codec.bitrate) <=0, use the
424// default configuration. If the value is beyond feasible bit rate of Opus,
425// clamp it. Returns the Opus bit rate for operation.
buildbot@webrtc.org879fac82014-10-30 07:50:13 +0000426static int GetOpusBitrate(const AudioCodec& codec, int max_playback_rate) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000427 int bitrate = 0;
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000428 bool use_param = true;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000429 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000430 bitrate = codec.bitrate;
431 use_param = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000432 }
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000433 if (bitrate <= 0) {
minyue@webrtc.org2dc6f312014-10-31 05:33:10 +0000434 if (max_playback_rate <= 8000) {
435 bitrate = kOpusBitrateNb;
436 } else if (max_playback_rate <= 16000) {
437 bitrate = kOpusBitrateWb;
438 } else {
439 bitrate = kOpusBitrateFb;
440 }
441
442 if (IsOpusStereoEnabled(codec)) {
443 bitrate *= 2;
444 }
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000445 } else if (bitrate < kOpusMinBitrate || bitrate > kOpusMaxBitrate) {
446 bitrate = (bitrate < kOpusMinBitrate) ? kOpusMinBitrate : kOpusMaxBitrate;
447 std::string rate_source =
448 use_param ? "Codec parameter \"maxaveragebitrate\"" :
449 "Supplied Opus bitrate";
450 LOG(LS_WARNING) << rate_source
451 << " is invalid and is replaced by: "
452 << bitrate;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000453 }
454 return bitrate;
455}
456
buildbot@webrtc.orgfbd13282014-06-19 19:50:55 +0000457// Return true if params[kCodecParamUseInbandFec] == "1", false
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000458// otherwise.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000459static bool IsOpusFecEnabled(const AudioCodec& codec) {
buildbot@webrtc.orgd27d9ae2014-06-19 01:56:46 +0000460 int value;
461 return codec.GetParam(kCodecParamUseInbandFec, &value) && value == 1;
462}
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000463
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000464// Returns kOpusDefaultPlaybackRate if params[kCodecParamMaxPlaybackRate] is not
465// defined. Returns the value of params[kCodecParamMaxPlaybackRate] otherwise.
466static int GetOpusMaxPlaybackRate(const AudioCodec& codec) {
467 int value;
468 if (codec.GetParam(kCodecParamMaxPlaybackRate, &value)) {
469 return value;
470 }
471 return kOpusDefaultMaxPlaybackRate;
472}
473
474static void GetOpusConfig(const AudioCodec& codec, webrtc::CodecInst* voe_codec,
475 bool* enable_codec_fec, int* max_playback_rate) {
476 *enable_codec_fec = IsOpusFecEnabled(codec);
477 *max_playback_rate = GetOpusMaxPlaybackRate(codec);
478
479 // If OPUS, change what we send according to the "stereo" codec
480 // parameter, and not the "channels" parameter. We set
481 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000482 // the bitrate is not specified, i.e. is <= zero, we set it to the
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000483 // appropriate default value for mono or stereo Opus.
484
buildbot@webrtc.org9d446f22014-10-23 12:22:06 +0000485 voe_codec->channels = IsOpusStereoEnabled(codec) ? 2 : 1;
buildbot@webrtc.org879fac82014-10-30 07:50:13 +0000486 voe_codec->rate = GetOpusBitrate(codec, *max_playback_rate);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +0000487}
488
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000489// Changes RTP timestamp rate of G722. This is due to the "bug" in the RFC
490// which says that G722 should be advertised as 8 kHz although it is a 16 kHz
491// codec.
492static void MaybeFixupG722(webrtc::CodecInst* voe_codec, int new_plfreq) {
493 if (_stricmp(voe_codec->plname, kG722CodecName) == 0) {
494 // If the ASSERT triggers, the codec definition in WebRTC VoiceEngine
495 // has changed, and this special case is no longer needed.
496 ASSERT(voe_codec->plfreq != new_plfreq);
497 voe_codec->plfreq = new_plfreq;
498 }
499}
500
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000501void WebRtcVoiceEngine::ConstructCodecs() {
502 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
503 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
504 for (int i = 0; i < ncodecs; ++i) {
505 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000506 if (GetVoeCodec(i, &voe_codec)) {
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000507 // Skip uncompressed formats.
508 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
509 continue;
510 }
511
512 const CodecPref* pref = NULL;
513 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
514 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
515 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
516 kCodecPrefs[j].channels == voe_codec.channels) {
517 pref = &kCodecPrefs[j];
518 break;
519 }
520 }
521
522 if (pref) {
523 // Use the payload type that we've configured in our pref table;
524 // use the offset in our pref table to determine the sort order.
525 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
526 voe_codec.rate, voe_codec.channels,
527 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
528 LOG(LS_INFO) << ToString(codec);
529 if (IsIsac(codec)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +0000530 // Indicate auto-bitrate in signaling.
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000531 codec.bitrate = 0;
532 }
533 if (IsOpus(codec)) {
534 // Only add fmtp parameters that differ from the spec.
535 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
536 codec.params[kCodecParamMinPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000537 rtc::ToString(kPreferredMinPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000538 }
539 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
540 codec.params[kCodecParamMaxPTime] =
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000541 rtc::ToString(kPreferredMaxPTime);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000542 }
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000543 codec.SetParam(kCodecParamUseInbandFec, 1);
minyue@webrtc.org4ef22d12014-11-17 09:26:39 +0000544
545 // TODO(hellner): Add ptime, sprop-stereo, and stereo
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000546 // when they can be set to values other than the default.
547 }
548 codecs_.push_back(codec);
549 } else {
550 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
551 }
552 }
553 }
554 // Make sure they are in local preference order.
555 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
556}
557
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000558bool WebRtcVoiceEngine::GetVoeCodec(int index, webrtc::CodecInst* codec) {
559 if (voe_wrapper_->codec()->GetCodec(index, *codec) == -1) {
560 return false;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000561 }
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +0000562 // Change the sample rate of G722 to 8000 to match SDP.
563 MaybeFixupG722(codec, 8000);
564 return true;
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +0000565}
566
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000567WebRtcVoiceEngine::~WebRtcVoiceEngine() {
568 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
569 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
570 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
571 }
572 if (adm_) {
573 voe_wrapper_.reset();
574 adm_->Release();
575 adm_ = NULL;
576 }
577 if (adm_sc_) {
578 voe_wrapper_sc_.reset();
579 adm_sc_->Release();
580 adm_sc_ = NULL;
581 }
582
583 // Test to see if the media processor was deregistered properly
584 ASSERT(SignalRxMediaFrame.is_empty());
585 ASSERT(SignalTxMediaFrame.is_empty());
586
587 tracing_->SetTraceCallback(NULL);
588}
589
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000590bool WebRtcVoiceEngine::Init(rtc::Thread* worker_thread) {
henrika@webrtc.org62f6e752015-02-11 08:38:35 +0000591 ASSERT(worker_thread == rtc::Thread::Current());
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000592 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
593 bool res = InitInternal();
594 if (res) {
595 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
596 } else {
597 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
598 Terminate();
599 }
600 return res;
601}
602
603bool WebRtcVoiceEngine::InitInternal() {
604 // Temporarily turn logging level up for the Init call
605 int old_filter = log_filter_;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000606 int extended_filter = log_filter_ | SeverityToFilter(rtc::LS_INFO);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000607 SetTraceFilter(extended_filter);
608 SetTraceOptions("");
609
610 // Init WebRtc VoiceEngine.
611 if (voe_wrapper_->base()->Init(adm_) == -1) {
612 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
613 SetTraceFilter(old_filter);
614 return false;
615 }
616
617 SetTraceFilter(old_filter);
618 SetTraceOptions(log_options_);
619
620 // Log the VoiceEngine version info
621 char buffer[1024] = "";
622 voe_wrapper_->base()->GetVersion(buffer);
623 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000624 LogMultiline(rtc::LS_INFO, buffer);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000625
626 // Save the default AGC configuration settings. This must happen before
627 // calling SetOptions or the default will be overwritten.
628 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
629 LOG_RTCERR0(GetAgcConfig);
630 return false;
631 }
632
633 // Set defaults for options, so that ApplyOptions applies them explicitly
634 // when we clear option (channel) overrides. External clients can still
635 // modify the defaults via SetOptions (on the media engine).
636 if (!SetOptions(GetDefaultEngineOptions())) {
637 return false;
638 }
639
640 // Print our codec list again for the call diagnostic log
641 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
642 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
643 it != codecs_.end(); ++it) {
644 LOG(LS_INFO) << ToString(*it);
645 }
646
647 // Disable the DTMF playout when a tone is sent.
648 // PlayDtmfTone will be used if local playout is needed.
649 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
650 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
651 }
652
653 initialized_ = true;
654 return true;
655}
656
657bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
658 if (voe_wrapper_sc_initialized_) {
659 return true;
660 }
661 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
662 // be false, so subsequent calls to EnsureSoundclipEngineInit will
663 // probably just fail again. That's acceptable behavior.
664#if defined(LINUX) && !defined(HAVE_LIBPULSE)
665 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
666#endif
667
668 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
669 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
670 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
671 return false;
672 }
673
674 // On Windows, tell it to use the default sound (not communication) devices.
675 // First check whether there is a valid sound device for playback.
676 // TODO(juberti): Clean this up when we support setting the soundclip device.
677#ifdef WIN32
678 // The SetPlayoutDevice may not be implemented in the case of external ADM.
679 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
680 // PeerConnection interface never set the adm_sc_, so need to check both
681 // in order to determine if the external adm is used.
682 if (!adm_ && !adm_sc_) {
683 int num_of_devices = 0;
684 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
685 num_of_devices > 0) {
686 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
687 == -1) {
688 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
689 voe_wrapper_sc_->error());
690 return false;
691 }
692 } else {
693 LOG(LS_WARNING) << "No valid sound playout device found.";
694 }
695 }
696#endif
697 voe_wrapper_sc_initialized_ = true;
698 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
699 return true;
700}
701
702void WebRtcVoiceEngine::Terminate() {
703 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
704 initialized_ = false;
705
706 StopAecDump();
707
708 if (voe_wrapper_sc_) {
709 voe_wrapper_sc_initialized_ = false;
710 voe_wrapper_sc_->base()->Terminate();
711 }
712 voe_wrapper_->base()->Terminate();
713 desired_local_monitor_enable_ = false;
714}
715
716int WebRtcVoiceEngine::GetCapabilities() {
717 return AUDIO_SEND | AUDIO_RECV;
718}
719
720VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
721 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
722 if (!ch->valid()) {
723 delete ch;
724 ch = NULL;
725 }
726 return ch;
727}
728
729SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
730 if (!EnsureSoundclipEngineInit()) {
731 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
732 << "initialize.";
733 return NULL;
734 }
735 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
736 if (!soundclip->Init() || !soundclip->Enable()) {
737 delete soundclip;
738 return NULL;
739 }
740 return soundclip;
741}
742
743bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
744 if (!ApplyOptions(options)) {
745 return false;
746 }
747 options_ = options;
748 return true;
749}
750
751bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
752 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
753 if (!ApplyOptions(overrides)) {
754 return false;
755 }
756 option_overrides_ = overrides;
757 return true;
758}
759
760bool WebRtcVoiceEngine::ClearOptionOverrides() {
761 LOG(LS_INFO) << "Clearing option overrides.";
762 AudioOptions options = options_;
763 // Only call ApplyOptions if |options_overrides_| contains overrided options.
764 // ApplyOptions affects NS, AGC other options that is shared between
765 // all WebRtcVoiceEngineChannels.
766 if (option_overrides_ == AudioOptions()) {
767 return true;
768 }
769
770 if (!ApplyOptions(options)) {
771 return false;
772 }
773 option_overrides_ = AudioOptions();
774 return true;
775}
776
777// AudioOptions defaults are set in InitInternal (for options with corresponding
778// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
779bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
780 AudioOptions options = options_in; // The options are modified below.
781 // kEcConference is AEC with high suppression.
782 webrtc::EcModes ec_mode = webrtc::kEcConference;
783 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
784 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
785 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
786 bool aecm_comfort_noise = false;
787 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
788 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
789 << aecm_comfort_noise << " (default is false).";
790 }
791
792#if defined(IOS)
793 // On iOS, VPIO provides built-in EC and AGC.
794 options.echo_cancellation.Set(false);
795 options.auto_gain_control.Set(false);
796#elif defined(ANDROID)
797 ec_mode = webrtc::kEcAecm;
798#endif
799
800#if defined(IOS) || defined(ANDROID)
801 // Set the AGC mode for iOS as well despite disabling it above, to avoid
802 // unsupported configuration errors from webrtc.
803 agc_mode = webrtc::kAgcFixedDigital;
804 options.typing_detection.Set(false);
805 options.experimental_agc.Set(false);
806 options.experimental_aec.Set(false);
807 options.experimental_ns.Set(false);
808#endif
809
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100810 // Delay Agnostic AEC automatically turns on EC if not set except on iOS
811 // where the feature is not supported.
812 bool use_delay_agnostic_aec = false;
813#if !defined(IOS)
814 if (options.delay_agnostic_aec.Get(&use_delay_agnostic_aec)) {
815 if (use_delay_agnostic_aec) {
816 options.echo_cancellation.Set(true);
817 options.experimental_aec.Set(true);
818 ec_mode = webrtc::kEcConference;
819 }
820 }
821#endif
822
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000823 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
824
825 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
826
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000827 bool echo_cancellation = false;
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000828 if (options.echo_cancellation.Get(&echo_cancellation)) {
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000829 // Check if platform supports built-in EC. Currently only supported on
830 // Android and in combination with Java based audio layer.
831 // TODO(henrika): investigate possibility to support built-in EC also
832 // in combination with Open SL ES audio.
833 const bool built_in_aec = voe_wrapper_->hw()->BuiltInAECIsAvailable();
834 if (built_in_aec) {
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100835 // Enabled built-in EC if the device has one and delay agnostic AEC is not
836 // enabled.
837 const bool enable_built_in_aec = echo_cancellation &
838 !use_delay_agnostic_aec;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000839 // Set mode of built-in EC according to the audio options.
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100840 voe_wrapper_->hw()->EnableBuiltInAEC(enable_built_in_aec);
841 if (enable_built_in_aec) {
842 // Disable internal software EC if built-in EC is enabled,
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000843 // i.e., replace the software EC with the built-in EC.
844 options.echo_cancellation.Set(false);
bjornv@webrtc.org3f118232015-03-16 14:22:03 +0000845 echo_cancellation = false;
henrika@webrtc.orga954c072014-12-09 16:22:09 +0000846 LOG(LS_INFO) << "Disabling EC since built-in EC will be used instead";
847 }
848 }
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000849 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
850 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
851 return false;
852 } else {
853 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
854 << " with mode " << ec_mode;
855 }
856#if !defined(ANDROID)
857 // TODO(ajm): Remove the error return on Android from webrtc.
858 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
859 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
860 return false;
861 }
862#endif
863 if (ec_mode == webrtc::kEcAecm) {
864 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
865 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
866 return false;
867 }
868 }
869 }
870
871 bool auto_gain_control;
872 if (options.auto_gain_control.Get(&auto_gain_control)) {
873 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
874 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
875 return false;
876 } else {
877 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
878 << " with mode " << agc_mode;
879 }
880 }
881
882 if (options.tx_agc_target_dbov.IsSet() ||
883 options.tx_agc_digital_compression_gain.IsSet() ||
884 options.tx_agc_limiter.IsSet()) {
885 // Override default_agc_config_. Generally, an unset option means "leave
886 // the VoE bits alone" in this function, so we want whatever is set to be
887 // stored as the new "default". If we didn't, then setting e.g.
888 // tx_agc_target_dbov would reset digital compression gain and limiter
889 // settings.
890 // Also, if we don't update default_agc_config_, then adjust_agc_delta
891 // would be an offset from the original values, and not whatever was set
892 // explicitly.
893 default_agc_config_.targetLeveldBOv =
894 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
895 default_agc_config_.targetLeveldBOv);
896 default_agc_config_.digitalCompressionGaindB =
897 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
898 default_agc_config_.digitalCompressionGaindB);
899 default_agc_config_.limiterEnable =
900 options.tx_agc_limiter.GetWithDefaultIfUnset(
901 default_agc_config_.limiterEnable);
902 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
903 LOG_RTCERR3(SetAgcConfig,
904 default_agc_config_.targetLeveldBOv,
905 default_agc_config_.digitalCompressionGaindB,
906 default_agc_config_.limiterEnable);
907 return false;
908 }
909 }
910
911 bool noise_suppression;
912 if (options.noise_suppression.Get(&noise_suppression)) {
913 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
914 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
915 return false;
916 } else {
917 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
918 << " with mode " << ns_mode;
919 }
920 }
921
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000922 bool highpass_filter;
923 if (options.highpass_filter.Get(&highpass_filter)) {
924 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
925 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
926 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
927 return false;
928 }
929 }
930
931 bool stereo_swapping;
932 if (options.stereo_swapping.Get(&stereo_swapping)) {
933 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
934 voep->EnableStereoChannelSwapping(stereo_swapping);
935 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
936 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
937 return false;
938 }
939 }
940
941 bool typing_detection;
942 if (options.typing_detection.Get(&typing_detection)) {
943 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
944 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
945 // In case of error, log the info and continue
946 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
947 }
948 }
949
950 int adjust_agc_delta;
951 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
952 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
953 if (!AdjustAgcLevel(adjust_agc_delta)) {
954 return false;
955 }
956 }
957
958 bool aec_dump;
959 if (options.aec_dump.Get(&aec_dump)) {
960 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
961 if (aec_dump)
962 StartAecDump(kAecDumpByAudioOptionFilename);
963 else
964 StopAecDump();
965 }
966
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000967 webrtc::Config config;
968
Bjorn Volckerbf395c12015-03-25 22:45:56 +0100969 delay_agnostic_aec_.SetFrom(options.delay_agnostic_aec);
970 bool delay_agnostic_aec;
971 if (delay_agnostic_aec_.Get(&delay_agnostic_aec)) {
972 LOG(LS_INFO) << "Delay agnostic aec is enabled? " << delay_agnostic_aec;
973 config.Set<webrtc::ReportedDelay>(
974 new webrtc::ReportedDelay(!delay_agnostic_aec));
975 }
976
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000977 experimental_aec_.SetFrom(options.experimental_aec);
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000978 bool experimental_aec;
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000979 if (experimental_aec_.Get(&experimental_aec)) {
980 LOG(LS_INFO) << "Experimental aec is enabled? " << experimental_aec;
981 config.Set<webrtc::DelayCorrection>(
982 new webrtc::DelayCorrection(experimental_aec));
983 }
984
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000985 experimental_ns_.SetFrom(options.experimental_ns);
986 bool experimental_ns;
987 if (experimental_ns_.Get(&experimental_ns)) {
988 LOG(LS_INFO) << "Experimental ns is enabled? " << experimental_ns;
989 config.Set<webrtc::ExperimentalNs>(
990 new webrtc::ExperimentalNs(experimental_ns));
991 }
buildbot@webrtc.org1f8a2372014-08-28 10:52:44 +0000992
993 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
994 // returns NULL on audio_processing().
995 webrtc::AudioProcessing* audioproc = voe_wrapper_->base()->audio_processing();
996 if (audioproc) {
997 audioproc->SetExtraOptions(config);
998 }
999
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001000 uint32 recording_sample_rate;
1001 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
1002 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
1003 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
1004 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
1005 }
1006 }
1007
1008 uint32 playout_sample_rate;
1009 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
1010 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
1011 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
1012 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
1013 }
1014 }
1015
1016 return true;
1017}
1018
1019bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
1020 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
1021 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
1022 LOG_RTCERR1(SetDelayOffsetMs, offset);
1023 return false;
1024 }
1025
1026 return true;
1027}
1028
1029struct ResumeEntry {
1030 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
1031 : channel(c),
1032 playout(p),
1033 send(s) {
1034 }
1035
1036 WebRtcVoiceMediaChannel *channel;
1037 bool playout;
1038 SendFlags send;
1039};
1040
1041// TODO(juberti): Refactor this so that the core logic can be used to set the
1042// soundclip device. At that time, reinstate the soundclip pause/resume code.
1043bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
1044 const Device* out_device) {
1045#if !defined(IOS)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001046 int in_id = in_device ? rtc::FromString<int>(in_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001047 kDefaultAudioDeviceId;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001048 int out_id = out_device ? rtc::FromString<int>(out_device->id) :
buildbot@webrtc.org13d67762014-05-02 17:33:29 +00001049 kDefaultAudioDeviceId;
1050 // The device manager uses -1 as the default device, which was the case for
1051 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
1052#ifndef WIN32
1053 if (-1 == in_id) {
1054 in_id = kDefaultAudioDeviceId;
1055 }
1056 if (-1 == out_id) {
1057 out_id = kDefaultAudioDeviceId;
1058 }
1059#endif
1060
1061 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
1062 in_device->name : "Default device";
1063 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
1064 out_device->name : "Default device";
1065 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
1066 << ") and speaker to (id=" << out_id << ", name=" << out_name
1067 << ")";
1068
1069 // If we're running the local monitor, we need to stop it first.
1070 bool ret = true;
1071 if (!PauseLocalMonitor()) {
1072 LOG(LS_WARNING) << "Failed to pause local monitor";
1073 ret = false;
1074 }
1075
1076 // Must also pause all audio playback and capture.
1077 for (ChannelList::const_iterator i = channels_.begin();
1078 i != channels_.end(); ++i) {
1079 WebRtcVoiceMediaChannel *channel = *i;
1080 if (!channel->PausePlayout()) {
1081 LOG(LS_WARNING) << "Failed to pause playout";
1082 ret = false;
1083 }
1084 if (!channel->PauseSend()) {
1085 LOG(LS_WARNING) << "Failed to pause send";
1086 ret = false;
1087 }
1088 }
1089
1090 // Find the recording device id in VoiceEngine and set recording device.
1091 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1092 ret = false;
1093 }
1094 if (ret) {
1095 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
1096 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
1097 ret = false;
1098 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00001099 webrtc::AudioProcessing* ap = voe()->base()->audio_processing();
1100 if (ap)
1101 ap->Initialize();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001102 }
1103
1104 // Find the playout device id in VoiceEngine and set playout device.
1105 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1106 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1107 ret = false;
1108 }
1109 if (ret) {
1110 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001111 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001112 ret = false;
1113 }
1114 }
1115
1116 // Resume all audio playback and capture.
1117 for (ChannelList::const_iterator i = channels_.begin();
1118 i != channels_.end(); ++i) {
1119 WebRtcVoiceMediaChannel *channel = *i;
1120 if (!channel->ResumePlayout()) {
1121 LOG(LS_WARNING) << "Failed to resume playout";
1122 ret = false;
1123 }
1124 if (!channel->ResumeSend()) {
1125 LOG(LS_WARNING) << "Failed to resume send";
1126 ret = false;
1127 }
1128 }
1129
1130 // Resume local monitor.
1131 if (!ResumeLocalMonitor()) {
1132 LOG(LS_WARNING) << "Failed to resume local monitor";
1133 ret = false;
1134 }
1135
1136 if (ret) {
1137 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1138 << ") and speaker to (id="<< out_id << " name=" << out_name
1139 << ")";
1140 }
1141
1142 return ret;
1143#else
1144 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001145#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001146}
1147
1148bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1149 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1150 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001151#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001152 *rtc_id = dev_id;
1153 return true;
1154#else
1155 // In Windows and Mac, we need to find the VoiceEngine device id by name
1156 // unless the input dev_id is the default device id.
1157 if (kDefaultAudioDeviceId == dev_id) {
1158 *rtc_id = dev_id;
1159 return true;
1160 }
1161
1162 // Get the number of VoiceEngine audio devices.
1163 int count = 0;
1164 if (is_input) {
1165 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1166 LOG_RTCERR0(GetNumOfRecordingDevices);
1167 return false;
1168 }
1169 } else {
1170 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1171 LOG_RTCERR0(GetNumOfPlayoutDevices);
1172 return false;
1173 }
1174 }
1175
1176 for (int i = 0; i < count; ++i) {
1177 char name[128];
1178 char guid[128];
1179 if (is_input) {
1180 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1181 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1182 } else {
1183 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1184 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1185 }
1186
1187 std::string webrtc_name(name);
1188 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1189 *rtc_id = i;
1190 return true;
1191 }
1192 }
1193 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1194 return false;
1195#endif
1196}
1197
1198bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1199 unsigned int ulevel;
1200 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1201 LOG_RTCERR1(GetSpeakerVolume, level);
1202 return false;
1203 }
1204 *level = ulevel;
1205 return true;
1206}
1207
1208bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1209 ASSERT(level >= 0 && level <= 255);
1210 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1211 LOG_RTCERR1(SetSpeakerVolume, level);
1212 return false;
1213 }
1214 return true;
1215}
1216
1217int WebRtcVoiceEngine::GetInputLevel() {
1218 unsigned int ulevel;
1219 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1220 static_cast<int>(ulevel) : -1;
1221}
1222
1223bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1224 desired_local_monitor_enable_ = enable;
1225 return ChangeLocalMonitor(desired_local_monitor_enable_);
1226}
1227
1228bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1229 // The voe file api is not available in chrome.
1230 if (!voe_wrapper_->file()) {
1231 return false;
1232 }
1233 if (enable && !monitor_) {
1234 monitor_.reset(new WebRtcMonitorStream);
1235 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1236 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1237 // Must call Stop() because there are some cases where Start will report
1238 // failure but still change the state, and if we leave VE in the on state
1239 // then it could crash later when trying to invoke methods on our monitor.
1240 voe_wrapper_->file()->StopRecordingMicrophone();
1241 monitor_.reset();
1242 return false;
1243 }
1244 } else if (!enable && monitor_) {
1245 voe_wrapper_->file()->StopRecordingMicrophone();
1246 monitor_.reset();
1247 }
1248 return true;
1249}
1250
1251bool WebRtcVoiceEngine::PauseLocalMonitor() {
1252 return ChangeLocalMonitor(false);
1253}
1254
1255bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1256 return ChangeLocalMonitor(desired_local_monitor_enable_);
1257}
1258
1259const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1260 return codecs_;
1261}
1262
1263bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1264 return FindWebRtcCodec(in, NULL);
1265}
1266
1267// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1268bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1269 webrtc::CodecInst* out) {
1270 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1271 for (int i = 0; i < ncodecs; ++i) {
1272 webrtc::CodecInst voe_codec;
henrik.lundin@webrtc.org8038d422014-11-11 08:38:24 +00001273 if (GetVoeCodec(i, &voe_codec)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001274 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1275 voe_codec.rate, voe_codec.channels, 0);
1276 bool multi_rate = IsCodecMultiRate(voe_codec);
1277 // Allow arbitrary rates for ISAC to be specified.
1278 if (multi_rate) {
1279 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1280 codec.bitrate = 0;
1281 }
1282 if (codec.Matches(in)) {
1283 if (out) {
1284 // Fixup the payload type.
1285 voe_codec.pltype = in.id;
1286
1287 // Set bitrate if specified.
1288 if (multi_rate && in.bitrate != 0) {
1289 voe_codec.rate = in.bitrate;
1290 }
1291
henrik.lundin@webrtc.orgf85dbce2014-11-07 12:25:00 +00001292 // Reset G722 sample rate to 16000 to match WebRTC.
1293 MaybeFixupG722(&voe_codec, 16000);
1294
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001295 // Apply codec-specific settings.
1296 if (IsIsac(codec)) {
1297 // If ISAC and an explicit bitrate is not specified,
minyue@webrtc.org26236952014-10-29 02:27:08 +00001298 // enable auto bitrate adjustment.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001299 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1300 }
1301 *out = voe_codec;
1302 }
1303 return true;
1304 }
1305 }
1306 }
1307 return false;
1308}
1309const std::vector<RtpHeaderExtension>&
1310WebRtcVoiceEngine::rtp_header_extensions() const {
1311 return rtp_header_extensions_;
1312}
1313
1314void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1315 // if min_sev == -1, we keep the current log level.
1316 if (min_sev >= 0) {
1317 SetTraceFilter(SeverityToFilter(min_sev));
1318 }
1319 log_options_ = filter;
1320 SetTraceOptions(initialized_ ? log_options_ : "");
1321}
1322
1323int WebRtcVoiceEngine::GetLastEngineError() {
1324 return voe_wrapper_->error();
1325}
1326
1327void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1328 log_filter_ = filter;
1329 tracing_->SetTraceFilter(filter);
1330}
1331
1332// We suppport three different logging settings for VoiceEngine:
1333// 1. Observer callback that goes into talk diagnostic logfile.
1334// Use --logfile and --loglevel
1335//
1336// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1337// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1338//
1339// 3. EC log and dump for debugging QualityEngine.
1340// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1341//
1342// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1343// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1344void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1345 // Set encrypted trace file.
1346 std::vector<std::string> opts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001347 rtc::tokenize(options, ' ', '"', '"', &opts);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001348 std::vector<std::string>::iterator tracefile =
1349 std::find(opts.begin(), opts.end(), "tracefile");
1350 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1351 // Write encrypted debug output (at same loglevel) to file
1352 // EncryptedTraceFile no longer supported.
1353 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1354 LOG_RTCERR1(SetTraceFile, *tracefile);
1355 }
1356 }
1357
wu@webrtc.org97077a32013-10-25 21:18:33 +00001358 // Allow trace options to override the trace filter. We default
1359 // it to log_filter_ (as a translation of libjingle log levels)
1360 // elsewhere, but this allows clients to explicitly set webrtc
1361 // log levels.
1362 std::vector<std::string>::iterator tracefilter =
1363 std::find(opts.begin(), opts.end(), "tracefilter");
1364 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001365 if (!tracing_->SetTraceFilter(rtc::FromString<int>(*tracefilter))) {
wu@webrtc.org97077a32013-10-25 21:18:33 +00001366 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1367 }
1368 }
1369
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370 // Set AEC dump file
1371 std::vector<std::string>::iterator recordEC =
1372 std::find(opts.begin(), opts.end(), "recordEC");
1373 if (recordEC != opts.end()) {
1374 ++recordEC;
1375 if (recordEC != opts.end())
1376 StartAecDump(recordEC->c_str());
1377 else
1378 StopAecDump();
1379 }
1380}
1381
1382// Ignore spammy trace messages, mostly from the stats API when we haven't
1383// gotten RTCP info yet from the remote side.
1384bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1385 static const char* kTracesToIgnore[] = {
1386 "\tfailed to GetReportBlockInformation",
1387 "GetRecCodec() failed to get received codec",
1388 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1389 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1390 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1391 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1392 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1393 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1394 "SenderInfoReceived No received SR",
1395 "StatisticsRTP() no statistics available",
1396 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1397 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1398 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1399 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1400 NULL
1401 };
1402 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1403 if (trace.find(*p) != std::string::npos) {
1404 return true;
1405 }
1406 }
1407 return false;
1408}
1409
1410void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1411 int length) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001412 rtc::LoggingSeverity sev = rtc::LS_VERBOSE;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001413 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001414 sev = rtc::LS_ERROR;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001415 else if (level == webrtc::kTraceWarning)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001416 sev = rtc::LS_WARNING;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001417 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001418 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001419 else if (level == webrtc::kTraceTerseInfo)
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001420 sev = rtc::LS_INFO;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001421
1422 // Skip past boilerplate prefix text
1423 if (length < 72) {
1424 std::string msg(trace, length);
1425 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1426 LOG_V(sev) << msg;
1427 } else {
1428 std::string msg(trace + 71, length - 72);
1429 if (!ShouldIgnoreTrace(msg)) {
1430 LOG_V(sev) << "webrtc: " << msg;
1431 }
1432 }
1433}
1434
1435void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001436 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001437 WebRtcVoiceMediaChannel* channel = NULL;
1438 uint32 ssrc = 0;
1439 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1440 << channel_num << ".";
1441 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1442 ASSERT(channel != NULL);
1443 channel->OnError(ssrc, err_code);
1444 } else {
1445 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1446 << " could not be found in channel list when error reported.";
1447 }
1448}
1449
1450bool WebRtcVoiceEngine::FindChannelAndSsrc(
1451 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1452 ASSERT(channel != NULL && ssrc != NULL);
1453
1454 *channel = NULL;
1455 *ssrc = 0;
1456 // Find corresponding channel and ssrc
1457 for (ChannelList::const_iterator it = channels_.begin();
1458 it != channels_.end(); ++it) {
1459 ASSERT(*it != NULL);
1460 if ((*it)->FindSsrc(channel_num, ssrc)) {
1461 *channel = *it;
1462 return true;
1463 }
1464 }
1465
1466 return false;
1467}
1468
1469// This method will search through the WebRtcVoiceMediaChannels and
1470// obtain the voice engine's channel number.
1471bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1472 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1473 ASSERT(channel_num != NULL);
1474 ASSERT(direction == MPD_RX || direction == MPD_TX);
1475
1476 *channel_num = -1;
1477 // Find corresponding channel for ssrc.
1478 for (ChannelList::const_iterator it = channels_.begin();
1479 it != channels_.end(); ++it) {
1480 ASSERT(*it != NULL);
1481 if (direction & MPD_RX) {
1482 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1483 }
1484 if (*channel_num == -1 && (direction & MPD_TX)) {
1485 *channel_num = (*it)->GetSendChannelNum(ssrc);
1486 }
1487 if (*channel_num != -1) {
1488 return true;
1489 }
1490 }
1491 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1492 return false;
1493}
1494
1495void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001496 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001497 channels_.push_back(channel);
1498}
1499
1500void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001501 rtc::CritScope lock(&channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001502 ChannelList::iterator i = std::find(channels_.begin(),
1503 channels_.end(),
1504 channel);
1505 if (i != channels_.end()) {
1506 channels_.erase(i);
1507 }
1508}
1509
1510void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1511 soundclips_.push_back(soundclip);
1512}
1513
1514void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1515 SoundclipList::iterator i = std::find(soundclips_.begin(),
1516 soundclips_.end(),
1517 soundclip);
1518 if (i != soundclips_.end()) {
1519 soundclips_.erase(i);
1520 }
1521}
1522
1523// Adjusts the default AGC target level by the specified delta.
1524// NB: If we start messing with other config fields, we'll want
1525// to save the current webrtc::AgcConfig as well.
1526bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1527 webrtc::AgcConfig config = default_agc_config_;
1528 config.targetLeveldBOv -= delta;
1529
1530 LOG(LS_INFO) << "Adjusting AGC level from default -"
1531 << default_agc_config_.targetLeveldBOv << "dB to -"
1532 << config.targetLeveldBOv << "dB";
1533
1534 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1535 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1536 return false;
1537 }
1538 return true;
1539}
1540
1541bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1542 webrtc::AudioDeviceModule* adm_sc) {
1543 if (initialized_) {
1544 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1545 return false;
1546 }
1547 if (adm_) {
1548 adm_->Release();
1549 adm_ = NULL;
1550 }
1551 if (adm) {
1552 adm_ = adm;
1553 adm_->AddRef();
1554 }
1555
1556 if (adm_sc_) {
1557 adm_sc_->Release();
1558 adm_sc_ = NULL;
1559 }
1560 if (adm_sc) {
1561 adm_sc_ = adm_sc;
1562 adm_sc_->AddRef();
1563 }
1564 return true;
1565}
1566
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001567bool WebRtcVoiceEngine::StartAecDump(rtc::PlatformFile file) {
1568 FILE* aec_dump_file_stream = rtc::FdopenPlatformFileForWriting(file);
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001569 if (!aec_dump_file_stream) {
1570 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001571 if (!rtc::ClosePlatformFile(file))
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001572 LOG(LS_WARNING) << "Could not close file.";
1573 return false;
1574 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001575 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001576 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001577 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001578 LOG_RTCERR0(StartDebugRecording);
1579 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001580 return false;
1581 }
1582 is_dumping_aec_ = true;
1583 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001584}
1585
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001586bool WebRtcVoiceEngine::RegisterProcessor(
1587 uint32 ssrc,
1588 VoiceProcessor* voice_processor,
1589 MediaProcessorDirection direction) {
1590 bool register_with_webrtc = false;
1591 int channel_id = -1;
1592 bool success = false;
1593 uint32* processor_ssrc = NULL;
1594 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1595 if (voice_processor == NULL || !found_channel) {
1596 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1597 << " foundChannel: " << found_channel;
1598 return false;
1599 }
1600
1601 webrtc::ProcessingTypes processing_type;
1602 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001603 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001604 if (direction == MPD_RX) {
1605 processing_type = webrtc::kPlaybackAllChannelsMixed;
1606 if (SignalRxMediaFrame.is_empty()) {
1607 register_with_webrtc = true;
1608 processor_ssrc = &rx_processor_ssrc_;
1609 }
1610 SignalRxMediaFrame.connect(voice_processor,
1611 &VoiceProcessor::OnFrame);
1612 } else {
1613 processing_type = webrtc::kRecordingPerChannel;
1614 if (SignalTxMediaFrame.is_empty()) {
1615 register_with_webrtc = true;
1616 processor_ssrc = &tx_processor_ssrc_;
1617 }
1618 SignalTxMediaFrame.connect(voice_processor,
1619 &VoiceProcessor::OnFrame);
1620 }
1621 }
1622 if (register_with_webrtc) {
1623 // TODO(janahan): when registering consider instantiating a
1624 // a VoeMediaProcess object and not make the engine extend the interface.
1625 if (voe()->media() && voe()->media()->
1626 RegisterExternalMediaProcessing(channel_id,
1627 processing_type,
1628 *this) != -1) {
1629 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1630 << channel_id;
1631 *processor_ssrc = ssrc;
1632 success = true;
1633 } else {
1634 LOG_RTCERR2(RegisterExternalMediaProcessing,
1635 channel_id,
1636 processing_type);
1637 success = false;
1638 }
1639 } else {
1640 // If we don't have to register with the engine, we just needed to
1641 // connect a new processor, set success to true;
1642 success = true;
1643 }
1644 return success;
1645}
1646
1647bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1648 MediaProcessorDirection channel_direction,
1649 uint32 ssrc,
1650 VoiceProcessor* voice_processor,
1651 MediaProcessorDirection processor_direction) {
1652 bool success = true;
1653 FrameSignal* signal;
1654 webrtc::ProcessingTypes processing_type;
1655 uint32* processor_ssrc = NULL;
1656 if (channel_direction == MPD_RX) {
1657 signal = &SignalRxMediaFrame;
1658 processing_type = webrtc::kPlaybackAllChannelsMixed;
1659 processor_ssrc = &rx_processor_ssrc_;
1660 } else {
1661 signal = &SignalTxMediaFrame;
1662 processing_type = webrtc::kRecordingPerChannel;
1663 processor_ssrc = &tx_processor_ssrc_;
1664 }
1665
1666 int deregister_id = -1;
1667 {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001668 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001669 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1670 signal->disconnect(voice_processor);
1671 int channel_id = -1;
1672 bool found_channel = FindChannelNumFromSsrc(ssrc,
1673 channel_direction,
1674 &channel_id);
1675 if (signal->is_empty() && found_channel) {
1676 deregister_id = channel_id;
1677 }
1678 }
1679 }
1680 if (deregister_id != -1) {
1681 if (voe()->media() &&
1682 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1683 processing_type) != -1) {
1684 *processor_ssrc = 0;
1685 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1686 << deregister_id;
1687 } else {
1688 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1689 deregister_id,
1690 processing_type);
1691 success = false;
1692 }
1693 }
1694 return success;
1695}
1696
1697bool WebRtcVoiceEngine::UnregisterProcessor(
1698 uint32 ssrc,
1699 VoiceProcessor* voice_processor,
1700 MediaProcessorDirection direction) {
1701 bool success = true;
1702 if (voice_processor == NULL) {
1703 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1704 << ssrc;
1705 return false;
1706 }
1707 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1708 success = false;
1709 }
1710 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1711 success = false;
1712 }
1713 return success;
1714}
1715
1716// Implementing method from WebRtc VoEMediaProcess interface
1717// Do not lock mux_channel_cs_ in this callback.
1718void WebRtcVoiceEngine::Process(int channel,
1719 webrtc::ProcessingTypes type,
1720 int16_t audio10ms[],
1721 int length,
1722 int sampling_freq,
1723 bool is_stereo) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001724 rtc::CritScope cs(&signal_media_critical_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001725 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1726 if (type == webrtc::kPlaybackAllChannelsMixed) {
1727 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1728 } else if (type == webrtc::kRecordingPerChannel) {
1729 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1730 } else {
1731 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1732 << " channel: " << channel << " type: " << type
1733 << " tx_ssrc: " << tx_processor_ssrc_
1734 << " rx_ssrc: " << rx_processor_ssrc_;
1735 }
1736}
1737
1738void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1739 if (!is_dumping_aec_) {
1740 // Start dumping AEC when we are not dumping.
1741 if (voe_wrapper_->processing()->StartDebugRecording(
1742 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001743 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001744 } else {
1745 is_dumping_aec_ = true;
1746 }
1747 }
1748}
1749
1750void WebRtcVoiceEngine::StopAecDump() {
1751 if (is_dumping_aec_) {
1752 // Stop dumping AEC when we are dumping.
1753 if (voe_wrapper_->processing()->StopDebugRecording() !=
1754 webrtc::AudioProcessing::kNoError) {
1755 LOG_RTCERR0(StopDebugRecording);
1756 }
1757 is_dumping_aec_ = false;
1758 }
1759}
1760
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001761int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001762 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001763}
1764
1765int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1766 return CreateVoiceChannel(voe_wrapper_.get());
1767}
1768
1769int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1770 return CreateVoiceChannel(voe_wrapper_sc_.get());
1771}
1772
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001773class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1774 : public AudioRenderer::Sink {
1775 public:
1776 WebRtcVoiceChannelRenderer(int ch,
1777 webrtc::AudioTransport* voe_audio_transport)
1778 : channel_(ch),
1779 voe_audio_transport_(voe_audio_transport),
1780 renderer_(NULL) {
1781 }
1782 virtual ~WebRtcVoiceChannelRenderer() {
1783 Stop();
1784 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001785
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001786 // Starts the rendering by setting a sink to the renderer to get data
1787 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001788 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001789 // TODO(xians): Make sure Start() is called only once.
1790 void Start(AudioRenderer* renderer) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001791 rtc::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001792 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001793 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001794 ASSERT(renderer_ == renderer);
1795 return;
1796 }
1797
1798 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1799 // in getUserMedia by default.
1800 renderer->AddChannel(channel_);
1801 renderer->SetSink(this);
1802 renderer_ = renderer;
1803 }
1804
1805 // Stops rendering by setting the sink of the renderer to NULL. No data
1806 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001807 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001808 void Stop() {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001809 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001810 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001811 return;
1812
1813 renderer_->RemoveChannel(channel_);
1814 renderer_->SetSink(NULL);
1815 renderer_ = NULL;
1816 }
1817
1818 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001819 // This method is called on the audio thread.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001820 void OnData(const void* audio_data,
1821 int bits_per_sample,
1822 int sample_rate,
1823 int number_of_channels,
1824 int number_of_frames) override {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001825 voe_audio_transport_->OnData(channel_,
1826 audio_data,
1827 bits_per_sample,
1828 sample_rate,
1829 number_of_channels,
1830 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001831 }
1832
1833 // Callback from the |renderer_| when it is going away. In case Start() has
1834 // never been called, this callback won't be triggered.
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +00001835 void OnClose() override {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001836 rtc::CritScope lock(&lock_);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001837 // Set |renderer_| to NULL to make sure no more callback will get into
1838 // the renderer.
1839 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001840 }
1841
1842 // Accessor to the VoE channel ID.
1843 int channel() const { return channel_; }
1844
1845 private:
1846 const int channel_;
1847 webrtc::AudioTransport* const voe_audio_transport_;
1848
1849 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1850 // PeerConnection will make sure invalidating the pointer before the object
1851 // goes away.
1852 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001853
1854 // Protects |renderer_| in Start(), Stop() and OnClose().
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001855 rtc::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001856};
1857
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001858// WebRtcVoiceMediaChannel
1859WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1860 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1861 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001862 engine->CreateMediaVoiceChannel()),
minyue@webrtc.org26236952014-10-29 02:27:08 +00001863 send_bitrate_setting_(false),
1864 send_bitrate_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001865 options_(),
1866 dtmf_allowed_(false),
1867 desired_playout_(false),
1868 nack_enabled_(false),
1869 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001870 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001871 desired_send_(SEND_NOTHING),
1872 send_(SEND_NOTHING),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001873 shared_bwe_vie_(NULL),
1874 shared_bwe_vie_channel_(-1),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001875 default_receive_ssrc_(0) {
1876 engine->RegisterChannel(this);
1877 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1878 << voe_channel();
1879
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001880 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001881}
1882
1883WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1884 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1885 << voe_channel();
buildbot@webrtc.org6e5c7842014-09-19 06:46:37 +00001886 SetupSharedBandwidthEstimation(NULL, -1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001887
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001888 // Remove any remaining send streams, the default channel will be deleted
1889 // later.
1890 while (!send_channels_.empty())
1891 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001892
1893 // Unregister ourselves from the engine.
1894 engine()->UnregisterChannel(this);
1895 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001896 while (!receive_channels_.empty()) {
1897 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001898 }
1899
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001900 // Delete the default channel.
1901 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001902}
1903
1904bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1905 LOG(LS_INFO) << "Setting voice channel options: "
1906 << options.ToString();
1907
wu@webrtc.orgde305012013-10-31 15:40:38 +00001908 // Check if DSCP value is changed from previous.
1909 bool dscp_option_changed = (options_.dscp != options.dscp);
1910
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001911 // TODO(xians): Add support to set different options for different send
1912 // streams after we support multiple APMs.
1913
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001914 // We retain all of the existing options, and apply the given ones
1915 // on top. This means there is no way to "clear" options such that
1916 // they go back to the engine default.
1917 options_.SetAll(options);
1918
1919 if (send_ != SEND_NOTHING) {
1920 if (!engine()->SetOptionOverrides(options_)) {
1921 LOG(LS_WARNING) <<
1922 "Failed to engine SetOptionOverrides during channel SetOptions.";
1923 return false;
1924 }
1925 } else {
1926 // Will be interpreted when appropriate.
1927 }
1928
wu@webrtc.org97077a32013-10-25 21:18:33 +00001929 // Receiver-side auto gain control happens per channel, so set it here from
1930 // options. Note that, like conference mode, setting it on the engine won't
1931 // have the desired effect, since voice channels don't inherit options from
1932 // the media engine when those options are applied per-channel.
1933 bool rx_auto_gain_control;
1934 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1935 if (engine()->voe()->processing()->SetRxAgcStatus(
1936 voe_channel(), rx_auto_gain_control,
1937 webrtc::kAgcFixedDigital) == -1) {
1938 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1939 return false;
1940 } else {
1941 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1942 << " with mode " << webrtc::kAgcFixedDigital;
1943 }
1944 }
1945 if (options.rx_agc_target_dbov.IsSet() ||
1946 options.rx_agc_digital_compression_gain.IsSet() ||
1947 options.rx_agc_limiter.IsSet()) {
1948 webrtc::AgcConfig config;
1949 // If only some of the options are being overridden, get the current
1950 // settings for the channel and bail if they aren't available.
1951 if (!options.rx_agc_target_dbov.IsSet() ||
1952 !options.rx_agc_digital_compression_gain.IsSet() ||
1953 !options.rx_agc_limiter.IsSet()) {
1954 if (engine()->voe()->processing()->GetRxAgcConfig(
1955 voe_channel(), config) != 0) {
1956 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1957 << "channel " << voe_channel() << ". Since not all rx "
1958 << "agc options are specified, unable to safely set rx "
1959 << "agc options.";
1960 return false;
1961 }
1962 }
1963 config.targetLeveldBOv =
1964 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1965 config.targetLeveldBOv);
1966 config.digitalCompressionGaindB =
1967 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1968 config.digitalCompressionGaindB);
1969 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1970 config.limiterEnable);
1971 if (engine()->voe()->processing()->SetRxAgcConfig(
1972 voe_channel(), config) == -1) {
1973 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1974 config.digitalCompressionGaindB, config.limiterEnable);
1975 return false;
1976 }
1977 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001978 if (dscp_option_changed) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001979 rtc::DiffServCodePoint dscp = rtc::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001980 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001981 dscp = kAudioDscpValue;
1982 if (MediaChannel::SetDscp(dscp) != 0) {
1983 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1984 }
1985 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001986
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00001987 // Force update of Video Engine BWE forwarding to reflect experiment setting.
1988 if (!SetupSharedBandwidthEstimation(shared_bwe_vie_,
1989 shared_bwe_vie_channel_)) {
1990 return false;
1991 }
1992
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001993 LOG(LS_INFO) << "Set voice channel options. Current options: "
1994 << options_.ToString();
1995 return true;
1996}
1997
1998bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1999 const std::vector<AudioCodec>& codecs) {
2000 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002001 LOG(LS_INFO) << "Setting receive voice codecs:";
2002
2003 std::vector<AudioCodec> new_codecs;
2004 // Find all new codecs. We allow adding new codecs but don't allow changing
2005 // the payload type of codecs that is already configured since we might
2006 // already be receiving packets with that payload type.
2007 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002008 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002009 AudioCodec old_codec;
2010 if (FindCodec(recv_codecs_, *it, &old_codec)) {
2011 if (old_codec.id != it->id) {
2012 LOG(LS_ERROR) << it->name << " payload type changed.";
2013 return false;
2014 }
2015 } else {
2016 new_codecs.push_back(*it);
2017 }
2018 }
2019 if (new_codecs.empty()) {
2020 // There are no new codecs to configure. Already configured codecs are
2021 // never removed.
2022 return true;
2023 }
2024
2025 if (playout_) {
2026 // Receive codecs can not be changed while playing. So we temporarily
2027 // pause playout.
2028 PausePlayout();
2029 }
2030
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002031 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002032 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
2033 it != new_codecs.end() && ret; ++it) {
2034 webrtc::CodecInst voe_codec;
2035 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2036 LOG(LS_INFO) << ToString(*it);
2037 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002038 if (default_receive_ssrc_ == 0) {
2039 // Set the receive codecs on the default channel explicitly if the
2040 // default channel is not used by |receive_channels_|, this happens in
2041 // conference mode or in non-conference mode when there is no playout
2042 // channel.
2043 // TODO(xians): Figure out how we use the default channel in conference
2044 // mode.
2045 if (engine()->voe()->codec()->SetRecPayloadType(
2046 voe_channel(), voe_codec) == -1) {
2047 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
2048 ret = false;
2049 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002050 }
2051
2052 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002053 for (ChannelMap::iterator it = receive_channels_.begin();
2054 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002055 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002056 it->second->channel(), voe_codec) == -1) {
2057 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002058 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002059 ret = false;
2060 }
2061 }
2062 } else {
2063 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2064 ret = false;
2065 }
2066 }
2067 if (ret) {
2068 recv_codecs_ = codecs;
2069 }
2070
2071 if (desired_playout_ && !playout_) {
2072 ResumePlayout();
2073 }
2074 return ret;
2075}
2076
2077bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002078 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002079 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002080 engine()->voe()->codec()->SetVADStatus(channel, false);
2081 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002082 engine()->voe()->rtp()->SetREDStatus(channel, false);
2083 engine()->voe()->codec()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002084
2085 // Scan through the list to figure out the codec to use for sending, along
2086 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002087 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002088 webrtc::CodecInst send_codec;
2089 memset(&send_codec, 0, sizeof(send_codec));
2090
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002091 bool nack_enabled = nack_enabled_;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002092 bool enable_codec_fec = false;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002093
minyue@webrtc.org26236952014-10-29 02:27:08 +00002094 int opus_max_playback_rate = 0;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002095
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002096 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002097 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2098 it != codecs.end(); ++it) {
2099 // Ignore codecs we don't know about. The negotiation step should prevent
2100 // this, but double-check to be sure.
2101 webrtc::CodecInst voe_codec;
2102 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002103 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002104 continue;
2105 }
2106
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002107 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2108 // Skip telephone-event/CN codec, which will be handled later.
2109 continue;
2110 }
2111
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002112 // We'll use the first codec in the list to actually send audio data.
2113 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002114 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002115 // used is specified in params.
2116 if (IsRedCodec(it->name)) {
2117 // Parse out the RED parameters. If we fail, just ignore RED;
2118 // we don't support all possible params/usage scenarios.
2119 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2120 continue;
2121 }
2122
2123 // Enable redundant encoding of the specified codec. Treat any
2124 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002125 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2126 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2127 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002128 return false;
2129 }
2130 } else {
2131 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002132 nack_enabled = IsNackEnabled(*it);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002133 // For Opus as the send codec, we are to enable inband FEC if requested
2134 // and set maximum playback rate.
2135 if (IsOpus(*it)) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00002136 GetOpusConfig(*it, &send_codec, &enable_codec_fec,
2137 &opus_max_playback_rate);
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002138 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002139 }
2140 found_send_codec = true;
2141 break;
2142 }
2143
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002144 if (nack_enabled_ != nack_enabled) {
2145 SetNack(channel, nack_enabled);
2146 nack_enabled_ = nack_enabled;
2147 }
2148
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002149 if (!found_send_codec) {
2150 LOG(LS_WARNING) << "Received empty list of codecs.";
2151 return false;
2152 }
2153
2154 // Set the codec immediately, since SetVADStatus() depends on whether
2155 // the current codec is mono or stereo.
2156 if (!SetSendCodec(channel, send_codec))
2157 return false;
2158
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002159 // FEC should be enabled after SetSendCodec.
2160 if (enable_codec_fec) {
2161 LOG(LS_INFO) << "Attempt to enable codec internal FEC on channel "
2162 << channel;
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002163 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2164 // Enable codec internal FEC. Treat any failure as fatal internal error.
2165 LOG_RTCERR2(SetFECStatus, channel, true);
2166 return false;
2167 }
buildbot@webrtc.org3ffa1f92014-07-02 19:51:26 +00002168 }
2169
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002170 // maxplaybackrate should be set after SetSendCodec.
minyue@webrtc.org26236952014-10-29 02:27:08 +00002171 // If opus_max_playback_rate <= 0, the default maximum playback rate of 48 kHz
2172 // will be used.
2173 if (opus_max_playback_rate > 0) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002174 LOG(LS_INFO) << "Attempt to set maximum playback rate to "
minyue@webrtc.org26236952014-10-29 02:27:08 +00002175 << opus_max_playback_rate
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002176 << " Hz on channel "
2177 << channel;
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002178 if (engine()->voe()->codec()->SetOpusMaxPlaybackRate(
minyue@webrtc.org26236952014-10-29 02:27:08 +00002179 channel, opus_max_playback_rate) == -1) {
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002180 LOG(LS_WARNING) << "Could not set maximum playback rate.";
2181 }
buildbot@webrtc.org5d639b32014-09-10 07:57:12 +00002182 }
2183
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002184 // Always update the |send_codec_| to the currently set send codec.
2185 send_codec_.reset(new webrtc::CodecInst(send_codec));
2186
minyue@webrtc.org26236952014-10-29 02:27:08 +00002187 if (send_bitrate_setting_) {
2188 SetSendBitrateInternal(send_bitrate_bps_);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002189 }
2190
2191 // Loop through the codecs list again to config the telephone-event/CN codec.
2192 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2193 it != codecs.end(); ++it) {
2194 // Ignore codecs we don't know about. The negotiation step should prevent
2195 // this, but double-check to be sure.
2196 webrtc::CodecInst voe_codec;
2197 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2198 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2199 continue;
2200 }
2201
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002202 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2203 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002204 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002205 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2206 channel, it->id) == -1) {
2207 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2208 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002209 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002210 } else if (IsCNCodec(it->name)) {
2211 // Turn voice activity detection/comfort noise on if supported.
2212 // Set the wideband CN payload type appropriately.
2213 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002214 webrtc::PayloadFrequencies cn_freq;
2215 switch (it->clockrate) {
2216 case 8000:
2217 cn_freq = webrtc::kFreq8000Hz;
2218 break;
2219 case 16000:
2220 cn_freq = webrtc::kFreq16000Hz;
2221 break;
2222 case 32000:
2223 cn_freq = webrtc::kFreq32000Hz;
2224 break;
2225 default:
2226 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2227 << " not supported.";
2228 continue;
2229 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002230 // Set the CN payloadtype and the VAD status.
2231 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2232 if (cn_freq != webrtc::kFreq8000Hz) {
2233 if (engine()->voe()->codec()->SetSendCNPayloadType(
2234 channel, it->id, cn_freq) == -1) {
2235 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2236 // TODO(ajm): This failure condition will be removed from VoE.
2237 // Restore the return here when we update to a new enough webrtc.
2238 //
2239 // Not returning false because the SetSendCNPayloadType will fail if
2240 // the channel is already sending.
2241 // This can happen if the remote description is applied twice, for
2242 // example in the case of ROAP on top of JSEP, where both side will
2243 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002244 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002245 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002246 // Only turn on VAD if we have a CN payload type that matches the
2247 // clockrate for the codec we are going to use.
2248 if (it->clockrate == send_codec.plfreq) {
2249 LOG(LS_INFO) << "Enabling VAD";
2250 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2251 LOG_RTCERR2(SetVADStatus, channel, true);
2252 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002253 }
2254 }
2255 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002256 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002257 return true;
2258}
2259
2260bool WebRtcVoiceMediaChannel::SetSendCodecs(
2261 const std::vector<AudioCodec>& codecs) {
2262 dtmf_allowed_ = false;
2263 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2264 it != codecs.end(); ++it) {
2265 // Find the DTMF telephone event "codec".
2266 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2267 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2268 dtmf_allowed_ = true;
2269 }
2270 }
2271
2272 // Cache the codecs in order to configure the channel created later.
2273 send_codecs_ = codecs;
2274 for (ChannelMap::iterator iter = send_channels_.begin();
2275 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002276 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002277 return false;
2278 }
2279 }
2280
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002281 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002282 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002283 return true;
2284}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002285
2286void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2287 bool nack_enabled) {
2288 for (ChannelMap::const_iterator it = channels.begin();
2289 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002290 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002291 }
2292}
2293
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002294void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002295 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002296 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002297 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2298 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002299 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002300 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2301 }
2302}
2303
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002304bool WebRtcVoiceMediaChannel::SetSendCodec(
2305 const webrtc::CodecInst& send_codec) {
2306 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2307 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002308 for (ChannelMap::iterator iter = send_channels_.begin();
2309 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002310 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002311 return false;
2312 }
2313
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002314 return true;
2315}
2316
2317bool WebRtcVoiceMediaChannel::SetSendCodec(
2318 int channel, const webrtc::CodecInst& send_codec) {
2319 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2320 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2321
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002322 webrtc::CodecInst current_codec;
2323 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2324 (send_codec == current_codec)) {
2325 // Codec is already configured, we can return without setting it again.
2326 return true;
2327 }
2328
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002329 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2330 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002331 return false;
2332 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002333 return true;
2334}
2335
2336bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2337 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002338 if (receive_extensions_ == extensions) {
2339 return true;
2340 }
2341
2342 // The default channel may or may not be in |receive_channels_|. Set the rtp
2343 // header extensions for default channel regardless.
2344 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2345 return false;
2346 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002347
2348 // Loop through all receive channels and enable/disable the extensions.
2349 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2350 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002351 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2352 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002353 return false;
2354 }
2355 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002356
2357 receive_extensions_ = extensions;
2358 return true;
2359}
2360
2361bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2362 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002363 const RtpHeaderExtension* audio_level_extension =
2364 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2365 if (!SetHeaderExtension(
2366 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2367 audio_level_extension)) {
2368 return false;
2369 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002370
2371 const RtpHeaderExtension* send_time_extension =
2372 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2373 if (!SetHeaderExtension(
2374 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2375 send_time_extension)) {
2376 return false;
2377 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002378 return true;
2379}
2380
2381bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2382 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002383 if (send_extensions_ == extensions) {
2384 return true;
2385 }
2386
2387 // The default channel may or may not be in |send_channels_|. Set the rtp
2388 // header extensions for default channel regardless.
2389
2390 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2391 return false;
2392 }
2393
2394 // Loop through all send channels and enable/disable the extensions.
2395 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2396 channel_it != send_channels_.end(); ++channel_it) {
2397 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2398 extensions)) {
2399 return false;
2400 }
2401 }
2402
2403 send_extensions_ = extensions;
2404 return true;
2405}
2406
2407bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2408 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002409 const RtpHeaderExtension* audio_level_extension =
2410 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002411
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002412 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002413 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002414 audio_level_extension)) {
2415 return false;
2416 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002417
2418 const RtpHeaderExtension* send_time_extension =
2419 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002420 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002421 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002422 send_time_extension)) {
2423 return false;
2424 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002425
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002426 return true;
2427}
2428
2429bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2430 desired_playout_ = playout;
2431 return ChangePlayout(desired_playout_);
2432}
2433
2434bool WebRtcVoiceMediaChannel::PausePlayout() {
2435 return ChangePlayout(false);
2436}
2437
2438bool WebRtcVoiceMediaChannel::ResumePlayout() {
2439 return ChangePlayout(desired_playout_);
2440}
2441
2442bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2443 if (playout_ == playout) {
2444 return true;
2445 }
2446
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002447 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002448 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002449 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002450 // Only toggle the default channel if we don't have any other channels.
2451 result = SetPlayout(voe_channel(), playout);
2452 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002453 for (ChannelMap::iterator it = receive_channels_.begin();
2454 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002455 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002456 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002457 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002458 result = false;
2459 }
2460 }
2461
2462 if (result) {
2463 playout_ = playout;
2464 }
2465 return result;
2466}
2467
2468bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2469 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002470 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002471 return ChangeSend(desired_send_);
2472 return true;
2473}
2474
2475bool WebRtcVoiceMediaChannel::PauseSend() {
2476 return ChangeSend(SEND_NOTHING);
2477}
2478
2479bool WebRtcVoiceMediaChannel::ResumeSend() {
2480 return ChangeSend(desired_send_);
2481}
2482
2483bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2484 if (send_ == send) {
2485 return true;
2486 }
2487
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002488 // Change the settings on each send channel.
2489 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002490 engine()->SetOptionOverrides(options_);
2491
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002492 // Change the settings on each send channel.
2493 for (ChannelMap::iterator iter = send_channels_.begin();
2494 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002495 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002496 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002497 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002498
2499 // Clear up the options after stopping sending.
2500 if (send == SEND_NOTHING)
2501 engine()->ClearOptionOverrides();
2502
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002503 send_ = send;
2504 return true;
2505}
2506
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002507bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2508 if (send == SEND_MICROPHONE) {
2509 if (engine()->voe()->base()->StartSend(channel) == -1) {
2510 LOG_RTCERR1(StartSend, channel);
2511 return false;
2512 }
2513 if (engine()->voe()->file() &&
2514 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2515 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2516 return false;
2517 }
2518 } else { // SEND_NOTHING
2519 ASSERT(send == SEND_NOTHING);
2520 if (engine()->voe()->base()->StopSend(channel) == -1) {
2521 LOG_RTCERR1(StopSend, channel);
2522 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002523 }
2524 }
2525
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002526 return true;
2527}
2528
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002529// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002530void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2531 if (engine()->voe()->network()->RegisterExternalTransport(
2532 channel, *this) == -1) {
2533 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2534 }
2535
2536 // Enable RTCP (for quality stats and feedback messages)
2537 EnableRtcp(channel);
2538
2539 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2540 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002541
2542 // Set RTP header extension for the new channel.
2543 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002544}
2545
2546bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2547 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2548 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2549 }
2550
2551 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2552 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002553 return false;
2554 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002555
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002556 return true;
2557}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002558
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002559bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2560 // If the default channel is already used for sending create a new channel
2561 // otherwise use the default channel for sending.
2562 int channel = GetSendChannelNum(sp.first_ssrc());
2563 if (channel != -1) {
2564 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2565 return false;
2566 }
2567
2568 bool default_channel_is_available = true;
2569 for (ChannelMap::const_iterator iter = send_channels_.begin();
2570 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002571 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002572 default_channel_is_available = false;
2573 break;
2574 }
2575 }
2576 if (default_channel_is_available) {
2577 channel = voe_channel();
2578 } else {
2579 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002580 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002581 if (channel == -1) {
2582 LOG_RTCERR0(CreateChannel);
2583 return false;
2584 }
2585
2586 ConfigureSendChannel(channel);
2587 }
2588
2589 // Save the channel to send_channels_, so that RemoveSendStream() can still
2590 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002591 webrtc::AudioTransport* audio_transport =
2592 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002593 send_channels_.insert(std::make_pair(
2594 sp.first_ssrc(),
2595 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002596
2597 // Set the send (local) SSRC.
2598 // If there are multiple send SSRCs, we can only set the first one here, and
2599 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2600 // (with a codec requires multiple SSRC(s)).
2601 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2602 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2603 return false;
2604 }
2605
2606 // At this point the channel's local SSRC has been updated. If the channel is
2607 // the default channel make sure that all the receive channels are updated as
2608 // well. Receive channels have to have the same SSRC as the default channel in
2609 // order to send receiver reports with this SSRC.
2610 if (IsDefaultChannel(channel)) {
2611 for (ChannelMap::const_iterator it = receive_channels_.begin();
2612 it != receive_channels_.end(); ++it) {
2613 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002614 if (!IsDefaultChannel(it->second->channel())) {
2615 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002616 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002617 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002618 return false;
2619 }
2620 }
2621 }
2622 }
2623
2624 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002625 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2626 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002627 }
2628
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002629 // Set the current codecs to be used for the new channel.
2630 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002631 return false;
2632
2633 return ChangeSend(channel, desired_send_);
2634}
2635
2636bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2637 ChannelMap::iterator it = send_channels_.find(ssrc);
2638 if (it == send_channels_.end()) {
2639 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2640 << " which doesn't exist.";
2641 return false;
2642 }
2643
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002644 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002645 ChangeSend(channel, SEND_NOTHING);
2646
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002647 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2648 // this will disconnect the audio renderer with the send channel.
2649 delete it->second;
2650 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002651
2652 if (IsDefaultChannel(channel)) {
2653 // Do not delete the default channel since the receive channels depend on
2654 // the default channel, recycle it instead.
2655 ChangeSend(channel, SEND_NOTHING);
2656 } else {
2657 // Clean up and delete the send channel.
2658 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2659 << " with VoiceEngine channel #" << channel << ".";
2660 if (!DeleteChannel(channel))
2661 return false;
2662 }
2663
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002664 if (send_channels_.empty())
2665 ChangeSend(SEND_NOTHING);
2666
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002667 return true;
2668}
2669
2670bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002671 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002672
2673 if (!VERIFY(sp.ssrcs.size() == 1))
2674 return false;
2675 uint32 ssrc = sp.first_ssrc();
2676
wu@webrtc.org78187522013-10-07 23:32:02 +00002677 if (ssrc == 0) {
2678 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2679 return false;
2680 }
2681
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002682 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2683 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002684 return false;
2685 }
2686
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002687 // Reuse default channel for recv stream in non-conference mode call
2688 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002689 webrtc::AudioTransport* audio_transport =
2690 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002691 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2692 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2693 << " reuse default channel";
2694 default_receive_ssrc_ = sp.first_ssrc();
2695 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002696 default_receive_ssrc_,
2697 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002698 if (!SetupSharedBweOnChannel(voe_channel())) {
2699 return false;
2700 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002701 return SetPlayout(voe_channel(), playout_);
2702 }
2703
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002704 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002705 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002706 if (channel == -1) {
2707 LOG_RTCERR0(CreateChannel);
2708 return false;
2709 }
2710
wu@webrtc.org78187522013-10-07 23:32:02 +00002711 if (!ConfigureRecvChannel(channel)) {
2712 DeleteChannel(channel);
2713 return false;
2714 }
2715
2716 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002717 std::make_pair(
2718 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002719
2720 LOG(LS_INFO) << "New audio stream " << ssrc
2721 << " registered to VoiceEngine channel #"
2722 << channel << ".";
2723 return true;
2724}
2725
2726bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002727 // Configure to use external transport, like our default channel.
2728 if (engine()->voe()->network()->RegisterExternalTransport(
2729 channel, *this) == -1) {
2730 LOG_RTCERR2(SetExternalTransport, channel, this);
2731 return false;
2732 }
2733
2734 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002735 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002736 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2737 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002738 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002739 return false;
2740 }
2741 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002742 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002743 return false;
2744 }
2745
2746 // Use the same recv payload types as our default channel.
2747 ResetRecvCodecs(channel);
2748 if (!recv_codecs_.empty()) {
2749 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2750 it != recv_codecs_.end(); ++it) {
2751 webrtc::CodecInst voe_codec;
2752 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2753 voe_codec.pltype = it->id;
2754 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2755 if (engine()->voe()->codec()->GetRecPayloadType(
2756 voe_channel(), voe_codec) != -1) {
2757 if (engine()->voe()->codec()->SetRecPayloadType(
2758 channel, voe_codec) == -1) {
2759 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2760 return false;
2761 }
2762 }
2763 }
2764 }
2765 }
2766
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002767 if (InConferenceMode()) {
2768 // To be in par with the video, voe_channel() is not used for receiving in
2769 // a conference call.
2770 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2771 // This is the first stream in a multi user meeting. We can now
2772 // disable playback of the default stream. This since the default
2773 // stream will probably have received some initial packets before
2774 // the new stream was added. This will mean that the CN state from
2775 // the default channel will be mixed in with the other streams
2776 // throughout the whole meeting, which might be disturbing.
2777 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2778 SetPlayout(voe_channel(), false);
2779 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002780 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002781 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002782
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002783 // Set RTP header extension for the new channel.
2784 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2785 return false;
2786 }
2787
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00002788 // Set up channel to be able to forward incoming packets to video engine BWE.
2789 if (!SetupSharedBweOnChannel(channel)) {
2790 return false;
2791 }
2792
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002793 return SetPlayout(channel, playout_);
2794}
2795
2796bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002797 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002798 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002799 if (it == receive_channels_.end()) {
2800 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2801 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002802 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002803 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002804
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002805 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2806 // will disconnect the audio renderer with the receive channel.
2807 // Cache the channel before the deletion.
2808 const int channel = it->second->channel();
2809 delete it->second;
2810 receive_channels_.erase(it);
2811
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002812 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002813 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002814 // Recycle the default channel is for recv stream.
2815 if (playout_)
2816 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002817
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002818 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002819 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002820 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002821
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002822 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002823 << " with VoiceEngine channel #" << channel << ".";
2824 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002825 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002826
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002827 bool enable_default_channel_playout = false;
2828 if (receive_channels_.empty()) {
2829 // The last stream was removed. We can now enable the default
2830 // channel for new channels to be played out immediately without
2831 // waiting for AddStream messages.
2832 // We do this for both conference mode and non-conference mode.
2833 // TODO(oja): Does the default channel still have it's CN state?
2834 enable_default_channel_playout = true;
2835 }
2836 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2837 default_receive_ssrc_ != 0) {
2838 // Only the default channel is active, enable the playout on default
2839 // channel.
2840 enable_default_channel_playout = true;
2841 }
2842 if (enable_default_channel_playout && playout_) {
2843 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2844 SetPlayout(voe_channel(), true);
2845 }
2846
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002847 return true;
2848}
2849
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002850bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2851 AudioRenderer* renderer) {
2852 ChannelMap::iterator it = receive_channels_.find(ssrc);
2853 if (it == receive_channels_.end()) {
2854 if (renderer) {
2855 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002856 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002857 return false;
2858 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002859
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002860 // The channel likely has gone away, do nothing.
2861 return true;
2862 }
2863
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002864 if (renderer)
2865 it->second->Start(renderer);
2866 else
2867 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002868
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002869 return true;
2870}
2871
2872bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2873 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002874 ChannelMap::iterator it = send_channels_.find(ssrc);
2875 if (it == send_channels_.end()) {
2876 if (renderer) {
2877 // Return an error if trying to set a valid renderer with an invalid ssrc.
2878 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2879 return false;
2880 }
2881
2882 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002883 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002884 }
2885
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002886 if (renderer)
2887 it->second->Start(renderer);
2888 else
2889 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002890
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002891 return true;
2892}
2893
2894bool WebRtcVoiceMediaChannel::GetActiveStreams(
2895 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002896 // In conference mode, the default channel should not be in
2897 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002898 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002899 for (ChannelMap::iterator it = receive_channels_.begin();
2900 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002901 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002902 if (level > 0) {
2903 actives->push_back(std::make_pair(it->first, level));
2904 }
2905 }
2906 return true;
2907}
2908
2909int WebRtcVoiceMediaChannel::GetOutputLevel() {
2910 // return the highest output level of all streams
2911 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002912 for (ChannelMap::iterator it = receive_channels_.begin();
2913 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002914 int level = GetOutputLevel(it->second->channel());
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002915 highest = std::max(level, highest);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002916 }
2917 return highest;
2918}
2919
2920int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2921 int ret;
2922 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2923 // In case of error, log the info and continue
2924 LOG_RTCERR0(TimeSinceLastTyping);
2925 ret = -1;
2926 } else {
2927 ret *= 1000; // We return ms, webrtc returns seconds.
2928 }
2929 return ret;
2930}
2931
2932void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2933 int cost_per_typing, int reporting_threshold, int penalty_decay,
2934 int type_event_delay) {
2935 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2936 time_window, cost_per_typing,
2937 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2938 // In case of error, log the info and continue
2939 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2940 cost_per_typing, reporting_threshold, penalty_decay,
2941 type_event_delay);
2942 }
2943}
2944
2945bool WebRtcVoiceMediaChannel::SetOutputScaling(
2946 uint32 ssrc, double left, double right) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002947 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002948 // Collect the channels to scale the output volume.
2949 std::vector<int> channels;
2950 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002951 // Default channel is not in receive_channels_ if it is not being used for
2952 // playout.
2953 if (default_receive_ssrc_ == 0)
2954 channels.push_back(voe_channel());
2955 for (ChannelMap::const_iterator it = receive_channels_.begin();
2956 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002957 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002958 }
2959 } else { // Collect only the channel of the specified ssrc.
2960 int channel = GetReceiveChannelNum(ssrc);
2961 if (-1 == channel) {
2962 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2963 return false;
2964 }
2965 channels.push_back(channel);
2966 }
2967
2968 // Scale the output volume for the collected channels. We first normalize to
2969 // scale the volume and then set the left and right pan.
andresp@webrtc.orgff689be2015-02-12 11:54:26 +00002970 float scale = static_cast<float>(std::max(left, right));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002971 if (scale > 0.0001f) {
2972 left /= scale;
2973 right /= scale;
2974 }
2975 for (std::vector<int>::const_iterator it = channels.begin();
2976 it != channels.end(); ++it) {
2977 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2978 *it, scale)) {
2979 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2980 return false;
2981 }
2982 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2983 *it, static_cast<float>(left), static_cast<float>(right))) {
2984 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2985 // Do not return if fails. SetOutputVolumePan is not available for all
2986 // pltforms.
2987 }
2988 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2989 << " right=" << right * scale
2990 << " for channel " << *it << " and ssrc " << ssrc;
2991 }
2992 return true;
2993}
2994
2995bool WebRtcVoiceMediaChannel::GetOutputScaling(
2996 uint32 ssrc, double* left, double* right) {
2997 if (!left || !right) return false;
2998
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002999 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003000 // Determine which channel based on ssrc.
3001 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
3002 if (channel == -1) {
3003 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
3004 return false;
3005 }
3006
3007 float scaling;
3008 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
3009 channel, scaling)) {
3010 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
3011 return false;
3012 }
3013
3014 float left_pan;
3015 float right_pan;
3016 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
3017 channel, left_pan, right_pan)) {
3018 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
3019 // If GetOutputVolumePan fails, we use the default left and right pan.
3020 left_pan = 1.0f;
3021 right_pan = 1.0f;
3022 }
3023
3024 *left = scaling * left_pan;
3025 *right = scaling * right_pan;
3026 return true;
3027}
3028
3029bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
3030 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
3031 return true;
3032}
3033
3034bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
3035 bool play, bool loop) {
3036 if (!ringback_tone_) {
3037 return false;
3038 }
3039
3040 // The voe file api is not available in chrome.
3041 if (!engine()->voe()->file()) {
3042 return false;
3043 }
3044
3045 // Determine which VoiceEngine channel to play on.
3046 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
3047 if (channel == -1) {
3048 return false;
3049 }
3050
3051 // Make sure the ringtone is cued properly, and play it out.
3052 if (play) {
3053 ringback_tone_->set_loop(loop);
3054 ringback_tone_->Rewind();
3055 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
3056 ringback_tone_.get()) == -1) {
3057 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
3058 LOG(LS_ERROR) << "Unable to start ringback tone";
3059 return false;
3060 }
3061 ringback_channels_.insert(channel);
3062 LOG(LS_INFO) << "Started ringback on channel " << channel;
3063 } else {
3064 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
3065 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
3066 LOG_RTCERR1(StopPlayingFileLocally, channel);
3067 return false;
3068 }
3069 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
3070 ringback_channels_.erase(channel);
3071 }
3072
3073 return true;
3074}
3075
3076bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
3077 return dtmf_allowed_;
3078}
3079
3080bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
3081 int duration, int flags) {
3082 if (!dtmf_allowed_) {
3083 return false;
3084 }
3085
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003086 // Send the event.
3087 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003088 int channel = -1;
3089 if (ssrc == 0) {
3090 bool default_channel_is_inuse = false;
3091 for (ChannelMap::const_iterator iter = send_channels_.begin();
3092 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003093 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003094 default_channel_is_inuse = true;
3095 break;
3096 }
3097 }
3098 if (default_channel_is_inuse) {
3099 channel = voe_channel();
3100 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003101 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00003102 }
3103 } else {
3104 channel = GetSendChannelNum(ssrc);
3105 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003106 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003107 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3108 << ssrc << " is not in use.";
3109 return false;
3110 }
3111 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003112 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3113 channel, event, true, duration) == -1) {
3114 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003115 return false;
3116 }
3117 }
3118
3119 // Play the event.
3120 if (flags & cricket::DF_PLAY) {
3121 // Play DTMF tone locally.
3122 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3123 LOG_RTCERR2(PlayDtmfTone, event, duration);
3124 return false;
3125 }
3126 }
3127
3128 return true;
3129}
3130
wu@webrtc.orga9890802013-12-13 00:21:03 +00003131void WebRtcVoiceMediaChannel::OnPacketReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003132 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003133 // Pick which channel to send this packet to. If this packet doesn't match
3134 // any multiplexed streams, just send it to the default channel. Otherwise,
3135 // send it to the specific decoder instance for that stream.
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003136 int which_channel =
3137 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), false));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003138 if (which_channel == -1) {
3139 which_channel = voe_channel();
3140 }
3141
3142 // Stop any ringback that might be playing on the channel.
3143 // It's possible the ringback has already stopped, ih which case we'll just
3144 // use the opportunity to remove the channel from ringback_channels_.
3145 if (engine()->voe()->file()) {
3146 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3147 if (it != ringback_channels_.end()) {
3148 if (engine()->voe()->file()->IsPlayingFileLocally(
3149 which_channel) == 1) {
3150 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3151 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3152 << " due to incoming media";
3153 }
3154 ringback_channels_.erase(which_channel);
3155 }
3156 }
3157
3158 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003159 engine()->voe()->network()->ReceivedRTPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003160 which_channel, packet->data(), packet->size(),
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003161 webrtc::PacketTime(packet_time.timestamp, packet_time.not_before));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003162}
3163
wu@webrtc.orga9890802013-12-13 00:21:03 +00003164void WebRtcVoiceMediaChannel::OnRtcpReceived(
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003165 rtc::Buffer* packet, const rtc::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003166 // Sending channels need all RTCP packets with feedback information.
3167 // Even sender reports can contain attached report blocks.
3168 // Receiving channels need sender reports in order to create
3169 // correct receiver reports.
3170 int type = 0;
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003171 if (!GetRtcpType(packet->data(), packet->size(), &type)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003172 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3173 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003174 }
3175
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003176 // If it is a sender report, find the channel that is listening.
3177 bool has_sent_to_default_channel = false;
3178 if (type == kRtcpTypeSR) {
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003179 int which_channel =
3180 GetReceiveChannelNum(ParseSsrc(packet->data(), packet->size(), true));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003181 if (which_channel != -1) {
3182 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003183 which_channel, packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003184
3185 if (IsDefaultChannel(which_channel))
3186 has_sent_to_default_channel = true;
3187 }
3188 }
3189
3190 // SR may continue RR and any RR entry may correspond to any one of the send
3191 // channels. So all RTCP packets must be forwarded all send channels. VoE
3192 // will filter out RR internally.
3193 for (ChannelMap::iterator iter = send_channels_.begin();
3194 iter != send_channels_.end(); ++iter) {
3195 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003196 if (IsDefaultChannel(iter->second->channel()) &&
3197 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003198 continue;
3199
3200 engine()->voe()->network()->ReceivedRTCPPacket(
kwiberg@webrtc.orgeebcab52015-03-24 09:19:06 +00003201 iter->second->channel(), packet->data(), packet->size());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003202 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003203}
3204
3205bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003206 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3207 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003208 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3209 return false;
3210 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003211 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3212 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003213 return false;
3214 }
buildbot@webrtc.org6b21b712014-07-31 15:08:53 +00003215 // We set the AGC to mute state only when all the channels are muted.
3216 // This implementation is not ideal, instead we should signal the AGC when
3217 // the mic channel is muted/unmuted. We can't do it today because there
3218 // is no good way to know which stream is mapping to the mic channel.
3219 bool all_muted = muted;
3220 for (ChannelMap::const_iterator iter = send_channels_.begin();
3221 iter != send_channels_.end() && all_muted; ++iter) {
3222 if (engine()->voe()->volume()->GetInputMute(iter->second->channel(),
3223 all_muted)) {
3224 LOG_RTCERR1(GetInputMute, iter->second->channel());
3225 return false;
3226 }
3227 }
3228
3229 webrtc::AudioProcessing* ap = engine()->voe()->base()->audio_processing();
3230 if (ap)
3231 ap->set_output_will_be_muted(all_muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003232 return true;
3233}
3234
minyue@webrtc.org26236952014-10-29 02:27:08 +00003235// TODO(minyue): SetMaxSendBandwidth() is subject to be renamed to
3236// SetMaxSendBitrate() in future.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003237bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
minyue@webrtc.org26236952014-10-29 02:27:08 +00003238 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetMaxSendBandwidth.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003239
minyue@webrtc.org26236952014-10-29 02:27:08 +00003240 return SetSendBitrateInternal(bps);
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003241}
3242
minyue@webrtc.org26236952014-10-29 02:27:08 +00003243bool WebRtcVoiceMediaChannel::SetSendBitrateInternal(int bps) {
3244 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBitrateInternal.";
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003245
minyue@webrtc.org26236952014-10-29 02:27:08 +00003246 send_bitrate_setting_ = true;
3247 send_bitrate_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003248
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003249 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003250 LOG(LS_INFO) << "The send codec has not been set up yet. "
minyue@webrtc.org26236952014-10-29 02:27:08 +00003251 << "The send bitrate setting will be applied later.";
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003252 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003253 }
3254
minyue@webrtc.org26236952014-10-29 02:27:08 +00003255 // Bitrate is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003256 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3257 // SetMaxSendBandwith(0), the second call removes the previous limit.
3258 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003259 return true;
3260
3261 webrtc::CodecInst codec = *send_codec_;
3262 bool is_multi_rate = IsCodecMultiRate(codec);
3263
3264 if (is_multi_rate) {
3265 // If codec is multi-rate then just set the bitrate.
3266 codec.rate = bps;
3267 if (!SetSendCodec(codec)) {
3268 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3269 << " to bitrate " << bps << " bps.";
3270 return false;
3271 }
3272 return true;
3273 } else {
3274 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3275 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3276 // fixed bitrate then ignore.
3277 if (bps < codec.rate) {
3278 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3279 << " to bitrate " << bps << " bps"
3280 << ", requires at least " << codec.rate << " bps.";
3281 return false;
3282 }
3283 return true;
3284 }
3285}
3286
3287bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003288 bool echo_metrics_on = false;
3289 // These can take on valid negative values, so use the lowest possible level
3290 // as default rather than -1.
3291 int echo_return_loss = -100;
3292 int echo_return_loss_enhancement = -100;
3293 // These can also be negative, but in practice -1 is only used to signal
3294 // insufficient data, since the resolution is limited to multiples of 4 ms.
3295 int echo_delay_median_ms = -1;
3296 int echo_delay_std_ms = -1;
3297 if (engine()->voe()->processing()->GetEcMetricsStatus(
3298 echo_metrics_on) != -1 && echo_metrics_on) {
3299 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3300 // here, but it appears to be unsuitable currently. Revisit after this is
3301 // investigated: http://b/issue?id=5666755
3302 int erl, erle, rerl, anlp;
3303 if (engine()->voe()->processing()->GetEchoMetrics(
3304 erl, erle, rerl, anlp) != -1) {
3305 echo_return_loss = erl;
3306 echo_return_loss_enhancement = erle;
3307 }
3308
3309 int median, std;
bjornv@webrtc.orgcc64a9c2015-02-05 12:52:44 +00003310 float dummy;
3311 if (engine()->voe()->processing()->GetEcDelayMetrics(
3312 median, std, dummy) != -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003313 echo_delay_median_ms = median;
3314 echo_delay_std_ms = std;
3315 }
3316 }
3317
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003318 webrtc::CallStatistics cs;
3319 unsigned int ssrc;
3320 webrtc::CodecInst codec;
3321 unsigned int level;
3322
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003323 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3324 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003325 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003326
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003327 // Fill in the sender info, based on what we know, and what the
3328 // remote side told us it got from its RTCP report.
3329 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003330
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003331 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3332 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3333 continue;
3334 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003335
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003336 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003337 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3338 sinfo.bytes_sent = cs.bytesSent;
3339 sinfo.packets_sent = cs.packetsSent;
3340 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3341 // returns 0 to indicate an error value.
3342 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3343
3344 // Get data from the last remote RTCP report. Use default values if no data
3345 // available.
3346 sinfo.fraction_lost = -1.0;
3347 sinfo.jitter_ms = -1;
3348 sinfo.packets_lost = -1;
3349 sinfo.ext_seqnum = -1;
3350 std::vector<webrtc::ReportBlock> receive_blocks;
3351 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3352 channel, &receive_blocks) != -1 &&
3353 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3354 std::vector<webrtc::ReportBlock>::iterator iter;
3355 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3356 ++iter) {
3357 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003358 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003359 // Convert Q8 to floating point.
3360 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3361 // Convert samples to milliseconds.
3362 if (codec.plfreq / 1000 > 0) {
3363 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3364 }
3365 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3366 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3367 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003368 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003369 }
3370 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003371
3372 // Local speech level.
3373 sinfo.audio_level = (engine()->voe()->volume()->
3374 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3375
3376 // TODO(xians): We are injecting the same APM logging to all the send
3377 // channels here because there is no good way to know which send channel
3378 // is using the APM. The correct fix is to allow the send channels to have
3379 // their own APM so that we can feed the correct APM logging to different
3380 // send channels. See issue crbug/264611 .
3381 sinfo.echo_return_loss = echo_return_loss;
3382 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3383 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3384 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003385 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3386 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003387 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003388
3389 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003390 }
3391
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003392 // Build the list of receivers, one for each receiving channel, or 1 in
3393 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003394 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003395 for (ChannelMap::const_iterator it = receive_channels_.begin();
3396 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003397 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003398 }
3399 if (channels.empty()) {
3400 channels.push_back(voe_channel());
3401 }
3402
3403 // Get the SSRC and stats for each receiver, based on our own calculations.
3404 for (std::vector<int>::const_iterator it = channels.begin();
3405 it != channels.end(); ++it) {
3406 memset(&cs, 0, sizeof(cs));
3407 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3408 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3409 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3410 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003411 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003412 rinfo.bytes_rcvd = cs.bytesReceived;
3413 rinfo.packets_rcvd = cs.packetsReceived;
3414 // The next four fields are from the most recently sent RTCP report.
3415 // Convert Q8 to floating point.
3416 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3417 rinfo.packets_lost = cs.cumulativeLost;
3418 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003419 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003420 if (codec.pltype != -1) {
3421 rinfo.codec_name = codec.plname;
3422 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003423 // Convert samples to milliseconds.
3424 if (codec.plfreq / 1000 > 0) {
3425 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3426 }
3427
3428 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3429 webrtc::NetworkStatistics ns;
3430 if (engine()->voe()->neteq() &&
3431 engine()->voe()->neteq()->GetNetworkStatistics(
3432 *it, ns) != -1) {
3433 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3434 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3435 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003436 static_cast<float>(ns.currentExpandRate) / (1 << 14);
minyue@webrtc.orgc0bd7be2015-02-18 15:24:13 +00003437 rinfo.speech_expand_rate =
3438 static_cast<float>(ns.currentSpeechExpandRate) / (1 << 14);
3439 rinfo.secondary_decoded_rate =
3440 static_cast<float>(ns.currentSecondaryDecodedRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003441 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003442
3443 webrtc::AudioDecodingCallStats ds;
3444 if (engine()->voe()->neteq() &&
3445 engine()->voe()->neteq()->GetDecodingCallStatistics(
3446 *it, &ds) != -1) {
3447 rinfo.decoding_calls_to_silence_generator =
3448 ds.calls_to_silence_generator;
3449 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3450 rinfo.decoding_normal = ds.decoded_normal;
3451 rinfo.decoding_plc = ds.decoded_plc;
3452 rinfo.decoding_cng = ds.decoded_cng;
3453 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3454 }
3455
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003456 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003457 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003458 int playout_buffer_delay_ms = 0;
3459 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003460 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3461 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3462 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003463 }
3464
3465 // Get speech level.
3466 rinfo.audio_level = (engine()->voe()->volume()->
3467 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3468 info->receivers.push_back(rinfo);
3469 }
3470 }
3471
3472 return true;
3473}
3474
3475void WebRtcVoiceMediaChannel::GetLastMediaError(
3476 uint32* ssrc, VoiceMediaChannel::Error* error) {
3477 ASSERT(ssrc != NULL);
3478 ASSERT(error != NULL);
3479 FindSsrc(voe_channel(), ssrc);
3480 *error = WebRtcErrorToChannelError(GetLastEngineError());
3481}
3482
3483bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003484 rtc::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003485 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003486 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003487 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3488 // This means the error is not limited to a specific channel. Signal the
3489 // message using ssrc=0. If the current channel is sending, use this
3490 // channel for sending the message.
3491 *ssrc = 0;
3492 return true;
3493 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003494 // Check whether this is a sending channel.
3495 for (ChannelMap::const_iterator it = send_channels_.begin();
3496 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003497 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003498 // This is a sending channel.
3499 uint32 local_ssrc = 0;
3500 if (engine()->voe()->rtp()->GetLocalSSRC(
3501 channel_num, local_ssrc) != -1) {
3502 *ssrc = local_ssrc;
3503 }
3504 return true;
3505 }
3506 }
3507
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003508 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003509 for (ChannelMap::const_iterator it = receive_channels_.begin();
3510 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003511 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003512 *ssrc = it->first;
3513 return true;
3514 }
3515 }
3516 }
3517 return false;
3518}
3519
3520void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003521 if (error == VE_TYPING_NOISE_WARNING) {
3522 typing_noise_detected_ = true;
3523 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3524 typing_noise_detected_ = false;
3525 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003526 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3527}
3528
3529int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3530 unsigned int ulevel;
3531 int ret =
3532 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3533 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3534}
3535
3536int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003537 ChannelMap::iterator it = receive_channels_.find(ssrc);
3538 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003539 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003540 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3541}
3542
3543int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003544 ChannelMap::iterator it = send_channels_.find(ssrc);
3545 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003546 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003547
3548 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003549}
3550
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003551bool WebRtcVoiceMediaChannel::SetupSharedBandwidthEstimation(
3552 webrtc::VideoEngine* vie, int vie_channel) {
3553 shared_bwe_vie_ = vie;
3554 shared_bwe_vie_channel_ = vie_channel;
3555
3556 if (!SetupSharedBweOnChannel(voe_channel())) {
3557 return false;
3558 }
3559 for (ChannelMap::iterator it = receive_channels_.begin();
3560 it != receive_channels_.end(); ++it) {
3561 if (!SetupSharedBweOnChannel(it->second->channel())) {
3562 return false;
3563 }
3564 }
3565 return true;
3566}
3567
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003568bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3569 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3570 // Get the RED encodings from the parameter with no name. This may
3571 // change based on what is discussed on the Jingle list.
3572 // The encoding parameter is of the form "a/b"; we only support where
3573 // a == b. Verify this and parse out the value into red_pt.
3574 // If the parameter value is absent (as it will be until we wire up the
3575 // signaling of this message), use the second codec specified (i.e. the
3576 // one after "red") as the encoding parameter.
3577 int red_pt = -1;
3578 std::string red_params;
3579 CodecParameterMap::const_iterator it = red_codec.params.find("");
3580 if (it != red_codec.params.end()) {
3581 red_params = it->second;
3582 std::vector<std::string> red_pts;
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003583 if (rtc::split(red_params, '/', &red_pts) != 2 ||
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003584 red_pts[0] != red_pts[1] ||
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003585 !rtc::FromString(red_pts[0], &red_pt)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003586 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3587 return false;
3588 }
3589 } else if (red_codec.params.empty()) {
3590 LOG(LS_WARNING) << "RED params not present, using defaults";
3591 if (all_codecs.size() > 1) {
3592 red_pt = all_codecs[1].id;
3593 }
3594 }
3595
3596 // Try to find red_pt in |codecs|.
3597 std::vector<AudioCodec>::const_iterator codec;
3598 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3599 if (codec->id == red_pt)
3600 break;
3601 }
3602
3603 // If we find the right codec, that will be the codec we pass to
3604 // SetSendCodec, with the desired payload type.
3605 if (codec != all_codecs.end() &&
3606 engine()->FindWebRtcCodec(*codec, send_codec)) {
3607 } else {
3608 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3609 return false;
3610 }
3611
3612 return true;
3613}
3614
3615bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3616 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003617 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003618 return false;
3619 }
3620 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3621 // what we want to do with them.
3622 // engine()->voe().EnableVQMon(voe_channel(), true);
3623 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3624 return true;
3625}
3626
3627bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3628 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3629 for (int i = 0; i < ncodecs; ++i) {
3630 webrtc::CodecInst voe_codec;
3631 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3632 voe_codec.pltype = -1;
3633 if (engine()->voe()->codec()->SetRecPayloadType(
3634 channel, voe_codec) == -1) {
3635 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3636 return false;
3637 }
3638 }
3639 }
3640 return true;
3641}
3642
3643bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3644 if (playout) {
3645 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3646 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3647 LOG_RTCERR1(StartPlayout, channel);
3648 return false;
3649 }
3650 } else {
3651 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3652 engine()->voe()->base()->StopPlayout(channel);
3653 }
3654 return true;
3655}
3656
3657uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3658 bool rtcp) {
3659 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3660 uint32 ssrc = 0;
3661 if (len >= (ssrc_pos + sizeof(ssrc))) {
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003662 ssrc = rtc::GetBE32(static_cast<const char*>(data) + ssrc_pos);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003663 }
3664 return ssrc;
3665}
3666
3667// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3668VoiceMediaChannel::Error
3669 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3670 switch (err_code) {
3671 case 0:
3672 return ERROR_NONE;
3673 case VE_CANNOT_START_RECORDING:
3674 case VE_MIC_VOL_ERROR:
3675 case VE_GET_MIC_VOL_ERROR:
3676 case VE_CANNOT_ACCESS_MIC_VOL:
3677 return ERROR_REC_DEVICE_OPEN_FAILED;
3678 case VE_SATURATION_WARNING:
3679 return ERROR_REC_DEVICE_SATURATION;
3680 case VE_REC_DEVICE_REMOVED:
3681 return ERROR_REC_DEVICE_REMOVED;
3682 case VE_RUNTIME_REC_WARNING:
3683 case VE_RUNTIME_REC_ERROR:
3684 return ERROR_REC_RUNTIME_ERROR;
3685 case VE_CANNOT_START_PLAYOUT:
3686 case VE_SPEAKER_VOL_ERROR:
3687 case VE_GET_SPEAKER_VOL_ERROR:
3688 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3689 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3690 case VE_RUNTIME_PLAY_WARNING:
3691 case VE_RUNTIME_PLAY_ERROR:
3692 return ERROR_PLAY_RUNTIME_ERROR;
3693 case VE_TYPING_NOISE_WARNING:
3694 return ERROR_REC_TYPING_NOISE_DETECTED;
3695 default:
3696 return VoiceMediaChannel::ERROR_OTHER;
3697 }
3698}
3699
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003700bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3701 int channel_id, const RtpHeaderExtension* extension) {
3702 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003703 int id = 0;
3704 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003705 if (extension) {
3706 enable = true;
3707 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003708 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003709 }
3710 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003711 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003712 return false;
3713 }
3714 return true;
3715}
3716
buildbot@webrtc.orgb4c7b092014-08-25 12:11:58 +00003717bool WebRtcVoiceMediaChannel::SetupSharedBweOnChannel(int voe_channel) {
3718 webrtc::ViENetwork* vie_network = NULL;
3719 int vie_channel = -1;
3720 if (options_.combined_audio_video_bwe.GetWithDefaultIfUnset(false) &&
3721 shared_bwe_vie_ != NULL && shared_bwe_vie_channel_ != -1) {
3722 vie_network = webrtc::ViENetwork::GetInterface(shared_bwe_vie_);
3723 vie_channel = shared_bwe_vie_channel_;
3724 }
3725 if (engine()->voe()->rtp()->SetVideoEngineBWETarget(voe_channel, vie_network,
3726 vie_channel) == -1) {
3727 LOG_RTCERR3(SetVideoEngineBWETarget, voe_channel, vie_network, vie_channel);
3728 if (vie_network != NULL) {
3729 // Don't fail if we're tearing down.
3730 return false;
3731 }
3732 }
3733 return true;
3734}
3735
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00003736int WebRtcSoundclipStream::Read(void *buf, size_t len) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003737 size_t res = 0;
3738 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003739 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003740}
3741
3742int WebRtcSoundclipStream::Rewind() {
3743 mem_.Rewind();
3744 // Return -1 to keep VoiceEngine from looping.
3745 return (loop_) ? 0 : -1;
3746}
3747
3748} // namespace cricket
3749
3750#endif // HAVE_WEBRTC_VOICE