blob: bf4cef6e0139305b4c8922722ac1d677d5cb3177 [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.org05e7b442014-04-01 17:44:24 +0000223// TODO(mallinath) - Remove this after trunk of webrtc is pushed to GTP.
224#if !defined(USE_WEBRTC_DEV_BRANCH)
225bool operator==(const webrtc::CodecInst& lhs, const webrtc::CodecInst& rhs) {
226 return lhs.pltype == rhs.pltype &&
227 (_stricmp(lhs.plname, rhs.plname) == 0) &&
228 lhs.plfreq == rhs.plfreq &&
229 lhs.pacsize == rhs.pacsize &&
230 lhs.channels == rhs.channels &&
231 lhs.rate == rhs.rate;
232}
233
234bool operator!=(const webrtc::CodecInst& lhs, const webrtc::CodecInst& rhs) {
235 return !(lhs == rhs);
236}
237#endif
238
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000239// Gets the default set of options applied to the engine. Historically, these
240// were supplied as a combination of flags from the channel manager (ec, agc,
241// ns, and highpass) and the rest hardcoded in InitInternal.
242static AudioOptions GetDefaultEngineOptions() {
243 AudioOptions options;
244 options.echo_cancellation.Set(true);
245 options.auto_gain_control.Set(true);
246 options.noise_suppression.Set(true);
247 options.highpass_filter.Set(true);
248 options.stereo_swapping.Set(false);
249 options.typing_detection.Set(true);
250 options.conference_mode.Set(false);
251 options.adjust_agc_delta.Set(0);
252 options.experimental_agc.Set(false);
253 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000254 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000255 options.aec_dump.Set(false);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000256 options.experimental_acm.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000257 return options;
258}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000259
260class WebRtcSoundclipMedia : public SoundclipMedia {
261 public:
262 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
263 : engine_(engine), webrtc_channel_(-1) {
264 engine_->RegisterSoundclip(this);
265 }
266
267 virtual ~WebRtcSoundclipMedia() {
268 engine_->UnregisterSoundclip(this);
269 if (webrtc_channel_ != -1) {
270 // We shouldn't have to call Disable() here. DeleteChannel() should call
271 // StopPlayout() while deleting the channel. We should fix the bug
272 // inside WebRTC and remove the Disable() call bellow. This work is
273 // tracked by bug http://b/issue?id=5382855.
274 PlaySound(NULL, 0, 0);
275 Disable();
276 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
277 == -1) {
278 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
279 }
280 }
281 }
282
283 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000284 if (!engine_->voe_sc()) {
285 return false;
286 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000287 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000288 if (webrtc_channel_ == -1) {
289 LOG_RTCERR0(CreateChannel);
290 return false;
291 }
292 return true;
293 }
294
295 bool Enable() {
296 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
297 LOG_RTCERR1(StartPlayout, webrtc_channel_);
298 return false;
299 }
300 return true;
301 }
302
303 bool Disable() {
304 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
305 LOG_RTCERR1(StopPlayout, webrtc_channel_);
306 return false;
307 }
308 return true;
309 }
310
311 virtual bool PlaySound(const char *buf, int len, int flags) {
312 // The voe file api is not available in chrome.
313 if (!engine_->voe_sc()->file()) {
314 return false;
315 }
316 // Must stop playing the current sound (if any), because we are about to
317 // modify the stream.
318 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
319 == -1) {
320 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
321 return false;
322 }
323
324 if (buf) {
325 stream_.reset(new WebRtcSoundclipStream(buf, len));
326 stream_->set_loop((flags & SF_LOOP) != 0);
327 stream_->Rewind();
328
329 // Play it.
330 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
331 webrtc_channel_, stream_.get()) == -1) {
332 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
333 LOG(LS_ERROR) << "Unable to start soundclip";
334 return false;
335 }
336 } else {
337 stream_.reset();
338 }
339 return true;
340 }
341
342 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
343
344 private:
345 WebRtcVoiceEngine *engine_;
346 int webrtc_channel_;
347 talk_base::scoped_ptr<WebRtcSoundclipStream> stream_;
348};
349
350WebRtcVoiceEngine::WebRtcVoiceEngine()
351 : voe_wrapper_(new VoEWrapper()),
352 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000353 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000354 tracing_(new VoETraceWrapper()),
355 adm_(NULL),
356 adm_sc_(NULL),
357 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
358 is_dumping_aec_(false),
359 desired_local_monitor_enable_(false),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000360 use_experimental_acm_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000361 tx_processor_ssrc_(0),
362 rx_processor_ssrc_(0) {
363 Construct();
364}
365
366WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
367 VoEWrapper* voe_wrapper_sc,
368 VoETraceWrapper* tracing)
369 : voe_wrapper_(voe_wrapper),
370 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000371 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000372 tracing_(tracing),
373 adm_(NULL),
374 adm_sc_(NULL),
375 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
376 is_dumping_aec_(false),
377 desired_local_monitor_enable_(false),
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000378 use_experimental_acm_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000379 tx_processor_ssrc_(0),
380 rx_processor_ssrc_(0) {
381 Construct();
382}
383
384void WebRtcVoiceEngine::Construct() {
385 SetTraceFilter(log_filter_);
386 initialized_ = false;
387 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
388 SetTraceOptions("");
389 if (tracing_->SetTraceCallback(this) == -1) {
390 LOG_RTCERR0(SetTraceCallback);
391 }
392 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
393 LOG_RTCERR0(RegisterVoiceEngineObserver);
394 }
395 // Clear the default agc state.
396 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
397
398 // Load our audio codec list.
399 ConstructCodecs();
400
401 // Load our RTP Header extensions.
402 rtp_header_extensions_.push_back(
403 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
henrike@webrtc.org79047f92014-03-06 23:46:59 +0000404 kRtpAudioLevelHeaderExtensionDefaultId));
405#ifdef USE_WEBRTC_DEV_BRANCH
406 rtp_header_extensions_.push_back(
407 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
408 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
409#endif
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000410 options_ = GetDefaultEngineOptions();
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000411
412 // Initialize the VoE Configuration to the default ACM.
413 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
414 new webrtc::AudioCodingModuleFactory);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000415}
416
417static bool IsOpus(const AudioCodec& codec) {
418 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
419}
420
421static bool IsIsac(const AudioCodec& codec) {
422 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
423}
424
425// True if params["stereo"] == "1"
426static bool IsOpusStereoEnabled(const AudioCodec& codec) {
427 CodecParameterMap::const_iterator param =
428 codec.params.find(kCodecParamStereo);
429 if (param == codec.params.end()) {
430 return false;
431 }
432 return param->second == kParamValueTrue;
433}
434
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000435static bool IsValidOpusBitrate(int bitrate) {
436 return (bitrate >= kOpusMinBitrate && bitrate <= kOpusMaxBitrate);
437}
438
439// Returns 0 if params[kCodecParamMaxAverageBitrate] is not defined or invalid.
440// Returns the value of params[kCodecParamMaxAverageBitrate] otherwise.
441static int GetOpusBitrateFromParams(const AudioCodec& codec) {
442 int bitrate = 0;
443 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
444 return 0;
445 }
446 if (!IsValidOpusBitrate(bitrate)) {
447 LOG(LS_WARNING) << "Codec parameter \"maxaveragebitrate\" has an "
448 << "invalid value: " << bitrate;
449 return 0;
450 }
451 return bitrate;
452}
453
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000454void WebRtcVoiceEngine::ConstructCodecs() {
455 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
456 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
457 for (int i = 0; i < ncodecs; ++i) {
458 webrtc::CodecInst voe_codec;
459 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
460 // Skip uncompressed formats.
461 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
462 continue;
463 }
464
465 const CodecPref* pref = NULL;
466 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
467 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
468 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
469 kCodecPrefs[j].channels == voe_codec.channels) {
470 pref = &kCodecPrefs[j];
471 break;
472 }
473 }
474
475 if (pref) {
476 // Use the payload type that we've configured in our pref table;
477 // use the offset in our pref table to determine the sort order.
478 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
479 voe_codec.rate, voe_codec.channels,
480 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
481 LOG(LS_INFO) << ToString(codec);
482 if (IsIsac(codec)) {
483 // Indicate auto-bandwidth in signaling.
484 codec.bitrate = 0;
485 }
486 if (IsOpus(codec)) {
487 // Only add fmtp parameters that differ from the spec.
488 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
489 codec.params[kCodecParamMinPTime] =
490 talk_base::ToString(kPreferredMinPTime);
491 }
492 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
493 codec.params[kCodecParamMaxPTime] =
494 talk_base::ToString(kPreferredMaxPTime);
495 }
496 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
497 // when they can be set to values other than the default.
498 }
499 codecs_.push_back(codec);
500 } else {
501 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
502 }
503 }
504 }
505 // Make sure they are in local preference order.
506 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
507}
508
509WebRtcVoiceEngine::~WebRtcVoiceEngine() {
510 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
511 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
512 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
513 }
514 if (adm_) {
515 voe_wrapper_.reset();
516 adm_->Release();
517 adm_ = NULL;
518 }
519 if (adm_sc_) {
520 voe_wrapper_sc_.reset();
521 adm_sc_->Release();
522 adm_sc_ = NULL;
523 }
524
525 // Test to see if the media processor was deregistered properly
526 ASSERT(SignalRxMediaFrame.is_empty());
527 ASSERT(SignalTxMediaFrame.is_empty());
528
529 tracing_->SetTraceCallback(NULL);
530}
531
532bool WebRtcVoiceEngine::Init(talk_base::Thread* worker_thread) {
533 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
534 bool res = InitInternal();
535 if (res) {
536 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
537 } else {
538 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
539 Terminate();
540 }
541 return res;
542}
543
544bool WebRtcVoiceEngine::InitInternal() {
545 // Temporarily turn logging level up for the Init call
546 int old_filter = log_filter_;
547 int extended_filter = log_filter_ | SeverityToFilter(talk_base::LS_INFO);
548 SetTraceFilter(extended_filter);
549 SetTraceOptions("");
550
551 // Init WebRtc VoiceEngine.
552 if (voe_wrapper_->base()->Init(adm_) == -1) {
553 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
554 SetTraceFilter(old_filter);
555 return false;
556 }
557
558 SetTraceFilter(old_filter);
559 SetTraceOptions(log_options_);
560
561 // Log the VoiceEngine version info
562 char buffer[1024] = "";
563 voe_wrapper_->base()->GetVersion(buffer);
564 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
565 LogMultiline(talk_base::LS_INFO, buffer);
566
567 // Save the default AGC configuration settings. This must happen before
568 // calling SetOptions or the default will be overwritten.
569 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
wu@webrtc.org97077a32013-10-25 21:18:33 +0000570 LOG_RTCERR0(GetAgcConfig);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000571 return false;
572 }
573
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000574 // Set defaults for options, so that ApplyOptions applies them explicitly
575 // when we clear option (channel) overrides. External clients can still
576 // modify the defaults via SetOptions (on the media engine).
577 if (!SetOptions(GetDefaultEngineOptions())) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000578 return false;
579 }
580
581 // Print our codec list again for the call diagnostic log
582 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
583 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
584 it != codecs_.end(); ++it) {
585 LOG(LS_INFO) << ToString(*it);
586 }
587
wu@webrtc.org4551b792013-10-09 15:37:36 +0000588 // Disable the DTMF playout when a tone is sent.
589 // PlayDtmfTone will be used if local playout is needed.
590 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
591 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
592 }
593
594 initialized_ = true;
595 return true;
596}
597
598bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
599 if (voe_wrapper_sc_initialized_) {
600 return true;
601 }
602 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
603 // be false, so subsequent calls to EnsureSoundclipEngineInit will
604 // probably just fail again. That's acceptable behavior.
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000605#if defined(LINUX) && !defined(HAVE_LIBPULSE)
606 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
607#endif
608
609 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
610 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
611 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
612 return false;
613 }
614
615 // On Windows, tell it to use the default sound (not communication) devices.
616 // First check whether there is a valid sound device for playback.
617 // TODO(juberti): Clean this up when we support setting the soundclip device.
618#ifdef WIN32
619 // The SetPlayoutDevice may not be implemented in the case of external ADM.
620 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
621 // PeerConnection interface never set the adm_sc_, so need to check both
622 // in order to determine if the external adm is used.
623 if (!adm_ && !adm_sc_) {
624 int num_of_devices = 0;
625 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
626 num_of_devices > 0) {
627 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
628 == -1) {
629 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
630 voe_wrapper_sc_->error());
631 return false;
632 }
633 } else {
634 LOG(LS_WARNING) << "No valid sound playout device found.";
635 }
636 }
637#endif
wu@webrtc.org4551b792013-10-09 15:37:36 +0000638 voe_wrapper_sc_initialized_ = true;
639 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000640 return true;
641}
642
643void WebRtcVoiceEngine::Terminate() {
644 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
645 initialized_ = false;
646
647 StopAecDump();
648
wu@webrtc.org4551b792013-10-09 15:37:36 +0000649 if (voe_wrapper_sc_) {
650 voe_wrapper_sc_initialized_ = false;
651 voe_wrapper_sc_->base()->Terminate();
652 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000653 voe_wrapper_->base()->Terminate();
654 desired_local_monitor_enable_ = false;
655}
656
657int WebRtcVoiceEngine::GetCapabilities() {
658 return AUDIO_SEND | AUDIO_RECV;
659}
660
661VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
662 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
663 if (!ch->valid()) {
664 delete ch;
665 ch = NULL;
666 }
667 return ch;
668}
669
670SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000671 if (!EnsureSoundclipEngineInit()) {
672 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
673 << "initialize.";
674 return NULL;
675 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000676 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
677 if (!soundclip->Init() || !soundclip->Enable()) {
678 delete soundclip;
679 return NULL;
680 }
681 return soundclip;
682}
683
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000684bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000685 if (!ApplyOptions(options)) {
686 return false;
687 }
688 options_ = options;
689 return true;
690}
691
692bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
693 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
694 if (!ApplyOptions(overrides)) {
695 return false;
696 }
697 option_overrides_ = overrides;
698 return true;
699}
700
701bool WebRtcVoiceEngine::ClearOptionOverrides() {
702 LOG(LS_INFO) << "Clearing option overrides.";
703 AudioOptions options = options_;
704 // Only call ApplyOptions if |options_overrides_| contains overrided options.
705 // ApplyOptions affects NS, AGC other options that is shared between
706 // all WebRtcVoiceEngineChannels.
707 if (option_overrides_ == AudioOptions()) {
708 return true;
709 }
710
711 if (!ApplyOptions(options)) {
712 return false;
713 }
714 option_overrides_ = AudioOptions();
715 return true;
716}
717
718// AudioOptions defaults are set in InitInternal (for options with corresponding
719// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
720bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
721 AudioOptions options = options_in; // The options are modified below.
722 // kEcConference is AEC with high suppression.
723 webrtc::EcModes ec_mode = webrtc::kEcConference;
724 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
725 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
726 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
727 bool aecm_comfort_noise = false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000728 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
729 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
730 << aecm_comfort_noise << " (default is false).";
731 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000732
733#if defined(IOS)
734 // On iOS, VPIO provides built-in EC and AGC.
735 options.echo_cancellation.Set(false);
736 options.auto_gain_control.Set(false);
737#elif defined(ANDROID)
738 ec_mode = webrtc::kEcAecm;
739#endif
740
741#if defined(IOS) || defined(ANDROID)
742 // Set the AGC mode for iOS as well despite disabling it above, to avoid
743 // unsupported configuration errors from webrtc.
744 agc_mode = webrtc::kAgcFixedDigital;
745 options.typing_detection.Set(false);
746 options.experimental_agc.Set(false);
747 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000748 options.experimental_ns.Set(false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000749#endif
750
751 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
752
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000753 // Configure whether ACM1 or ACM2 is used.
754 bool enable_acm2 = false;
755 if (options.experimental_acm.Get(&enable_acm2)) {
756 EnableExperimentalAcm(enable_acm2);
757 }
758
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000759 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
760
761 bool echo_cancellation;
762 if (options.echo_cancellation.Get(&echo_cancellation)) {
763 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
764 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
765 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000766 } else {
767 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
768 << " with mode " << ec_mode;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000769 }
770#if !defined(ANDROID)
771 // TODO(ajm): Remove the error return on Android from webrtc.
772 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
773 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
774 return false;
775 }
776#endif
777 if (ec_mode == webrtc::kEcAecm) {
778 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
779 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
780 return false;
781 }
782 }
783 }
784
785 bool auto_gain_control;
786 if (options.auto_gain_control.Get(&auto_gain_control)) {
787 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
788 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
789 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000790 } else {
791 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
792 << " with mode " << agc_mode;
793 }
794 }
795
796 if (options.tx_agc_target_dbov.IsSet() ||
797 options.tx_agc_digital_compression_gain.IsSet() ||
798 options.tx_agc_limiter.IsSet()) {
799 // Override default_agc_config_. Generally, an unset option means "leave
800 // the VoE bits alone" in this function, so we want whatever is set to be
801 // stored as the new "default". If we didn't, then setting e.g.
802 // tx_agc_target_dbov would reset digital compression gain and limiter
803 // settings.
804 // Also, if we don't update default_agc_config_, then adjust_agc_delta
805 // would be an offset from the original values, and not whatever was set
806 // explicitly.
807 default_agc_config_.targetLeveldBOv =
808 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
809 default_agc_config_.targetLeveldBOv);
810 default_agc_config_.digitalCompressionGaindB =
811 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
812 default_agc_config_.digitalCompressionGaindB);
813 default_agc_config_.limiterEnable =
814 options.tx_agc_limiter.GetWithDefaultIfUnset(
815 default_agc_config_.limiterEnable);
816 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
817 LOG_RTCERR3(SetAgcConfig,
818 default_agc_config_.targetLeveldBOv,
819 default_agc_config_.digitalCompressionGaindB,
820 default_agc_config_.limiterEnable);
821 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000822 }
823 }
824
825 bool noise_suppression;
826 if (options.noise_suppression.Get(&noise_suppression)) {
827 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
828 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
829 return false;
wu@webrtc.org97077a32013-10-25 21:18:33 +0000830 } else {
831 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
832 << " with mode " << ns_mode;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000833 }
834 }
835
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000836#ifdef USE_WEBRTC_DEV_BRANCH
837 bool experimental_ns;
838 if (options.experimental_ns.Get(&experimental_ns)) {
839 webrtc::AudioProcessing* audioproc =
840 voe_wrapper_->base()->audio_processing();
841 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
842 // returns NULL on audio_processing().
843 if (audioproc) {
844 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
845 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
846 return false;
847 }
848 } else {
849 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
850 << experimental_ns;
851 }
852 }
853#endif // USE_WEBRTC_DEV_BRANCH
854
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000855 bool highpass_filter;
856 if (options.highpass_filter.Get(&highpass_filter)) {
857 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
858 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
859 return false;
860 }
861 }
862
863 bool stereo_swapping;
864 if (options.stereo_swapping.Get(&stereo_swapping)) {
865 voep->EnableStereoChannelSwapping(stereo_swapping);
866 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
867 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
868 return false;
869 }
870 }
871
872 bool typing_detection;
873 if (options.typing_detection.Get(&typing_detection)) {
874 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
875 // In case of error, log the info and continue
876 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
877 }
878 }
879
880 int adjust_agc_delta;
881 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
882 if (!AdjustAgcLevel(adjust_agc_delta)) {
883 return false;
884 }
885 }
886
887 bool aec_dump;
888 if (options.aec_dump.Get(&aec_dump)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000889 if (aec_dump)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000890 StartAecDump(kAecDumpByAudioOptionFilename);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000891 else
892 StopAecDump();
893 }
894
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +0000895 bool experimental_aec;
896 if (options.experimental_aec.Get(&experimental_aec)) {
897 webrtc::AudioProcessing* audioproc =
898 voe_wrapper_->base()->audio_processing();
899 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
900 // returns NULL on audio_processing().
901 if (audioproc) {
902 webrtc::Config config;
903 config.Set<webrtc::DelayCorrection>(
904 new webrtc::DelayCorrection(experimental_aec));
905 audioproc->SetExtraOptions(config);
906 }
907 }
908
wu@webrtc.org97077a32013-10-25 21:18:33 +0000909 uint32 recording_sample_rate;
910 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
911 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
912 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
913 }
914 }
915
916 uint32 playout_sample_rate;
917 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
918 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
919 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
920 }
921 }
922
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000923
924 return true;
925}
926
927bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
928 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
929 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
930 LOG_RTCERR1(SetDelayOffsetMs, offset);
931 return false;
932 }
933
934 return true;
935}
936
937struct ResumeEntry {
938 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
939 : channel(c),
940 playout(p),
941 send(s) {
942 }
943
944 WebRtcVoiceMediaChannel *channel;
945 bool playout;
946 SendFlags send;
947};
948
949// TODO(juberti): Refactor this so that the core logic can be used to set the
950// soundclip device. At that time, reinstate the soundclip pause/resume code.
951bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
952 const Device* out_device) {
wu@webrtc.orgcecfd182013-10-30 05:18:12 +0000953#if !defined(IOS)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000954 int in_id = in_device ? talk_base::FromString<int>(in_device->id) :
955 kDefaultAudioDeviceId;
956 int out_id = out_device ? talk_base::FromString<int>(out_device->id) :
957 kDefaultAudioDeviceId;
958 // The device manager uses -1 as the default device, which was the case for
959 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
960#ifndef WIN32
961 if (-1 == in_id) {
962 in_id = kDefaultAudioDeviceId;
963 }
964 if (-1 == out_id) {
965 out_id = kDefaultAudioDeviceId;
966 }
967#endif
968
969 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
970 in_device->name : "Default device";
971 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
972 out_device->name : "Default device";
973 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
974 << ") and speaker to (id=" << out_id << ", name=" << out_name
975 << ")";
976
977 // If we're running the local monitor, we need to stop it first.
978 bool ret = true;
979 if (!PauseLocalMonitor()) {
980 LOG(LS_WARNING) << "Failed to pause local monitor";
981 ret = false;
982 }
983
984 // Must also pause all audio playback and capture.
985 for (ChannelList::const_iterator i = channels_.begin();
986 i != channels_.end(); ++i) {
987 WebRtcVoiceMediaChannel *channel = *i;
988 if (!channel->PausePlayout()) {
989 LOG(LS_WARNING) << "Failed to pause playout";
990 ret = false;
991 }
992 if (!channel->PauseSend()) {
993 LOG(LS_WARNING) << "Failed to pause send";
994 ret = false;
995 }
996 }
997
998 // Find the recording device id in VoiceEngine and set recording device.
999 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
1000 ret = false;
1001 }
1002 if (ret) {
1003 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001004 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001005 ret = false;
1006 }
1007 }
1008
1009 // Find the playout device id in VoiceEngine and set playout device.
1010 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
1011 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
1012 ret = false;
1013 }
1014 if (ret) {
1015 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001016 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001017 ret = false;
1018 }
1019 }
1020
1021 // Resume all audio playback and capture.
1022 for (ChannelList::const_iterator i = channels_.begin();
1023 i != channels_.end(); ++i) {
1024 WebRtcVoiceMediaChannel *channel = *i;
1025 if (!channel->ResumePlayout()) {
1026 LOG(LS_WARNING) << "Failed to resume playout";
1027 ret = false;
1028 }
1029 if (!channel->ResumeSend()) {
1030 LOG(LS_WARNING) << "Failed to resume send";
1031 ret = false;
1032 }
1033 }
1034
1035 // Resume local monitor.
1036 if (!ResumeLocalMonitor()) {
1037 LOG(LS_WARNING) << "Failed to resume local monitor";
1038 ret = false;
1039 }
1040
1041 if (ret) {
1042 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1043 << ") and speaker to (id="<< out_id << " name=" << out_name
1044 << ")";
1045 }
1046
1047 return ret;
1048#else
1049 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001050#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001051}
1052
1053bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1054 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1055 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001056#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001057 *rtc_id = dev_id;
1058 return true;
1059#else
1060 // In Windows and Mac, we need to find the VoiceEngine device id by name
1061 // unless the input dev_id is the default device id.
1062 if (kDefaultAudioDeviceId == dev_id) {
1063 *rtc_id = dev_id;
1064 return true;
1065 }
1066
1067 // Get the number of VoiceEngine audio devices.
1068 int count = 0;
1069 if (is_input) {
1070 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1071 LOG_RTCERR0(GetNumOfRecordingDevices);
1072 return false;
1073 }
1074 } else {
1075 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1076 LOG_RTCERR0(GetNumOfPlayoutDevices);
1077 return false;
1078 }
1079 }
1080
1081 for (int i = 0; i < count; ++i) {
1082 char name[128];
1083 char guid[128];
1084 if (is_input) {
1085 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1086 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1087 } else {
1088 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1089 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1090 }
1091
1092 std::string webrtc_name(name);
1093 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1094 *rtc_id = i;
1095 return true;
1096 }
1097 }
1098 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1099 return false;
1100#endif
1101}
1102
1103bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1104 unsigned int ulevel;
1105 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1106 LOG_RTCERR1(GetSpeakerVolume, level);
1107 return false;
1108 }
1109 *level = ulevel;
1110 return true;
1111}
1112
1113bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1114 ASSERT(level >= 0 && level <= 255);
1115 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1116 LOG_RTCERR1(SetSpeakerVolume, level);
1117 return false;
1118 }
1119 return true;
1120}
1121
1122int WebRtcVoiceEngine::GetInputLevel() {
1123 unsigned int ulevel;
1124 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1125 static_cast<int>(ulevel) : -1;
1126}
1127
1128bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1129 desired_local_monitor_enable_ = enable;
1130 return ChangeLocalMonitor(desired_local_monitor_enable_);
1131}
1132
1133bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1134 // The voe file api is not available in chrome.
1135 if (!voe_wrapper_->file()) {
1136 return false;
1137 }
1138 if (enable && !monitor_) {
1139 monitor_.reset(new WebRtcMonitorStream);
1140 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1141 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1142 // Must call Stop() because there are some cases where Start will report
1143 // failure but still change the state, and if we leave VE in the on state
1144 // then it could crash later when trying to invoke methods on our monitor.
1145 voe_wrapper_->file()->StopRecordingMicrophone();
1146 monitor_.reset();
1147 return false;
1148 }
1149 } else if (!enable && monitor_) {
1150 voe_wrapper_->file()->StopRecordingMicrophone();
1151 monitor_.reset();
1152 }
1153 return true;
1154}
1155
1156bool WebRtcVoiceEngine::PauseLocalMonitor() {
1157 return ChangeLocalMonitor(false);
1158}
1159
1160bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1161 return ChangeLocalMonitor(desired_local_monitor_enable_);
1162}
1163
1164const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1165 return codecs_;
1166}
1167
1168bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1169 return FindWebRtcCodec(in, NULL);
1170}
1171
1172// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1173bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1174 webrtc::CodecInst* out) {
1175 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1176 for (int i = 0; i < ncodecs; ++i) {
1177 webrtc::CodecInst voe_codec;
1178 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1179 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1180 voe_codec.rate, voe_codec.channels, 0);
1181 bool multi_rate = IsCodecMultiRate(voe_codec);
1182 // Allow arbitrary rates for ISAC to be specified.
1183 if (multi_rate) {
1184 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1185 codec.bitrate = 0;
1186 }
1187 if (codec.Matches(in)) {
1188 if (out) {
1189 // Fixup the payload type.
1190 voe_codec.pltype = in.id;
1191
1192 // Set bitrate if specified.
1193 if (multi_rate && in.bitrate != 0) {
1194 voe_codec.rate = in.bitrate;
1195 }
1196
1197 // Apply codec-specific settings.
1198 if (IsIsac(codec)) {
1199 // If ISAC and an explicit bitrate is not specified,
1200 // enable auto bandwidth adjustment.
1201 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1202 }
1203 *out = voe_codec;
1204 }
1205 return true;
1206 }
1207 }
1208 }
1209 return false;
1210}
1211const std::vector<RtpHeaderExtension>&
1212WebRtcVoiceEngine::rtp_header_extensions() const {
1213 return rtp_header_extensions_;
1214}
1215
1216void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1217 // if min_sev == -1, we keep the current log level.
1218 if (min_sev >= 0) {
1219 SetTraceFilter(SeverityToFilter(min_sev));
1220 }
1221 log_options_ = filter;
1222 SetTraceOptions(initialized_ ? log_options_ : "");
1223}
1224
1225int WebRtcVoiceEngine::GetLastEngineError() {
1226 return voe_wrapper_->error();
1227}
1228
1229void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1230 log_filter_ = filter;
1231 tracing_->SetTraceFilter(filter);
1232}
1233
1234// We suppport three different logging settings for VoiceEngine:
1235// 1. Observer callback that goes into talk diagnostic logfile.
1236// Use --logfile and --loglevel
1237//
1238// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1239// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1240//
1241// 3. EC log and dump for debugging QualityEngine.
1242// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1243//
1244// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1245// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1246void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1247 // Set encrypted trace file.
1248 std::vector<std::string> opts;
1249 talk_base::tokenize(options, ' ', '"', '"', &opts);
1250 std::vector<std::string>::iterator tracefile =
1251 std::find(opts.begin(), opts.end(), "tracefile");
1252 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1253 // Write encrypted debug output (at same loglevel) to file
1254 // EncryptedTraceFile no longer supported.
1255 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1256 LOG_RTCERR1(SetTraceFile, *tracefile);
1257 }
1258 }
1259
wu@webrtc.org97077a32013-10-25 21:18:33 +00001260 // Allow trace options to override the trace filter. We default
1261 // it to log_filter_ (as a translation of libjingle log levels)
1262 // elsewhere, but this allows clients to explicitly set webrtc
1263 // log levels.
1264 std::vector<std::string>::iterator tracefilter =
1265 std::find(opts.begin(), opts.end(), "tracefilter");
1266 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
1267 if (!tracing_->SetTraceFilter(talk_base::FromString<int>(*tracefilter))) {
1268 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1269 }
1270 }
1271
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001272 // Set AEC dump file
1273 std::vector<std::string>::iterator recordEC =
1274 std::find(opts.begin(), opts.end(), "recordEC");
1275 if (recordEC != opts.end()) {
1276 ++recordEC;
1277 if (recordEC != opts.end())
1278 StartAecDump(recordEC->c_str());
1279 else
1280 StopAecDump();
1281 }
1282}
1283
1284// Ignore spammy trace messages, mostly from the stats API when we haven't
1285// gotten RTCP info yet from the remote side.
1286bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1287 static const char* kTracesToIgnore[] = {
1288 "\tfailed to GetReportBlockInformation",
1289 "GetRecCodec() failed to get received codec",
1290 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1291 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1292 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1293 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1294 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1295 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1296 "SenderInfoReceived No received SR",
1297 "StatisticsRTP() no statistics available",
1298 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1299 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1300 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1301 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1302 NULL
1303 };
1304 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1305 if (trace.find(*p) != std::string::npos) {
1306 return true;
1307 }
1308 }
1309 return false;
1310}
1311
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001312void WebRtcVoiceEngine::EnableExperimentalAcm(bool enable) {
1313 if (enable == use_experimental_acm_)
1314 return;
1315 if (enable) {
1316 LOG(LS_INFO) << "VoiceEngine is set to use new ACM (ACM2 + NetEq4).";
1317 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
1318 new webrtc::NewAudioCodingModuleFactory());
1319 } else {
1320 LOG(LS_INFO) << "VoiceEngine is set to use legacy ACM (ACM1 + Neteq3).";
1321 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
1322 new webrtc::AudioCodingModuleFactory());
1323 }
1324 use_experimental_acm_ = enable;
1325}
1326
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001327void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1328 int length) {
1329 talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
1330 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
1331 sev = talk_base::LS_ERROR;
1332 else if (level == webrtc::kTraceWarning)
1333 sev = talk_base::LS_WARNING;
1334 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
1335 sev = talk_base::LS_INFO;
1336 else if (level == webrtc::kTraceTerseInfo)
1337 sev = talk_base::LS_INFO;
1338
1339 // Skip past boilerplate prefix text
1340 if (length < 72) {
1341 std::string msg(trace, length);
1342 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1343 LOG_V(sev) << msg;
1344 } else {
1345 std::string msg(trace + 71, length - 72);
1346 if (!ShouldIgnoreTrace(msg)) {
1347 LOG_V(sev) << "webrtc: " << msg;
1348 }
1349 }
1350}
1351
1352void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
1353 talk_base::CritScope lock(&channels_cs_);
1354 WebRtcVoiceMediaChannel* channel = NULL;
1355 uint32 ssrc = 0;
1356 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1357 << channel_num << ".";
1358 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1359 ASSERT(channel != NULL);
1360 channel->OnError(ssrc, err_code);
1361 } else {
1362 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1363 << " could not be found in channel list when error reported.";
1364 }
1365}
1366
1367bool WebRtcVoiceEngine::FindChannelAndSsrc(
1368 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1369 ASSERT(channel != NULL && ssrc != NULL);
1370
1371 *channel = NULL;
1372 *ssrc = 0;
1373 // Find corresponding channel and ssrc
1374 for (ChannelList::const_iterator it = channels_.begin();
1375 it != channels_.end(); ++it) {
1376 ASSERT(*it != NULL);
1377 if ((*it)->FindSsrc(channel_num, ssrc)) {
1378 *channel = *it;
1379 return true;
1380 }
1381 }
1382
1383 return false;
1384}
1385
1386// This method will search through the WebRtcVoiceMediaChannels and
1387// obtain the voice engine's channel number.
1388bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1389 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1390 ASSERT(channel_num != NULL);
1391 ASSERT(direction == MPD_RX || direction == MPD_TX);
1392
1393 *channel_num = -1;
1394 // Find corresponding channel for ssrc.
1395 for (ChannelList::const_iterator it = channels_.begin();
1396 it != channels_.end(); ++it) {
1397 ASSERT(*it != NULL);
1398 if (direction & MPD_RX) {
1399 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1400 }
1401 if (*channel_num == -1 && (direction & MPD_TX)) {
1402 *channel_num = (*it)->GetSendChannelNum(ssrc);
1403 }
1404 if (*channel_num != -1) {
1405 return true;
1406 }
1407 }
1408 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1409 return false;
1410}
1411
1412void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
1413 talk_base::CritScope lock(&channels_cs_);
1414 channels_.push_back(channel);
1415}
1416
1417void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
1418 talk_base::CritScope lock(&channels_cs_);
1419 ChannelList::iterator i = std::find(channels_.begin(),
1420 channels_.end(),
1421 channel);
1422 if (i != channels_.end()) {
1423 channels_.erase(i);
1424 }
1425}
1426
1427void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1428 soundclips_.push_back(soundclip);
1429}
1430
1431void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1432 SoundclipList::iterator i = std::find(soundclips_.begin(),
1433 soundclips_.end(),
1434 soundclip);
1435 if (i != soundclips_.end()) {
1436 soundclips_.erase(i);
1437 }
1438}
1439
1440// Adjusts the default AGC target level by the specified delta.
1441// NB: If we start messing with other config fields, we'll want
1442// to save the current webrtc::AgcConfig as well.
1443bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1444 webrtc::AgcConfig config = default_agc_config_;
1445 config.targetLeveldBOv -= delta;
1446
1447 LOG(LS_INFO) << "Adjusting AGC level from default -"
1448 << default_agc_config_.targetLeveldBOv << "dB to -"
1449 << config.targetLeveldBOv << "dB";
1450
1451 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1452 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1453 return false;
1454 }
1455 return true;
1456}
1457
1458bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1459 webrtc::AudioDeviceModule* adm_sc) {
1460 if (initialized_) {
1461 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1462 return false;
1463 }
1464 if (adm_) {
1465 adm_->Release();
1466 adm_ = NULL;
1467 }
1468 if (adm) {
1469 adm_ = adm;
1470 adm_->AddRef();
1471 }
1472
1473 if (adm_sc_) {
1474 adm_sc_->Release();
1475 adm_sc_ = NULL;
1476 }
1477 if (adm_sc) {
1478 adm_sc_ = adm_sc;
1479 adm_sc_->AddRef();
1480 }
1481 return true;
1482}
1483
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001484bool WebRtcVoiceEngine::StartAecDump(talk_base::PlatformFile file) {
1485 FILE* aec_dump_file_stream = talk_base::FdopenPlatformFileForWriting(file);
1486 if (!aec_dump_file_stream) {
1487 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
1488 if (!talk_base::ClosePlatformFile(file))
1489 LOG(LS_WARNING) << "Could not close file.";
1490 return false;
1491 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001492 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001493 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001494 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001495 LOG_RTCERR0(StartDebugRecording);
1496 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001497 return false;
1498 }
1499 is_dumping_aec_ = true;
1500 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001501}
1502
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001503bool WebRtcVoiceEngine::RegisterProcessor(
1504 uint32 ssrc,
1505 VoiceProcessor* voice_processor,
1506 MediaProcessorDirection direction) {
1507 bool register_with_webrtc = false;
1508 int channel_id = -1;
1509 bool success = false;
1510 uint32* processor_ssrc = NULL;
1511 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1512 if (voice_processor == NULL || !found_channel) {
1513 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1514 << " foundChannel: " << found_channel;
1515 return false;
1516 }
1517
1518 webrtc::ProcessingTypes processing_type;
1519 {
1520 talk_base::CritScope cs(&signal_media_critical_);
1521 if (direction == MPD_RX) {
1522 processing_type = webrtc::kPlaybackAllChannelsMixed;
1523 if (SignalRxMediaFrame.is_empty()) {
1524 register_with_webrtc = true;
1525 processor_ssrc = &rx_processor_ssrc_;
1526 }
1527 SignalRxMediaFrame.connect(voice_processor,
1528 &VoiceProcessor::OnFrame);
1529 } else {
1530 processing_type = webrtc::kRecordingPerChannel;
1531 if (SignalTxMediaFrame.is_empty()) {
1532 register_with_webrtc = true;
1533 processor_ssrc = &tx_processor_ssrc_;
1534 }
1535 SignalTxMediaFrame.connect(voice_processor,
1536 &VoiceProcessor::OnFrame);
1537 }
1538 }
1539 if (register_with_webrtc) {
1540 // TODO(janahan): when registering consider instantiating a
1541 // a VoeMediaProcess object and not make the engine extend the interface.
1542 if (voe()->media() && voe()->media()->
1543 RegisterExternalMediaProcessing(channel_id,
1544 processing_type,
1545 *this) != -1) {
1546 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1547 << channel_id;
1548 *processor_ssrc = ssrc;
1549 success = true;
1550 } else {
1551 LOG_RTCERR2(RegisterExternalMediaProcessing,
1552 channel_id,
1553 processing_type);
1554 success = false;
1555 }
1556 } else {
1557 // If we don't have to register with the engine, we just needed to
1558 // connect a new processor, set success to true;
1559 success = true;
1560 }
1561 return success;
1562}
1563
1564bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1565 MediaProcessorDirection channel_direction,
1566 uint32 ssrc,
1567 VoiceProcessor* voice_processor,
1568 MediaProcessorDirection processor_direction) {
1569 bool success = true;
1570 FrameSignal* signal;
1571 webrtc::ProcessingTypes processing_type;
1572 uint32* processor_ssrc = NULL;
1573 if (channel_direction == MPD_RX) {
1574 signal = &SignalRxMediaFrame;
1575 processing_type = webrtc::kPlaybackAllChannelsMixed;
1576 processor_ssrc = &rx_processor_ssrc_;
1577 } else {
1578 signal = &SignalTxMediaFrame;
1579 processing_type = webrtc::kRecordingPerChannel;
1580 processor_ssrc = &tx_processor_ssrc_;
1581 }
1582
1583 int deregister_id = -1;
1584 {
1585 talk_base::CritScope cs(&signal_media_critical_);
1586 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1587 signal->disconnect(voice_processor);
1588 int channel_id = -1;
1589 bool found_channel = FindChannelNumFromSsrc(ssrc,
1590 channel_direction,
1591 &channel_id);
1592 if (signal->is_empty() && found_channel) {
1593 deregister_id = channel_id;
1594 }
1595 }
1596 }
1597 if (deregister_id != -1) {
1598 if (voe()->media() &&
1599 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1600 processing_type) != -1) {
1601 *processor_ssrc = 0;
1602 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1603 << deregister_id;
1604 } else {
1605 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1606 deregister_id,
1607 processing_type);
1608 success = false;
1609 }
1610 }
1611 return success;
1612}
1613
1614bool WebRtcVoiceEngine::UnregisterProcessor(
1615 uint32 ssrc,
1616 VoiceProcessor* voice_processor,
1617 MediaProcessorDirection direction) {
1618 bool success = true;
1619 if (voice_processor == NULL) {
1620 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1621 << ssrc;
1622 return false;
1623 }
1624 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1625 success = false;
1626 }
1627 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1628 success = false;
1629 }
1630 return success;
1631}
1632
1633// Implementing method from WebRtc VoEMediaProcess interface
1634// Do not lock mux_channel_cs_ in this callback.
1635void WebRtcVoiceEngine::Process(int channel,
1636 webrtc::ProcessingTypes type,
1637 int16_t audio10ms[],
1638 int length,
1639 int sampling_freq,
1640 bool is_stereo) {
1641 talk_base::CritScope cs(&signal_media_critical_);
1642 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1643 if (type == webrtc::kPlaybackAllChannelsMixed) {
1644 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1645 } else if (type == webrtc::kRecordingPerChannel) {
1646 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1647 } else {
1648 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1649 << " channel: " << channel << " type: " << type
1650 << " tx_ssrc: " << tx_processor_ssrc_
1651 << " rx_ssrc: " << rx_processor_ssrc_;
1652 }
1653}
1654
1655void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1656 if (!is_dumping_aec_) {
1657 // Start dumping AEC when we are not dumping.
1658 if (voe_wrapper_->processing()->StartDebugRecording(
1659 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001660 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001661 } else {
1662 is_dumping_aec_ = true;
1663 }
1664 }
1665}
1666
1667void WebRtcVoiceEngine::StopAecDump() {
1668 if (is_dumping_aec_) {
1669 // Stop dumping AEC when we are dumping.
1670 if (voe_wrapper_->processing()->StopDebugRecording() !=
1671 webrtc::AudioProcessing::kNoError) {
1672 LOG_RTCERR0(StopDebugRecording);
1673 }
1674 is_dumping_aec_ = false;
1675 }
1676}
1677
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001678int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001679 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001680}
1681
1682int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1683 return CreateVoiceChannel(voe_wrapper_.get());
1684}
1685
1686int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1687 return CreateVoiceChannel(voe_wrapper_sc_.get());
1688}
1689
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001690class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1691 : public AudioRenderer::Sink {
1692 public:
1693 WebRtcVoiceChannelRenderer(int ch,
1694 webrtc::AudioTransport* voe_audio_transport)
1695 : channel_(ch),
1696 voe_audio_transport_(voe_audio_transport),
1697 renderer_(NULL) {
1698 }
1699 virtual ~WebRtcVoiceChannelRenderer() {
1700 Stop();
1701 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001702
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001703 // Starts the rendering by setting a sink to the renderer to get data
1704 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001705 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001706 // TODO(xians): Make sure Start() is called only once.
1707 void Start(AudioRenderer* renderer) {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001708 talk_base::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001709 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001710 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001711 ASSERT(renderer_ == renderer);
1712 return;
1713 }
1714
1715 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1716 // in getUserMedia by default.
1717 renderer->AddChannel(channel_);
1718 renderer->SetSink(this);
1719 renderer_ = renderer;
1720 }
1721
1722 // Stops rendering by setting the sink of the renderer to NULL. No data
1723 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001724 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001725 void Stop() {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001726 talk_base::CritScope lock(&lock_);
1727 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001728 return;
1729
1730 renderer_->RemoveChannel(channel_);
1731 renderer_->SetSink(NULL);
1732 renderer_ = NULL;
1733 }
1734
1735 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001736 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001737 virtual void OnData(const void* audio_data,
1738 int bits_per_sample,
1739 int sample_rate,
1740 int number_of_channels,
1741 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001742#ifdef USE_WEBRTC_DEV_BRANCH
1743 voe_audio_transport_->OnData(channel_,
1744 audio_data,
1745 bits_per_sample,
1746 sample_rate,
1747 number_of_channels,
1748 number_of_frames);
1749#endif
1750 }
1751
1752 // Callback from the |renderer_| when it is going away. In case Start() has
1753 // never been called, this callback won't be triggered.
1754 virtual void OnClose() OVERRIDE {
1755 talk_base::CritScope lock(&lock_);
1756 // Set |renderer_| to NULL to make sure no more callback will get into
1757 // the renderer.
1758 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001759 }
1760
1761 // Accessor to the VoE channel ID.
1762 int channel() const { return channel_; }
1763
1764 private:
1765 const int channel_;
1766 webrtc::AudioTransport* const voe_audio_transport_;
1767
1768 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1769 // PeerConnection will make sure invalidating the pointer before the object
1770 // goes away.
1771 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001772
1773 // Protects |renderer_| in Start(), Stop() and OnClose().
1774 talk_base::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001775};
1776
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001777// WebRtcVoiceMediaChannel
1778WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1779 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1780 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001781 engine->CreateMediaVoiceChannel()),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001782 send_bw_setting_(false),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001783 send_bw_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001784 options_(),
1785 dtmf_allowed_(false),
1786 desired_playout_(false),
1787 nack_enabled_(false),
1788 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001789 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001790 desired_send_(SEND_NOTHING),
1791 send_(SEND_NOTHING),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001792 default_receive_ssrc_(0) {
1793 engine->RegisterChannel(this);
1794 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1795 << voe_channel();
1796
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001797 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001798}
1799
1800WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1801 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1802 << voe_channel();
1803
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001804 // Remove any remaining send streams, the default channel will be deleted
1805 // later.
1806 while (!send_channels_.empty())
1807 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001808
1809 // Unregister ourselves from the engine.
1810 engine()->UnregisterChannel(this);
1811 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001812 while (!receive_channels_.empty()) {
1813 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001814 }
1815
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001816 // Delete the default channel.
1817 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001818}
1819
1820bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1821 LOG(LS_INFO) << "Setting voice channel options: "
1822 << options.ToString();
1823
wu@webrtc.orgde305012013-10-31 15:40:38 +00001824 // Check if DSCP value is changed from previous.
1825 bool dscp_option_changed = (options_.dscp != options.dscp);
1826
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001827 // TODO(xians): Add support to set different options for different send
1828 // streams after we support multiple APMs.
1829
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001830 // We retain all of the existing options, and apply the given ones
1831 // on top. This means there is no way to "clear" options such that
1832 // they go back to the engine default.
1833 options_.SetAll(options);
1834
1835 if (send_ != SEND_NOTHING) {
1836 if (!engine()->SetOptionOverrides(options_)) {
1837 LOG(LS_WARNING) <<
1838 "Failed to engine SetOptionOverrides during channel SetOptions.";
1839 return false;
1840 }
1841 } else {
1842 // Will be interpreted when appropriate.
1843 }
1844
wu@webrtc.org97077a32013-10-25 21:18:33 +00001845 // Receiver-side auto gain control happens per channel, so set it here from
1846 // options. Note that, like conference mode, setting it on the engine won't
1847 // have the desired effect, since voice channels don't inherit options from
1848 // the media engine when those options are applied per-channel.
1849 bool rx_auto_gain_control;
1850 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1851 if (engine()->voe()->processing()->SetRxAgcStatus(
1852 voe_channel(), rx_auto_gain_control,
1853 webrtc::kAgcFixedDigital) == -1) {
1854 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1855 return false;
1856 } else {
1857 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1858 << " with mode " << webrtc::kAgcFixedDigital;
1859 }
1860 }
1861 if (options.rx_agc_target_dbov.IsSet() ||
1862 options.rx_agc_digital_compression_gain.IsSet() ||
1863 options.rx_agc_limiter.IsSet()) {
1864 webrtc::AgcConfig config;
1865 // If only some of the options are being overridden, get the current
1866 // settings for the channel and bail if they aren't available.
1867 if (!options.rx_agc_target_dbov.IsSet() ||
1868 !options.rx_agc_digital_compression_gain.IsSet() ||
1869 !options.rx_agc_limiter.IsSet()) {
1870 if (engine()->voe()->processing()->GetRxAgcConfig(
1871 voe_channel(), config) != 0) {
1872 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1873 << "channel " << voe_channel() << ". Since not all rx "
1874 << "agc options are specified, unable to safely set rx "
1875 << "agc options.";
1876 return false;
1877 }
1878 }
1879 config.targetLeveldBOv =
1880 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1881 config.targetLeveldBOv);
1882 config.digitalCompressionGaindB =
1883 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1884 config.digitalCompressionGaindB);
1885 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1886 config.limiterEnable);
1887 if (engine()->voe()->processing()->SetRxAgcConfig(
1888 voe_channel(), config) == -1) {
1889 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1890 config.digitalCompressionGaindB, config.limiterEnable);
1891 return false;
1892 }
1893 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001894 if (dscp_option_changed) {
1895 talk_base::DiffServCodePoint dscp = talk_base::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001896 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001897 dscp = kAudioDscpValue;
1898 if (MediaChannel::SetDscp(dscp) != 0) {
1899 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1900 }
1901 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001902
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001903 LOG(LS_INFO) << "Set voice channel options. Current options: "
1904 << options_.ToString();
1905 return true;
1906}
1907
1908bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1909 const std::vector<AudioCodec>& codecs) {
1910 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001911 LOG(LS_INFO) << "Setting receive voice codecs:";
1912
1913 std::vector<AudioCodec> new_codecs;
1914 // Find all new codecs. We allow adding new codecs but don't allow changing
1915 // the payload type of codecs that is already configured since we might
1916 // already be receiving packets with that payload type.
1917 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001918 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001919 AudioCodec old_codec;
1920 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1921 if (old_codec.id != it->id) {
1922 LOG(LS_ERROR) << it->name << " payload type changed.";
1923 return false;
1924 }
1925 } else {
1926 new_codecs.push_back(*it);
1927 }
1928 }
1929 if (new_codecs.empty()) {
1930 // There are no new codecs to configure. Already configured codecs are
1931 // never removed.
1932 return true;
1933 }
1934
1935 if (playout_) {
1936 // Receive codecs can not be changed while playing. So we temporarily
1937 // pause playout.
1938 PausePlayout();
1939 }
1940
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001941 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001942 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1943 it != new_codecs.end() && ret; ++it) {
1944 webrtc::CodecInst voe_codec;
1945 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1946 LOG(LS_INFO) << ToString(*it);
1947 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001948 if (default_receive_ssrc_ == 0) {
1949 // Set the receive codecs on the default channel explicitly if the
1950 // default channel is not used by |receive_channels_|, this happens in
1951 // conference mode or in non-conference mode when there is no playout
1952 // channel.
1953 // TODO(xians): Figure out how we use the default channel in conference
1954 // mode.
1955 if (engine()->voe()->codec()->SetRecPayloadType(
1956 voe_channel(), voe_codec) == -1) {
1957 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1958 ret = false;
1959 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001960 }
1961
1962 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001963 for (ChannelMap::iterator it = receive_channels_.begin();
1964 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001965 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001966 it->second->channel(), voe_codec) == -1) {
1967 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001968 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001969 ret = false;
1970 }
1971 }
1972 } else {
1973 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1974 ret = false;
1975 }
1976 }
1977 if (ret) {
1978 recv_codecs_ = codecs;
1979 }
1980
1981 if (desired_playout_ && !playout_) {
1982 ResumePlayout();
1983 }
1984 return ret;
1985}
1986
1987bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001988 int channel, const std::vector<AudioCodec>& codecs) {
1989 // Disable VAD, and FEC unless we know the other side wants them.
1990 engine()->voe()->codec()->SetVADStatus(channel, false);
1991 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1992 engine()->voe()->rtp()->SetFECStatus(channel, false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001993
1994 // Scan through the list to figure out the codec to use for sending, along
1995 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001996 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001997 webrtc::CodecInst send_codec;
1998 memset(&send_codec, 0, sizeof(send_codec));
1999
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002000 bool nack_enabled = nack_enabled_;
2001
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002002 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002003 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2004 it != codecs.end(); ++it) {
2005 // Ignore codecs we don't know about. The negotiation step should prevent
2006 // this, but double-check to be sure.
2007 webrtc::CodecInst voe_codec;
2008 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002009 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002010 continue;
2011 }
2012
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002013 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
2014 // Skip telephone-event/CN codec, which will be handled later.
2015 continue;
2016 }
2017
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002018 // If OPUS, change what we send according to the "stereo" codec
2019 // parameter, and not the "channels" parameter. We set
2020 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
2021 // the bitrate is not specified, i.e. is zero, we set it to the
2022 // appropriate default value for mono or stereo Opus.
2023 if (IsOpus(*it)) {
2024 if (IsOpusStereoEnabled(*it)) {
2025 voe_codec.channels = 2;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002026 if (!IsValidOpusBitrate(it->bitrate)) {
2027 if (it->bitrate != 0) {
2028 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2029 << it->bitrate
2030 << ") with default opus stereo bitrate: "
2031 << kOpusStereoBitrate;
2032 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002033 voe_codec.rate = kOpusStereoBitrate;
2034 }
2035 } else {
2036 voe_codec.channels = 1;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002037 if (!IsValidOpusBitrate(it->bitrate)) {
2038 if (it->bitrate != 0) {
2039 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2040 << it->bitrate
2041 << ") with default opus mono bitrate: "
2042 << kOpusMonoBitrate;
2043 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002044 voe_codec.rate = kOpusMonoBitrate;
2045 }
2046 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002047 int bitrate_from_params = GetOpusBitrateFromParams(*it);
2048 if (bitrate_from_params != 0) {
2049 voe_codec.rate = bitrate_from_params;
2050 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002051 }
2052
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002053 // We'll use the first codec in the list to actually send audio data.
2054 // Be sure to use the payload type requested by the remote side.
2055 // "red", for FEC audio, is a special case where the actual codec to be
2056 // used is specified in params.
2057 if (IsRedCodec(it->name)) {
2058 // Parse out the RED parameters. If we fail, just ignore RED;
2059 // we don't support all possible params/usage scenarios.
2060 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2061 continue;
2062 }
2063
2064 // Enable redundant encoding of the specified codec. Treat any
2065 // failure as a fatal internal error.
2066 LOG(LS_INFO) << "Enabling FEC";
2067 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2068 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
2069 return false;
2070 }
2071 } else {
2072 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002073 nack_enabled = IsNackEnabled(*it);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002074 }
2075 found_send_codec = true;
2076 break;
2077 }
2078
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002079 if (nack_enabled_ != nack_enabled) {
2080 SetNack(channel, nack_enabled);
2081 nack_enabled_ = nack_enabled;
2082 }
2083
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002084 if (!found_send_codec) {
2085 LOG(LS_WARNING) << "Received empty list of codecs.";
2086 return false;
2087 }
2088
2089 // Set the codec immediately, since SetVADStatus() depends on whether
2090 // the current codec is mono or stereo.
2091 if (!SetSendCodec(channel, send_codec))
2092 return false;
2093
2094 // Always update the |send_codec_| to the currently set send codec.
2095 send_codec_.reset(new webrtc::CodecInst(send_codec));
2096
2097 if (send_bw_setting_) {
2098 SetSendBandwidthInternal(send_bw_bps_);
2099 }
2100
2101 // Loop through the codecs list again to config the telephone-event/CN codec.
2102 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2103 it != codecs.end(); ++it) {
2104 // Ignore codecs we don't know about. The negotiation step should prevent
2105 // this, but double-check to be sure.
2106 webrtc::CodecInst voe_codec;
2107 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2108 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2109 continue;
2110 }
2111
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002112 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2113 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002114 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002115 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2116 channel, it->id) == -1) {
2117 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2118 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002119 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002120 } else if (IsCNCodec(it->name)) {
2121 // Turn voice activity detection/comfort noise on if supported.
2122 // Set the wideband CN payload type appropriately.
2123 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002124 webrtc::PayloadFrequencies cn_freq;
2125 switch (it->clockrate) {
2126 case 8000:
2127 cn_freq = webrtc::kFreq8000Hz;
2128 break;
2129 case 16000:
2130 cn_freq = webrtc::kFreq16000Hz;
2131 break;
2132 case 32000:
2133 cn_freq = webrtc::kFreq32000Hz;
2134 break;
2135 default:
2136 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2137 << " not supported.";
2138 continue;
2139 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002140 // Set the CN payloadtype and the VAD status.
2141 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2142 if (cn_freq != webrtc::kFreq8000Hz) {
2143 if (engine()->voe()->codec()->SetSendCNPayloadType(
2144 channel, it->id, cn_freq) == -1) {
2145 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2146 // TODO(ajm): This failure condition will be removed from VoE.
2147 // Restore the return here when we update to a new enough webrtc.
2148 //
2149 // Not returning false because the SetSendCNPayloadType will fail if
2150 // the channel is already sending.
2151 // This can happen if the remote description is applied twice, for
2152 // example in the case of ROAP on top of JSEP, where both side will
2153 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002154 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002155 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002156 // Only turn on VAD if we have a CN payload type that matches the
2157 // clockrate for the codec we are going to use.
2158 if (it->clockrate == send_codec.plfreq) {
2159 LOG(LS_INFO) << "Enabling VAD";
2160 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2161 LOG_RTCERR2(SetVADStatus, channel, true);
2162 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002163 }
2164 }
2165 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002166 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002167 return true;
2168}
2169
2170bool WebRtcVoiceMediaChannel::SetSendCodecs(
2171 const std::vector<AudioCodec>& codecs) {
2172 dtmf_allowed_ = false;
2173 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2174 it != codecs.end(); ++it) {
2175 // Find the DTMF telephone event "codec".
2176 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2177 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2178 dtmf_allowed_ = true;
2179 }
2180 }
2181
2182 // Cache the codecs in order to configure the channel created later.
2183 send_codecs_ = codecs;
2184 for (ChannelMap::iterator iter = send_channels_.begin();
2185 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002186 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002187 return false;
2188 }
2189 }
2190
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002191 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002192 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002193 return true;
2194}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002195
2196void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2197 bool nack_enabled) {
2198 for (ChannelMap::const_iterator it = channels.begin();
2199 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002200 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002201 }
2202}
2203
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002204void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002205 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002206 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002207 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2208 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002209 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002210 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2211 }
2212}
2213
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002214bool WebRtcVoiceMediaChannel::SetSendCodec(
2215 const webrtc::CodecInst& send_codec) {
2216 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2217 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002218 for (ChannelMap::iterator iter = send_channels_.begin();
2219 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002220 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002221 return false;
2222 }
2223
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002224 return true;
2225}
2226
2227bool WebRtcVoiceMediaChannel::SetSendCodec(
2228 int channel, const webrtc::CodecInst& send_codec) {
2229 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2230 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2231
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002232 webrtc::CodecInst current_codec;
2233 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2234 (send_codec == current_codec)) {
2235 // Codec is already configured, we can return without setting it again.
2236 return true;
2237 }
2238
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002239 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2240 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002241 return false;
2242 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002243 return true;
2244}
2245
2246bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2247 const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002248#ifdef USE_WEBRTC_DEV_BRANCH
2249 const RtpHeaderExtension* send_time_extension =
2250 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2251
2252 // Loop through all receive channels and enable/disable the extensions.
2253 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2254 channel_it != receive_channels_.end(); ++channel_it) {
2255 int channel_id = channel_it->second->channel();
2256 if (!SetHeaderExtension(
2257 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2258 send_time_extension)) {
2259 return false;
2260 }
2261 }
2262#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002263 return true;
2264}
2265
2266bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2267 const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002268 const RtpHeaderExtension* audio_level_extension =
2269 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2270#ifdef USE_WEBRTC_DEV_BRANCH
2271 const RtpHeaderExtension* send_time_extension =
2272 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2273#endif
2274
2275#ifndef USE_WEBRTC_DEV_BRANCH
2276 if (!SetHeaderExtension(
2277 &webrtc::VoERTP_RTCP::SetRTPAudioLevelIndicationStatus, voe_channel(),
2278 audio_level_extension)) {
2279 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002280 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002281#else
2282 if (!SetHeaderExtension(
2283 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, voe_channel(),
2284 audio_level_extension)) {
2285 return false;
2286 }
2287 if (!SetHeaderExtension(
2288 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, voe_channel(),
2289 send_time_extension)) {
2290 return false;
2291 }
2292#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002293
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002294 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2295 channel_it != send_channels_.end(); ++channel_it) {
2296 int channel_id = channel_it->second->channel();
2297#ifndef USE_WEBRTC_DEV_BRANCH
2298 if (!SetHeaderExtension(
2299 &webrtc::VoERTP_RTCP::SetRTPAudioLevelIndicationStatus, channel_id,
2300 audio_level_extension)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002301 return false;
2302 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002303#else
2304 if (!SetHeaderExtension(
2305 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
2306 audio_level_extension)) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002307 return false;
2308 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002309 if (!SetHeaderExtension(
2310 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
2311 send_time_extension)) {
2312 return false;
2313 }
2314#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002315 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002316 return true;
2317}
2318
2319bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2320 desired_playout_ = playout;
2321 return ChangePlayout(desired_playout_);
2322}
2323
2324bool WebRtcVoiceMediaChannel::PausePlayout() {
2325 return ChangePlayout(false);
2326}
2327
2328bool WebRtcVoiceMediaChannel::ResumePlayout() {
2329 return ChangePlayout(desired_playout_);
2330}
2331
2332bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2333 if (playout_ == playout) {
2334 return true;
2335 }
2336
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002337 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002338 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002339 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002340 // Only toggle the default channel if we don't have any other channels.
2341 result = SetPlayout(voe_channel(), playout);
2342 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002343 for (ChannelMap::iterator it = receive_channels_.begin();
2344 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002345 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002346 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002347 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002348 result = false;
2349 }
2350 }
2351
2352 if (result) {
2353 playout_ = playout;
2354 }
2355 return result;
2356}
2357
2358bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2359 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002360 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002361 return ChangeSend(desired_send_);
2362 return true;
2363}
2364
2365bool WebRtcVoiceMediaChannel::PauseSend() {
2366 return ChangeSend(SEND_NOTHING);
2367}
2368
2369bool WebRtcVoiceMediaChannel::ResumeSend() {
2370 return ChangeSend(desired_send_);
2371}
2372
2373bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2374 if (send_ == send) {
2375 return true;
2376 }
2377
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002378 // Change the settings on each send channel.
2379 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002380 engine()->SetOptionOverrides(options_);
2381
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002382 // Change the settings on each send channel.
2383 for (ChannelMap::iterator iter = send_channels_.begin();
2384 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002385 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002386 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002387 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002388
2389 // Clear up the options after stopping sending.
2390 if (send == SEND_NOTHING)
2391 engine()->ClearOptionOverrides();
2392
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002393 send_ = send;
2394 return true;
2395}
2396
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002397bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2398 if (send == SEND_MICROPHONE) {
2399 if (engine()->voe()->base()->StartSend(channel) == -1) {
2400 LOG_RTCERR1(StartSend, channel);
2401 return false;
2402 }
2403 if (engine()->voe()->file() &&
2404 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2405 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2406 return false;
2407 }
2408 } else { // SEND_NOTHING
2409 ASSERT(send == SEND_NOTHING);
2410 if (engine()->voe()->base()->StopSend(channel) == -1) {
2411 LOG_RTCERR1(StopSend, channel);
2412 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002413 }
2414 }
2415
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002416 return true;
2417}
2418
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002419void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2420 if (engine()->voe()->network()->RegisterExternalTransport(
2421 channel, *this) == -1) {
2422 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2423 }
2424
2425 // Enable RTCP (for quality stats and feedback messages)
2426 EnableRtcp(channel);
2427
2428 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2429 ResetRecvCodecs(channel);
2430}
2431
2432bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2433 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2434 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2435 }
2436
2437 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2438 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002439 return false;
2440 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002441
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002442 return true;
2443}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002444
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002445bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2446 // If the default channel is already used for sending create a new channel
2447 // otherwise use the default channel for sending.
2448 int channel = GetSendChannelNum(sp.first_ssrc());
2449 if (channel != -1) {
2450 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2451 return false;
2452 }
2453
2454 bool default_channel_is_available = true;
2455 for (ChannelMap::const_iterator iter = send_channels_.begin();
2456 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002457 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002458 default_channel_is_available = false;
2459 break;
2460 }
2461 }
2462 if (default_channel_is_available) {
2463 channel = voe_channel();
2464 } else {
2465 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002466 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002467 if (channel == -1) {
2468 LOG_RTCERR0(CreateChannel);
2469 return false;
2470 }
2471
2472 ConfigureSendChannel(channel);
2473 }
2474
2475 // Save the channel to send_channels_, so that RemoveSendStream() can still
2476 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002477#ifdef USE_WEBRTC_DEV_BRANCH
2478 webrtc::AudioTransport* audio_transport =
2479 engine()->voe()->base()->audio_transport();
2480#else
2481 webrtc::AudioTransport* audio_transport = NULL;
2482#endif
2483 send_channels_.insert(std::make_pair(
2484 sp.first_ssrc(),
2485 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002486
2487 // Set the send (local) SSRC.
2488 // If there are multiple send SSRCs, we can only set the first one here, and
2489 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2490 // (with a codec requires multiple SSRC(s)).
2491 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2492 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2493 return false;
2494 }
2495
2496 // At this point the channel's local SSRC has been updated. If the channel is
2497 // the default channel make sure that all the receive channels are updated as
2498 // well. Receive channels have to have the same SSRC as the default channel in
2499 // order to send receiver reports with this SSRC.
2500 if (IsDefaultChannel(channel)) {
2501 for (ChannelMap::const_iterator it = receive_channels_.begin();
2502 it != receive_channels_.end(); ++it) {
2503 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002504 if (!IsDefaultChannel(it->second->channel())) {
2505 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002506 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002507 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002508 return false;
2509 }
2510 }
2511 }
2512 }
2513
2514 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
2515 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2516 return false;
2517 }
2518
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002519 // Set the current codecs to be used for the new channel.
2520 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002521 return false;
2522
2523 return ChangeSend(channel, desired_send_);
2524}
2525
2526bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2527 ChannelMap::iterator it = send_channels_.find(ssrc);
2528 if (it == send_channels_.end()) {
2529 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2530 << " which doesn't exist.";
2531 return false;
2532 }
2533
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002534 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002535 ChangeSend(channel, SEND_NOTHING);
2536
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002537 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2538 // this will disconnect the audio renderer with the send channel.
2539 delete it->second;
2540 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002541
2542 if (IsDefaultChannel(channel)) {
2543 // Do not delete the default channel since the receive channels depend on
2544 // the default channel, recycle it instead.
2545 ChangeSend(channel, SEND_NOTHING);
2546 } else {
2547 // Clean up and delete the send channel.
2548 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2549 << " with VoiceEngine channel #" << channel << ".";
2550 if (!DeleteChannel(channel))
2551 return false;
2552 }
2553
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002554 if (send_channels_.empty())
2555 ChangeSend(SEND_NOTHING);
2556
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002557 return true;
2558}
2559
2560bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002561 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002562
2563 if (!VERIFY(sp.ssrcs.size() == 1))
2564 return false;
2565 uint32 ssrc = sp.first_ssrc();
2566
wu@webrtc.org78187522013-10-07 23:32:02 +00002567 if (ssrc == 0) {
2568 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2569 return false;
2570 }
2571
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002572 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2573 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002574 return false;
2575 }
2576
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002577 // Reuse default channel for recv stream in non-conference mode call
2578 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002579#ifdef USE_WEBRTC_DEV_BRANCH
2580 webrtc::AudioTransport* audio_transport =
2581 engine()->voe()->base()->audio_transport();
2582#else
2583 webrtc::AudioTransport* audio_transport = NULL;
2584#endif
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002585 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2586 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2587 << " reuse default channel";
2588 default_receive_ssrc_ = sp.first_ssrc();
2589 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002590 default_receive_ssrc_,
2591 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002592 return SetPlayout(voe_channel(), playout_);
2593 }
2594
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002595 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002596 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002597 if (channel == -1) {
2598 LOG_RTCERR0(CreateChannel);
2599 return false;
2600 }
2601
wu@webrtc.org78187522013-10-07 23:32:02 +00002602 if (!ConfigureRecvChannel(channel)) {
2603 DeleteChannel(channel);
2604 return false;
2605 }
2606
2607 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002608 std::make_pair(
2609 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002610
2611 LOG(LS_INFO) << "New audio stream " << ssrc
2612 << " registered to VoiceEngine channel #"
2613 << channel << ".";
2614 return true;
2615}
2616
2617bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002618 // Configure to use external transport, like our default channel.
2619 if (engine()->voe()->network()->RegisterExternalTransport(
2620 channel, *this) == -1) {
2621 LOG_RTCERR2(SetExternalTransport, channel, this);
2622 return false;
2623 }
2624
2625 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002626 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002627 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2628 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002629 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002630 return false;
2631 }
2632 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002633 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002634 return false;
2635 }
2636
2637 // Use the same recv payload types as our default channel.
2638 ResetRecvCodecs(channel);
2639 if (!recv_codecs_.empty()) {
2640 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2641 it != recv_codecs_.end(); ++it) {
2642 webrtc::CodecInst voe_codec;
2643 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2644 voe_codec.pltype = it->id;
2645 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2646 if (engine()->voe()->codec()->GetRecPayloadType(
2647 voe_channel(), voe_codec) != -1) {
2648 if (engine()->voe()->codec()->SetRecPayloadType(
2649 channel, voe_codec) == -1) {
2650 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2651 return false;
2652 }
2653 }
2654 }
2655 }
2656 }
2657
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002658 if (InConferenceMode()) {
2659 // To be in par with the video, voe_channel() is not used for receiving in
2660 // a conference call.
2661 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2662 // This is the first stream in a multi user meeting. We can now
2663 // disable playback of the default stream. This since the default
2664 // stream will probably have received some initial packets before
2665 // the new stream was added. This will mean that the CN state from
2666 // the default channel will be mixed in with the other streams
2667 // throughout the whole meeting, which might be disturbing.
2668 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2669 SetPlayout(voe_channel(), false);
2670 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002671 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002672 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002673
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002674 return SetPlayout(channel, playout_);
2675}
2676
2677bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002678 talk_base::CritScope lock(&receive_channels_cs_);
2679 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002680 if (it == receive_channels_.end()) {
2681 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2682 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002683 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002684 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002685
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002686 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2687 // will disconnect the audio renderer with the receive channel.
2688 // Cache the channel before the deletion.
2689 const int channel = it->second->channel();
2690 delete it->second;
2691 receive_channels_.erase(it);
2692
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002693 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002694 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002695 // Recycle the default channel is for recv stream.
2696 if (playout_)
2697 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002698
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002699 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002700 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002701 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002702
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002703 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002704 << " with VoiceEngine channel #" << channel << ".";
2705 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002706 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002707
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002708 bool enable_default_channel_playout = false;
2709 if (receive_channels_.empty()) {
2710 // The last stream was removed. We can now enable the default
2711 // channel for new channels to be played out immediately without
2712 // waiting for AddStream messages.
2713 // We do this for both conference mode and non-conference mode.
2714 // TODO(oja): Does the default channel still have it's CN state?
2715 enable_default_channel_playout = true;
2716 }
2717 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2718 default_receive_ssrc_ != 0) {
2719 // Only the default channel is active, enable the playout on default
2720 // channel.
2721 enable_default_channel_playout = true;
2722 }
2723 if (enable_default_channel_playout && playout_) {
2724 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2725 SetPlayout(voe_channel(), true);
2726 }
2727
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002728 return true;
2729}
2730
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002731bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2732 AudioRenderer* renderer) {
2733 ChannelMap::iterator it = receive_channels_.find(ssrc);
2734 if (it == receive_channels_.end()) {
2735 if (renderer) {
2736 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002737 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002738 return false;
2739 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002740
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002741 // The channel likely has gone away, do nothing.
2742 return true;
2743 }
2744
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002745 if (renderer)
2746 it->second->Start(renderer);
2747 else
2748 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002749
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002750 return true;
2751}
2752
2753bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2754 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002755 ChannelMap::iterator it = send_channels_.find(ssrc);
2756 if (it == send_channels_.end()) {
2757 if (renderer) {
2758 // Return an error if trying to set a valid renderer with an invalid ssrc.
2759 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2760 return false;
2761 }
2762
2763 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002764 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002765 }
2766
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002767 if (renderer)
2768 it->second->Start(renderer);
2769 else
2770 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002771
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002772 return true;
2773}
2774
2775bool WebRtcVoiceMediaChannel::GetActiveStreams(
2776 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002777 // In conference mode, the default channel should not be in
2778 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002779 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002780 for (ChannelMap::iterator it = receive_channels_.begin();
2781 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002782 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002783 if (level > 0) {
2784 actives->push_back(std::make_pair(it->first, level));
2785 }
2786 }
2787 return true;
2788}
2789
2790int WebRtcVoiceMediaChannel::GetOutputLevel() {
2791 // return the highest output level of all streams
2792 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002793 for (ChannelMap::iterator it = receive_channels_.begin();
2794 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002795 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002796 highest = talk_base::_max(level, highest);
2797 }
2798 return highest;
2799}
2800
2801int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2802 int ret;
2803 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2804 // In case of error, log the info and continue
2805 LOG_RTCERR0(TimeSinceLastTyping);
2806 ret = -1;
2807 } else {
2808 ret *= 1000; // We return ms, webrtc returns seconds.
2809 }
2810 return ret;
2811}
2812
2813void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2814 int cost_per_typing, int reporting_threshold, int penalty_decay,
2815 int type_event_delay) {
2816 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2817 time_window, cost_per_typing,
2818 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2819 // In case of error, log the info and continue
2820 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2821 cost_per_typing, reporting_threshold, penalty_decay,
2822 type_event_delay);
2823 }
2824}
2825
2826bool WebRtcVoiceMediaChannel::SetOutputScaling(
2827 uint32 ssrc, double left, double right) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002828 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002829 // Collect the channels to scale the output volume.
2830 std::vector<int> channels;
2831 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002832 // Default channel is not in receive_channels_ if it is not being used for
2833 // playout.
2834 if (default_receive_ssrc_ == 0)
2835 channels.push_back(voe_channel());
2836 for (ChannelMap::const_iterator it = receive_channels_.begin();
2837 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002838 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002839 }
2840 } else { // Collect only the channel of the specified ssrc.
2841 int channel = GetReceiveChannelNum(ssrc);
2842 if (-1 == channel) {
2843 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2844 return false;
2845 }
2846 channels.push_back(channel);
2847 }
2848
2849 // Scale the output volume for the collected channels. We first normalize to
2850 // scale the volume and then set the left and right pan.
2851 float scale = static_cast<float>(talk_base::_max(left, right));
2852 if (scale > 0.0001f) {
2853 left /= scale;
2854 right /= scale;
2855 }
2856 for (std::vector<int>::const_iterator it = channels.begin();
2857 it != channels.end(); ++it) {
2858 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2859 *it, scale)) {
2860 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2861 return false;
2862 }
2863 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2864 *it, static_cast<float>(left), static_cast<float>(right))) {
2865 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2866 // Do not return if fails. SetOutputVolumePan is not available for all
2867 // pltforms.
2868 }
2869 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2870 << " right=" << right * scale
2871 << " for channel " << *it << " and ssrc " << ssrc;
2872 }
2873 return true;
2874}
2875
2876bool WebRtcVoiceMediaChannel::GetOutputScaling(
2877 uint32 ssrc, double* left, double* right) {
2878 if (!left || !right) return false;
2879
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002880 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002881 // Determine which channel based on ssrc.
2882 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2883 if (channel == -1) {
2884 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2885 return false;
2886 }
2887
2888 float scaling;
2889 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2890 channel, scaling)) {
2891 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2892 return false;
2893 }
2894
2895 float left_pan;
2896 float right_pan;
2897 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2898 channel, left_pan, right_pan)) {
2899 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2900 // If GetOutputVolumePan fails, we use the default left and right pan.
2901 left_pan = 1.0f;
2902 right_pan = 1.0f;
2903 }
2904
2905 *left = scaling * left_pan;
2906 *right = scaling * right_pan;
2907 return true;
2908}
2909
2910bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2911 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2912 return true;
2913}
2914
2915bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2916 bool play, bool loop) {
2917 if (!ringback_tone_) {
2918 return false;
2919 }
2920
2921 // The voe file api is not available in chrome.
2922 if (!engine()->voe()->file()) {
2923 return false;
2924 }
2925
2926 // Determine which VoiceEngine channel to play on.
2927 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2928 if (channel == -1) {
2929 return false;
2930 }
2931
2932 // Make sure the ringtone is cued properly, and play it out.
2933 if (play) {
2934 ringback_tone_->set_loop(loop);
2935 ringback_tone_->Rewind();
2936 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2937 ringback_tone_.get()) == -1) {
2938 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2939 LOG(LS_ERROR) << "Unable to start ringback tone";
2940 return false;
2941 }
2942 ringback_channels_.insert(channel);
2943 LOG(LS_INFO) << "Started ringback on channel " << channel;
2944 } else {
2945 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2946 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2947 LOG_RTCERR1(StopPlayingFileLocally, channel);
2948 return false;
2949 }
2950 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2951 ringback_channels_.erase(channel);
2952 }
2953
2954 return true;
2955}
2956
2957bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2958 return dtmf_allowed_;
2959}
2960
2961bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2962 int duration, int flags) {
2963 if (!dtmf_allowed_) {
2964 return false;
2965 }
2966
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002967 // Send the event.
2968 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002969 int channel = -1;
2970 if (ssrc == 0) {
2971 bool default_channel_is_inuse = false;
2972 for (ChannelMap::const_iterator iter = send_channels_.begin();
2973 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002974 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002975 default_channel_is_inuse = true;
2976 break;
2977 }
2978 }
2979 if (default_channel_is_inuse) {
2980 channel = voe_channel();
2981 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002982 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002983 }
2984 } else {
2985 channel = GetSendChannelNum(ssrc);
2986 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002987 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002988 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2989 << ssrc << " is not in use.";
2990 return false;
2991 }
2992 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002993 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2994 channel, event, true, duration) == -1) {
2995 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002996 return false;
2997 }
2998 }
2999
3000 // Play the event.
3001 if (flags & cricket::DF_PLAY) {
3002 // Play DTMF tone locally.
3003 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3004 LOG_RTCERR2(PlayDtmfTone, event, duration);
3005 return false;
3006 }
3007 }
3008
3009 return true;
3010}
3011
wu@webrtc.orga9890802013-12-13 00:21:03 +00003012void WebRtcVoiceMediaChannel::OnPacketReceived(
3013 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003014 // Pick which channel to send this packet to. If this packet doesn't match
3015 // any multiplexed streams, just send it to the default channel. Otherwise,
3016 // send it to the specific decoder instance for that stream.
3017 int which_channel = GetReceiveChannelNum(
3018 ParseSsrc(packet->data(), packet->length(), false));
3019 if (which_channel == -1) {
3020 which_channel = voe_channel();
3021 }
3022
3023 // Stop any ringback that might be playing on the channel.
3024 // It's possible the ringback has already stopped, ih which case we'll just
3025 // use the opportunity to remove the channel from ringback_channels_.
3026 if (engine()->voe()->file()) {
3027 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3028 if (it != ringback_channels_.end()) {
3029 if (engine()->voe()->file()->IsPlayingFileLocally(
3030 which_channel) == 1) {
3031 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3032 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3033 << " due to incoming media";
3034 }
3035 ringback_channels_.erase(which_channel);
3036 }
3037 }
3038
3039 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003040 engine()->voe()->network()->ReceivedRTPPacket(
3041 which_channel,
3042 packet->data(),
3043 static_cast<unsigned int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003044}
3045
wu@webrtc.orga9890802013-12-13 00:21:03 +00003046void WebRtcVoiceMediaChannel::OnRtcpReceived(
3047 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003048 // Sending channels need all RTCP packets with feedback information.
3049 // Even sender reports can contain attached report blocks.
3050 // Receiving channels need sender reports in order to create
3051 // correct receiver reports.
3052 int type = 0;
3053 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3054 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3055 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003056 }
3057
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003058 // If it is a sender report, find the channel that is listening.
3059 bool has_sent_to_default_channel = false;
3060 if (type == kRtcpTypeSR) {
3061 int which_channel = GetReceiveChannelNum(
3062 ParseSsrc(packet->data(), packet->length(), true));
3063 if (which_channel != -1) {
3064 engine()->voe()->network()->ReceivedRTCPPacket(
3065 which_channel,
3066 packet->data(),
3067 static_cast<unsigned int>(packet->length()));
3068
3069 if (IsDefaultChannel(which_channel))
3070 has_sent_to_default_channel = true;
3071 }
3072 }
3073
3074 // SR may continue RR and any RR entry may correspond to any one of the send
3075 // channels. So all RTCP packets must be forwarded all send channels. VoE
3076 // will filter out RR internally.
3077 for (ChannelMap::iterator iter = send_channels_.begin();
3078 iter != send_channels_.end(); ++iter) {
3079 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003080 if (IsDefaultChannel(iter->second->channel()) &&
3081 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003082 continue;
3083
3084 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003085 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003086 packet->data(),
3087 static_cast<unsigned int>(packet->length()));
3088 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003089}
3090
3091bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003092 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3093 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003094 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3095 return false;
3096 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003097 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3098 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003099 return false;
3100 }
3101 return true;
3102}
3103
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003104bool WebRtcVoiceMediaChannel::SetStartSendBandwidth(int bps) {
3105 // TODO(andresp): Add support for setting an independent start bandwidth when
3106 // bandwidth estimation is enabled for voice engine.
3107 return false;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003108}
3109
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003110bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
3111 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
3112
3113 return SetSendBandwidthInternal(bps);
3114}
3115
3116bool WebRtcVoiceMediaChannel::SetSendBandwidthInternal(int bps) {
3117 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBandwidthInternal.";
3118
3119 send_bw_setting_ = true;
3120 send_bw_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003121
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003122 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003123 LOG(LS_INFO) << "The send codec has not been set up yet. "
3124 << "The send bandwidth setting will be applied later.";
3125 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003126 }
3127
3128 // Bandwidth is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003129 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3130 // SetMaxSendBandwith(0), the second call removes the previous limit.
3131 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003132 return true;
3133
3134 webrtc::CodecInst codec = *send_codec_;
3135 bool is_multi_rate = IsCodecMultiRate(codec);
3136
3137 if (is_multi_rate) {
3138 // If codec is multi-rate then just set the bitrate.
3139 codec.rate = bps;
3140 if (!SetSendCodec(codec)) {
3141 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3142 << " to bitrate " << bps << " bps.";
3143 return false;
3144 }
3145 return true;
3146 } else {
3147 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3148 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3149 // fixed bitrate then ignore.
3150 if (bps < codec.rate) {
3151 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3152 << " to bitrate " << bps << " bps"
3153 << ", requires at least " << codec.rate << " bps.";
3154 return false;
3155 }
3156 return true;
3157 }
3158}
3159
3160bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003161 bool echo_metrics_on = false;
3162 // These can take on valid negative values, so use the lowest possible level
3163 // as default rather than -1.
3164 int echo_return_loss = -100;
3165 int echo_return_loss_enhancement = -100;
3166 // These can also be negative, but in practice -1 is only used to signal
3167 // insufficient data, since the resolution is limited to multiples of 4 ms.
3168 int echo_delay_median_ms = -1;
3169 int echo_delay_std_ms = -1;
3170 if (engine()->voe()->processing()->GetEcMetricsStatus(
3171 echo_metrics_on) != -1 && echo_metrics_on) {
3172 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3173 // here, but it appears to be unsuitable currently. Revisit after this is
3174 // investigated: http://b/issue?id=5666755
3175 int erl, erle, rerl, anlp;
3176 if (engine()->voe()->processing()->GetEchoMetrics(
3177 erl, erle, rerl, anlp) != -1) {
3178 echo_return_loss = erl;
3179 echo_return_loss_enhancement = erle;
3180 }
3181
3182 int median, std;
3183 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3184 echo_delay_median_ms = median;
3185 echo_delay_std_ms = std;
3186 }
3187 }
3188
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003189 webrtc::CallStatistics cs;
3190 unsigned int ssrc;
3191 webrtc::CodecInst codec;
3192 unsigned int level;
3193
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003194 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3195 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003196 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003197
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003198 // Fill in the sender info, based on what we know, and what the
3199 // remote side told us it got from its RTCP report.
3200 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003201
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003202 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3203 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3204 continue;
3205 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003206
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003207 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003208 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3209 sinfo.bytes_sent = cs.bytesSent;
3210 sinfo.packets_sent = cs.packetsSent;
3211 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3212 // returns 0 to indicate an error value.
3213 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3214
3215 // Get data from the last remote RTCP report. Use default values if no data
3216 // available.
3217 sinfo.fraction_lost = -1.0;
3218 sinfo.jitter_ms = -1;
3219 sinfo.packets_lost = -1;
3220 sinfo.ext_seqnum = -1;
3221 std::vector<webrtc::ReportBlock> receive_blocks;
3222 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3223 channel, &receive_blocks) != -1 &&
3224 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3225 std::vector<webrtc::ReportBlock>::iterator iter;
3226 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3227 ++iter) {
3228 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003229 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003230 // Convert Q8 to floating point.
3231 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3232 // Convert samples to milliseconds.
3233 if (codec.plfreq / 1000 > 0) {
3234 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3235 }
3236 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3237 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3238 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003239 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003240 }
3241 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003242
3243 // Local speech level.
3244 sinfo.audio_level = (engine()->voe()->volume()->
3245 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3246
3247 // TODO(xians): We are injecting the same APM logging to all the send
3248 // channels here because there is no good way to know which send channel
3249 // is using the APM. The correct fix is to allow the send channels to have
3250 // their own APM so that we can feed the correct APM logging to different
3251 // send channels. See issue crbug/264611 .
3252 sinfo.echo_return_loss = echo_return_loss;
3253 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3254 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3255 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003256 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3257 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003258 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003259
3260 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003261 }
3262
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003263 // Build the list of receivers, one for each receiving channel, or 1 in
3264 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003265 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003266 for (ChannelMap::const_iterator it = receive_channels_.begin();
3267 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003268 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003269 }
3270 if (channels.empty()) {
3271 channels.push_back(voe_channel());
3272 }
3273
3274 // Get the SSRC and stats for each receiver, based on our own calculations.
3275 for (std::vector<int>::const_iterator it = channels.begin();
3276 it != channels.end(); ++it) {
3277 memset(&cs, 0, sizeof(cs));
3278 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3279 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3280 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3281 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003282 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003283 rinfo.bytes_rcvd = cs.bytesReceived;
3284 rinfo.packets_rcvd = cs.packetsReceived;
3285 // The next four fields are from the most recently sent RTCP report.
3286 // Convert Q8 to floating point.
3287 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3288 rinfo.packets_lost = cs.cumulativeLost;
3289 rinfo.ext_seqnum = cs.extendedMax;
3290 // Convert samples to milliseconds.
3291 if (codec.plfreq / 1000 > 0) {
3292 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3293 }
3294
3295 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3296 webrtc::NetworkStatistics ns;
3297 if (engine()->voe()->neteq() &&
3298 engine()->voe()->neteq()->GetNetworkStatistics(
3299 *it, ns) != -1) {
3300 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3301 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3302 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003303 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003304 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003305
3306 webrtc::AudioDecodingCallStats ds;
3307 if (engine()->voe()->neteq() &&
3308 engine()->voe()->neteq()->GetDecodingCallStatistics(
3309 *it, &ds) != -1) {
3310 rinfo.decoding_calls_to_silence_generator =
3311 ds.calls_to_silence_generator;
3312 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3313 rinfo.decoding_normal = ds.decoded_normal;
3314 rinfo.decoding_plc = ds.decoded_plc;
3315 rinfo.decoding_cng = ds.decoded_cng;
3316 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3317 }
3318
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003319 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003320 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003321 int playout_buffer_delay_ms = 0;
3322 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003323 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3324 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3325 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003326 }
3327
3328 // Get speech level.
3329 rinfo.audio_level = (engine()->voe()->volume()->
3330 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3331 info->receivers.push_back(rinfo);
3332 }
3333 }
3334
3335 return true;
3336}
3337
3338void WebRtcVoiceMediaChannel::GetLastMediaError(
3339 uint32* ssrc, VoiceMediaChannel::Error* error) {
3340 ASSERT(ssrc != NULL);
3341 ASSERT(error != NULL);
3342 FindSsrc(voe_channel(), ssrc);
3343 *error = WebRtcErrorToChannelError(GetLastEngineError());
3344}
3345
3346bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003347 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003348 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003349 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003350 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3351 // This means the error is not limited to a specific channel. Signal the
3352 // message using ssrc=0. If the current channel is sending, use this
3353 // channel for sending the message.
3354 *ssrc = 0;
3355 return true;
3356 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003357 // Check whether this is a sending channel.
3358 for (ChannelMap::const_iterator it = send_channels_.begin();
3359 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003360 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003361 // This is a sending channel.
3362 uint32 local_ssrc = 0;
3363 if (engine()->voe()->rtp()->GetLocalSSRC(
3364 channel_num, local_ssrc) != -1) {
3365 *ssrc = local_ssrc;
3366 }
3367 return true;
3368 }
3369 }
3370
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003371 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003372 for (ChannelMap::const_iterator it = receive_channels_.begin();
3373 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003374 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003375 *ssrc = it->first;
3376 return true;
3377 }
3378 }
3379 }
3380 return false;
3381}
3382
3383void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003384 if (error == VE_TYPING_NOISE_WARNING) {
3385 typing_noise_detected_ = true;
3386 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3387 typing_noise_detected_ = false;
3388 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003389 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3390}
3391
3392int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3393 unsigned int ulevel;
3394 int ret =
3395 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3396 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3397}
3398
3399int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003400 ChannelMap::iterator it = receive_channels_.find(ssrc);
3401 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003402 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003403 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3404}
3405
3406int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003407 ChannelMap::iterator it = send_channels_.find(ssrc);
3408 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003409 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003410
3411 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003412}
3413
3414bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3415 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3416 // Get the RED encodings from the parameter with no name. This may
3417 // change based on what is discussed on the Jingle list.
3418 // The encoding parameter is of the form "a/b"; we only support where
3419 // a == b. Verify this and parse out the value into red_pt.
3420 // If the parameter value is absent (as it will be until we wire up the
3421 // signaling of this message), use the second codec specified (i.e. the
3422 // one after "red") as the encoding parameter.
3423 int red_pt = -1;
3424 std::string red_params;
3425 CodecParameterMap::const_iterator it = red_codec.params.find("");
3426 if (it != red_codec.params.end()) {
3427 red_params = it->second;
3428 std::vector<std::string> red_pts;
3429 if (talk_base::split(red_params, '/', &red_pts) != 2 ||
3430 red_pts[0] != red_pts[1] ||
3431 !talk_base::FromString(red_pts[0], &red_pt)) {
3432 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3433 return false;
3434 }
3435 } else if (red_codec.params.empty()) {
3436 LOG(LS_WARNING) << "RED params not present, using defaults";
3437 if (all_codecs.size() > 1) {
3438 red_pt = all_codecs[1].id;
3439 }
3440 }
3441
3442 // Try to find red_pt in |codecs|.
3443 std::vector<AudioCodec>::const_iterator codec;
3444 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3445 if (codec->id == red_pt)
3446 break;
3447 }
3448
3449 // If we find the right codec, that will be the codec we pass to
3450 // SetSendCodec, with the desired payload type.
3451 if (codec != all_codecs.end() &&
3452 engine()->FindWebRtcCodec(*codec, send_codec)) {
3453 } else {
3454 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3455 return false;
3456 }
3457
3458 return true;
3459}
3460
3461bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3462 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003463 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003464 return false;
3465 }
3466 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3467 // what we want to do with them.
3468 // engine()->voe().EnableVQMon(voe_channel(), true);
3469 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3470 return true;
3471}
3472
3473bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3474 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3475 for (int i = 0; i < ncodecs; ++i) {
3476 webrtc::CodecInst voe_codec;
3477 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3478 voe_codec.pltype = -1;
3479 if (engine()->voe()->codec()->SetRecPayloadType(
3480 channel, voe_codec) == -1) {
3481 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3482 return false;
3483 }
3484 }
3485 }
3486 return true;
3487}
3488
3489bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3490 if (playout) {
3491 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3492 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3493 LOG_RTCERR1(StartPlayout, channel);
3494 return false;
3495 }
3496 } else {
3497 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3498 engine()->voe()->base()->StopPlayout(channel);
3499 }
3500 return true;
3501}
3502
3503uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3504 bool rtcp) {
3505 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3506 uint32 ssrc = 0;
3507 if (len >= (ssrc_pos + sizeof(ssrc))) {
3508 ssrc = talk_base::GetBE32(static_cast<const char*>(data) + ssrc_pos);
3509 }
3510 return ssrc;
3511}
3512
3513// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3514VoiceMediaChannel::Error
3515 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3516 switch (err_code) {
3517 case 0:
3518 return ERROR_NONE;
3519 case VE_CANNOT_START_RECORDING:
3520 case VE_MIC_VOL_ERROR:
3521 case VE_GET_MIC_VOL_ERROR:
3522 case VE_CANNOT_ACCESS_MIC_VOL:
3523 return ERROR_REC_DEVICE_OPEN_FAILED;
3524 case VE_SATURATION_WARNING:
3525 return ERROR_REC_DEVICE_SATURATION;
3526 case VE_REC_DEVICE_REMOVED:
3527 return ERROR_REC_DEVICE_REMOVED;
3528 case VE_RUNTIME_REC_WARNING:
3529 case VE_RUNTIME_REC_ERROR:
3530 return ERROR_REC_RUNTIME_ERROR;
3531 case VE_CANNOT_START_PLAYOUT:
3532 case VE_SPEAKER_VOL_ERROR:
3533 case VE_GET_SPEAKER_VOL_ERROR:
3534 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3535 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3536 case VE_RUNTIME_PLAY_WARNING:
3537 case VE_RUNTIME_PLAY_ERROR:
3538 return ERROR_PLAY_RUNTIME_ERROR;
3539 case VE_TYPING_NOISE_WARNING:
3540 return ERROR_REC_TYPING_NOISE_DETECTED;
3541 default:
3542 return VoiceMediaChannel::ERROR_OTHER;
3543 }
3544}
3545
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003546bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3547 int channel_id, const RtpHeaderExtension* extension) {
3548 bool enable = false;
3549 unsigned char id = 0;
3550 if (extension) {
3551 enable = true;
3552 id = extension->id;
3553 }
3554 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
3555 LOG_RTCERR4(*setter, extension->uri, channel_id, enable, id);
3556 return false;
3557 }
3558 return true;
3559}
3560
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003561int WebRtcSoundclipStream::Read(void *buf, int len) {
3562 size_t res = 0;
3563 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003564 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003565}
3566
3567int WebRtcSoundclipStream::Rewind() {
3568 mem_.Rewind();
3569 // Return -1 to keep VoiceEngine from looping.
3570 return (loop_) ? 0 : -1;
3571}
3572
3573} // namespace cricket
3574
3575#endif // HAVE_WEBRTC_VOICE