blob: b308e4e6d9612387c668ce99843f06b1ad185f9d [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
41#include "talk/base/base64.h"
42#include "talk/base/byteorder.h"
43#include "talk/base/common.h"
44#include "talk/base/helpers.h"
45#include "talk/base/logging.h"
46#include "talk/base/stringencode.h"
47#include "talk/base/stringutils.h"
48#include "talk/media/base/audiorenderer.h"
49#include "talk/media/base/constants.h"
50#include "talk/media/base/streamparams.h"
51#include "talk/media/base/voiceprocessor.h"
52#include "talk/media/webrtc/webrtcvoe.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"
55
56#ifdef WIN32
57#include <objbase.h> // NOLINT
58#endif
59
60namespace cricket {
61
62struct CodecPref {
63 const char* name;
64 int clockrate;
65 int channels;
66 int payload_type;
67 bool is_multi_rate;
68};
69
70static const CodecPref kCodecPrefs[] = {
71 { "OPUS", 48000, 2, 111, true },
72 { "ISAC", 16000, 1, 103, true },
73 { "ISAC", 32000, 1, 104, true },
74 { "CELT", 32000, 1, 109, true },
75 { "CELT", 32000, 2, 110, true },
76 { "G722", 16000, 1, 9, false },
77 { "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";
112// Codec parameters for Opus.
113static const int kOpusMonoBitrate = 32000;
114// 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;
117static const int kOpusStereoBitrate = 64000;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000118// draft-spittka-payload-rtp-opus-03
119// Opus bitrate should be in the range between 6000 and 510000.
120static const int kOpusMinBitrate = 6000;
121static const int kOpusMaxBitrate = 510000;
wu@webrtc.orgde305012013-10-31 15:40:38 +0000122// Default audio dscp value.
123// See http://tools.ietf.org/html/rfc2474 for details.
124// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
125static const talk_base::DiffServCodePoint kAudioDscpValue = talk_base::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000126
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000127// Ensure we open the file in a writeable path on ChromeOS and Android. This
128// workaround can be removed when it's possible to specify a filename for audio
129// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000130//
131// TODO(grunell): Use a string in the options instead of hardcoding it here
132// and let the embedder choose the filename (crbug.com/264223).
133//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000134// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
135// below.
136#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000137static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000138#elif defined(ANDROID)
139static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000140#else
141static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
142#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000143
144// Dumps an AudioCodec in RFC 2327-ish format.
145static std::string ToString(const AudioCodec& codec) {
146 std::stringstream ss;
147 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
148 << " (" << codec.id << ")";
149 return ss.str();
150}
151static std::string ToString(const webrtc::CodecInst& codec) {
152 std::stringstream ss;
153 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
154 << " (" << codec.pltype << ")";
155 return ss.str();
156}
157
158static void LogMultiline(talk_base::LoggingSeverity sev, char* text) {
159 const char* delim = "\r\n";
160 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
161 LOG_V(sev) << tok;
162 }
163}
164
165// Severity is an integer because it comes is assumed to be from command line.
166static int SeverityToFilter(int severity) {
167 int filter = webrtc::kTraceNone;
168 switch (severity) {
169 case talk_base::LS_VERBOSE:
170 filter |= webrtc::kTraceAll;
171 case talk_base::LS_INFO:
172 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
173 case talk_base::LS_WARNING:
174 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
175 case talk_base::LS_ERROR:
176 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
177 }
178 return filter;
179}
180
181static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
182 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
183 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
184 kCodecPrefs[i].clockrate == codec.plfreq) {
185 return kCodecPrefs[i].is_multi_rate;
186 }
187 }
188 return false;
189}
190
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000191static bool IsTelephoneEventCodec(const std::string& name) {
192 return _stricmp(name.c_str(), "telephone-event") == 0;
193}
194
195static bool IsCNCodec(const std::string& name) {
196 return _stricmp(name.c_str(), "CN") == 0;
197}
198
199static bool IsRedCodec(const std::string& name) {
200 return _stricmp(name.c_str(), "red") == 0;
201}
202
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000203static bool FindCodec(const std::vector<AudioCodec>& codecs,
204 const AudioCodec& codec,
205 AudioCodec* found_codec) {
206 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
207 it != codecs.end(); ++it) {
208 if (it->Matches(codec)) {
209 if (found_codec != NULL) {
210 *found_codec = *it;
211 }
212 return true;
213 }
214 }
215 return false;
216}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000217
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000218static bool IsNackEnabled(const AudioCodec& codec) {
219 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
220 kParamValueEmpty));
221}
222
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000223// Gets the default set of options applied to the engine. Historically, these
224// were supplied as a combination of flags from the channel manager (ec, agc,
225// ns, and highpass) and the rest hardcoded in InitInternal.
226static AudioOptions GetDefaultEngineOptions() {
227 AudioOptions options;
228 options.echo_cancellation.Set(true);
229 options.auto_gain_control.Set(true);
230 options.noise_suppression.Set(true);
231 options.highpass_filter.Set(true);
232 options.stereo_swapping.Set(false);
233 options.typing_detection.Set(true);
234 options.conference_mode.Set(false);
235 options.adjust_agc_delta.Set(0);
236 options.experimental_agc.Set(false);
237 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000238 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000239 options.aec_dump.Set(false);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000240 options.experimental_acm.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000241 return options;
242}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000243
244class WebRtcSoundclipMedia : public SoundclipMedia {
245 public:
246 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
247 : engine_(engine), webrtc_channel_(-1) {
248 engine_->RegisterSoundclip(this);
249 }
250
251 virtual ~WebRtcSoundclipMedia() {
252 engine_->UnregisterSoundclip(this);
253 if (webrtc_channel_ != -1) {
254 // We shouldn't have to call Disable() here. DeleteChannel() should call
255 // StopPlayout() while deleting the channel. We should fix the bug
256 // inside WebRTC and remove the Disable() call bellow. This work is
257 // tracked by bug http://b/issue?id=5382855.
258 PlaySound(NULL, 0, 0);
259 Disable();
260 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
261 == -1) {
262 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
263 }
264 }
265 }
266
267 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000268 if (!engine_->voe_sc()) {
269 return false;
270 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000271 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000272 if (webrtc_channel_ == -1) {
273 LOG_RTCERR0(CreateChannel);
274 return false;
275 }
276 return true;
277 }
278
279 bool Enable() {
280 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
281 LOG_RTCERR1(StartPlayout, webrtc_channel_);
282 return false;
283 }
284 return true;
285 }
286
287 bool Disable() {
288 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
289 LOG_RTCERR1(StopPlayout, webrtc_channel_);
290 return false;
291 }
292 return true;
293 }
294
295 virtual bool PlaySound(const char *buf, int len, int flags) {
296 // The voe file api is not available in chrome.
297 if (!engine_->voe_sc()->file()) {
298 return false;
299 }
300 // Must stop playing the current sound (if any), because we are about to
301 // modify the stream.
302 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
303 == -1) {
304 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
305 return false;
306 }
307
308 if (buf) {
309 stream_.reset(new WebRtcSoundclipStream(buf, len));
310 stream_->set_loop((flags & SF_LOOP) != 0);
311 stream_->Rewind();
312
313 // Play it.
314 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
315 webrtc_channel_, stream_.get()) == -1) {
316 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
317 LOG(LS_ERROR) << "Unable to start soundclip";
318 return false;
319 }
320 } else {
321 stream_.reset();
322 }
323 return true;
324 }
325
326 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
327
328 private:
329 WebRtcVoiceEngine *engine_;
330 int webrtc_channel_;
331 talk_base::scoped_ptr<WebRtcSoundclipStream> stream_;
332};
333
334WebRtcVoiceEngine::WebRtcVoiceEngine()
335 : voe_wrapper_(new VoEWrapper()),
336 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000337 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000338 tracing_(new VoETraceWrapper()),
339 adm_(NULL),
340 adm_sc_(NULL),
341 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
342 is_dumping_aec_(false),
343 desired_local_monitor_enable_(false),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000344 use_experimental_acm_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000345 tx_processor_ssrc_(0),
346 rx_processor_ssrc_(0) {
347 Construct();
348}
349
350WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
351 VoEWrapper* voe_wrapper_sc,
352 VoETraceWrapper* tracing)
353 : voe_wrapper_(voe_wrapper),
354 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000355 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000356 tracing_(tracing),
357 adm_(NULL),
358 adm_sc_(NULL),
359 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
360 is_dumping_aec_(false),
361 desired_local_monitor_enable_(false),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000362 use_experimental_acm_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000363 tx_processor_ssrc_(0),
364 rx_processor_ssrc_(0) {
365 Construct();
366}
367
368void WebRtcVoiceEngine::Construct() {
369 SetTraceFilter(log_filter_);
370 initialized_ = false;
371 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
372 SetTraceOptions("");
373 if (tracing_->SetTraceCallback(this) == -1) {
374 LOG_RTCERR0(SetTraceCallback);
375 }
376 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
377 LOG_RTCERR0(RegisterVoiceEngineObserver);
378 }
379 // Clear the default agc state.
380 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
381
382 // Load our audio codec list.
383 ConstructCodecs();
384
385 // Load our RTP Header extensions.
386 rtp_header_extensions_.push_back(
387 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
henrike@webrtc.org79047f92014-03-06 23:46:59 +0000388 kRtpAudioLevelHeaderExtensionDefaultId));
389#ifdef USE_WEBRTC_DEV_BRANCH
390 rtp_header_extensions_.push_back(
391 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
392 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
393#endif
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000394 options_ = GetDefaultEngineOptions();
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000395
396 // Initialize the VoE Configuration to the default ACM.
397 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
398 new webrtc::AudioCodingModuleFactory);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000399}
400
401static bool IsOpus(const AudioCodec& codec) {
402 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
403}
404
405static bool IsIsac(const AudioCodec& codec) {
406 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
407}
408
409// True if params["stereo"] == "1"
410static bool IsOpusStereoEnabled(const AudioCodec& codec) {
411 CodecParameterMap::const_iterator param =
412 codec.params.find(kCodecParamStereo);
413 if (param == codec.params.end()) {
414 return false;
415 }
416 return param->second == kParamValueTrue;
417}
418
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000419static bool IsValidOpusBitrate(int bitrate) {
420 return (bitrate >= kOpusMinBitrate && bitrate <= kOpusMaxBitrate);
421}
422
423// Returns 0 if params[kCodecParamMaxAverageBitrate] is not defined or invalid.
424// Returns the value of params[kCodecParamMaxAverageBitrate] otherwise.
425static int GetOpusBitrateFromParams(const AudioCodec& codec) {
426 int bitrate = 0;
427 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
428 return 0;
429 }
430 if (!IsValidOpusBitrate(bitrate)) {
431 LOG(LS_WARNING) << "Codec parameter \"maxaveragebitrate\" has an "
432 << "invalid value: " << bitrate;
433 return 0;
434 }
435 return bitrate;
436}
437
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000438void WebRtcVoiceEngine::ConstructCodecs() {
439 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
440 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
441 for (int i = 0; i < ncodecs; ++i) {
442 webrtc::CodecInst voe_codec;
443 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
444 // Skip uncompressed formats.
445 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
446 continue;
447 }
448
449 const CodecPref* pref = NULL;
450 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
451 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
452 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
453 kCodecPrefs[j].channels == voe_codec.channels) {
454 pref = &kCodecPrefs[j];
455 break;
456 }
457 }
458
459 if (pref) {
460 // Use the payload type that we've configured in our pref table;
461 // use the offset in our pref table to determine the sort order.
462 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
463 voe_codec.rate, voe_codec.channels,
464 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
465 LOG(LS_INFO) << ToString(codec);
466 if (IsIsac(codec)) {
467 // Indicate auto-bandwidth in signaling.
468 codec.bitrate = 0;
469 }
470 if (IsOpus(codec)) {
471 // Only add fmtp parameters that differ from the spec.
472 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
473 codec.params[kCodecParamMinPTime] =
474 talk_base::ToString(kPreferredMinPTime);
475 }
476 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
477 codec.params[kCodecParamMaxPTime] =
478 talk_base::ToString(kPreferredMaxPTime);
479 }
480 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
481 // when they can be set to values other than the default.
482 }
483 codecs_.push_back(codec);
484 } else {
485 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
486 }
487 }
488 }
489 // Make sure they are in local preference order.
490 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
491}
492
493WebRtcVoiceEngine::~WebRtcVoiceEngine() {
494 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
495 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
496 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
497 }
498 if (adm_) {
499 voe_wrapper_.reset();
500 adm_->Release();
501 adm_ = NULL;
502 }
503 if (adm_sc_) {
504 voe_wrapper_sc_.reset();
505 adm_sc_->Release();
506 adm_sc_ = NULL;
507 }
508
509 // Test to see if the media processor was deregistered properly
510 ASSERT(SignalRxMediaFrame.is_empty());
511 ASSERT(SignalTxMediaFrame.is_empty());
512
513 tracing_->SetTraceCallback(NULL);
514}
515
516bool WebRtcVoiceEngine::Init(talk_base::Thread* worker_thread) {
517 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
518 bool res = InitInternal();
519 if (res) {
520 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
521 } else {
522 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
523 Terminate();
524 }
525 return res;
526}
527
528bool WebRtcVoiceEngine::InitInternal() {
529 // Temporarily turn logging level up for the Init call
530 int old_filter = log_filter_;
531 int extended_filter = log_filter_ | SeverityToFilter(talk_base::LS_INFO);
532 SetTraceFilter(extended_filter);
533 SetTraceOptions("");
534
535 // Init WebRtc VoiceEngine.
536 if (voe_wrapper_->base()->Init(adm_) == -1) {
537 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
538 SetTraceFilter(old_filter);
539 return false;
540 }
541
542 SetTraceFilter(old_filter);
543 SetTraceOptions(log_options_);
544
545 // Log the VoiceEngine version info
546 char buffer[1024] = "";
547 voe_wrapper_->base()->GetVersion(buffer);
548 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
549 LogMultiline(talk_base::LS_INFO, buffer);
550
551 // Save the default AGC configuration settings. This must happen before
552 // calling SetOptions or the default will be overwritten.
553 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
wu@webrtc.org97077a32013-10-25 21:18:33 +0000554 LOG_RTCERR0(GetAgcConfig);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000555 return false;
556 }
557
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000558 // Set defaults for options, so that ApplyOptions applies them explicitly
559 // when we clear option (channel) overrides. External clients can still
560 // modify the defaults via SetOptions (on the media engine).
561 if (!SetOptions(GetDefaultEngineOptions())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000562 return false;
563 }
564
565 // Print our codec list again for the call diagnostic log
566 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
567 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
568 it != codecs_.end(); ++it) {
569 LOG(LS_INFO) << ToString(*it);
570 }
571
wu@webrtc.org4551b792013-10-09 15:37:36 +0000572 // Disable the DTMF playout when a tone is sent.
573 // PlayDtmfTone will be used if local playout is needed.
574 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
575 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
576 }
577
578 initialized_ = true;
579 return true;
580}
581
582bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
583 if (voe_wrapper_sc_initialized_) {
584 return true;
585 }
586 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
587 // be false, so subsequent calls to EnsureSoundclipEngineInit will
588 // probably just fail again. That's acceptable behavior.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000589#if defined(LINUX) && !defined(HAVE_LIBPULSE)
590 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
591#endif
592
593 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
594 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
595 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
596 return false;
597 }
598
599 // On Windows, tell it to use the default sound (not communication) devices.
600 // First check whether there is a valid sound device for playback.
601 // TODO(juberti): Clean this up when we support setting the soundclip device.
602#ifdef WIN32
603 // The SetPlayoutDevice may not be implemented in the case of external ADM.
604 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
605 // PeerConnection interface never set the adm_sc_, so need to check both
606 // in order to determine if the external adm is used.
607 if (!adm_ && !adm_sc_) {
608 int num_of_devices = 0;
609 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
610 num_of_devices > 0) {
611 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
612 == -1) {
613 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
614 voe_wrapper_sc_->error());
615 return false;
616 }
617 } else {
618 LOG(LS_WARNING) << "No valid sound playout device found.";
619 }
620 }
621#endif
wu@webrtc.org4551b792013-10-09 15:37:36 +0000622 voe_wrapper_sc_initialized_ = true;
623 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000624 return true;
625}
626
627void WebRtcVoiceEngine::Terminate() {
628 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
629 initialized_ = false;
630
631 StopAecDump();
632
wu@webrtc.org4551b792013-10-09 15:37:36 +0000633 if (voe_wrapper_sc_) {
634 voe_wrapper_sc_initialized_ = false;
635 voe_wrapper_sc_->base()->Terminate();
636 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000637 voe_wrapper_->base()->Terminate();
638 desired_local_monitor_enable_ = false;
639}
640
641int WebRtcVoiceEngine::GetCapabilities() {
642 return AUDIO_SEND | AUDIO_RECV;
643}
644
645VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
646 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
647 if (!ch->valid()) {
648 delete ch;
649 ch = NULL;
650 }
651 return ch;
652}
653
654SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000655 if (!EnsureSoundclipEngineInit()) {
656 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
657 << "initialize.";
658 return NULL;
659 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000660 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
661 if (!soundclip->Init() || !soundclip->Enable()) {
662 delete soundclip;
663 return NULL;
664 }
665 return soundclip;
666}
667
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000668bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000669 if (!ApplyOptions(options)) {
670 return false;
671 }
672 options_ = options;
673 return true;
674}
675
676bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
677 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
678 if (!ApplyOptions(overrides)) {
679 return false;
680 }
681 option_overrides_ = overrides;
682 return true;
683}
684
685bool WebRtcVoiceEngine::ClearOptionOverrides() {
686 LOG(LS_INFO) << "Clearing option overrides.";
687 AudioOptions options = options_;
688 // Only call ApplyOptions if |options_overrides_| contains overrided options.
689 // ApplyOptions affects NS, AGC other options that is shared between
690 // all WebRtcVoiceEngineChannels.
691 if (option_overrides_ == AudioOptions()) {
692 return true;
693 }
694
695 if (!ApplyOptions(options)) {
696 return false;
697 }
698 option_overrides_ = AudioOptions();
699 return true;
700}
701
702// AudioOptions defaults are set in InitInternal (for options with corresponding
703// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
704bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
705 AudioOptions options = options_in; // The options are modified below.
706 // kEcConference is AEC with high suppression.
707 webrtc::EcModes ec_mode = webrtc::kEcConference;
708 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
709 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
710 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
711 bool aecm_comfort_noise = false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000712 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
713 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
714 << aecm_comfort_noise << " (default is false).";
715 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000716
717#if defined(IOS)
718 // On iOS, VPIO provides built-in EC and AGC.
719 options.echo_cancellation.Set(false);
720 options.auto_gain_control.Set(false);
721#elif defined(ANDROID)
722 ec_mode = webrtc::kEcAecm;
723#endif
724
725#if defined(IOS) || defined(ANDROID)
726 // Set the AGC mode for iOS as well despite disabling it above, to avoid
727 // unsupported configuration errors from webrtc.
728 agc_mode = webrtc::kAgcFixedDigital;
729 options.typing_detection.Set(false);
730 options.experimental_agc.Set(false);
731 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000732 options.experimental_ns.Set(false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000733#endif
734
735 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
736
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000737 // Configure whether ACM1 or ACM2 is used.
738 bool enable_acm2 = false;
739 if (options.experimental_acm.Get(&enable_acm2)) {
740 EnableExperimentalAcm(enable_acm2);
741 }
742
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000743 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
744
745 bool echo_cancellation;
746 if (options.echo_cancellation.Get(&echo_cancellation)) {
747 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
748 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
749 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000750 } else {
751 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
752 << " with mode " << ec_mode;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000753 }
754#if !defined(ANDROID)
755 // TODO(ajm): Remove the error return on Android from webrtc.
756 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
757 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
758 return false;
759 }
760#endif
761 if (ec_mode == webrtc::kEcAecm) {
762 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
763 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
764 return false;
765 }
766 }
767 }
768
769 bool auto_gain_control;
770 if (options.auto_gain_control.Get(&auto_gain_control)) {
771 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
772 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
773 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000774 } else {
775 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
776 << " with mode " << agc_mode;
777 }
778 }
779
780 if (options.tx_agc_target_dbov.IsSet() ||
781 options.tx_agc_digital_compression_gain.IsSet() ||
782 options.tx_agc_limiter.IsSet()) {
783 // Override default_agc_config_. Generally, an unset option means "leave
784 // the VoE bits alone" in this function, so we want whatever is set to be
785 // stored as the new "default". If we didn't, then setting e.g.
786 // tx_agc_target_dbov would reset digital compression gain and limiter
787 // settings.
788 // Also, if we don't update default_agc_config_, then adjust_agc_delta
789 // would be an offset from the original values, and not whatever was set
790 // explicitly.
791 default_agc_config_.targetLeveldBOv =
792 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
793 default_agc_config_.targetLeveldBOv);
794 default_agc_config_.digitalCompressionGaindB =
795 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
796 default_agc_config_.digitalCompressionGaindB);
797 default_agc_config_.limiterEnable =
798 options.tx_agc_limiter.GetWithDefaultIfUnset(
799 default_agc_config_.limiterEnable);
800 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
801 LOG_RTCERR3(SetAgcConfig,
802 default_agc_config_.targetLeveldBOv,
803 default_agc_config_.digitalCompressionGaindB,
804 default_agc_config_.limiterEnable);
805 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000806 }
807 }
808
809 bool noise_suppression;
810 if (options.noise_suppression.Get(&noise_suppression)) {
811 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
812 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
813 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000814 } else {
815 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
816 << " with mode " << ns_mode;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000817 }
818 }
819
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000820#ifdef USE_WEBRTC_DEV_BRANCH
821 bool experimental_ns;
822 if (options.experimental_ns.Get(&experimental_ns)) {
823 webrtc::AudioProcessing* audioproc =
824 voe_wrapper_->base()->audio_processing();
825 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
826 // returns NULL on audio_processing().
827 if (audioproc) {
828 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
829 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
830 return false;
831 }
832 } else {
833 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
834 << experimental_ns;
835 }
836 }
837#endif // USE_WEBRTC_DEV_BRANCH
838
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000839 bool highpass_filter;
840 if (options.highpass_filter.Get(&highpass_filter)) {
841 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
842 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
843 return false;
844 }
845 }
846
847 bool stereo_swapping;
848 if (options.stereo_swapping.Get(&stereo_swapping)) {
849 voep->EnableStereoChannelSwapping(stereo_swapping);
850 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
851 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
852 return false;
853 }
854 }
855
856 bool typing_detection;
857 if (options.typing_detection.Get(&typing_detection)) {
858 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
859 // In case of error, log the info and continue
860 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
861 }
862 }
863
864 int adjust_agc_delta;
865 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
866 if (!AdjustAgcLevel(adjust_agc_delta)) {
867 return false;
868 }
869 }
870
871 bool aec_dump;
872 if (options.aec_dump.Get(&aec_dump)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000873 if (aec_dump)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000874 StartAecDump(kAecDumpByAudioOptionFilename);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000875 else
876 StopAecDump();
877 }
878
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000879 bool experimental_aec;
880 if (options.experimental_aec.Get(&experimental_aec)) {
881 webrtc::AudioProcessing* audioproc =
882 voe_wrapper_->base()->audio_processing();
883 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
884 // returns NULL on audio_processing().
885 if (audioproc) {
886 webrtc::Config config;
887 config.Set<webrtc::DelayCorrection>(
888 new webrtc::DelayCorrection(experimental_aec));
889 audioproc->SetExtraOptions(config);
890 }
891 }
892
wu@webrtc.org97077a32013-10-25 21:18:33 +0000893 uint32 recording_sample_rate;
894 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
895 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
896 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
897 }
898 }
899
900 uint32 playout_sample_rate;
901 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
902 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
903 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
904 }
905 }
906
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000907
908 return true;
909}
910
911bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
912 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
913 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
914 LOG_RTCERR1(SetDelayOffsetMs, offset);
915 return false;
916 }
917
918 return true;
919}
920
921struct ResumeEntry {
922 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
923 : channel(c),
924 playout(p),
925 send(s) {
926 }
927
928 WebRtcVoiceMediaChannel *channel;
929 bool playout;
930 SendFlags send;
931};
932
933// TODO(juberti): Refactor this so that the core logic can be used to set the
934// soundclip device. At that time, reinstate the soundclip pause/resume code.
935bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
936 const Device* out_device) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000937#if !defined(IOS)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000938 int in_id = in_device ? talk_base::FromString<int>(in_device->id) :
939 kDefaultAudioDeviceId;
940 int out_id = out_device ? talk_base::FromString<int>(out_device->id) :
941 kDefaultAudioDeviceId;
942 // The device manager uses -1 as the default device, which was the case for
943 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
944#ifndef WIN32
945 if (-1 == in_id) {
946 in_id = kDefaultAudioDeviceId;
947 }
948 if (-1 == out_id) {
949 out_id = kDefaultAudioDeviceId;
950 }
951#endif
952
953 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
954 in_device->name : "Default device";
955 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
956 out_device->name : "Default device";
957 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
958 << ") and speaker to (id=" << out_id << ", name=" << out_name
959 << ")";
960
961 // If we're running the local monitor, we need to stop it first.
962 bool ret = true;
963 if (!PauseLocalMonitor()) {
964 LOG(LS_WARNING) << "Failed to pause local monitor";
965 ret = false;
966 }
967
968 // Must also pause all audio playback and capture.
969 for (ChannelList::const_iterator i = channels_.begin();
970 i != channels_.end(); ++i) {
971 WebRtcVoiceMediaChannel *channel = *i;
972 if (!channel->PausePlayout()) {
973 LOG(LS_WARNING) << "Failed to pause playout";
974 ret = false;
975 }
976 if (!channel->PauseSend()) {
977 LOG(LS_WARNING) << "Failed to pause send";
978 ret = false;
979 }
980 }
981
982 // Find the recording device id in VoiceEngine and set recording device.
983 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
984 ret = false;
985 }
986 if (ret) {
987 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000988 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000989 ret = false;
990 }
991 }
992
993 // Find the playout device id in VoiceEngine and set playout device.
994 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
995 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
996 ret = false;
997 }
998 if (ret) {
999 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001000 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001001 ret = false;
1002 }
1003 }
1004
1005 // Resume all audio playback and capture.
1006 for (ChannelList::const_iterator i = channels_.begin();
1007 i != channels_.end(); ++i) {
1008 WebRtcVoiceMediaChannel *channel = *i;
1009 if (!channel->ResumePlayout()) {
1010 LOG(LS_WARNING) << "Failed to resume playout";
1011 ret = false;
1012 }
1013 if (!channel->ResumeSend()) {
1014 LOG(LS_WARNING) << "Failed to resume send";
1015 ret = false;
1016 }
1017 }
1018
1019 // Resume local monitor.
1020 if (!ResumeLocalMonitor()) {
1021 LOG(LS_WARNING) << "Failed to resume local monitor";
1022 ret = false;
1023 }
1024
1025 if (ret) {
1026 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1027 << ") and speaker to (id="<< out_id << " name=" << out_name
1028 << ")";
1029 }
1030
1031 return ret;
1032#else
1033 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001034#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001035}
1036
1037bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1038 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1039 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001040#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001041 *rtc_id = dev_id;
1042 return true;
1043#else
1044 // In Windows and Mac, we need to find the VoiceEngine device id by name
1045 // unless the input dev_id is the default device id.
1046 if (kDefaultAudioDeviceId == dev_id) {
1047 *rtc_id = dev_id;
1048 return true;
1049 }
1050
1051 // Get the number of VoiceEngine audio devices.
1052 int count = 0;
1053 if (is_input) {
1054 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1055 LOG_RTCERR0(GetNumOfRecordingDevices);
1056 return false;
1057 }
1058 } else {
1059 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1060 LOG_RTCERR0(GetNumOfPlayoutDevices);
1061 return false;
1062 }
1063 }
1064
1065 for (int i = 0; i < count; ++i) {
1066 char name[128];
1067 char guid[128];
1068 if (is_input) {
1069 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1070 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1071 } else {
1072 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1073 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1074 }
1075
1076 std::string webrtc_name(name);
1077 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1078 *rtc_id = i;
1079 return true;
1080 }
1081 }
1082 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1083 return false;
1084#endif
1085}
1086
1087bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1088 unsigned int ulevel;
1089 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1090 LOG_RTCERR1(GetSpeakerVolume, level);
1091 return false;
1092 }
1093 *level = ulevel;
1094 return true;
1095}
1096
1097bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1098 ASSERT(level >= 0 && level <= 255);
1099 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1100 LOG_RTCERR1(SetSpeakerVolume, level);
1101 return false;
1102 }
1103 return true;
1104}
1105
1106int WebRtcVoiceEngine::GetInputLevel() {
1107 unsigned int ulevel;
1108 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1109 static_cast<int>(ulevel) : -1;
1110}
1111
1112bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1113 desired_local_monitor_enable_ = enable;
1114 return ChangeLocalMonitor(desired_local_monitor_enable_);
1115}
1116
1117bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1118 // The voe file api is not available in chrome.
1119 if (!voe_wrapper_->file()) {
1120 return false;
1121 }
1122 if (enable && !monitor_) {
1123 monitor_.reset(new WebRtcMonitorStream);
1124 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1125 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1126 // Must call Stop() because there are some cases where Start will report
1127 // failure but still change the state, and if we leave VE in the on state
1128 // then it could crash later when trying to invoke methods on our monitor.
1129 voe_wrapper_->file()->StopRecordingMicrophone();
1130 monitor_.reset();
1131 return false;
1132 }
1133 } else if (!enable && monitor_) {
1134 voe_wrapper_->file()->StopRecordingMicrophone();
1135 monitor_.reset();
1136 }
1137 return true;
1138}
1139
1140bool WebRtcVoiceEngine::PauseLocalMonitor() {
1141 return ChangeLocalMonitor(false);
1142}
1143
1144bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1145 return ChangeLocalMonitor(desired_local_monitor_enable_);
1146}
1147
1148const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1149 return codecs_;
1150}
1151
1152bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1153 return FindWebRtcCodec(in, NULL);
1154}
1155
1156// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1157bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1158 webrtc::CodecInst* out) {
1159 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1160 for (int i = 0; i < ncodecs; ++i) {
1161 webrtc::CodecInst voe_codec;
1162 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1163 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1164 voe_codec.rate, voe_codec.channels, 0);
1165 bool multi_rate = IsCodecMultiRate(voe_codec);
1166 // Allow arbitrary rates for ISAC to be specified.
1167 if (multi_rate) {
1168 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1169 codec.bitrate = 0;
1170 }
1171 if (codec.Matches(in)) {
1172 if (out) {
1173 // Fixup the payload type.
1174 voe_codec.pltype = in.id;
1175
1176 // Set bitrate if specified.
1177 if (multi_rate && in.bitrate != 0) {
1178 voe_codec.rate = in.bitrate;
1179 }
1180
1181 // Apply codec-specific settings.
1182 if (IsIsac(codec)) {
1183 // If ISAC and an explicit bitrate is not specified,
1184 // enable auto bandwidth adjustment.
1185 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1186 }
1187 *out = voe_codec;
1188 }
1189 return true;
1190 }
1191 }
1192 }
1193 return false;
1194}
1195const std::vector<RtpHeaderExtension>&
1196WebRtcVoiceEngine::rtp_header_extensions() const {
1197 return rtp_header_extensions_;
1198}
1199
1200void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1201 // if min_sev == -1, we keep the current log level.
1202 if (min_sev >= 0) {
1203 SetTraceFilter(SeverityToFilter(min_sev));
1204 }
1205 log_options_ = filter;
1206 SetTraceOptions(initialized_ ? log_options_ : "");
1207}
1208
1209int WebRtcVoiceEngine::GetLastEngineError() {
1210 return voe_wrapper_->error();
1211}
1212
1213void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1214 log_filter_ = filter;
1215 tracing_->SetTraceFilter(filter);
1216}
1217
1218// We suppport three different logging settings for VoiceEngine:
1219// 1. Observer callback that goes into talk diagnostic logfile.
1220// Use --logfile and --loglevel
1221//
1222// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1223// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1224//
1225// 3. EC log and dump for debugging QualityEngine.
1226// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1227//
1228// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1229// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1230void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1231 // Set encrypted trace file.
1232 std::vector<std::string> opts;
1233 talk_base::tokenize(options, ' ', '"', '"', &opts);
1234 std::vector<std::string>::iterator tracefile =
1235 std::find(opts.begin(), opts.end(), "tracefile");
1236 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1237 // Write encrypted debug output (at same loglevel) to file
1238 // EncryptedTraceFile no longer supported.
1239 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1240 LOG_RTCERR1(SetTraceFile, *tracefile);
1241 }
1242 }
1243
wu@webrtc.org97077a32013-10-25 21:18:33 +00001244 // Allow trace options to override the trace filter. We default
1245 // it to log_filter_ (as a translation of libjingle log levels)
1246 // elsewhere, but this allows clients to explicitly set webrtc
1247 // log levels.
1248 std::vector<std::string>::iterator tracefilter =
1249 std::find(opts.begin(), opts.end(), "tracefilter");
1250 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
1251 if (!tracing_->SetTraceFilter(talk_base::FromString<int>(*tracefilter))) {
1252 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1253 }
1254 }
1255
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001256 // Set AEC dump file
1257 std::vector<std::string>::iterator recordEC =
1258 std::find(opts.begin(), opts.end(), "recordEC");
1259 if (recordEC != opts.end()) {
1260 ++recordEC;
1261 if (recordEC != opts.end())
1262 StartAecDump(recordEC->c_str());
1263 else
1264 StopAecDump();
1265 }
1266}
1267
1268// Ignore spammy trace messages, mostly from the stats API when we haven't
1269// gotten RTCP info yet from the remote side.
1270bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1271 static const char* kTracesToIgnore[] = {
1272 "\tfailed to GetReportBlockInformation",
1273 "GetRecCodec() failed to get received codec",
1274 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1275 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1276 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1277 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1278 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1279 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1280 "SenderInfoReceived No received SR",
1281 "StatisticsRTP() no statistics available",
1282 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1283 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1284 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1285 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1286 NULL
1287 };
1288 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1289 if (trace.find(*p) != std::string::npos) {
1290 return true;
1291 }
1292 }
1293 return false;
1294}
1295
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001296void WebRtcVoiceEngine::EnableExperimentalAcm(bool enable) {
1297 if (enable == use_experimental_acm_)
1298 return;
1299 if (enable) {
1300 LOG(LS_INFO) << "VoiceEngine is set to use new ACM (ACM2 + NetEq4).";
1301 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
1302 new webrtc::NewAudioCodingModuleFactory());
1303 } else {
1304 LOG(LS_INFO) << "VoiceEngine is set to use legacy ACM (ACM1 + Neteq3).";
1305 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
1306 new webrtc::AudioCodingModuleFactory());
1307 }
1308 use_experimental_acm_ = enable;
1309}
1310
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1312 int length) {
1313 talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
1314 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
1315 sev = talk_base::LS_ERROR;
1316 else if (level == webrtc::kTraceWarning)
1317 sev = talk_base::LS_WARNING;
1318 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
1319 sev = talk_base::LS_INFO;
1320 else if (level == webrtc::kTraceTerseInfo)
1321 sev = talk_base::LS_INFO;
1322
1323 // Skip past boilerplate prefix text
1324 if (length < 72) {
1325 std::string msg(trace, length);
1326 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1327 LOG_V(sev) << msg;
1328 } else {
1329 std::string msg(trace + 71, length - 72);
1330 if (!ShouldIgnoreTrace(msg)) {
1331 LOG_V(sev) << "webrtc: " << msg;
1332 }
1333 }
1334}
1335
1336void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
1337 talk_base::CritScope lock(&channels_cs_);
1338 WebRtcVoiceMediaChannel* channel = NULL;
1339 uint32 ssrc = 0;
1340 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1341 << channel_num << ".";
1342 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1343 ASSERT(channel != NULL);
1344 channel->OnError(ssrc, err_code);
1345 } else {
1346 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1347 << " could not be found in channel list when error reported.";
1348 }
1349}
1350
1351bool WebRtcVoiceEngine::FindChannelAndSsrc(
1352 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1353 ASSERT(channel != NULL && ssrc != NULL);
1354
1355 *channel = NULL;
1356 *ssrc = 0;
1357 // Find corresponding channel and ssrc
1358 for (ChannelList::const_iterator it = channels_.begin();
1359 it != channels_.end(); ++it) {
1360 ASSERT(*it != NULL);
1361 if ((*it)->FindSsrc(channel_num, ssrc)) {
1362 *channel = *it;
1363 return true;
1364 }
1365 }
1366
1367 return false;
1368}
1369
1370// This method will search through the WebRtcVoiceMediaChannels and
1371// obtain the voice engine's channel number.
1372bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1373 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1374 ASSERT(channel_num != NULL);
1375 ASSERT(direction == MPD_RX || direction == MPD_TX);
1376
1377 *channel_num = -1;
1378 // Find corresponding channel for ssrc.
1379 for (ChannelList::const_iterator it = channels_.begin();
1380 it != channels_.end(); ++it) {
1381 ASSERT(*it != NULL);
1382 if (direction & MPD_RX) {
1383 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1384 }
1385 if (*channel_num == -1 && (direction & MPD_TX)) {
1386 *channel_num = (*it)->GetSendChannelNum(ssrc);
1387 }
1388 if (*channel_num != -1) {
1389 return true;
1390 }
1391 }
1392 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1393 return false;
1394}
1395
1396void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
1397 talk_base::CritScope lock(&channels_cs_);
1398 channels_.push_back(channel);
1399}
1400
1401void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
1402 talk_base::CritScope lock(&channels_cs_);
1403 ChannelList::iterator i = std::find(channels_.begin(),
1404 channels_.end(),
1405 channel);
1406 if (i != channels_.end()) {
1407 channels_.erase(i);
1408 }
1409}
1410
1411void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1412 soundclips_.push_back(soundclip);
1413}
1414
1415void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1416 SoundclipList::iterator i = std::find(soundclips_.begin(),
1417 soundclips_.end(),
1418 soundclip);
1419 if (i != soundclips_.end()) {
1420 soundclips_.erase(i);
1421 }
1422}
1423
1424// Adjusts the default AGC target level by the specified delta.
1425// NB: If we start messing with other config fields, we'll want
1426// to save the current webrtc::AgcConfig as well.
1427bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1428 webrtc::AgcConfig config = default_agc_config_;
1429 config.targetLeveldBOv -= delta;
1430
1431 LOG(LS_INFO) << "Adjusting AGC level from default -"
1432 << default_agc_config_.targetLeveldBOv << "dB to -"
1433 << config.targetLeveldBOv << "dB";
1434
1435 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1436 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1437 return false;
1438 }
1439 return true;
1440}
1441
1442bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1443 webrtc::AudioDeviceModule* adm_sc) {
1444 if (initialized_) {
1445 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1446 return false;
1447 }
1448 if (adm_) {
1449 adm_->Release();
1450 adm_ = NULL;
1451 }
1452 if (adm) {
1453 adm_ = adm;
1454 adm_->AddRef();
1455 }
1456
1457 if (adm_sc_) {
1458 adm_sc_->Release();
1459 adm_sc_ = NULL;
1460 }
1461 if (adm_sc) {
1462 adm_sc_ = adm_sc;
1463 adm_sc_->AddRef();
1464 }
1465 return true;
1466}
1467
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001468bool WebRtcVoiceEngine::StartAecDump(talk_base::PlatformFile file) {
1469 FILE* aec_dump_file_stream = talk_base::FdopenPlatformFileForWriting(file);
1470 if (!aec_dump_file_stream) {
1471 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
1472 if (!talk_base::ClosePlatformFile(file))
1473 LOG(LS_WARNING) << "Could not close file.";
1474 return false;
1475 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001476 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001477 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001478 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001479 LOG_RTCERR0(StartDebugRecording);
1480 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001481 return false;
1482 }
1483 is_dumping_aec_ = true;
1484 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001485}
1486
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001487bool WebRtcVoiceEngine::RegisterProcessor(
1488 uint32 ssrc,
1489 VoiceProcessor* voice_processor,
1490 MediaProcessorDirection direction) {
1491 bool register_with_webrtc = false;
1492 int channel_id = -1;
1493 bool success = false;
1494 uint32* processor_ssrc = NULL;
1495 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1496 if (voice_processor == NULL || !found_channel) {
1497 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1498 << " foundChannel: " << found_channel;
1499 return false;
1500 }
1501
1502 webrtc::ProcessingTypes processing_type;
1503 {
1504 talk_base::CritScope cs(&signal_media_critical_);
1505 if (direction == MPD_RX) {
1506 processing_type = webrtc::kPlaybackAllChannelsMixed;
1507 if (SignalRxMediaFrame.is_empty()) {
1508 register_with_webrtc = true;
1509 processor_ssrc = &rx_processor_ssrc_;
1510 }
1511 SignalRxMediaFrame.connect(voice_processor,
1512 &VoiceProcessor::OnFrame);
1513 } else {
1514 processing_type = webrtc::kRecordingPerChannel;
1515 if (SignalTxMediaFrame.is_empty()) {
1516 register_with_webrtc = true;
1517 processor_ssrc = &tx_processor_ssrc_;
1518 }
1519 SignalTxMediaFrame.connect(voice_processor,
1520 &VoiceProcessor::OnFrame);
1521 }
1522 }
1523 if (register_with_webrtc) {
1524 // TODO(janahan): when registering consider instantiating a
1525 // a VoeMediaProcess object and not make the engine extend the interface.
1526 if (voe()->media() && voe()->media()->
1527 RegisterExternalMediaProcessing(channel_id,
1528 processing_type,
1529 *this) != -1) {
1530 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1531 << channel_id;
1532 *processor_ssrc = ssrc;
1533 success = true;
1534 } else {
1535 LOG_RTCERR2(RegisterExternalMediaProcessing,
1536 channel_id,
1537 processing_type);
1538 success = false;
1539 }
1540 } else {
1541 // If we don't have to register with the engine, we just needed to
1542 // connect a new processor, set success to true;
1543 success = true;
1544 }
1545 return success;
1546}
1547
1548bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1549 MediaProcessorDirection channel_direction,
1550 uint32 ssrc,
1551 VoiceProcessor* voice_processor,
1552 MediaProcessorDirection processor_direction) {
1553 bool success = true;
1554 FrameSignal* signal;
1555 webrtc::ProcessingTypes processing_type;
1556 uint32* processor_ssrc = NULL;
1557 if (channel_direction == MPD_RX) {
1558 signal = &SignalRxMediaFrame;
1559 processing_type = webrtc::kPlaybackAllChannelsMixed;
1560 processor_ssrc = &rx_processor_ssrc_;
1561 } else {
1562 signal = &SignalTxMediaFrame;
1563 processing_type = webrtc::kRecordingPerChannel;
1564 processor_ssrc = &tx_processor_ssrc_;
1565 }
1566
1567 int deregister_id = -1;
1568 {
1569 talk_base::CritScope cs(&signal_media_critical_);
1570 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1571 signal->disconnect(voice_processor);
1572 int channel_id = -1;
1573 bool found_channel = FindChannelNumFromSsrc(ssrc,
1574 channel_direction,
1575 &channel_id);
1576 if (signal->is_empty() && found_channel) {
1577 deregister_id = channel_id;
1578 }
1579 }
1580 }
1581 if (deregister_id != -1) {
1582 if (voe()->media() &&
1583 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1584 processing_type) != -1) {
1585 *processor_ssrc = 0;
1586 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1587 << deregister_id;
1588 } else {
1589 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1590 deregister_id,
1591 processing_type);
1592 success = false;
1593 }
1594 }
1595 return success;
1596}
1597
1598bool WebRtcVoiceEngine::UnregisterProcessor(
1599 uint32 ssrc,
1600 VoiceProcessor* voice_processor,
1601 MediaProcessorDirection direction) {
1602 bool success = true;
1603 if (voice_processor == NULL) {
1604 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1605 << ssrc;
1606 return false;
1607 }
1608 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1609 success = false;
1610 }
1611 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1612 success = false;
1613 }
1614 return success;
1615}
1616
1617// Implementing method from WebRtc VoEMediaProcess interface
1618// Do not lock mux_channel_cs_ in this callback.
1619void WebRtcVoiceEngine::Process(int channel,
1620 webrtc::ProcessingTypes type,
1621 int16_t audio10ms[],
1622 int length,
1623 int sampling_freq,
1624 bool is_stereo) {
1625 talk_base::CritScope cs(&signal_media_critical_);
1626 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1627 if (type == webrtc::kPlaybackAllChannelsMixed) {
1628 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1629 } else if (type == webrtc::kRecordingPerChannel) {
1630 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1631 } else {
1632 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1633 << " channel: " << channel << " type: " << type
1634 << " tx_ssrc: " << tx_processor_ssrc_
1635 << " rx_ssrc: " << rx_processor_ssrc_;
1636 }
1637}
1638
1639void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1640 if (!is_dumping_aec_) {
1641 // Start dumping AEC when we are not dumping.
1642 if (voe_wrapper_->processing()->StartDebugRecording(
1643 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001644 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001645 } else {
1646 is_dumping_aec_ = true;
1647 }
1648 }
1649}
1650
1651void WebRtcVoiceEngine::StopAecDump() {
1652 if (is_dumping_aec_) {
1653 // Stop dumping AEC when we are dumping.
1654 if (voe_wrapper_->processing()->StopDebugRecording() !=
1655 webrtc::AudioProcessing::kNoError) {
1656 LOG_RTCERR0(StopDebugRecording);
1657 }
1658 is_dumping_aec_ = false;
1659 }
1660}
1661
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001662int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001663 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001664}
1665
1666int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1667 return CreateVoiceChannel(voe_wrapper_.get());
1668}
1669
1670int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1671 return CreateVoiceChannel(voe_wrapper_sc_.get());
1672}
1673
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001674class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1675 : public AudioRenderer::Sink {
1676 public:
1677 WebRtcVoiceChannelRenderer(int ch,
1678 webrtc::AudioTransport* voe_audio_transport)
1679 : channel_(ch),
1680 voe_audio_transport_(voe_audio_transport),
1681 renderer_(NULL) {
1682 }
1683 virtual ~WebRtcVoiceChannelRenderer() {
1684 Stop();
1685 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001686
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001687 // Starts the rendering by setting a sink to the renderer to get data
1688 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001689 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001690 // TODO(xians): Make sure Start() is called only once.
1691 void Start(AudioRenderer* renderer) {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001692 talk_base::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001693 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001694 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001695 ASSERT(renderer_ == renderer);
1696 return;
1697 }
1698
1699 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1700 // in getUserMedia by default.
1701 renderer->AddChannel(channel_);
1702 renderer->SetSink(this);
1703 renderer_ = renderer;
1704 }
1705
1706 // Stops rendering by setting the sink of the renderer to NULL. No data
1707 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001708 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001709 void Stop() {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001710 talk_base::CritScope lock(&lock_);
1711 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001712 return;
1713
1714 renderer_->RemoveChannel(channel_);
1715 renderer_->SetSink(NULL);
1716 renderer_ = NULL;
1717 }
1718
1719 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001720 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001721 virtual void OnData(const void* audio_data,
1722 int bits_per_sample,
1723 int sample_rate,
1724 int number_of_channels,
1725 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001726#ifdef USE_WEBRTC_DEV_BRANCH
1727 voe_audio_transport_->OnData(channel_,
1728 audio_data,
1729 bits_per_sample,
1730 sample_rate,
1731 number_of_channels,
1732 number_of_frames);
1733#endif
1734 }
1735
1736 // Callback from the |renderer_| when it is going away. In case Start() has
1737 // never been called, this callback won't be triggered.
1738 virtual void OnClose() OVERRIDE {
1739 talk_base::CritScope lock(&lock_);
1740 // Set |renderer_| to NULL to make sure no more callback will get into
1741 // the renderer.
1742 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001743 }
1744
1745 // Accessor to the VoE channel ID.
1746 int channel() const { return channel_; }
1747
1748 private:
1749 const int channel_;
1750 webrtc::AudioTransport* const voe_audio_transport_;
1751
1752 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1753 // PeerConnection will make sure invalidating the pointer before the object
1754 // goes away.
1755 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001756
1757 // Protects |renderer_| in Start(), Stop() and OnClose().
1758 talk_base::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001759};
1760
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001761// WebRtcVoiceMediaChannel
1762WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1763 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1764 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001765 engine->CreateMediaVoiceChannel()),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001766 send_bw_setting_(false),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001767 send_bw_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001768 options_(),
1769 dtmf_allowed_(false),
1770 desired_playout_(false),
1771 nack_enabled_(false),
1772 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001773 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001774 desired_send_(SEND_NOTHING),
1775 send_(SEND_NOTHING),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001776 default_receive_ssrc_(0) {
1777 engine->RegisterChannel(this);
1778 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1779 << voe_channel();
1780
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001781 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001782}
1783
1784WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1785 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1786 << voe_channel();
1787
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001788 // Remove any remaining send streams, the default channel will be deleted
1789 // later.
1790 while (!send_channels_.empty())
1791 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001792
1793 // Unregister ourselves from the engine.
1794 engine()->UnregisterChannel(this);
1795 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001796 while (!receive_channels_.empty()) {
1797 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001798 }
1799
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001800 // Delete the default channel.
1801 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001802}
1803
1804bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1805 LOG(LS_INFO) << "Setting voice channel options: "
1806 << options.ToString();
1807
wu@webrtc.orgde305012013-10-31 15:40:38 +00001808 // Check if DSCP value is changed from previous.
1809 bool dscp_option_changed = (options_.dscp != options.dscp);
1810
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001811 // TODO(xians): Add support to set different options for different send
1812 // streams after we support multiple APMs.
1813
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001814 // We retain all of the existing options, and apply the given ones
1815 // on top. This means there is no way to "clear" options such that
1816 // they go back to the engine default.
1817 options_.SetAll(options);
1818
1819 if (send_ != SEND_NOTHING) {
1820 if (!engine()->SetOptionOverrides(options_)) {
1821 LOG(LS_WARNING) <<
1822 "Failed to engine SetOptionOverrides during channel SetOptions.";
1823 return false;
1824 }
1825 } else {
1826 // Will be interpreted when appropriate.
1827 }
1828
wu@webrtc.org97077a32013-10-25 21:18:33 +00001829 // Receiver-side auto gain control happens per channel, so set it here from
1830 // options. Note that, like conference mode, setting it on the engine won't
1831 // have the desired effect, since voice channels don't inherit options from
1832 // the media engine when those options are applied per-channel.
1833 bool rx_auto_gain_control;
1834 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1835 if (engine()->voe()->processing()->SetRxAgcStatus(
1836 voe_channel(), rx_auto_gain_control,
1837 webrtc::kAgcFixedDigital) == -1) {
1838 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1839 return false;
1840 } else {
1841 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1842 << " with mode " << webrtc::kAgcFixedDigital;
1843 }
1844 }
1845 if (options.rx_agc_target_dbov.IsSet() ||
1846 options.rx_agc_digital_compression_gain.IsSet() ||
1847 options.rx_agc_limiter.IsSet()) {
1848 webrtc::AgcConfig config;
1849 // If only some of the options are being overridden, get the current
1850 // settings for the channel and bail if they aren't available.
1851 if (!options.rx_agc_target_dbov.IsSet() ||
1852 !options.rx_agc_digital_compression_gain.IsSet() ||
1853 !options.rx_agc_limiter.IsSet()) {
1854 if (engine()->voe()->processing()->GetRxAgcConfig(
1855 voe_channel(), config) != 0) {
1856 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1857 << "channel " << voe_channel() << ". Since not all rx "
1858 << "agc options are specified, unable to safely set rx "
1859 << "agc options.";
1860 return false;
1861 }
1862 }
1863 config.targetLeveldBOv =
1864 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1865 config.targetLeveldBOv);
1866 config.digitalCompressionGaindB =
1867 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1868 config.digitalCompressionGaindB);
1869 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1870 config.limiterEnable);
1871 if (engine()->voe()->processing()->SetRxAgcConfig(
1872 voe_channel(), config) == -1) {
1873 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1874 config.digitalCompressionGaindB, config.limiterEnable);
1875 return false;
1876 }
1877 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001878 if (dscp_option_changed) {
1879 talk_base::DiffServCodePoint dscp = talk_base::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001880 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001881 dscp = kAudioDscpValue;
1882 if (MediaChannel::SetDscp(dscp) != 0) {
1883 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1884 }
1885 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001886
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001887 LOG(LS_INFO) << "Set voice channel options. Current options: "
1888 << options_.ToString();
1889 return true;
1890}
1891
1892bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1893 const std::vector<AudioCodec>& codecs) {
1894 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001895 LOG(LS_INFO) << "Setting receive voice codecs:";
1896
1897 std::vector<AudioCodec> new_codecs;
1898 // Find all new codecs. We allow adding new codecs but don't allow changing
1899 // the payload type of codecs that is already configured since we might
1900 // already be receiving packets with that payload type.
1901 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001902 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001903 AudioCodec old_codec;
1904 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1905 if (old_codec.id != it->id) {
1906 LOG(LS_ERROR) << it->name << " payload type changed.";
1907 return false;
1908 }
1909 } else {
1910 new_codecs.push_back(*it);
1911 }
1912 }
1913 if (new_codecs.empty()) {
1914 // There are no new codecs to configure. Already configured codecs are
1915 // never removed.
1916 return true;
1917 }
1918
1919 if (playout_) {
1920 // Receive codecs can not be changed while playing. So we temporarily
1921 // pause playout.
1922 PausePlayout();
1923 }
1924
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001925 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001926 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1927 it != new_codecs.end() && ret; ++it) {
1928 webrtc::CodecInst voe_codec;
1929 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1930 LOG(LS_INFO) << ToString(*it);
1931 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001932 if (default_receive_ssrc_ == 0) {
1933 // Set the receive codecs on the default channel explicitly if the
1934 // default channel is not used by |receive_channels_|, this happens in
1935 // conference mode or in non-conference mode when there is no playout
1936 // channel.
1937 // TODO(xians): Figure out how we use the default channel in conference
1938 // mode.
1939 if (engine()->voe()->codec()->SetRecPayloadType(
1940 voe_channel(), voe_codec) == -1) {
1941 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1942 ret = false;
1943 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001944 }
1945
1946 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001947 for (ChannelMap::iterator it = receive_channels_.begin();
1948 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001949 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001950 it->second->channel(), voe_codec) == -1) {
1951 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001952 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001953 ret = false;
1954 }
1955 }
1956 } else {
1957 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1958 ret = false;
1959 }
1960 }
1961 if (ret) {
1962 recv_codecs_ = codecs;
1963 }
1964
1965 if (desired_playout_ && !playout_) {
1966 ResumePlayout();
1967 }
1968 return ret;
1969}
1970
1971bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001972 int channel, const std::vector<AudioCodec>& codecs) {
1973 // Disable VAD, and FEC unless we know the other side wants them.
1974 engine()->voe()->codec()->SetVADStatus(channel, false);
1975 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1976 engine()->voe()->rtp()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001977
1978 // Scan through the list to figure out the codec to use for sending, along
1979 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001980 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001981 webrtc::CodecInst send_codec;
1982 memset(&send_codec, 0, sizeof(send_codec));
1983
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001984 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001985 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1986 it != codecs.end(); ++it) {
1987 // Ignore codecs we don't know about. The negotiation step should prevent
1988 // this, but double-check to be sure.
1989 webrtc::CodecInst voe_codec;
1990 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001991 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001992 continue;
1993 }
1994
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001995 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
1996 // Skip telephone-event/CN codec, which will be handled later.
1997 continue;
1998 }
1999
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002000 // If OPUS, change what we send according to the "stereo" codec
2001 // parameter, and not the "channels" parameter. We set
2002 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
2003 // the bitrate is not specified, i.e. is zero, we set it to the
2004 // appropriate default value for mono or stereo Opus.
2005 if (IsOpus(*it)) {
2006 if (IsOpusStereoEnabled(*it)) {
2007 voe_codec.channels = 2;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002008 if (!IsValidOpusBitrate(it->bitrate)) {
2009 if (it->bitrate != 0) {
2010 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2011 << it->bitrate
2012 << ") with default opus stereo bitrate: "
2013 << kOpusStereoBitrate;
2014 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002015 voe_codec.rate = kOpusStereoBitrate;
2016 }
2017 } else {
2018 voe_codec.channels = 1;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002019 if (!IsValidOpusBitrate(it->bitrate)) {
2020 if (it->bitrate != 0) {
2021 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2022 << it->bitrate
2023 << ") with default opus mono bitrate: "
2024 << kOpusMonoBitrate;
2025 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002026 voe_codec.rate = kOpusMonoBitrate;
2027 }
2028 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002029 int bitrate_from_params = GetOpusBitrateFromParams(*it);
2030 if (bitrate_from_params != 0) {
2031 voe_codec.rate = bitrate_from_params;
2032 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002033 }
2034
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002035 // We'll use the first codec in the list to actually send audio data.
2036 // Be sure to use the payload type requested by the remote side.
2037 // "red", for FEC audio, is a special case where the actual codec to be
2038 // used is specified in params.
2039 if (IsRedCodec(it->name)) {
2040 // Parse out the RED parameters. If we fail, just ignore RED;
2041 // we don't support all possible params/usage scenarios.
2042 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2043 continue;
2044 }
2045
2046 // Enable redundant encoding of the specified codec. Treat any
2047 // failure as a fatal internal error.
2048 LOG(LS_INFO) << "Enabling FEC";
2049 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2050 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
2051 return false;
2052 }
2053 } else {
2054 send_codec = voe_codec;
2055 nack_enabled_ = IsNackEnabled(*it);
2056 SetNack(channel, nack_enabled_);
2057 }
2058 found_send_codec = true;
2059 break;
2060 }
2061
2062 if (!found_send_codec) {
2063 LOG(LS_WARNING) << "Received empty list of codecs.";
2064 return false;
2065 }
2066
2067 // Set the codec immediately, since SetVADStatus() depends on whether
2068 // the current codec is mono or stereo.
2069 if (!SetSendCodec(channel, send_codec))
2070 return false;
2071
2072 // Always update the |send_codec_| to the currently set send codec.
2073 send_codec_.reset(new webrtc::CodecInst(send_codec));
2074
2075 if (send_bw_setting_) {
2076 SetSendBandwidthInternal(send_bw_bps_);
2077 }
2078
2079 // Loop through the codecs list again to config the telephone-event/CN codec.
2080 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2081 it != codecs.end(); ++it) {
2082 // Ignore codecs we don't know about. The negotiation step should prevent
2083 // this, but double-check to be sure.
2084 webrtc::CodecInst voe_codec;
2085 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2086 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2087 continue;
2088 }
2089
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002090 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2091 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002092 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002093 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2094 channel, it->id) == -1) {
2095 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2096 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002097 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002098 } else if (IsCNCodec(it->name)) {
2099 // Turn voice activity detection/comfort noise on if supported.
2100 // Set the wideband CN payload type appropriately.
2101 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002102 webrtc::PayloadFrequencies cn_freq;
2103 switch (it->clockrate) {
2104 case 8000:
2105 cn_freq = webrtc::kFreq8000Hz;
2106 break;
2107 case 16000:
2108 cn_freq = webrtc::kFreq16000Hz;
2109 break;
2110 case 32000:
2111 cn_freq = webrtc::kFreq32000Hz;
2112 break;
2113 default:
2114 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2115 << " not supported.";
2116 continue;
2117 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002118 // Set the CN payloadtype and the VAD status.
2119 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2120 if (cn_freq != webrtc::kFreq8000Hz) {
2121 if (engine()->voe()->codec()->SetSendCNPayloadType(
2122 channel, it->id, cn_freq) == -1) {
2123 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2124 // TODO(ajm): This failure condition will be removed from VoE.
2125 // Restore the return here when we update to a new enough webrtc.
2126 //
2127 // Not returning false because the SetSendCNPayloadType will fail if
2128 // the channel is already sending.
2129 // This can happen if the remote description is applied twice, for
2130 // example in the case of ROAP on top of JSEP, where both side will
2131 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002132 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002133 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002134 // Only turn on VAD if we have a CN payload type that matches the
2135 // clockrate for the codec we are going to use.
2136 if (it->clockrate == send_codec.plfreq) {
2137 LOG(LS_INFO) << "Enabling VAD";
2138 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2139 LOG_RTCERR2(SetVADStatus, channel, true);
2140 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002141 }
2142 }
2143 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002144 }
2145
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002146 return true;
2147}
2148
2149bool WebRtcVoiceMediaChannel::SetSendCodecs(
2150 const std::vector<AudioCodec>& codecs) {
2151 dtmf_allowed_ = false;
2152 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2153 it != codecs.end(); ++it) {
2154 // Find the DTMF telephone event "codec".
2155 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2156 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2157 dtmf_allowed_ = true;
2158 }
2159 }
2160
2161 // Cache the codecs in order to configure the channel created later.
2162 send_codecs_ = codecs;
2163 for (ChannelMap::iterator iter = send_channels_.begin();
2164 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002165 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002166 return false;
2167 }
2168 }
2169
2170 SetNack(receive_channels_, nack_enabled_);
2171
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002172 return true;
2173}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002174
2175void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2176 bool nack_enabled) {
2177 for (ChannelMap::const_iterator it = channels.begin();
2178 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002179 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002180 }
2181}
2182
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002183void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002184 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002185 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002186 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2187 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002188 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002189 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2190 }
2191}
2192
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002193bool WebRtcVoiceMediaChannel::SetSendCodec(
2194 const webrtc::CodecInst& send_codec) {
2195 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2196 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002197 for (ChannelMap::iterator iter = send_channels_.begin();
2198 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002199 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002200 return false;
2201 }
2202
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002203 return true;
2204}
2205
2206bool WebRtcVoiceMediaChannel::SetSendCodec(
2207 int channel, const webrtc::CodecInst& send_codec) {
2208 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2209 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2210
2211 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2212 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002213 return false;
2214 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002215 return true;
2216}
2217
2218bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2219 const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002220#ifdef USE_WEBRTC_DEV_BRANCH
2221 const RtpHeaderExtension* send_time_extension =
2222 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2223
2224 // Loop through all receive channels and enable/disable the extensions.
2225 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2226 channel_it != receive_channels_.end(); ++channel_it) {
2227 int channel_id = channel_it->second->channel();
2228 if (!SetHeaderExtension(
2229 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2230 send_time_extension)) {
2231 return false;
2232 }
2233 }
2234#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002235 return true;
2236}
2237
2238bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2239 const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002240 const RtpHeaderExtension* audio_level_extension =
2241 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2242#ifdef USE_WEBRTC_DEV_BRANCH
2243 const RtpHeaderExtension* send_time_extension =
2244 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2245#endif
2246
2247#ifndef USE_WEBRTC_DEV_BRANCH
2248 if (!SetHeaderExtension(
2249 &webrtc::VoERTP_RTCP::SetRTPAudioLevelIndicationStatus, voe_channel(),
2250 audio_level_extension)) {
2251 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002252 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002253#else
2254 if (!SetHeaderExtension(
2255 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, voe_channel(),
2256 audio_level_extension)) {
2257 return false;
2258 }
2259 if (!SetHeaderExtension(
2260 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, voe_channel(),
2261 send_time_extension)) {
2262 return false;
2263 }
2264#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002265
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002266 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2267 channel_it != send_channels_.end(); ++channel_it) {
2268 int channel_id = channel_it->second->channel();
2269#ifndef USE_WEBRTC_DEV_BRANCH
2270 if (!SetHeaderExtension(
2271 &webrtc::VoERTP_RTCP::SetRTPAudioLevelIndicationStatus, channel_id,
2272 audio_level_extension)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002273 return false;
2274 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002275#else
2276 if (!SetHeaderExtension(
2277 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
2278 audio_level_extension)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002279 return false;
2280 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002281 if (!SetHeaderExtension(
2282 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
2283 send_time_extension)) {
2284 return false;
2285 }
2286#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002287 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002288 return true;
2289}
2290
2291bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2292 desired_playout_ = playout;
2293 return ChangePlayout(desired_playout_);
2294}
2295
2296bool WebRtcVoiceMediaChannel::PausePlayout() {
2297 return ChangePlayout(false);
2298}
2299
2300bool WebRtcVoiceMediaChannel::ResumePlayout() {
2301 return ChangePlayout(desired_playout_);
2302}
2303
2304bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2305 if (playout_ == playout) {
2306 return true;
2307 }
2308
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002309 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002310 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002311 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002312 // Only toggle the default channel if we don't have any other channels.
2313 result = SetPlayout(voe_channel(), playout);
2314 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002315 for (ChannelMap::iterator it = receive_channels_.begin();
2316 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002317 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002318 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002319 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002320 result = false;
2321 }
2322 }
2323
2324 if (result) {
2325 playout_ = playout;
2326 }
2327 return result;
2328}
2329
2330bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2331 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002332 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002333 return ChangeSend(desired_send_);
2334 return true;
2335}
2336
2337bool WebRtcVoiceMediaChannel::PauseSend() {
2338 return ChangeSend(SEND_NOTHING);
2339}
2340
2341bool WebRtcVoiceMediaChannel::ResumeSend() {
2342 return ChangeSend(desired_send_);
2343}
2344
2345bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2346 if (send_ == send) {
2347 return true;
2348 }
2349
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002350 // Change the settings on each send channel.
2351 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002352 engine()->SetOptionOverrides(options_);
2353
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002354 // Change the settings on each send channel.
2355 for (ChannelMap::iterator iter = send_channels_.begin();
2356 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002357 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002358 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002359 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002360
2361 // Clear up the options after stopping sending.
2362 if (send == SEND_NOTHING)
2363 engine()->ClearOptionOverrides();
2364
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002365 send_ = send;
2366 return true;
2367}
2368
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002369bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2370 if (send == SEND_MICROPHONE) {
2371 if (engine()->voe()->base()->StartSend(channel) == -1) {
2372 LOG_RTCERR1(StartSend, channel);
2373 return false;
2374 }
2375 if (engine()->voe()->file() &&
2376 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2377 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2378 return false;
2379 }
2380 } else { // SEND_NOTHING
2381 ASSERT(send == SEND_NOTHING);
2382 if (engine()->voe()->base()->StopSend(channel) == -1) {
2383 LOG_RTCERR1(StopSend, channel);
2384 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002385 }
2386 }
2387
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002388 return true;
2389}
2390
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002391void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2392 if (engine()->voe()->network()->RegisterExternalTransport(
2393 channel, *this) == -1) {
2394 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2395 }
2396
2397 // Enable RTCP (for quality stats and feedback messages)
2398 EnableRtcp(channel);
2399
2400 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2401 ResetRecvCodecs(channel);
2402}
2403
2404bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2405 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2406 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2407 }
2408
2409 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2410 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002411 return false;
2412 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002413
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002414 return true;
2415}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002416
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002417bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2418 // If the default channel is already used for sending create a new channel
2419 // otherwise use the default channel for sending.
2420 int channel = GetSendChannelNum(sp.first_ssrc());
2421 if (channel != -1) {
2422 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2423 return false;
2424 }
2425
2426 bool default_channel_is_available = true;
2427 for (ChannelMap::const_iterator iter = send_channels_.begin();
2428 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002429 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002430 default_channel_is_available = false;
2431 break;
2432 }
2433 }
2434 if (default_channel_is_available) {
2435 channel = voe_channel();
2436 } else {
2437 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002438 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002439 if (channel == -1) {
2440 LOG_RTCERR0(CreateChannel);
2441 return false;
2442 }
2443
2444 ConfigureSendChannel(channel);
2445 }
2446
2447 // Save the channel to send_channels_, so that RemoveSendStream() can still
2448 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002449#ifdef USE_WEBRTC_DEV_BRANCH
2450 webrtc::AudioTransport* audio_transport =
2451 engine()->voe()->base()->audio_transport();
2452#else
2453 webrtc::AudioTransport* audio_transport = NULL;
2454#endif
2455 send_channels_.insert(std::make_pair(
2456 sp.first_ssrc(),
2457 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002458
2459 // Set the send (local) SSRC.
2460 // If there are multiple send SSRCs, we can only set the first one here, and
2461 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2462 // (with a codec requires multiple SSRC(s)).
2463 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2464 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2465 return false;
2466 }
2467
2468 // At this point the channel's local SSRC has been updated. If the channel is
2469 // the default channel make sure that all the receive channels are updated as
2470 // well. Receive channels have to have the same SSRC as the default channel in
2471 // order to send receiver reports with this SSRC.
2472 if (IsDefaultChannel(channel)) {
2473 for (ChannelMap::const_iterator it = receive_channels_.begin();
2474 it != receive_channels_.end(); ++it) {
2475 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002476 if (!IsDefaultChannel(it->second->channel())) {
2477 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002478 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002479 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002480 return false;
2481 }
2482 }
2483 }
2484 }
2485
2486 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
2487 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2488 return false;
2489 }
2490
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002491 // Set the current codecs to be used for the new channel.
2492 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002493 return false;
2494
2495 return ChangeSend(channel, desired_send_);
2496}
2497
2498bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2499 ChannelMap::iterator it = send_channels_.find(ssrc);
2500 if (it == send_channels_.end()) {
2501 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2502 << " which doesn't exist.";
2503 return false;
2504 }
2505
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002506 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002507 ChangeSend(channel, SEND_NOTHING);
2508
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002509 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2510 // this will disconnect the audio renderer with the send channel.
2511 delete it->second;
2512 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002513
2514 if (IsDefaultChannel(channel)) {
2515 // Do not delete the default channel since the receive channels depend on
2516 // the default channel, recycle it instead.
2517 ChangeSend(channel, SEND_NOTHING);
2518 } else {
2519 // Clean up and delete the send channel.
2520 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2521 << " with VoiceEngine channel #" << channel << ".";
2522 if (!DeleteChannel(channel))
2523 return false;
2524 }
2525
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002526 if (send_channels_.empty())
2527 ChangeSend(SEND_NOTHING);
2528
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002529 return true;
2530}
2531
2532bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002533 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002534
2535 if (!VERIFY(sp.ssrcs.size() == 1))
2536 return false;
2537 uint32 ssrc = sp.first_ssrc();
2538
wu@webrtc.org78187522013-10-07 23:32:02 +00002539 if (ssrc == 0) {
2540 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2541 return false;
2542 }
2543
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002544 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2545 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002546 return false;
2547 }
2548
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002549 // Reuse default channel for recv stream in non-conference mode call
2550 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002551#ifdef USE_WEBRTC_DEV_BRANCH
2552 webrtc::AudioTransport* audio_transport =
2553 engine()->voe()->base()->audio_transport();
2554#else
2555 webrtc::AudioTransport* audio_transport = NULL;
2556#endif
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002557 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2558 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2559 << " reuse default channel";
2560 default_receive_ssrc_ = sp.first_ssrc();
2561 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002562 default_receive_ssrc_,
2563 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002564 return SetPlayout(voe_channel(), playout_);
2565 }
2566
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002567 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002568 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002569 if (channel == -1) {
2570 LOG_RTCERR0(CreateChannel);
2571 return false;
2572 }
2573
wu@webrtc.org78187522013-10-07 23:32:02 +00002574 if (!ConfigureRecvChannel(channel)) {
2575 DeleteChannel(channel);
2576 return false;
2577 }
2578
2579 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002580 std::make_pair(
2581 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002582
2583 LOG(LS_INFO) << "New audio stream " << ssrc
2584 << " registered to VoiceEngine channel #"
2585 << channel << ".";
2586 return true;
2587}
2588
2589bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002590 // Configure to use external transport, like our default channel.
2591 if (engine()->voe()->network()->RegisterExternalTransport(
2592 channel, *this) == -1) {
2593 LOG_RTCERR2(SetExternalTransport, channel, this);
2594 return false;
2595 }
2596
2597 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002598 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002599 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2600 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002601 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002602 return false;
2603 }
2604 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002605 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002606 return false;
2607 }
2608
2609 // Use the same recv payload types as our default channel.
2610 ResetRecvCodecs(channel);
2611 if (!recv_codecs_.empty()) {
2612 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2613 it != recv_codecs_.end(); ++it) {
2614 webrtc::CodecInst voe_codec;
2615 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2616 voe_codec.pltype = it->id;
2617 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2618 if (engine()->voe()->codec()->GetRecPayloadType(
2619 voe_channel(), voe_codec) != -1) {
2620 if (engine()->voe()->codec()->SetRecPayloadType(
2621 channel, voe_codec) == -1) {
2622 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2623 return false;
2624 }
2625 }
2626 }
2627 }
2628 }
2629
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002630 if (InConferenceMode()) {
2631 // To be in par with the video, voe_channel() is not used for receiving in
2632 // a conference call.
2633 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2634 // This is the first stream in a multi user meeting. We can now
2635 // disable playback of the default stream. This since the default
2636 // stream will probably have received some initial packets before
2637 // the new stream was added. This will mean that the CN state from
2638 // the default channel will be mixed in with the other streams
2639 // throughout the whole meeting, which might be disturbing.
2640 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2641 SetPlayout(voe_channel(), false);
2642 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002643 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002644 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002645
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002646 return SetPlayout(channel, playout_);
2647}
2648
2649bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002650 talk_base::CritScope lock(&receive_channels_cs_);
2651 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002652 if (it == receive_channels_.end()) {
2653 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2654 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002655 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002656 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002657
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002658 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2659 // will disconnect the audio renderer with the receive channel.
2660 // Cache the channel before the deletion.
2661 const int channel = it->second->channel();
2662 delete it->second;
2663 receive_channels_.erase(it);
2664
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002665 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002666 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002667 // Recycle the default channel is for recv stream.
2668 if (playout_)
2669 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002670
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002671 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002672 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002673 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002674
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002675 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002676 << " with VoiceEngine channel #" << channel << ".";
2677 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002678 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002679
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002680 bool enable_default_channel_playout = false;
2681 if (receive_channels_.empty()) {
2682 // The last stream was removed. We can now enable the default
2683 // channel for new channels to be played out immediately without
2684 // waiting for AddStream messages.
2685 // We do this for both conference mode and non-conference mode.
2686 // TODO(oja): Does the default channel still have it's CN state?
2687 enable_default_channel_playout = true;
2688 }
2689 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2690 default_receive_ssrc_ != 0) {
2691 // Only the default channel is active, enable the playout on default
2692 // channel.
2693 enable_default_channel_playout = true;
2694 }
2695 if (enable_default_channel_playout && playout_) {
2696 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2697 SetPlayout(voe_channel(), true);
2698 }
2699
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002700 return true;
2701}
2702
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002703bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2704 AudioRenderer* renderer) {
2705 ChannelMap::iterator it = receive_channels_.find(ssrc);
2706 if (it == receive_channels_.end()) {
2707 if (renderer) {
2708 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002709 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002710 return false;
2711 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002712
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002713 // The channel likely has gone away, do nothing.
2714 return true;
2715 }
2716
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002717 if (renderer)
2718 it->second->Start(renderer);
2719 else
2720 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002721
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002722 return true;
2723}
2724
2725bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2726 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002727 ChannelMap::iterator it = send_channels_.find(ssrc);
2728 if (it == send_channels_.end()) {
2729 if (renderer) {
2730 // Return an error if trying to set a valid renderer with an invalid ssrc.
2731 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2732 return false;
2733 }
2734
2735 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002736 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002737 }
2738
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002739 if (renderer)
2740 it->second->Start(renderer);
2741 else
2742 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002743
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002744 return true;
2745}
2746
2747bool WebRtcVoiceMediaChannel::GetActiveStreams(
2748 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002749 // In conference mode, the default channel should not be in
2750 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002751 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002752 for (ChannelMap::iterator it = receive_channels_.begin();
2753 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002754 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002755 if (level > 0) {
2756 actives->push_back(std::make_pair(it->first, level));
2757 }
2758 }
2759 return true;
2760}
2761
2762int WebRtcVoiceMediaChannel::GetOutputLevel() {
2763 // return the highest output level of all streams
2764 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002765 for (ChannelMap::iterator it = receive_channels_.begin();
2766 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002767 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002768 highest = talk_base::_max(level, highest);
2769 }
2770 return highest;
2771}
2772
2773int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2774 int ret;
2775 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2776 // In case of error, log the info and continue
2777 LOG_RTCERR0(TimeSinceLastTyping);
2778 ret = -1;
2779 } else {
2780 ret *= 1000; // We return ms, webrtc returns seconds.
2781 }
2782 return ret;
2783}
2784
2785void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2786 int cost_per_typing, int reporting_threshold, int penalty_decay,
2787 int type_event_delay) {
2788 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2789 time_window, cost_per_typing,
2790 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2791 // In case of error, log the info and continue
2792 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2793 cost_per_typing, reporting_threshold, penalty_decay,
2794 type_event_delay);
2795 }
2796}
2797
2798bool WebRtcVoiceMediaChannel::SetOutputScaling(
2799 uint32 ssrc, double left, double right) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002800 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002801 // Collect the channels to scale the output volume.
2802 std::vector<int> channels;
2803 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002804 // Default channel is not in receive_channels_ if it is not being used for
2805 // playout.
2806 if (default_receive_ssrc_ == 0)
2807 channels.push_back(voe_channel());
2808 for (ChannelMap::const_iterator it = receive_channels_.begin();
2809 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002810 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002811 }
2812 } else { // Collect only the channel of the specified ssrc.
2813 int channel = GetReceiveChannelNum(ssrc);
2814 if (-1 == channel) {
2815 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2816 return false;
2817 }
2818 channels.push_back(channel);
2819 }
2820
2821 // Scale the output volume for the collected channels. We first normalize to
2822 // scale the volume and then set the left and right pan.
2823 float scale = static_cast<float>(talk_base::_max(left, right));
2824 if (scale > 0.0001f) {
2825 left /= scale;
2826 right /= scale;
2827 }
2828 for (std::vector<int>::const_iterator it = channels.begin();
2829 it != channels.end(); ++it) {
2830 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2831 *it, scale)) {
2832 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2833 return false;
2834 }
2835 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2836 *it, static_cast<float>(left), static_cast<float>(right))) {
2837 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2838 // Do not return if fails. SetOutputVolumePan is not available for all
2839 // pltforms.
2840 }
2841 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2842 << " right=" << right * scale
2843 << " for channel " << *it << " and ssrc " << ssrc;
2844 }
2845 return true;
2846}
2847
2848bool WebRtcVoiceMediaChannel::GetOutputScaling(
2849 uint32 ssrc, double* left, double* right) {
2850 if (!left || !right) return false;
2851
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002852 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002853 // Determine which channel based on ssrc.
2854 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2855 if (channel == -1) {
2856 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2857 return false;
2858 }
2859
2860 float scaling;
2861 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2862 channel, scaling)) {
2863 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2864 return false;
2865 }
2866
2867 float left_pan;
2868 float right_pan;
2869 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2870 channel, left_pan, right_pan)) {
2871 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2872 // If GetOutputVolumePan fails, we use the default left and right pan.
2873 left_pan = 1.0f;
2874 right_pan = 1.0f;
2875 }
2876
2877 *left = scaling * left_pan;
2878 *right = scaling * right_pan;
2879 return true;
2880}
2881
2882bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2883 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2884 return true;
2885}
2886
2887bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2888 bool play, bool loop) {
2889 if (!ringback_tone_) {
2890 return false;
2891 }
2892
2893 // The voe file api is not available in chrome.
2894 if (!engine()->voe()->file()) {
2895 return false;
2896 }
2897
2898 // Determine which VoiceEngine channel to play on.
2899 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2900 if (channel == -1) {
2901 return false;
2902 }
2903
2904 // Make sure the ringtone is cued properly, and play it out.
2905 if (play) {
2906 ringback_tone_->set_loop(loop);
2907 ringback_tone_->Rewind();
2908 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2909 ringback_tone_.get()) == -1) {
2910 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2911 LOG(LS_ERROR) << "Unable to start ringback tone";
2912 return false;
2913 }
2914 ringback_channels_.insert(channel);
2915 LOG(LS_INFO) << "Started ringback on channel " << channel;
2916 } else {
2917 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2918 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2919 LOG_RTCERR1(StopPlayingFileLocally, channel);
2920 return false;
2921 }
2922 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2923 ringback_channels_.erase(channel);
2924 }
2925
2926 return true;
2927}
2928
2929bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2930 return dtmf_allowed_;
2931}
2932
2933bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2934 int duration, int flags) {
2935 if (!dtmf_allowed_) {
2936 return false;
2937 }
2938
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002939 // Send the event.
2940 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002941 int channel = -1;
2942 if (ssrc == 0) {
2943 bool default_channel_is_inuse = false;
2944 for (ChannelMap::const_iterator iter = send_channels_.begin();
2945 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002946 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002947 default_channel_is_inuse = true;
2948 break;
2949 }
2950 }
2951 if (default_channel_is_inuse) {
2952 channel = voe_channel();
2953 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002954 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002955 }
2956 } else {
2957 channel = GetSendChannelNum(ssrc);
2958 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002959 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002960 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2961 << ssrc << " is not in use.";
2962 return false;
2963 }
2964 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002965 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2966 channel, event, true, duration) == -1) {
2967 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002968 return false;
2969 }
2970 }
2971
2972 // Play the event.
2973 if (flags & cricket::DF_PLAY) {
2974 // Play DTMF tone locally.
2975 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
2976 LOG_RTCERR2(PlayDtmfTone, event, duration);
2977 return false;
2978 }
2979 }
2980
2981 return true;
2982}
2983
wu@webrtc.orga9890802013-12-13 00:21:03 +00002984void WebRtcVoiceMediaChannel::OnPacketReceived(
2985 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002986 // Pick which channel to send this packet to. If this packet doesn't match
2987 // any multiplexed streams, just send it to the default channel. Otherwise,
2988 // send it to the specific decoder instance for that stream.
2989 int which_channel = GetReceiveChannelNum(
2990 ParseSsrc(packet->data(), packet->length(), false));
2991 if (which_channel == -1) {
2992 which_channel = voe_channel();
2993 }
2994
2995 // Stop any ringback that might be playing on the channel.
2996 // It's possible the ringback has already stopped, ih which case we'll just
2997 // use the opportunity to remove the channel from ringback_channels_.
2998 if (engine()->voe()->file()) {
2999 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3000 if (it != ringback_channels_.end()) {
3001 if (engine()->voe()->file()->IsPlayingFileLocally(
3002 which_channel) == 1) {
3003 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3004 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3005 << " due to incoming media";
3006 }
3007 ringback_channels_.erase(which_channel);
3008 }
3009 }
3010
3011 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003012 engine()->voe()->network()->ReceivedRTPPacket(
3013 which_channel,
3014 packet->data(),
3015 static_cast<unsigned int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003016}
3017
wu@webrtc.orga9890802013-12-13 00:21:03 +00003018void WebRtcVoiceMediaChannel::OnRtcpReceived(
3019 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003020 // Sending channels need all RTCP packets with feedback information.
3021 // Even sender reports can contain attached report blocks.
3022 // Receiving channels need sender reports in order to create
3023 // correct receiver reports.
3024 int type = 0;
3025 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3026 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3027 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003028 }
3029
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003030 // If it is a sender report, find the channel that is listening.
3031 bool has_sent_to_default_channel = false;
3032 if (type == kRtcpTypeSR) {
3033 int which_channel = GetReceiveChannelNum(
3034 ParseSsrc(packet->data(), packet->length(), true));
3035 if (which_channel != -1) {
3036 engine()->voe()->network()->ReceivedRTCPPacket(
3037 which_channel,
3038 packet->data(),
3039 static_cast<unsigned int>(packet->length()));
3040
3041 if (IsDefaultChannel(which_channel))
3042 has_sent_to_default_channel = true;
3043 }
3044 }
3045
3046 // SR may continue RR and any RR entry may correspond to any one of the send
3047 // channels. So all RTCP packets must be forwarded all send channels. VoE
3048 // will filter out RR internally.
3049 for (ChannelMap::iterator iter = send_channels_.begin();
3050 iter != send_channels_.end(); ++iter) {
3051 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003052 if (IsDefaultChannel(iter->second->channel()) &&
3053 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003054 continue;
3055
3056 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003057 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003058 packet->data(),
3059 static_cast<unsigned int>(packet->length()));
3060 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003061}
3062
3063bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003064 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3065 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003066 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3067 return false;
3068 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003069 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3070 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003071 return false;
3072 }
3073 return true;
3074}
3075
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003076bool WebRtcVoiceMediaChannel::SetStartSendBandwidth(int bps) {
3077 // TODO(andresp): Add support for setting an independent start bandwidth when
3078 // bandwidth estimation is enabled for voice engine.
3079 return false;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003080}
3081
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003082bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
3083 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
3084
3085 return SetSendBandwidthInternal(bps);
3086}
3087
3088bool WebRtcVoiceMediaChannel::SetSendBandwidthInternal(int bps) {
3089 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBandwidthInternal.";
3090
3091 send_bw_setting_ = true;
3092 send_bw_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003093
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003094 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003095 LOG(LS_INFO) << "The send codec has not been set up yet. "
3096 << "The send bandwidth setting will be applied later.";
3097 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003098 }
3099
3100 // Bandwidth is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003101 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3102 // SetMaxSendBandwith(0), the second call removes the previous limit.
3103 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003104 return true;
3105
3106 webrtc::CodecInst codec = *send_codec_;
3107 bool is_multi_rate = IsCodecMultiRate(codec);
3108
3109 if (is_multi_rate) {
3110 // If codec is multi-rate then just set the bitrate.
3111 codec.rate = bps;
3112 if (!SetSendCodec(codec)) {
3113 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3114 << " to bitrate " << bps << " bps.";
3115 return false;
3116 }
3117 return true;
3118 } else {
3119 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3120 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3121 // fixed bitrate then ignore.
3122 if (bps < codec.rate) {
3123 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3124 << " to bitrate " << bps << " bps"
3125 << ", requires at least " << codec.rate << " bps.";
3126 return false;
3127 }
3128 return true;
3129 }
3130}
3131
3132bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003133 bool echo_metrics_on = false;
3134 // These can take on valid negative values, so use the lowest possible level
3135 // as default rather than -1.
3136 int echo_return_loss = -100;
3137 int echo_return_loss_enhancement = -100;
3138 // These can also be negative, but in practice -1 is only used to signal
3139 // insufficient data, since the resolution is limited to multiples of 4 ms.
3140 int echo_delay_median_ms = -1;
3141 int echo_delay_std_ms = -1;
3142 if (engine()->voe()->processing()->GetEcMetricsStatus(
3143 echo_metrics_on) != -1 && echo_metrics_on) {
3144 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3145 // here, but it appears to be unsuitable currently. Revisit after this is
3146 // investigated: http://b/issue?id=5666755
3147 int erl, erle, rerl, anlp;
3148 if (engine()->voe()->processing()->GetEchoMetrics(
3149 erl, erle, rerl, anlp) != -1) {
3150 echo_return_loss = erl;
3151 echo_return_loss_enhancement = erle;
3152 }
3153
3154 int median, std;
3155 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3156 echo_delay_median_ms = median;
3157 echo_delay_std_ms = std;
3158 }
3159 }
3160
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003161 webrtc::CallStatistics cs;
3162 unsigned int ssrc;
3163 webrtc::CodecInst codec;
3164 unsigned int level;
3165
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003166 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3167 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003168 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003169
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003170 // Fill in the sender info, based on what we know, and what the
3171 // remote side told us it got from its RTCP report.
3172 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003173
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003174 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3175 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3176 continue;
3177 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003178
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003179 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003180 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3181 sinfo.bytes_sent = cs.bytesSent;
3182 sinfo.packets_sent = cs.packetsSent;
3183 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3184 // returns 0 to indicate an error value.
3185 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3186
3187 // Get data from the last remote RTCP report. Use default values if no data
3188 // available.
3189 sinfo.fraction_lost = -1.0;
3190 sinfo.jitter_ms = -1;
3191 sinfo.packets_lost = -1;
3192 sinfo.ext_seqnum = -1;
3193 std::vector<webrtc::ReportBlock> receive_blocks;
3194 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3195 channel, &receive_blocks) != -1 &&
3196 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3197 std::vector<webrtc::ReportBlock>::iterator iter;
3198 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3199 ++iter) {
3200 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003201 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003202 // Convert Q8 to floating point.
3203 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3204 // Convert samples to milliseconds.
3205 if (codec.plfreq / 1000 > 0) {
3206 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3207 }
3208 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3209 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3210 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003211 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003212 }
3213 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003214
3215 // Local speech level.
3216 sinfo.audio_level = (engine()->voe()->volume()->
3217 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3218
3219 // TODO(xians): We are injecting the same APM logging to all the send
3220 // channels here because there is no good way to know which send channel
3221 // is using the APM. The correct fix is to allow the send channels to have
3222 // their own APM so that we can feed the correct APM logging to different
3223 // send channels. See issue crbug/264611 .
3224 sinfo.echo_return_loss = echo_return_loss;
3225 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3226 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3227 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003228 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3229 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003230 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003231
3232 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003233 }
3234
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003235 // Build the list of receivers, one for each receiving channel, or 1 in
3236 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003237 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003238 for (ChannelMap::const_iterator it = receive_channels_.begin();
3239 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003240 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003241 }
3242 if (channels.empty()) {
3243 channels.push_back(voe_channel());
3244 }
3245
3246 // Get the SSRC and stats for each receiver, based on our own calculations.
3247 for (std::vector<int>::const_iterator it = channels.begin();
3248 it != channels.end(); ++it) {
3249 memset(&cs, 0, sizeof(cs));
3250 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3251 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3252 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3253 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003254 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003255 rinfo.bytes_rcvd = cs.bytesReceived;
3256 rinfo.packets_rcvd = cs.packetsReceived;
3257 // The next four fields are from the most recently sent RTCP report.
3258 // Convert Q8 to floating point.
3259 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3260 rinfo.packets_lost = cs.cumulativeLost;
3261 rinfo.ext_seqnum = cs.extendedMax;
3262 // Convert samples to milliseconds.
3263 if (codec.plfreq / 1000 > 0) {
3264 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3265 }
3266
3267 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3268 webrtc::NetworkStatistics ns;
3269 if (engine()->voe()->neteq() &&
3270 engine()->voe()->neteq()->GetNetworkStatistics(
3271 *it, ns) != -1) {
3272 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3273 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3274 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003275 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003276 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003277
3278 webrtc::AudioDecodingCallStats ds;
3279 if (engine()->voe()->neteq() &&
3280 engine()->voe()->neteq()->GetDecodingCallStatistics(
3281 *it, &ds) != -1) {
3282 rinfo.decoding_calls_to_silence_generator =
3283 ds.calls_to_silence_generator;
3284 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3285 rinfo.decoding_normal = ds.decoded_normal;
3286 rinfo.decoding_plc = ds.decoded_plc;
3287 rinfo.decoding_cng = ds.decoded_cng;
3288 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3289 }
3290
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003291 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003292 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003293 int playout_buffer_delay_ms = 0;
3294 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003295 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3296 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3297 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003298 }
3299
3300 // Get speech level.
3301 rinfo.audio_level = (engine()->voe()->volume()->
3302 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3303 info->receivers.push_back(rinfo);
3304 }
3305 }
3306
3307 return true;
3308}
3309
3310void WebRtcVoiceMediaChannel::GetLastMediaError(
3311 uint32* ssrc, VoiceMediaChannel::Error* error) {
3312 ASSERT(ssrc != NULL);
3313 ASSERT(error != NULL);
3314 FindSsrc(voe_channel(), ssrc);
3315 *error = WebRtcErrorToChannelError(GetLastEngineError());
3316}
3317
3318bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003319 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003320 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003321 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003322 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3323 // This means the error is not limited to a specific channel. Signal the
3324 // message using ssrc=0. If the current channel is sending, use this
3325 // channel for sending the message.
3326 *ssrc = 0;
3327 return true;
3328 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003329 // Check whether this is a sending channel.
3330 for (ChannelMap::const_iterator it = send_channels_.begin();
3331 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003332 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003333 // This is a sending channel.
3334 uint32 local_ssrc = 0;
3335 if (engine()->voe()->rtp()->GetLocalSSRC(
3336 channel_num, local_ssrc) != -1) {
3337 *ssrc = local_ssrc;
3338 }
3339 return true;
3340 }
3341 }
3342
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003343 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003344 for (ChannelMap::const_iterator it = receive_channels_.begin();
3345 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003346 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003347 *ssrc = it->first;
3348 return true;
3349 }
3350 }
3351 }
3352 return false;
3353}
3354
3355void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003356 if (error == VE_TYPING_NOISE_WARNING) {
3357 typing_noise_detected_ = true;
3358 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3359 typing_noise_detected_ = false;
3360 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003361 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3362}
3363
3364int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3365 unsigned int ulevel;
3366 int ret =
3367 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3368 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3369}
3370
3371int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003372 ChannelMap::iterator it = receive_channels_.find(ssrc);
3373 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003374 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003375 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3376}
3377
3378int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003379 ChannelMap::iterator it = send_channels_.find(ssrc);
3380 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003381 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003382
3383 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003384}
3385
3386bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3387 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3388 // Get the RED encodings from the parameter with no name. This may
3389 // change based on what is discussed on the Jingle list.
3390 // The encoding parameter is of the form "a/b"; we only support where
3391 // a == b. Verify this and parse out the value into red_pt.
3392 // If the parameter value is absent (as it will be until we wire up the
3393 // signaling of this message), use the second codec specified (i.e. the
3394 // one after "red") as the encoding parameter.
3395 int red_pt = -1;
3396 std::string red_params;
3397 CodecParameterMap::const_iterator it = red_codec.params.find("");
3398 if (it != red_codec.params.end()) {
3399 red_params = it->second;
3400 std::vector<std::string> red_pts;
3401 if (talk_base::split(red_params, '/', &red_pts) != 2 ||
3402 red_pts[0] != red_pts[1] ||
3403 !talk_base::FromString(red_pts[0], &red_pt)) {
3404 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3405 return false;
3406 }
3407 } else if (red_codec.params.empty()) {
3408 LOG(LS_WARNING) << "RED params not present, using defaults";
3409 if (all_codecs.size() > 1) {
3410 red_pt = all_codecs[1].id;
3411 }
3412 }
3413
3414 // Try to find red_pt in |codecs|.
3415 std::vector<AudioCodec>::const_iterator codec;
3416 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3417 if (codec->id == red_pt)
3418 break;
3419 }
3420
3421 // If we find the right codec, that will be the codec we pass to
3422 // SetSendCodec, with the desired payload type.
3423 if (codec != all_codecs.end() &&
3424 engine()->FindWebRtcCodec(*codec, send_codec)) {
3425 } else {
3426 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3427 return false;
3428 }
3429
3430 return true;
3431}
3432
3433bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3434 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003435 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003436 return false;
3437 }
3438 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3439 // what we want to do with them.
3440 // engine()->voe().EnableVQMon(voe_channel(), true);
3441 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3442 return true;
3443}
3444
3445bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3446 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3447 for (int i = 0; i < ncodecs; ++i) {
3448 webrtc::CodecInst voe_codec;
3449 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3450 voe_codec.pltype = -1;
3451 if (engine()->voe()->codec()->SetRecPayloadType(
3452 channel, voe_codec) == -1) {
3453 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3454 return false;
3455 }
3456 }
3457 }
3458 return true;
3459}
3460
3461bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3462 if (playout) {
3463 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3464 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3465 LOG_RTCERR1(StartPlayout, channel);
3466 return false;
3467 }
3468 } else {
3469 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3470 engine()->voe()->base()->StopPlayout(channel);
3471 }
3472 return true;
3473}
3474
3475uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3476 bool rtcp) {
3477 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3478 uint32 ssrc = 0;
3479 if (len >= (ssrc_pos + sizeof(ssrc))) {
3480 ssrc = talk_base::GetBE32(static_cast<const char*>(data) + ssrc_pos);
3481 }
3482 return ssrc;
3483}
3484
3485// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3486VoiceMediaChannel::Error
3487 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3488 switch (err_code) {
3489 case 0:
3490 return ERROR_NONE;
3491 case VE_CANNOT_START_RECORDING:
3492 case VE_MIC_VOL_ERROR:
3493 case VE_GET_MIC_VOL_ERROR:
3494 case VE_CANNOT_ACCESS_MIC_VOL:
3495 return ERROR_REC_DEVICE_OPEN_FAILED;
3496 case VE_SATURATION_WARNING:
3497 return ERROR_REC_DEVICE_SATURATION;
3498 case VE_REC_DEVICE_REMOVED:
3499 return ERROR_REC_DEVICE_REMOVED;
3500 case VE_RUNTIME_REC_WARNING:
3501 case VE_RUNTIME_REC_ERROR:
3502 return ERROR_REC_RUNTIME_ERROR;
3503 case VE_CANNOT_START_PLAYOUT:
3504 case VE_SPEAKER_VOL_ERROR:
3505 case VE_GET_SPEAKER_VOL_ERROR:
3506 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3507 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3508 case VE_RUNTIME_PLAY_WARNING:
3509 case VE_RUNTIME_PLAY_ERROR:
3510 return ERROR_PLAY_RUNTIME_ERROR;
3511 case VE_TYPING_NOISE_WARNING:
3512 return ERROR_REC_TYPING_NOISE_DETECTED;
3513 default:
3514 return VoiceMediaChannel::ERROR_OTHER;
3515 }
3516}
3517
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003518bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3519 int channel_id, const RtpHeaderExtension* extension) {
3520 bool enable = false;
3521 unsigned char id = 0;
3522 if (extension) {
3523 enable = true;
3524 id = extension->id;
3525 }
3526 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
3527 LOG_RTCERR4(*setter, extension->uri, channel_id, enable, id);
3528 return false;
3529 }
3530 return true;
3531}
3532
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003533int WebRtcSoundclipStream::Read(void *buf, int len) {
3534 size_t res = 0;
3535 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003536 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003537}
3538
3539int WebRtcSoundclipStream::Rewind() {
3540 mem_.Rewind();
3541 // Return -1 to keep VoiceEngine from looping.
3542 return (loop_) ? 0 : -1;
3543}
3544
3545} // namespace cricket
3546
3547#endif // HAVE_WEBRTC_VOICE