blob: 785cdf11cb705f5b0d1f342072452785061273ef [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
2 * libjingle
3 * Copyright 2004 Google Inc.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice,
9 * this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright notice,
11 * this list of conditions and the following disclaimer in the documentation
12 * and/or other materials provided with the distribution.
13 * 3. The name of the author may not be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#ifdef HAVE_CONFIG_H
29#include <config.h>
30#endif
31
32#ifdef HAVE_WEBRTC_VOICE
33
34#include "talk/media/webrtc/webrtcvoiceengine.h"
35
36#include <algorithm>
37#include <cstdio>
38#include <string>
39#include <vector>
40
41#include "talk/base/base64.h"
42#include "talk/base/byteorder.h"
43#include "talk/base/common.h"
44#include "talk/base/helpers.h"
45#include "talk/base/logging.h"
46#include "talk/base/stringencode.h"
47#include "talk/base/stringutils.h"
48#include "talk/media/base/audiorenderer.h"
49#include "talk/media/base/constants.h"
50#include "talk/media/base/streamparams.h"
51#include "talk/media/base/voiceprocessor.h"
52#include "talk/media/webrtc/webrtcvoe.h"
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +000053#include "webrtc/common.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054#include "webrtc/modules/audio_processing/include/audio_processing.h"
55
56#ifdef WIN32
57#include <objbase.h> // NOLINT
58#endif
59
60namespace cricket {
61
62struct CodecPref {
63 const char* name;
64 int clockrate;
65 int channels;
66 int payload_type;
67 bool is_multi_rate;
68};
69
70static const CodecPref kCodecPrefs[] = {
71 { "OPUS", 48000, 2, 111, true },
72 { "ISAC", 16000, 1, 103, true },
73 { "ISAC", 32000, 1, 104, true },
74 { "CELT", 32000, 1, 109, true },
75 { "CELT", 32000, 2, 110, true },
76 { "G722", 16000, 1, 9, false },
77 { "ILBC", 8000, 1, 102, false },
78 { "PCMU", 8000, 1, 0, false },
79 { "PCMA", 8000, 1, 8, false },
80 { "CN", 48000, 1, 107, false },
81 { "CN", 32000, 1, 106, false },
82 { "CN", 16000, 1, 105, false },
83 { "CN", 8000, 1, 13, false },
84 { "red", 8000, 1, 127, false },
85 { "telephone-event", 8000, 1, 126, false },
86};
87
88// For Linux/Mac, using the default device is done by specifying index 0 for
89// VoE 4.0 and not -1 (which was the case for VoE 3.5).
90//
91// On Windows Vista and newer, Microsoft introduced the concept of "Default
92// Communications Device". This means that there are two types of default
93// devices (old Wave Audio style default and Default Communications Device).
94//
95// On Windows systems which only support Wave Audio style default, uses either
96// -1 or 0 to select the default device.
97//
98// On Windows systems which support both "Default Communication Device" and
99// old Wave Audio style default, use -1 for Default Communications Device and
100// -2 for Wave Audio style default, which is what we want to use for clips.
101// It's not clear yet whether the -2 index is handled properly on other OSes.
102
103#ifdef WIN32
104static const int kDefaultAudioDeviceId = -1;
105static const int kDefaultSoundclipDeviceId = -2;
106#else
107static const int kDefaultAudioDeviceId = 0;
108#endif
109
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110static const char kIsacCodecName[] = "ISAC";
111static const char kL16CodecName[] = "L16";
112// Codec parameters for Opus.
113static const int kOpusMonoBitrate = 32000;
114// Parameter used for NACK.
115// This value is equivalent to 5 seconds of audio data at 20 ms per packet.
116static const int kNackMaxPackets = 250;
117static const int kOpusStereoBitrate = 64000;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000118// draft-spittka-payload-rtp-opus-03
119// Opus bitrate should be in the range between 6000 and 510000.
120static const int kOpusMinBitrate = 6000;
121static const int kOpusMaxBitrate = 510000;
wu@webrtc.orgde305012013-10-31 15:40:38 +0000122// Default audio dscp value.
123// See http://tools.ietf.org/html/rfc2474 for details.
124// See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
125static const talk_base::DiffServCodePoint kAudioDscpValue = talk_base::DSCP_EF;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000126
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000127// Ensure we open the file in a writeable path on ChromeOS and Android. This
128// workaround can be removed when it's possible to specify a filename for audio
129// option based AEC dumps.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000130//
131// TODO(grunell): Use a string in the options instead of hardcoding it here
132// and let the embedder choose the filename (crbug.com/264223).
133//
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000134// NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
135// below.
136#if defined(CHROMEOS)
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000137static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
sergeyu@chromium.orga59696b2013-09-13 23:48:58 +0000138#elif defined(ANDROID)
139static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +0000140#else
141static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
142#endif
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000143
144// Dumps an AudioCodec in RFC 2327-ish format.
145static std::string ToString(const AudioCodec& codec) {
146 std::stringstream ss;
147 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
148 << " (" << codec.id << ")";
149 return ss.str();
150}
151static std::string ToString(const webrtc::CodecInst& codec) {
152 std::stringstream ss;
153 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
154 << " (" << codec.pltype << ")";
155 return ss.str();
156}
157
158static void LogMultiline(talk_base::LoggingSeverity sev, char* text) {
159 const char* delim = "\r\n";
160 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
161 LOG_V(sev) << tok;
162 }
163}
164
165// Severity is an integer because it comes is assumed to be from command line.
166static int SeverityToFilter(int severity) {
167 int filter = webrtc::kTraceNone;
168 switch (severity) {
169 case talk_base::LS_VERBOSE:
170 filter |= webrtc::kTraceAll;
171 case talk_base::LS_INFO:
172 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
173 case talk_base::LS_WARNING:
174 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
175 case talk_base::LS_ERROR:
176 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
177 }
178 return filter;
179}
180
181static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
182 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
183 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
184 kCodecPrefs[i].clockrate == codec.plfreq) {
185 return kCodecPrefs[i].is_multi_rate;
186 }
187 }
188 return false;
189}
190
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +0000191static bool IsTelephoneEventCodec(const std::string& name) {
192 return _stricmp(name.c_str(), "telephone-event") == 0;
193}
194
195static bool IsCNCodec(const std::string& name) {
196 return _stricmp(name.c_str(), "CN") == 0;
197}
198
199static bool IsRedCodec(const std::string& name) {
200 return _stricmp(name.c_str(), "red") == 0;
201}
202
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000203static bool FindCodec(const std::vector<AudioCodec>& codecs,
204 const AudioCodec& codec,
205 AudioCodec* found_codec) {
206 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
207 it != codecs.end(); ++it) {
208 if (it->Matches(codec)) {
209 if (found_codec != NULL) {
210 *found_codec = *it;
211 }
212 return true;
213 }
214 }
215 return false;
216}
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000217
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000218static bool IsNackEnabled(const AudioCodec& codec) {
219 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
220 kParamValueEmpty));
221}
222
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000223// Gets the default set of options applied to the engine. Historically, these
224// were supplied as a combination of flags from the channel manager (ec, agc,
225// ns, and highpass) and the rest hardcoded in InitInternal.
226static AudioOptions GetDefaultEngineOptions() {
227 AudioOptions options;
228 options.echo_cancellation.Set(true);
229 options.auto_gain_control.Set(true);
230 options.noise_suppression.Set(true);
231 options.highpass_filter.Set(true);
232 options.stereo_swapping.Set(false);
233 options.typing_detection.Set(true);
234 options.conference_mode.Set(false);
235 options.adjust_agc_delta.Set(0);
236 options.experimental_agc.Set(false);
237 options.experimental_aec.Set(false);
sergeyu@chromium.org9cf037b2014-02-07 19:03:26 +0000238 options.experimental_ns.Set(false);
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +0000239 options.aec_dump.Set(false);
240 return options;
241}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000242
243class WebRtcSoundclipMedia : public SoundclipMedia {
244 public:
245 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
246 : engine_(engine), webrtc_channel_(-1) {
247 engine_->RegisterSoundclip(this);
248 }
249
250 virtual ~WebRtcSoundclipMedia() {
251 engine_->UnregisterSoundclip(this);
252 if (webrtc_channel_ != -1) {
253 // We shouldn't have to call Disable() here. DeleteChannel() should call
254 // StopPlayout() while deleting the channel. We should fix the bug
255 // inside WebRTC and remove the Disable() call bellow. This work is
256 // tracked by bug http://b/issue?id=5382855.
257 PlaySound(NULL, 0, 0);
258 Disable();
259 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
260 == -1) {
261 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
262 }
263 }
264 }
265
266 bool Init() {
wu@webrtc.org4551b792013-10-09 15:37:36 +0000267 if (!engine_->voe_sc()) {
268 return false;
269 }
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +0000270 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000271 if (webrtc_channel_ == -1) {
272 LOG_RTCERR0(CreateChannel);
273 return false;
274 }
275 return true;
276 }
277
278 bool Enable() {
279 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
280 LOG_RTCERR1(StartPlayout, webrtc_channel_);
281 return false;
282 }
283 return true;
284 }
285
286 bool Disable() {
287 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
288 LOG_RTCERR1(StopPlayout, webrtc_channel_);
289 return false;
290 }
291 return true;
292 }
293
294 virtual bool PlaySound(const char *buf, int len, int flags) {
295 // The voe file api is not available in chrome.
296 if (!engine_->voe_sc()->file()) {
297 return false;
298 }
299 // Must stop playing the current sound (if any), because we are about to
300 // modify the stream.
301 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
302 == -1) {
303 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
304 return false;
305 }
306
307 if (buf) {
308 stream_.reset(new WebRtcSoundclipStream(buf, len));
309 stream_->set_loop((flags & SF_LOOP) != 0);
310 stream_->Rewind();
311
312 // Play it.
313 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
314 webrtc_channel_, stream_.get()) == -1) {
315 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
316 LOG(LS_ERROR) << "Unable to start soundclip";
317 return false;
318 }
319 } else {
320 stream_.reset();
321 }
322 return true;
323 }
324
325 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
326
327 private:
328 WebRtcVoiceEngine *engine_;
329 int webrtc_channel_;
330 talk_base::scoped_ptr<WebRtcSoundclipStream> stream_;
331};
332
333WebRtcVoiceEngine::WebRtcVoiceEngine()
334 : voe_wrapper_(new VoEWrapper()),
335 voe_wrapper_sc_(new VoEWrapper()),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000336 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000337 tracing_(new VoETraceWrapper()),
338 adm_(NULL),
339 adm_sc_(NULL),
340 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
341 is_dumping_aec_(false),
342 desired_local_monitor_enable_(false),
343 tx_processor_ssrc_(0),
344 rx_processor_ssrc_(0) {
345 Construct();
346}
347
348WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
349 VoEWrapper* voe_wrapper_sc,
350 VoETraceWrapper* tracing)
351 : voe_wrapper_(voe_wrapper),
352 voe_wrapper_sc_(voe_wrapper_sc),
wu@webrtc.org4551b792013-10-09 15:37:36 +0000353 voe_wrapper_sc_initialized_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000354 tracing_(tracing),
355 adm_(NULL),
356 adm_sc_(NULL),
357 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
358 is_dumping_aec_(false),
359 desired_local_monitor_enable_(false),
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000360 tx_processor_ssrc_(0),
361 rx_processor_ssrc_(0) {
362 Construct();
363}
364
365void WebRtcVoiceEngine::Construct() {
366 SetTraceFilter(log_filter_);
367 initialized_ = false;
368 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
369 SetTraceOptions("");
370 if (tracing_->SetTraceCallback(this) == -1) {
371 LOG_RTCERR0(SetTraceCallback);
372 }
373 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
374 LOG_RTCERR0(RegisterVoiceEngineObserver);
375 }
376 // Clear the default agc state.
377 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
378
379 // Load our audio codec list.
380 ConstructCodecs();
381
382 // Load our RTP Header extensions.
383 rtp_header_extensions_.push_back(
384 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
385 kRtpAudioLevelHeaderExtensionDefaultId));
386 rtp_header_extensions_.push_back(
387 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
388 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
389 options_ = GetDefaultEngineOptions();
390}
391
392static bool IsOpus(const AudioCodec& codec) {
393 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
394}
395
396static bool IsIsac(const AudioCodec& codec) {
397 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
398}
399
400// True if params["stereo"] == "1"
401static bool IsOpusStereoEnabled(const AudioCodec& codec) {
402 CodecParameterMap::const_iterator param =
403 codec.params.find(kCodecParamStereo);
404 if (param == codec.params.end()) {
405 return false;
406 }
407 return param->second == kParamValueTrue;
408}
409
410static bool IsValidOpusBitrate(int bitrate) {
411 return (bitrate >= kOpusMinBitrate && bitrate <= kOpusMaxBitrate);
412}
413
414// Returns 0 if params[kCodecParamMaxAverageBitrate] is not defined or invalid.
415// Returns the value of params[kCodecParamMaxAverageBitrate] otherwise.
416static int GetOpusBitrateFromParams(const AudioCodec& codec) {
417 int bitrate = 0;
418 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
419 return 0;
420 }
421 if (!IsValidOpusBitrate(bitrate)) {
422 LOG(LS_WARNING) << "Codec parameter \"maxaveragebitrate\" has an "
423 << "invalid value: " << bitrate;
424 return 0;
425 }
426 return bitrate;
427}
428
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +0000429// True if params["useinbandfec"] == "1"
430static bool IsOpusFecEnabled(const AudioCodec& codec) {
431 CodecParameterMap::const_iterator param =
432 codec.params.find(kCodecParamUseInbandFec);
433 if (param == codec.params.end())
434 return false;
435
436 return param->second == kParamValueTrue;
437}
438
buildbot@webrtc.org13d67762014-05-02 17:33:29 +0000439void WebRtcVoiceEngine::ConstructCodecs() {
440 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
441 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
442 for (int i = 0; i < ncodecs; ++i) {
443 webrtc::CodecInst voe_codec;
444 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
445 // Skip uncompressed formats.
446 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
447 continue;
448 }
449
450 const CodecPref* pref = NULL;
451 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
452 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
453 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
454 kCodecPrefs[j].channels == voe_codec.channels) {
455 pref = &kCodecPrefs[j];
456 break;
457 }
458 }
459
460 if (pref) {
461 // Use the payload type that we've configured in our pref table;
462 // use the offset in our pref table to determine the sort order.
463 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
464 voe_codec.rate, voe_codec.channels,
465 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
466 LOG(LS_INFO) << ToString(codec);
467 if (IsIsac(codec)) {
468 // Indicate auto-bandwidth in signaling.
469 codec.bitrate = 0;
470 }
471 if (IsOpus(codec)) {
472 // Only add fmtp parameters that differ from the spec.
473 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
474 codec.params[kCodecParamMinPTime] =
475 talk_base::ToString(kPreferredMinPTime);
476 }
477 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
478 codec.params[kCodecParamMaxPTime] =
479 talk_base::ToString(kPreferredMaxPTime);
480 }
481 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
482 // when they can be set to values other than the default.
483 }
484 codecs_.push_back(codec);
485 } else {
486 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
487 }
488 }
489 }
490 // Make sure they are in local preference order.
491 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
492}
493
494WebRtcVoiceEngine::~WebRtcVoiceEngine() {
495 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
496 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
497 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
498 }
499 if (adm_) {
500 voe_wrapper_.reset();
501 adm_->Release();
502 adm_ = NULL;
503 }
504 if (adm_sc_) {
505 voe_wrapper_sc_.reset();
506 adm_sc_->Release();
507 adm_sc_ = NULL;
508 }
509
510 // Test to see if the media processor was deregistered properly
511 ASSERT(SignalRxMediaFrame.is_empty());
512 ASSERT(SignalTxMediaFrame.is_empty());
513
514 tracing_->SetTraceCallback(NULL);
515}
516
517bool WebRtcVoiceEngine::Init(talk_base::Thread* worker_thread) {
518 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
519 bool res = InitInternal();
520 if (res) {
521 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
522 } else {
523 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
524 Terminate();
525 }
526 return res;
527}
528
529bool WebRtcVoiceEngine::InitInternal() {
530 // Temporarily turn logging level up for the Init call
531 int old_filter = log_filter_;
532 int extended_filter = log_filter_ | SeverityToFilter(talk_base::LS_INFO);
533 SetTraceFilter(extended_filter);
534 SetTraceOptions("");
535
536 // Init WebRtc VoiceEngine.
537 if (voe_wrapper_->base()->Init(adm_) == -1) {
538 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
539 SetTraceFilter(old_filter);
540 return false;
541 }
542
543 SetTraceFilter(old_filter);
544 SetTraceOptions(log_options_);
545
546 // Log the VoiceEngine version info
547 char buffer[1024] = "";
548 voe_wrapper_->base()->GetVersion(buffer);
549 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
550 LogMultiline(talk_base::LS_INFO, buffer);
551
552 // Save the default AGC configuration settings. This must happen before
553 // calling SetOptions or the default will be overwritten.
554 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
555 LOG_RTCERR0(GetAgcConfig);
556 return false;
557 }
558
559 // Set defaults for options, so that ApplyOptions applies them explicitly
560 // when we clear option (channel) overrides. External clients can still
561 // modify the defaults via SetOptions (on the media engine).
562 if (!SetOptions(GetDefaultEngineOptions())) {
563 return false;
564 }
565
566 // Print our codec list again for the call diagnostic log
567 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
568 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
569 it != codecs_.end(); ++it) {
570 LOG(LS_INFO) << ToString(*it);
571 }
572
573 // Disable the DTMF playout when a tone is sent.
574 // PlayDtmfTone will be used if local playout is needed.
575 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
576 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
577 }
578
579 initialized_ = true;
580 return true;
581}
582
583bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
584 if (voe_wrapper_sc_initialized_) {
585 return true;
586 }
587 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
588 // be false, so subsequent calls to EnsureSoundclipEngineInit will
589 // probably just fail again. That's acceptable behavior.
590#if defined(LINUX) && !defined(HAVE_LIBPULSE)
591 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
592#endif
593
594 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
595 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
596 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
597 return false;
598 }
599
600 // On Windows, tell it to use the default sound (not communication) devices.
601 // First check whether there is a valid sound device for playback.
602 // TODO(juberti): Clean this up when we support setting the soundclip device.
603#ifdef WIN32
604 // The SetPlayoutDevice may not be implemented in the case of external ADM.
605 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
606 // PeerConnection interface never set the adm_sc_, so need to check both
607 // in order to determine if the external adm is used.
608 if (!adm_ && !adm_sc_) {
609 int num_of_devices = 0;
610 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
611 num_of_devices > 0) {
612 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
613 == -1) {
614 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
615 voe_wrapper_sc_->error());
616 return false;
617 }
618 } else {
619 LOG(LS_WARNING) << "No valid sound playout device found.";
620 }
621 }
622#endif
623 voe_wrapper_sc_initialized_ = true;
624 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
625 return true;
626}
627
628void WebRtcVoiceEngine::Terminate() {
629 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
630 initialized_ = false;
631
632 StopAecDump();
633
634 if (voe_wrapper_sc_) {
635 voe_wrapper_sc_initialized_ = false;
636 voe_wrapper_sc_->base()->Terminate();
637 }
638 voe_wrapper_->base()->Terminate();
639 desired_local_monitor_enable_ = false;
640}
641
642int WebRtcVoiceEngine::GetCapabilities() {
643 return AUDIO_SEND | AUDIO_RECV;
644}
645
646VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
647 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
648 if (!ch->valid()) {
649 delete ch;
650 ch = NULL;
651 }
652 return ch;
653}
654
655SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
656 if (!EnsureSoundclipEngineInit()) {
657 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
658 << "initialize.";
659 return NULL;
660 }
661 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
662 if (!soundclip->Init() || !soundclip->Enable()) {
663 delete soundclip;
664 return NULL;
665 }
666 return soundclip;
667}
668
669bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
670 if (!ApplyOptions(options)) {
671 return false;
672 }
673 options_ = options;
674 return true;
675}
676
677bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
678 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
679 if (!ApplyOptions(overrides)) {
680 return false;
681 }
682 option_overrides_ = overrides;
683 return true;
684}
685
686bool WebRtcVoiceEngine::ClearOptionOverrides() {
687 LOG(LS_INFO) << "Clearing option overrides.";
688 AudioOptions options = options_;
689 // Only call ApplyOptions if |options_overrides_| contains overrided options.
690 // ApplyOptions affects NS, AGC other options that is shared between
691 // all WebRtcVoiceEngineChannels.
692 if (option_overrides_ == AudioOptions()) {
693 return true;
694 }
695
696 if (!ApplyOptions(options)) {
697 return false;
698 }
699 option_overrides_ = AudioOptions();
700 return true;
701}
702
703// AudioOptions defaults are set in InitInternal (for options with corresponding
704// MediaEngineInterface flags) and in SetOptions(int) for flagless options.
705bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
706 AudioOptions options = options_in; // The options are modified below.
707 // kEcConference is AEC with high suppression.
708 webrtc::EcModes ec_mode = webrtc::kEcConference;
709 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
710 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
711 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
712 bool aecm_comfort_noise = false;
713 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
714 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
715 << aecm_comfort_noise << " (default is false).";
716 }
717
718#if defined(IOS)
719 // On iOS, VPIO provides built-in EC and AGC.
720 options.echo_cancellation.Set(false);
721 options.auto_gain_control.Set(false);
722#elif defined(ANDROID)
723 ec_mode = webrtc::kEcAecm;
724#endif
725
726#if defined(IOS) || defined(ANDROID)
727 // Set the AGC mode for iOS as well despite disabling it above, to avoid
728 // unsupported configuration errors from webrtc.
729 agc_mode = webrtc::kAgcFixedDigital;
730 options.typing_detection.Set(false);
731 options.experimental_agc.Set(false);
732 options.experimental_aec.Set(false);
733 options.experimental_ns.Set(false);
734#endif
735
736 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
737
738 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
739
740 bool echo_cancellation;
741 if (options.echo_cancellation.Get(&echo_cancellation)) {
742 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
743 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
744 return false;
745 } else {
746 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
747 << " with mode " << ec_mode;
748 }
749#if !defined(ANDROID)
750 // TODO(ajm): Remove the error return on Android from webrtc.
751 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
752 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
753 return false;
754 }
755#endif
756 if (ec_mode == webrtc::kEcAecm) {
757 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
758 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
759 return false;
760 }
761 }
762 }
763
764 bool auto_gain_control;
765 if (options.auto_gain_control.Get(&auto_gain_control)) {
766 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
767 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
768 return false;
769 } else {
770 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
771 << " with mode " << agc_mode;
772 }
773 }
774
775 if (options.tx_agc_target_dbov.IsSet() ||
776 options.tx_agc_digital_compression_gain.IsSet() ||
777 options.tx_agc_limiter.IsSet()) {
778 // Override default_agc_config_. Generally, an unset option means "leave
779 // the VoE bits alone" in this function, so we want whatever is set to be
780 // stored as the new "default". If we didn't, then setting e.g.
781 // tx_agc_target_dbov would reset digital compression gain and limiter
782 // settings.
783 // Also, if we don't update default_agc_config_, then adjust_agc_delta
784 // would be an offset from the original values, and not whatever was set
785 // explicitly.
786 default_agc_config_.targetLeveldBOv =
787 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
788 default_agc_config_.targetLeveldBOv);
789 default_agc_config_.digitalCompressionGaindB =
790 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
791 default_agc_config_.digitalCompressionGaindB);
792 default_agc_config_.limiterEnable =
793 options.tx_agc_limiter.GetWithDefaultIfUnset(
794 default_agc_config_.limiterEnable);
795 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
796 LOG_RTCERR3(SetAgcConfig,
797 default_agc_config_.targetLeveldBOv,
798 default_agc_config_.digitalCompressionGaindB,
799 default_agc_config_.limiterEnable);
800 return false;
801 }
802 }
803
804 bool noise_suppression;
805 if (options.noise_suppression.Get(&noise_suppression)) {
806 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
807 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
808 return false;
809 } else {
810 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
811 << " with mode " << ns_mode;
812 }
813 }
814
815 bool experimental_ns;
816 if (options.experimental_ns.Get(&experimental_ns)) {
817 webrtc::AudioProcessing* audioproc =
818 voe_wrapper_->base()->audio_processing();
819 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
820 // returns NULL on audio_processing().
821 if (audioproc) {
822 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
823 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
824 return false;
825 }
826 } else {
827 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
828 << experimental_ns;
829 }
830 }
831
832 bool highpass_filter;
833 if (options.highpass_filter.Get(&highpass_filter)) {
834 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
835 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
836 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
837 return false;
838 }
839 }
840
841 bool stereo_swapping;
842 if (options.stereo_swapping.Get(&stereo_swapping)) {
843 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
844 voep->EnableStereoChannelSwapping(stereo_swapping);
845 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
846 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
847 return false;
848 }
849 }
850
851 bool typing_detection;
852 if (options.typing_detection.Get(&typing_detection)) {
853 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
854 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
855 // In case of error, log the info and continue
856 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
857 }
858 }
859
860 int adjust_agc_delta;
861 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
862 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
863 if (!AdjustAgcLevel(adjust_agc_delta)) {
864 return false;
865 }
866 }
867
868 bool aec_dump;
869 if (options.aec_dump.Get(&aec_dump)) {
870 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
871 if (aec_dump)
872 StartAecDump(kAecDumpByAudioOptionFilename);
873 else
874 StopAecDump();
875 }
876
877 bool experimental_aec;
878 if (options.experimental_aec.Get(&experimental_aec)) {
879 LOG(LS_INFO) << "Experimental aec is " << experimental_aec;
880 webrtc::AudioProcessing* audioproc =
881 voe_wrapper_->base()->audio_processing();
882 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
883 // returns NULL on audio_processing().
884 if (audioproc) {
885 webrtc::Config config;
886 config.Set<webrtc::DelayCorrection>(
887 new webrtc::DelayCorrection(experimental_aec));
888 audioproc->SetExtraOptions(config);
889 }
890 }
891
892 uint32 recording_sample_rate;
893 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
894 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
895 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
896 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
897 }
898 }
899
900 uint32 playout_sample_rate;
901 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
902 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
903 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
904 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
905 }
906 }
907
908 return true;
909}
910
911bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
912 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
913 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
914 LOG_RTCERR1(SetDelayOffsetMs, offset);
915 return false;
916 }
917
918 return true;
919}
920
921struct ResumeEntry {
922 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
923 : channel(c),
924 playout(p),
925 send(s) {
926 }
927
928 WebRtcVoiceMediaChannel *channel;
929 bool playout;
930 SendFlags send;
931};
932
933// TODO(juberti): Refactor this so that the core logic can be used to set the
934// soundclip device. At that time, reinstate the soundclip pause/resume code.
935bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
936 const Device* out_device) {
937#if !defined(IOS)
938 int in_id = in_device ? talk_base::FromString<int>(in_device->id) :
939 kDefaultAudioDeviceId;
940 int out_id = out_device ? talk_base::FromString<int>(out_device->id) :
941 kDefaultAudioDeviceId;
942 // The device manager uses -1 as the default device, which was the case for
943 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
944#ifndef WIN32
945 if (-1 == in_id) {
946 in_id = kDefaultAudioDeviceId;
947 }
948 if (-1 == out_id) {
949 out_id = kDefaultAudioDeviceId;
950 }
951#endif
952
953 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
954 in_device->name : "Default device";
955 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
956 out_device->name : "Default device";
957 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
958 << ") and speaker to (id=" << out_id << ", name=" << out_name
959 << ")";
960
961 // If we're running the local monitor, we need to stop it first.
962 bool ret = true;
963 if (!PauseLocalMonitor()) {
964 LOG(LS_WARNING) << "Failed to pause local monitor";
965 ret = false;
966 }
967
968 // Must also pause all audio playback and capture.
969 for (ChannelList::const_iterator i = channels_.begin();
970 i != channels_.end(); ++i) {
971 WebRtcVoiceMediaChannel *channel = *i;
972 if (!channel->PausePlayout()) {
973 LOG(LS_WARNING) << "Failed to pause playout";
974 ret = false;
975 }
976 if (!channel->PauseSend()) {
977 LOG(LS_WARNING) << "Failed to pause send";
978 ret = false;
979 }
980 }
981
982 // Find the recording device id in VoiceEngine and set recording device.
983 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
984 ret = false;
985 }
986 if (ret) {
987 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
988 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
989 ret = false;
990 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000991 }
992
993 // Find the playout device id in VoiceEngine and set playout device.
994 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
995 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
996 ret = false;
997 }
998 if (ret) {
999 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001000 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001001 ret = false;
1002 }
1003 }
1004
1005 // Resume all audio playback and capture.
1006 for (ChannelList::const_iterator i = channels_.begin();
1007 i != channels_.end(); ++i) {
1008 WebRtcVoiceMediaChannel *channel = *i;
1009 if (!channel->ResumePlayout()) {
1010 LOG(LS_WARNING) << "Failed to resume playout";
1011 ret = false;
1012 }
1013 if (!channel->ResumeSend()) {
1014 LOG(LS_WARNING) << "Failed to resume send";
1015 ret = false;
1016 }
1017 }
1018
1019 // Resume local monitor.
1020 if (!ResumeLocalMonitor()) {
1021 LOG(LS_WARNING) << "Failed to resume local monitor";
1022 ret = false;
1023 }
1024
1025 if (ret) {
1026 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1027 << ") and speaker to (id="<< out_id << " name=" << out_name
1028 << ")";
1029 }
1030
1031 return ret;
1032#else
1033 return true;
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001034#endif // !IOS
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001035}
1036
1037bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1038 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1039 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
wu@webrtc.orgcecfd182013-10-30 05:18:12 +00001040#if defined(LINUX) || defined(ANDROID)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001041 *rtc_id = dev_id;
1042 return true;
1043#else
1044 // In Windows and Mac, we need to find the VoiceEngine device id by name
1045 // unless the input dev_id is the default device id.
1046 if (kDefaultAudioDeviceId == dev_id) {
1047 *rtc_id = dev_id;
1048 return true;
1049 }
1050
1051 // Get the number of VoiceEngine audio devices.
1052 int count = 0;
1053 if (is_input) {
1054 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1055 LOG_RTCERR0(GetNumOfRecordingDevices);
1056 return false;
1057 }
1058 } else {
1059 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1060 LOG_RTCERR0(GetNumOfPlayoutDevices);
1061 return false;
1062 }
1063 }
1064
1065 for (int i = 0; i < count; ++i) {
1066 char name[128];
1067 char guid[128];
1068 if (is_input) {
1069 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1070 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1071 } else {
1072 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1073 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1074 }
1075
1076 std::string webrtc_name(name);
1077 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1078 *rtc_id = i;
1079 return true;
1080 }
1081 }
1082 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1083 return false;
1084#endif
1085}
1086
1087bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1088 unsigned int ulevel;
1089 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1090 LOG_RTCERR1(GetSpeakerVolume, level);
1091 return false;
1092 }
1093 *level = ulevel;
1094 return true;
1095}
1096
1097bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1098 ASSERT(level >= 0 && level <= 255);
1099 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1100 LOG_RTCERR1(SetSpeakerVolume, level);
1101 return false;
1102 }
1103 return true;
1104}
1105
1106int WebRtcVoiceEngine::GetInputLevel() {
1107 unsigned int ulevel;
1108 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1109 static_cast<int>(ulevel) : -1;
1110}
1111
1112bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1113 desired_local_monitor_enable_ = enable;
1114 return ChangeLocalMonitor(desired_local_monitor_enable_);
1115}
1116
1117bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1118 // The voe file api is not available in chrome.
1119 if (!voe_wrapper_->file()) {
1120 return false;
1121 }
1122 if (enable && !monitor_) {
1123 monitor_.reset(new WebRtcMonitorStream);
1124 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1125 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1126 // Must call Stop() because there are some cases where Start will report
1127 // failure but still change the state, and if we leave VE in the on state
1128 // then it could crash later when trying to invoke methods on our monitor.
1129 voe_wrapper_->file()->StopRecordingMicrophone();
1130 monitor_.reset();
1131 return false;
1132 }
1133 } else if (!enable && monitor_) {
1134 voe_wrapper_->file()->StopRecordingMicrophone();
1135 monitor_.reset();
1136 }
1137 return true;
1138}
1139
1140bool WebRtcVoiceEngine::PauseLocalMonitor() {
1141 return ChangeLocalMonitor(false);
1142}
1143
1144bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1145 return ChangeLocalMonitor(desired_local_monitor_enable_);
1146}
1147
1148const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1149 return codecs_;
1150}
1151
1152bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1153 return FindWebRtcCodec(in, NULL);
1154}
1155
1156// Get the VoiceEngine codec that matches |in|, with the supplied settings.
1157bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1158 webrtc::CodecInst* out) {
1159 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1160 for (int i = 0; i < ncodecs; ++i) {
1161 webrtc::CodecInst voe_codec;
1162 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1163 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1164 voe_codec.rate, voe_codec.channels, 0);
1165 bool multi_rate = IsCodecMultiRate(voe_codec);
1166 // Allow arbitrary rates for ISAC to be specified.
1167 if (multi_rate) {
1168 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1169 codec.bitrate = 0;
1170 }
1171 if (codec.Matches(in)) {
1172 if (out) {
1173 // Fixup the payload type.
1174 voe_codec.pltype = in.id;
1175
1176 // Set bitrate if specified.
1177 if (multi_rate && in.bitrate != 0) {
1178 voe_codec.rate = in.bitrate;
1179 }
1180
1181 // Apply codec-specific settings.
1182 if (IsIsac(codec)) {
1183 // If ISAC and an explicit bitrate is not specified,
1184 // enable auto bandwidth adjustment.
1185 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1186 }
1187 *out = voe_codec;
1188 }
1189 return true;
1190 }
1191 }
1192 }
1193 return false;
1194}
1195const std::vector<RtpHeaderExtension>&
1196WebRtcVoiceEngine::rtp_header_extensions() const {
1197 return rtp_header_extensions_;
1198}
1199
1200void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1201 // if min_sev == -1, we keep the current log level.
1202 if (min_sev >= 0) {
1203 SetTraceFilter(SeverityToFilter(min_sev));
1204 }
1205 log_options_ = filter;
1206 SetTraceOptions(initialized_ ? log_options_ : "");
1207}
1208
1209int WebRtcVoiceEngine::GetLastEngineError() {
1210 return voe_wrapper_->error();
1211}
1212
1213void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1214 log_filter_ = filter;
1215 tracing_->SetTraceFilter(filter);
1216}
1217
1218// We suppport three different logging settings for VoiceEngine:
1219// 1. Observer callback that goes into talk diagnostic logfile.
1220// Use --logfile and --loglevel
1221//
1222// 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1223// Use --voice_loglevel --voice_logfilter "tracefile file_name"
1224//
1225// 3. EC log and dump for debugging QualityEngine.
1226// Use --voice_loglevel --voice_logfilter "recordEC file_name"
1227//
1228// For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1229// Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1230void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1231 // Set encrypted trace file.
1232 std::vector<std::string> opts;
1233 talk_base::tokenize(options, ' ', '"', '"', &opts);
1234 std::vector<std::string>::iterator tracefile =
1235 std::find(opts.begin(), opts.end(), "tracefile");
1236 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1237 // Write encrypted debug output (at same loglevel) to file
1238 // EncryptedTraceFile no longer supported.
1239 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1240 LOG_RTCERR1(SetTraceFile, *tracefile);
1241 }
1242 }
1243
wu@webrtc.org97077a32013-10-25 21:18:33 +00001244 // Allow trace options to override the trace filter. We default
1245 // it to log_filter_ (as a translation of libjingle log levels)
1246 // elsewhere, but this allows clients to explicitly set webrtc
1247 // log levels.
1248 std::vector<std::string>::iterator tracefilter =
1249 std::find(opts.begin(), opts.end(), "tracefilter");
1250 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
1251 if (!tracing_->SetTraceFilter(talk_base::FromString<int>(*tracefilter))) {
1252 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1253 }
1254 }
1255
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001256 // Set AEC dump file
1257 std::vector<std::string>::iterator recordEC =
1258 std::find(opts.begin(), opts.end(), "recordEC");
1259 if (recordEC != opts.end()) {
1260 ++recordEC;
1261 if (recordEC != opts.end())
1262 StartAecDump(recordEC->c_str());
1263 else
1264 StopAecDump();
1265 }
1266}
1267
1268// Ignore spammy trace messages, mostly from the stats API when we haven't
1269// gotten RTCP info yet from the remote side.
1270bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1271 static const char* kTracesToIgnore[] = {
1272 "\tfailed to GetReportBlockInformation",
1273 "GetRecCodec() failed to get received codec",
1274 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1275 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1276 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1277 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1278 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1279 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1280 "SenderInfoReceived No received SR",
1281 "StatisticsRTP() no statistics available",
1282 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1283 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1284 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1285 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1286 NULL
1287 };
1288 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1289 if (trace.find(*p) != std::string::npos) {
1290 return true;
1291 }
1292 }
1293 return false;
1294}
1295
1296void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1297 int length) {
1298 talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
1299 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
1300 sev = talk_base::LS_ERROR;
1301 else if (level == webrtc::kTraceWarning)
1302 sev = talk_base::LS_WARNING;
1303 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
1304 sev = talk_base::LS_INFO;
1305 else if (level == webrtc::kTraceTerseInfo)
1306 sev = talk_base::LS_INFO;
1307
1308 // Skip past boilerplate prefix text
1309 if (length < 72) {
1310 std::string msg(trace, length);
1311 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1312 LOG_V(sev) << msg;
1313 } else {
1314 std::string msg(trace + 71, length - 72);
1315 if (!ShouldIgnoreTrace(msg)) {
1316 LOG_V(sev) << "webrtc: " << msg;
1317 }
1318 }
1319}
1320
1321void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
1322 talk_base::CritScope lock(&channels_cs_);
1323 WebRtcVoiceMediaChannel* channel = NULL;
1324 uint32 ssrc = 0;
1325 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1326 << channel_num << ".";
1327 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1328 ASSERT(channel != NULL);
1329 channel->OnError(ssrc, err_code);
1330 } else {
1331 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1332 << " could not be found in channel list when error reported.";
1333 }
1334}
1335
1336bool WebRtcVoiceEngine::FindChannelAndSsrc(
1337 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1338 ASSERT(channel != NULL && ssrc != NULL);
1339
1340 *channel = NULL;
1341 *ssrc = 0;
1342 // Find corresponding channel and ssrc
1343 for (ChannelList::const_iterator it = channels_.begin();
1344 it != channels_.end(); ++it) {
1345 ASSERT(*it != NULL);
1346 if ((*it)->FindSsrc(channel_num, ssrc)) {
1347 *channel = *it;
1348 return true;
1349 }
1350 }
1351
1352 return false;
1353}
1354
1355// This method will search through the WebRtcVoiceMediaChannels and
1356// obtain the voice engine's channel number.
1357bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1358 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1359 ASSERT(channel_num != NULL);
1360 ASSERT(direction == MPD_RX || direction == MPD_TX);
1361
1362 *channel_num = -1;
1363 // Find corresponding channel for ssrc.
1364 for (ChannelList::const_iterator it = channels_.begin();
1365 it != channels_.end(); ++it) {
1366 ASSERT(*it != NULL);
1367 if (direction & MPD_RX) {
1368 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1369 }
1370 if (*channel_num == -1 && (direction & MPD_TX)) {
1371 *channel_num = (*it)->GetSendChannelNum(ssrc);
1372 }
1373 if (*channel_num != -1) {
1374 return true;
1375 }
1376 }
1377 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1378 return false;
1379}
1380
1381void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
1382 talk_base::CritScope lock(&channels_cs_);
1383 channels_.push_back(channel);
1384}
1385
1386void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
1387 talk_base::CritScope lock(&channels_cs_);
1388 ChannelList::iterator i = std::find(channels_.begin(),
1389 channels_.end(),
1390 channel);
1391 if (i != channels_.end()) {
1392 channels_.erase(i);
1393 }
1394}
1395
1396void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1397 soundclips_.push_back(soundclip);
1398}
1399
1400void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1401 SoundclipList::iterator i = std::find(soundclips_.begin(),
1402 soundclips_.end(),
1403 soundclip);
1404 if (i != soundclips_.end()) {
1405 soundclips_.erase(i);
1406 }
1407}
1408
1409// Adjusts the default AGC target level by the specified delta.
1410// NB: If we start messing with other config fields, we'll want
1411// to save the current webrtc::AgcConfig as well.
1412bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1413 webrtc::AgcConfig config = default_agc_config_;
1414 config.targetLeveldBOv -= delta;
1415
1416 LOG(LS_INFO) << "Adjusting AGC level from default -"
1417 << default_agc_config_.targetLeveldBOv << "dB to -"
1418 << config.targetLeveldBOv << "dB";
1419
1420 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1421 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1422 return false;
1423 }
1424 return true;
1425}
1426
1427bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1428 webrtc::AudioDeviceModule* adm_sc) {
1429 if (initialized_) {
1430 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1431 return false;
1432 }
1433 if (adm_) {
1434 adm_->Release();
1435 adm_ = NULL;
1436 }
1437 if (adm) {
1438 adm_ = adm;
1439 adm_->AddRef();
1440 }
1441
1442 if (adm_sc_) {
1443 adm_sc_->Release();
1444 adm_sc_ = NULL;
1445 }
1446 if (adm_sc) {
1447 adm_sc_ = adm_sc;
1448 adm_sc_->AddRef();
1449 }
1450 return true;
1451}
1452
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001453bool WebRtcVoiceEngine::StartAecDump(talk_base::PlatformFile file) {
1454 FILE* aec_dump_file_stream = talk_base::FdopenPlatformFileForWriting(file);
1455 if (!aec_dump_file_stream) {
1456 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
1457 if (!talk_base::ClosePlatformFile(file))
1458 LOG(LS_WARNING) << "Could not close file.";
1459 return false;
1460 }
wu@webrtc.orga9890802013-12-13 00:21:03 +00001461 StopAecDump();
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001462 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
wu@webrtc.orga9890802013-12-13 00:21:03 +00001463 webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga8910d22014-01-23 22:12:45 +00001464 LOG_RTCERR0(StartDebugRecording);
1465 fclose(aec_dump_file_stream);
wu@webrtc.orga9890802013-12-13 00:21:03 +00001466 return false;
1467 }
1468 is_dumping_aec_ = true;
1469 return true;
wu@webrtc.orga9890802013-12-13 00:21:03 +00001470}
1471
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001472bool WebRtcVoiceEngine::RegisterProcessor(
1473 uint32 ssrc,
1474 VoiceProcessor* voice_processor,
1475 MediaProcessorDirection direction) {
1476 bool register_with_webrtc = false;
1477 int channel_id = -1;
1478 bool success = false;
1479 uint32* processor_ssrc = NULL;
1480 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1481 if (voice_processor == NULL || !found_channel) {
1482 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1483 << " foundChannel: " << found_channel;
1484 return false;
1485 }
1486
1487 webrtc::ProcessingTypes processing_type;
1488 {
1489 talk_base::CritScope cs(&signal_media_critical_);
1490 if (direction == MPD_RX) {
1491 processing_type = webrtc::kPlaybackAllChannelsMixed;
1492 if (SignalRxMediaFrame.is_empty()) {
1493 register_with_webrtc = true;
1494 processor_ssrc = &rx_processor_ssrc_;
1495 }
1496 SignalRxMediaFrame.connect(voice_processor,
1497 &VoiceProcessor::OnFrame);
1498 } else {
1499 processing_type = webrtc::kRecordingPerChannel;
1500 if (SignalTxMediaFrame.is_empty()) {
1501 register_with_webrtc = true;
1502 processor_ssrc = &tx_processor_ssrc_;
1503 }
1504 SignalTxMediaFrame.connect(voice_processor,
1505 &VoiceProcessor::OnFrame);
1506 }
1507 }
1508 if (register_with_webrtc) {
1509 // TODO(janahan): when registering consider instantiating a
1510 // a VoeMediaProcess object and not make the engine extend the interface.
1511 if (voe()->media() && voe()->media()->
1512 RegisterExternalMediaProcessing(channel_id,
1513 processing_type,
1514 *this) != -1) {
1515 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1516 << channel_id;
1517 *processor_ssrc = ssrc;
1518 success = true;
1519 } else {
1520 LOG_RTCERR2(RegisterExternalMediaProcessing,
1521 channel_id,
1522 processing_type);
1523 success = false;
1524 }
1525 } else {
1526 // If we don't have to register with the engine, we just needed to
1527 // connect a new processor, set success to true;
1528 success = true;
1529 }
1530 return success;
1531}
1532
1533bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1534 MediaProcessorDirection channel_direction,
1535 uint32 ssrc,
1536 VoiceProcessor* voice_processor,
1537 MediaProcessorDirection processor_direction) {
1538 bool success = true;
1539 FrameSignal* signal;
1540 webrtc::ProcessingTypes processing_type;
1541 uint32* processor_ssrc = NULL;
1542 if (channel_direction == MPD_RX) {
1543 signal = &SignalRxMediaFrame;
1544 processing_type = webrtc::kPlaybackAllChannelsMixed;
1545 processor_ssrc = &rx_processor_ssrc_;
1546 } else {
1547 signal = &SignalTxMediaFrame;
1548 processing_type = webrtc::kRecordingPerChannel;
1549 processor_ssrc = &tx_processor_ssrc_;
1550 }
1551
1552 int deregister_id = -1;
1553 {
1554 talk_base::CritScope cs(&signal_media_critical_);
1555 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1556 signal->disconnect(voice_processor);
1557 int channel_id = -1;
1558 bool found_channel = FindChannelNumFromSsrc(ssrc,
1559 channel_direction,
1560 &channel_id);
1561 if (signal->is_empty() && found_channel) {
1562 deregister_id = channel_id;
1563 }
1564 }
1565 }
1566 if (deregister_id != -1) {
1567 if (voe()->media() &&
1568 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1569 processing_type) != -1) {
1570 *processor_ssrc = 0;
1571 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1572 << deregister_id;
1573 } else {
1574 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1575 deregister_id,
1576 processing_type);
1577 success = false;
1578 }
1579 }
1580 return success;
1581}
1582
1583bool WebRtcVoiceEngine::UnregisterProcessor(
1584 uint32 ssrc,
1585 VoiceProcessor* voice_processor,
1586 MediaProcessorDirection direction) {
1587 bool success = true;
1588 if (voice_processor == NULL) {
1589 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1590 << ssrc;
1591 return false;
1592 }
1593 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1594 success = false;
1595 }
1596 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1597 success = false;
1598 }
1599 return success;
1600}
1601
1602// Implementing method from WebRtc VoEMediaProcess interface
1603// Do not lock mux_channel_cs_ in this callback.
1604void WebRtcVoiceEngine::Process(int channel,
1605 webrtc::ProcessingTypes type,
1606 int16_t audio10ms[],
1607 int length,
1608 int sampling_freq,
1609 bool is_stereo) {
1610 talk_base::CritScope cs(&signal_media_critical_);
1611 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1612 if (type == webrtc::kPlaybackAllChannelsMixed) {
1613 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1614 } else if (type == webrtc::kRecordingPerChannel) {
1615 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1616 } else {
1617 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1618 << " channel: " << channel << " type: " << type
1619 << " tx_ssrc: " << tx_processor_ssrc_
1620 << " rx_ssrc: " << rx_processor_ssrc_;
1621 }
1622}
1623
1624void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1625 if (!is_dumping_aec_) {
1626 // Start dumping AEC when we are not dumping.
1627 if (voe_wrapper_->processing()->StartDebugRecording(
1628 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
wu@webrtc.orga9890802013-12-13 00:21:03 +00001629 LOG_RTCERR1(StartDebugRecording, filename.c_str());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001630 } else {
1631 is_dumping_aec_ = true;
1632 }
1633 }
1634}
1635
1636void WebRtcVoiceEngine::StopAecDump() {
1637 if (is_dumping_aec_) {
1638 // Stop dumping AEC when we are dumping.
1639 if (voe_wrapper_->processing()->StopDebugRecording() !=
1640 webrtc::AudioProcessing::kNoError) {
1641 LOG_RTCERR0(StopDebugRecording);
1642 }
1643 is_dumping_aec_ = false;
1644 }
1645}
1646
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001647int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001648 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001649}
1650
1651int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1652 return CreateVoiceChannel(voe_wrapper_.get());
1653}
1654
1655int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1656 return CreateVoiceChannel(voe_wrapper_sc_.get());
1657}
1658
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001659class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1660 : public AudioRenderer::Sink {
1661 public:
1662 WebRtcVoiceChannelRenderer(int ch,
1663 webrtc::AudioTransport* voe_audio_transport)
1664 : channel_(ch),
1665 voe_audio_transport_(voe_audio_transport),
1666 renderer_(NULL) {
1667 }
1668 virtual ~WebRtcVoiceChannelRenderer() {
1669 Stop();
1670 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001671
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001672 // Starts the rendering by setting a sink to the renderer to get data
1673 // callback.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001674 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001675 // TODO(xians): Make sure Start() is called only once.
1676 void Start(AudioRenderer* renderer) {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001677 talk_base::CritScope lock(&lock_);
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001678 ASSERT(renderer != NULL);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001679 if (renderer_ != NULL) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001680 ASSERT(renderer_ == renderer);
1681 return;
1682 }
1683
1684 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1685 // in getUserMedia by default.
1686 renderer->AddChannel(channel_);
1687 renderer->SetSink(this);
1688 renderer_ = renderer;
1689 }
1690
1691 // Stops rendering by setting the sink of the renderer to NULL. No data
1692 // callback will be received after this method.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001693 // This method is called on the libjingle worker thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001694 void Stop() {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001695 talk_base::CritScope lock(&lock_);
1696 if (renderer_ == NULL)
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001697 return;
1698
1699 renderer_->RemoveChannel(channel_);
1700 renderer_->SetSink(NULL);
1701 renderer_ = NULL;
1702 }
1703
1704 // AudioRenderer::Sink implementation.
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001705 // This method is called on the audio thread.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001706 virtual void OnData(const void* audio_data,
1707 int bits_per_sample,
1708 int sample_rate,
1709 int number_of_channels,
1710 int number_of_frames) OVERRIDE {
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001711 voe_audio_transport_->OnData(channel_,
1712 audio_data,
1713 bits_per_sample,
1714 sample_rate,
1715 number_of_channels,
1716 number_of_frames);
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001717 }
1718
1719 // Callback from the |renderer_| when it is going away. In case Start() has
1720 // never been called, this callback won't be triggered.
1721 virtual void OnClose() OVERRIDE {
1722 talk_base::CritScope lock(&lock_);
1723 // Set |renderer_| to NULL to make sure no more callback will get into
1724 // the renderer.
1725 renderer_ = NULL;
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001726 }
1727
1728 // Accessor to the VoE channel ID.
1729 int channel() const { return channel_; }
1730
1731 private:
1732 const int channel_;
1733 webrtc::AudioTransport* const voe_audio_transport_;
1734
1735 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1736 // PeerConnection will make sure invalidating the pointer before the object
1737 // goes away.
1738 AudioRenderer* renderer_;
henrike@webrtc.orga7b98182014-02-21 15:51:43 +00001739
1740 // Protects |renderer_| in Start(), Stop() and OnClose().
1741 talk_base::CriticalSection lock_;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001742};
1743
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001744// WebRtcVoiceMediaChannel
1745WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1746 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1747 engine,
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00001748 engine->CreateMediaVoiceChannel()),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001749 send_bw_setting_(false),
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00001750 send_bw_bps_(0),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001751 options_(),
1752 dtmf_allowed_(false),
1753 desired_playout_(false),
1754 nack_enabled_(false),
1755 playout_(false),
wu@webrtc.org967bfff2013-09-19 05:49:50 +00001756 typing_noise_detected_(false),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001757 desired_send_(SEND_NOTHING),
1758 send_(SEND_NOTHING),
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001759 default_receive_ssrc_(0) {
1760 engine->RegisterChannel(this);
1761 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1762 << voe_channel();
1763
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001764 ConfigureSendChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001765}
1766
1767WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1768 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1769 << voe_channel();
1770
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001771 // Remove any remaining send streams, the default channel will be deleted
1772 // later.
1773 while (!send_channels_.empty())
1774 RemoveSendStream(send_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001775
1776 // Unregister ourselves from the engine.
1777 engine()->UnregisterChannel(this);
1778 // Remove any remaining streams.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001779 while (!receive_channels_.empty()) {
1780 RemoveRecvStream(receive_channels_.begin()->first);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001781 }
1782
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001783 // Delete the default channel.
1784 DeleteChannel(voe_channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001785}
1786
1787bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1788 LOG(LS_INFO) << "Setting voice channel options: "
1789 << options.ToString();
1790
wu@webrtc.orgde305012013-10-31 15:40:38 +00001791 // Check if DSCP value is changed from previous.
1792 bool dscp_option_changed = (options_.dscp != options.dscp);
1793
wu@webrtc.org9dba5252013-08-05 20:36:57 +00001794 // TODO(xians): Add support to set different options for different send
1795 // streams after we support multiple APMs.
1796
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001797 // We retain all of the existing options, and apply the given ones
1798 // on top. This means there is no way to "clear" options such that
1799 // they go back to the engine default.
1800 options_.SetAll(options);
1801
1802 if (send_ != SEND_NOTHING) {
1803 if (!engine()->SetOptionOverrides(options_)) {
1804 LOG(LS_WARNING) <<
1805 "Failed to engine SetOptionOverrides during channel SetOptions.";
1806 return false;
1807 }
1808 } else {
1809 // Will be interpreted when appropriate.
1810 }
1811
wu@webrtc.org97077a32013-10-25 21:18:33 +00001812 // Receiver-side auto gain control happens per channel, so set it here from
1813 // options. Note that, like conference mode, setting it on the engine won't
1814 // have the desired effect, since voice channels don't inherit options from
1815 // the media engine when those options are applied per-channel.
1816 bool rx_auto_gain_control;
1817 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1818 if (engine()->voe()->processing()->SetRxAgcStatus(
1819 voe_channel(), rx_auto_gain_control,
1820 webrtc::kAgcFixedDigital) == -1) {
1821 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1822 return false;
1823 } else {
1824 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1825 << " with mode " << webrtc::kAgcFixedDigital;
1826 }
1827 }
1828 if (options.rx_agc_target_dbov.IsSet() ||
1829 options.rx_agc_digital_compression_gain.IsSet() ||
1830 options.rx_agc_limiter.IsSet()) {
1831 webrtc::AgcConfig config;
1832 // If only some of the options are being overridden, get the current
1833 // settings for the channel and bail if they aren't available.
1834 if (!options.rx_agc_target_dbov.IsSet() ||
1835 !options.rx_agc_digital_compression_gain.IsSet() ||
1836 !options.rx_agc_limiter.IsSet()) {
1837 if (engine()->voe()->processing()->GetRxAgcConfig(
1838 voe_channel(), config) != 0) {
1839 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1840 << "channel " << voe_channel() << ". Since not all rx "
1841 << "agc options are specified, unable to safely set rx "
1842 << "agc options.";
1843 return false;
1844 }
1845 }
1846 config.targetLeveldBOv =
1847 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1848 config.targetLeveldBOv);
1849 config.digitalCompressionGaindB =
1850 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1851 config.digitalCompressionGaindB);
1852 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1853 config.limiterEnable);
1854 if (engine()->voe()->processing()->SetRxAgcConfig(
1855 voe_channel(), config) == -1) {
1856 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1857 config.digitalCompressionGaindB, config.limiterEnable);
1858 return false;
1859 }
1860 }
wu@webrtc.orgde305012013-10-31 15:40:38 +00001861 if (dscp_option_changed) {
1862 talk_base::DiffServCodePoint dscp = talk_base::DSCP_DEFAULT;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001863 if (options_.dscp.GetWithDefaultIfUnset(false))
wu@webrtc.orgde305012013-10-31 15:40:38 +00001864 dscp = kAudioDscpValue;
1865 if (MediaChannel::SetDscp(dscp) != 0) {
1866 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1867 }
1868 }
wu@webrtc.org97077a32013-10-25 21:18:33 +00001869
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001870 LOG(LS_INFO) << "Set voice channel options. Current options: "
1871 << options_.ToString();
1872 return true;
1873}
1874
1875bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1876 const std::vector<AudioCodec>& codecs) {
1877 // Set the payload types to be used for incoming media.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001878 LOG(LS_INFO) << "Setting receive voice codecs:";
1879
1880 std::vector<AudioCodec> new_codecs;
1881 // Find all new codecs. We allow adding new codecs but don't allow changing
1882 // the payload type of codecs that is already configured since we might
1883 // already be receiving packets with that payload type.
1884 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001885 it != codecs.end(); ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001886 AudioCodec old_codec;
1887 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1888 if (old_codec.id != it->id) {
1889 LOG(LS_ERROR) << it->name << " payload type changed.";
1890 return false;
1891 }
1892 } else {
1893 new_codecs.push_back(*it);
1894 }
1895 }
1896 if (new_codecs.empty()) {
1897 // There are no new codecs to configure. Already configured codecs are
1898 // never removed.
1899 return true;
1900 }
1901
1902 if (playout_) {
1903 // Receive codecs can not be changed while playing. So we temporarily
1904 // pause playout.
1905 PausePlayout();
1906 }
1907
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001908 bool ret = true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001909 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1910 it != new_codecs.end() && ret; ++it) {
1911 webrtc::CodecInst voe_codec;
1912 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1913 LOG(LS_INFO) << ToString(*it);
1914 voe_codec.pltype = it->id;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001915 if (default_receive_ssrc_ == 0) {
1916 // Set the receive codecs on the default channel explicitly if the
1917 // default channel is not used by |receive_channels_|, this happens in
1918 // conference mode or in non-conference mode when there is no playout
1919 // channel.
1920 // TODO(xians): Figure out how we use the default channel in conference
1921 // mode.
1922 if (engine()->voe()->codec()->SetRecPayloadType(
1923 voe_channel(), voe_codec) == -1) {
1924 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1925 ret = false;
1926 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001927 }
1928
1929 // Set the receive codecs on all receiving channels.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001930 for (ChannelMap::iterator it = receive_channels_.begin();
1931 it != receive_channels_.end() && ret; ++it) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001932 if (engine()->voe()->codec()->SetRecPayloadType(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00001933 it->second->channel(), voe_codec) == -1) {
1934 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001935 ToString(voe_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001936 ret = false;
1937 }
1938 }
1939 } else {
1940 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1941 ret = false;
1942 }
1943 }
1944 if (ret) {
1945 recv_codecs_ = codecs;
1946 }
1947
1948 if (desired_playout_ && !playout_) {
1949 ResumePlayout();
1950 }
1951 return ret;
1952}
1953
1954bool WebRtcVoiceMediaChannel::SetSendCodecs(
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001955 int channel, const std::vector<AudioCodec>& codecs) {
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001956 // Disable VAD, FEC, and RED unless we know the other side wants them.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001957 engine()->voe()->codec()->SetVADStatus(channel, false);
1958 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001959#ifdef USE_WEBRTC_DEV_BRANCH
1960 engine()->voe()->rtp()->SetREDStatus(channel, false);
1961 engine()->voe()->codec()->SetFECStatus(channel, false);
1962#else
1963 // TODO(minyue): Remove code under #else case after new WebRTC roll.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00001964 engine()->voe()->rtp()->SetFECStatus(channel, false);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00001965#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001966
1967 // Scan through the list to figure out the codec to use for sending, along
1968 // with the proper configuration for VAD and DTMF.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001969 bool found_send_codec = false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001970 webrtc::CodecInst send_codec;
1971 memset(&send_codec, 0, sizeof(send_codec));
1972
wu@webrtc.org05e7b442014-04-01 17:44:24 +00001973 bool nack_enabled = nack_enabled_;
1974
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001975 // Set send codec (the first non-telephone-event/CN codec)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001976 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1977 it != codecs.end(); ++it) {
1978 // Ignore codecs we don't know about. The negotiation step should prevent
1979 // this, but double-check to be sure.
1980 webrtc::CodecInst voe_codec;
1981 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001982 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001983 continue;
1984 }
1985
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00001986 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
1987 // Skip telephone-event/CN codec, which will be handled later.
1988 continue;
1989 }
1990
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001991 // If OPUS, change what we send according to the "stereo" codec
1992 // parameter, and not the "channels" parameter. We set
1993 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
1994 // the bitrate is not specified, i.e. is zero, we set it to the
1995 // appropriate default value for mono or stereo Opus.
1996 if (IsOpus(*it)) {
1997 if (IsOpusStereoEnabled(*it)) {
1998 voe_codec.channels = 2;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00001999 if (!IsValidOpusBitrate(it->bitrate)) {
2000 if (it->bitrate != 0) {
2001 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2002 << it->bitrate
2003 << ") with default opus stereo bitrate: "
2004 << kOpusStereoBitrate;
2005 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002006 voe_codec.rate = kOpusStereoBitrate;
2007 }
2008 } else {
2009 voe_codec.channels = 1;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002010 if (!IsValidOpusBitrate(it->bitrate)) {
2011 if (it->bitrate != 0) {
2012 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
2013 << it->bitrate
2014 << ") with default opus mono bitrate: "
2015 << kOpusMonoBitrate;
2016 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002017 voe_codec.rate = kOpusMonoBitrate;
2018 }
2019 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002020 int bitrate_from_params = GetOpusBitrateFromParams(*it);
2021 if (bitrate_from_params != 0) {
2022 voe_codec.rate = bitrate_from_params;
2023 }
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002024
2025 // If FEC is enabled.
2026 if (IsOpusFecEnabled(*it)) {
2027 LOG(LS_INFO) << "Enabling Opus FEC on channel " << channel;
2028#ifdef USE_WEBRTC_DEV_BRANCH
2029 if (engine()->voe()->codec()->SetFECStatus(channel, true) == -1) {
2030 // Enable in-band FEC of the Opus codec. Treat any failure as a fatal
2031 // internal error.
2032 LOG_RTCERR2(SetFECStatus, channel, true);
2033 return false;
2034 }
2035#endif // USE_WEBRTC_DEV_BRANCH
2036 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002037 }
2038
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002039 // We'll use the first codec in the list to actually send audio data.
2040 // Be sure to use the payload type requested by the remote side.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002041 // "red", for RED audio, is a special case where the actual codec to be
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002042 // used is specified in params.
2043 if (IsRedCodec(it->name)) {
2044 // Parse out the RED parameters. If we fail, just ignore RED;
2045 // we don't support all possible params/usage scenarios.
2046 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2047 continue;
2048 }
2049
2050 // Enable redundant encoding of the specified codec. Treat any
2051 // failure as a fatal internal error.
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002052#ifdef USE_WEBRTC_DEV_BRANCH
2053 LOG(LS_INFO) << "Enabling RED on channel " << channel;
2054 if (engine()->voe()->rtp()->SetREDStatus(channel, true, it->id) == -1) {
2055 LOG_RTCERR3(SetREDStatus, channel, true, it->id);
2056#else
2057 // TODO(minyue): Remove code under #else case after new WebRTC roll.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002058 LOG(LS_INFO) << "Enabling FEC";
2059 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2060 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
buildbot@webrtc.orgae740dd2014-06-17 10:56:41 +00002061#endif // USE_WEBRTC_DEV_BRANCH
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002062 return false;
2063 }
2064 } else {
2065 send_codec = voe_codec;
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002066 nack_enabled = IsNackEnabled(*it);
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002067 }
2068 found_send_codec = true;
2069 break;
2070 }
2071
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002072 if (nack_enabled_ != nack_enabled) {
2073 SetNack(channel, nack_enabled);
2074 nack_enabled_ = nack_enabled;
2075 }
2076
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002077 if (!found_send_codec) {
2078 LOG(LS_WARNING) << "Received empty list of codecs.";
2079 return false;
2080 }
2081
2082 // Set the codec immediately, since SetVADStatus() depends on whether
2083 // the current codec is mono or stereo.
2084 if (!SetSendCodec(channel, send_codec))
2085 return false;
2086
2087 // Always update the |send_codec_| to the currently set send codec.
2088 send_codec_.reset(new webrtc::CodecInst(send_codec));
2089
2090 if (send_bw_setting_) {
2091 SetSendBandwidthInternal(send_bw_bps_);
2092 }
2093
2094 // Loop through the codecs list again to config the telephone-event/CN codec.
2095 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2096 it != codecs.end(); ++it) {
2097 // Ignore codecs we don't know about. The negotiation step should prevent
2098 // this, but double-check to be sure.
2099 webrtc::CodecInst voe_codec;
2100 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2101 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2102 continue;
2103 }
2104
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002105 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2106 // about it.
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002107 if (IsTelephoneEventCodec(it->name)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002108 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2109 channel, it->id) == -1) {
2110 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2111 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002112 }
henrike@webrtc.org704bf9e2014-02-27 17:52:04 +00002113 } else if (IsCNCodec(it->name)) {
2114 // Turn voice activity detection/comfort noise on if supported.
2115 // Set the wideband CN payload type appropriately.
2116 // (narrowband always uses the static payload type 13).
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002117 webrtc::PayloadFrequencies cn_freq;
2118 switch (it->clockrate) {
2119 case 8000:
2120 cn_freq = webrtc::kFreq8000Hz;
2121 break;
2122 case 16000:
2123 cn_freq = webrtc::kFreq16000Hz;
2124 break;
2125 case 32000:
2126 cn_freq = webrtc::kFreq32000Hz;
2127 break;
2128 default:
2129 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2130 << " not supported.";
2131 continue;
2132 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002133 // Set the CN payloadtype and the VAD status.
2134 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2135 if (cn_freq != webrtc::kFreq8000Hz) {
2136 if (engine()->voe()->codec()->SetSendCNPayloadType(
2137 channel, it->id, cn_freq) == -1) {
2138 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2139 // TODO(ajm): This failure condition will be removed from VoE.
2140 // Restore the return here when we update to a new enough webrtc.
2141 //
2142 // Not returning false because the SetSendCNPayloadType will fail if
2143 // the channel is already sending.
2144 // This can happen if the remote description is applied twice, for
2145 // example in the case of ROAP on top of JSEP, where both side will
2146 // send the offer.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002147 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002148 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002149 // Only turn on VAD if we have a CN payload type that matches the
2150 // clockrate for the codec we are going to use.
2151 if (it->clockrate == send_codec.plfreq) {
2152 LOG(LS_INFO) << "Enabling VAD";
2153 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2154 LOG_RTCERR2(SetVADStatus, channel, true);
2155 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002156 }
2157 }
2158 }
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00002159 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002160 return true;
2161}
2162
2163bool WebRtcVoiceMediaChannel::SetSendCodecs(
2164 const std::vector<AudioCodec>& codecs) {
2165 dtmf_allowed_ = false;
2166 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2167 it != codecs.end(); ++it) {
2168 // Find the DTMF telephone event "codec".
2169 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2170 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2171 dtmf_allowed_ = true;
2172 }
2173 }
2174
2175 // Cache the codecs in order to configure the channel created later.
2176 send_codecs_ = codecs;
2177 for (ChannelMap::iterator iter = send_channels_.begin();
2178 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002179 if (!SetSendCodecs(iter->second->channel(), codecs)) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002180 return false;
2181 }
2182 }
2183
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002184 // Set nack status on receive channels and update |nack_enabled_|.
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002185 SetNack(receive_channels_, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002186 return true;
2187}
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002188
2189void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2190 bool nack_enabled) {
2191 for (ChannelMap::const_iterator it = channels.begin();
2192 it != channels.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002193 SetNack(it->second->channel(), nack_enabled);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002194 }
2195}
2196
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002197void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002198 if (nack_enabled) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002199 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002200 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2201 } else {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002202 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002203 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2204 }
2205}
2206
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002207bool WebRtcVoiceMediaChannel::SetSendCodec(
2208 const webrtc::CodecInst& send_codec) {
2209 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2210 << ", bitrate=" << send_codec.rate;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002211 for (ChannelMap::iterator iter = send_channels_.begin();
2212 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002213 if (!SetSendCodec(iter->second->channel(), send_codec))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002214 return false;
2215 }
2216
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002217 return true;
2218}
2219
2220bool WebRtcVoiceMediaChannel::SetSendCodec(
2221 int channel, const webrtc::CodecInst& send_codec) {
2222 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2223 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2224
wu@webrtc.org05e7b442014-04-01 17:44:24 +00002225 webrtc::CodecInst current_codec;
2226 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2227 (send_codec == current_codec)) {
2228 // Codec is already configured, we can return without setting it again.
2229 return true;
2230 }
2231
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002232 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2233 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002234 return false;
2235 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002236 return true;
2237}
2238
2239bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2240 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002241 if (receive_extensions_ == extensions) {
2242 return true;
2243 }
2244
2245 // The default channel may or may not be in |receive_channels_|. Set the rtp
2246 // header extensions for default channel regardless.
2247 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2248 return false;
2249 }
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002250
2251 // Loop through all receive channels and enable/disable the extensions.
2252 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2253 channel_it != receive_channels_.end(); ++channel_it) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002254 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2255 extensions)) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002256 return false;
2257 }
2258 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002259
2260 receive_extensions_ = extensions;
2261 return true;
2262}
2263
2264bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2265 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
2266#ifdef USE_WEBRTC_DEV_BRANCH
2267 const RtpHeaderExtension* audio_level_extension =
2268 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2269 if (!SetHeaderExtension(
2270 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2271 audio_level_extension)) {
2272 return false;
2273 }
2274#endif // USE_WEBRTC_DEV_BRANCH
2275
2276 const RtpHeaderExtension* send_time_extension =
2277 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2278 if (!SetHeaderExtension(
2279 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2280 send_time_extension)) {
2281 return false;
2282 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002283 return true;
2284}
2285
2286bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2287 const std::vector<RtpHeaderExtension>& extensions) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002288 if (send_extensions_ == extensions) {
2289 return true;
2290 }
2291
2292 // The default channel may or may not be in |send_channels_|. Set the rtp
2293 // header extensions for default channel regardless.
2294
2295 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2296 return false;
2297 }
2298
2299 // Loop through all send channels and enable/disable the extensions.
2300 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2301 channel_it != send_channels_.end(); ++channel_it) {
2302 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2303 extensions)) {
2304 return false;
2305 }
2306 }
2307
2308 send_extensions_ = extensions;
2309 return true;
2310}
2311
2312bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2313 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002314 const RtpHeaderExtension* audio_level_extension =
2315 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002316
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002317 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002318 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002319 audio_level_extension)) {
2320 return false;
2321 }
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002322
2323 const RtpHeaderExtension* send_time_extension =
2324 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002325 if (!SetHeaderExtension(
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002326 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
henrike@webrtc.org79047f92014-03-06 23:46:59 +00002327 send_time_extension)) {
2328 return false;
2329 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002330
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002331 return true;
2332}
2333
2334bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2335 desired_playout_ = playout;
2336 return ChangePlayout(desired_playout_);
2337}
2338
2339bool WebRtcVoiceMediaChannel::PausePlayout() {
2340 return ChangePlayout(false);
2341}
2342
2343bool WebRtcVoiceMediaChannel::ResumePlayout() {
2344 return ChangePlayout(desired_playout_);
2345}
2346
2347bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2348 if (playout_ == playout) {
2349 return true;
2350 }
2351
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002352 // Change the playout of all channels to the new state.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002353 bool result = true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002354 if (receive_channels_.empty()) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002355 // Only toggle the default channel if we don't have any other channels.
2356 result = SetPlayout(voe_channel(), playout);
2357 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002358 for (ChannelMap::iterator it = receive_channels_.begin();
2359 it != receive_channels_.end() && result; ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002360 if (!SetPlayout(it->second->channel(), playout)) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002361 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002362 << it->second->channel() << " failed";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002363 result = false;
2364 }
2365 }
2366
2367 if (result) {
2368 playout_ = playout;
2369 }
2370 return result;
2371}
2372
2373bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2374 desired_send_ = send;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002375 if (!send_channels_.empty())
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002376 return ChangeSend(desired_send_);
2377 return true;
2378}
2379
2380bool WebRtcVoiceMediaChannel::PauseSend() {
2381 return ChangeSend(SEND_NOTHING);
2382}
2383
2384bool WebRtcVoiceMediaChannel::ResumeSend() {
2385 return ChangeSend(desired_send_);
2386}
2387
2388bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2389 if (send_ == send) {
2390 return true;
2391 }
2392
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002393 // Change the settings on each send channel.
2394 if (send == SEND_MICROPHONE)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002395 engine()->SetOptionOverrides(options_);
2396
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002397 // Change the settings on each send channel.
2398 for (ChannelMap::iterator iter = send_channels_.begin();
2399 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002400 if (!ChangeSend(iter->second->channel(), send))
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002401 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002402 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002403
2404 // Clear up the options after stopping sending.
2405 if (send == SEND_NOTHING)
2406 engine()->ClearOptionOverrides();
2407
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002408 send_ = send;
2409 return true;
2410}
2411
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002412bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2413 if (send == SEND_MICROPHONE) {
2414 if (engine()->voe()->base()->StartSend(channel) == -1) {
2415 LOG_RTCERR1(StartSend, channel);
2416 return false;
2417 }
2418 if (engine()->voe()->file() &&
2419 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2420 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2421 return false;
2422 }
2423 } else { // SEND_NOTHING
2424 ASSERT(send == SEND_NOTHING);
2425 if (engine()->voe()->base()->StopSend(channel) == -1) {
2426 LOG_RTCERR1(StopSend, channel);
2427 return false;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002428 }
2429 }
2430
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002431 return true;
2432}
2433
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002434// TODO(ronghuawu): Change this method to return bool.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002435void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2436 if (engine()->voe()->network()->RegisterExternalTransport(
2437 channel, *this) == -1) {
2438 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2439 }
2440
2441 // Enable RTCP (for quality stats and feedback messages)
2442 EnableRtcp(channel);
2443
2444 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2445 ResetRecvCodecs(channel);
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002446
2447 // Set RTP header extension for the new channel.
2448 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002449}
2450
2451bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2452 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2453 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2454 }
2455
2456 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2457 LOG_RTCERR1(DeleteChannel, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002458 return false;
2459 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002460
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002461 return true;
2462}
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002463
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002464bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2465 // If the default channel is already used for sending create a new channel
2466 // otherwise use the default channel for sending.
2467 int channel = GetSendChannelNum(sp.first_ssrc());
2468 if (channel != -1) {
2469 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2470 return false;
2471 }
2472
2473 bool default_channel_is_available = true;
2474 for (ChannelMap::const_iterator iter = send_channels_.begin();
2475 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002476 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002477 default_channel_is_available = false;
2478 break;
2479 }
2480 }
2481 if (default_channel_is_available) {
2482 channel = voe_channel();
2483 } else {
2484 // Create a new channel for sending audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002485 channel = engine()->CreateMediaVoiceChannel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002486 if (channel == -1) {
2487 LOG_RTCERR0(CreateChannel);
2488 return false;
2489 }
2490
2491 ConfigureSendChannel(channel);
2492 }
2493
2494 // Save the channel to send_channels_, so that RemoveSendStream() can still
2495 // delete the channel in case failure happens below.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002496 webrtc::AudioTransport* audio_transport =
2497 engine()->voe()->base()->audio_transport();
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002498 send_channels_.insert(std::make_pair(
2499 sp.first_ssrc(),
2500 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002501
2502 // Set the send (local) SSRC.
2503 // If there are multiple send SSRCs, we can only set the first one here, and
2504 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2505 // (with a codec requires multiple SSRC(s)).
2506 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2507 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2508 return false;
2509 }
2510
2511 // At this point the channel's local SSRC has been updated. If the channel is
2512 // the default channel make sure that all the receive channels are updated as
2513 // well. Receive channels have to have the same SSRC as the default channel in
2514 // order to send receiver reports with this SSRC.
2515 if (IsDefaultChannel(channel)) {
2516 for (ChannelMap::const_iterator it = receive_channels_.begin();
2517 it != receive_channels_.end(); ++it) {
2518 // Only update the SSRC for non-default channels.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002519 if (!IsDefaultChannel(it->second->channel())) {
2520 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002521 sp.first_ssrc()) != 0) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002522 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002523 return false;
2524 }
2525 }
2526 }
2527 }
2528
2529 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
2530 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2531 return false;
2532 }
2533
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002534 // Set the current codecs to be used for the new channel.
2535 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002536 return false;
2537
2538 return ChangeSend(channel, desired_send_);
2539}
2540
2541bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2542 ChannelMap::iterator it = send_channels_.find(ssrc);
2543 if (it == send_channels_.end()) {
2544 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2545 << " which doesn't exist.";
2546 return false;
2547 }
2548
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002549 int channel = it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002550 ChangeSend(channel, SEND_NOTHING);
2551
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002552 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2553 // this will disconnect the audio renderer with the send channel.
2554 delete it->second;
2555 send_channels_.erase(it);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002556
2557 if (IsDefaultChannel(channel)) {
2558 // Do not delete the default channel since the receive channels depend on
2559 // the default channel, recycle it instead.
2560 ChangeSend(channel, SEND_NOTHING);
2561 } else {
2562 // Clean up and delete the send channel.
2563 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2564 << " with VoiceEngine channel #" << channel << ".";
2565 if (!DeleteChannel(channel))
2566 return false;
2567 }
2568
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002569 if (send_channels_.empty())
2570 ChangeSend(SEND_NOTHING);
2571
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002572 return true;
2573}
2574
2575bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002576 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002577
2578 if (!VERIFY(sp.ssrcs.size() == 1))
2579 return false;
2580 uint32 ssrc = sp.first_ssrc();
2581
wu@webrtc.org78187522013-10-07 23:32:02 +00002582 if (ssrc == 0) {
2583 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2584 return false;
2585 }
2586
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002587 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2588 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002589 return false;
2590 }
2591
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002592 // Reuse default channel for recv stream in non-conference mode call
2593 // when the default channel is not being used.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002594 webrtc::AudioTransport* audio_transport =
2595 engine()->voe()->base()->audio_transport();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002596 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2597 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2598 << " reuse default channel";
2599 default_receive_ssrc_ = sp.first_ssrc();
2600 receive_channels_.insert(std::make_pair(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002601 default_receive_ssrc_,
2602 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002603 return SetPlayout(voe_channel(), playout_);
2604 }
2605
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002606 // Create a new channel for receiving audio data.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00002607 int channel = engine()->CreateMediaVoiceChannel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002608 if (channel == -1) {
2609 LOG_RTCERR0(CreateChannel);
2610 return false;
2611 }
2612
wu@webrtc.org78187522013-10-07 23:32:02 +00002613 if (!ConfigureRecvChannel(channel)) {
2614 DeleteChannel(channel);
2615 return false;
2616 }
2617
2618 receive_channels_.insert(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002619 std::make_pair(
2620 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
wu@webrtc.org78187522013-10-07 23:32:02 +00002621
2622 LOG(LS_INFO) << "New audio stream " << ssrc
2623 << " registered to VoiceEngine channel #"
2624 << channel << ".";
2625 return true;
2626}
2627
2628bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002629 // Configure to use external transport, like our default channel.
2630 if (engine()->voe()->network()->RegisterExternalTransport(
2631 channel, *this) == -1) {
2632 LOG_RTCERR2(SetExternalTransport, channel, this);
2633 return false;
2634 }
2635
2636 // Use the same SSRC as our default channel (so the RTCP reports are correct).
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002637 unsigned int send_ssrc = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002638 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2639 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002640 LOG_RTCERR1(GetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002641 return false;
2642 }
2643 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00002644 LOG_RTCERR1(SetSendSSRC, channel);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002645 return false;
2646 }
2647
2648 // Use the same recv payload types as our default channel.
2649 ResetRecvCodecs(channel);
2650 if (!recv_codecs_.empty()) {
2651 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2652 it != recv_codecs_.end(); ++it) {
2653 webrtc::CodecInst voe_codec;
2654 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2655 voe_codec.pltype = it->id;
2656 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2657 if (engine()->voe()->codec()->GetRecPayloadType(
2658 voe_channel(), voe_codec) != -1) {
2659 if (engine()->voe()->codec()->SetRecPayloadType(
2660 channel, voe_codec) == -1) {
2661 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2662 return false;
2663 }
2664 }
2665 }
2666 }
2667 }
2668
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002669 if (InConferenceMode()) {
2670 // To be in par with the video, voe_channel() is not used for receiving in
2671 // a conference call.
2672 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2673 // This is the first stream in a multi user meeting. We can now
2674 // disable playback of the default stream. This since the default
2675 // stream will probably have received some initial packets before
2676 // the new stream was added. This will mean that the CN state from
2677 // the default channel will be mixed in with the other streams
2678 // throughout the whole meeting, which might be disturbing.
2679 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2680 SetPlayout(voe_channel(), false);
2681 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002682 }
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002683 SetNack(channel, nack_enabled_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002684
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00002685 // Set RTP header extension for the new channel.
2686 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2687 return false;
2688 }
2689
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002690 return SetPlayout(channel, playout_);
2691}
2692
2693bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002694 talk_base::CritScope lock(&receive_channels_cs_);
2695 ChannelMap::iterator it = receive_channels_.find(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002696 if (it == receive_channels_.end()) {
2697 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2698 << " which doesn't exist.";
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002699 return false;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002700 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002701
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002702 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2703 // will disconnect the audio renderer with the receive channel.
2704 // Cache the channel before the deletion.
2705 const int channel = it->second->channel();
2706 delete it->second;
2707 receive_channels_.erase(it);
2708
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002709 if (ssrc == default_receive_ssrc_) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002710 ASSERT(IsDefaultChannel(channel));
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002711 // Recycle the default channel is for recv stream.
2712 if (playout_)
2713 SetPlayout(voe_channel(), false);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002714
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002715 default_receive_ssrc_ = 0;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002716 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002717 }
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002718
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002719 LOG(LS_INFO) << "Removing audio stream " << ssrc
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002720 << " with VoiceEngine channel #" << channel << ".";
2721 if (!DeleteChannel(channel))
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002722 return false;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002723
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002724 bool enable_default_channel_playout = false;
2725 if (receive_channels_.empty()) {
2726 // The last stream was removed. We can now enable the default
2727 // channel for new channels to be played out immediately without
2728 // waiting for AddStream messages.
2729 // We do this for both conference mode and non-conference mode.
2730 // TODO(oja): Does the default channel still have it's CN state?
2731 enable_default_channel_playout = true;
2732 }
2733 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2734 default_receive_ssrc_ != 0) {
2735 // Only the default channel is active, enable the playout on default
2736 // channel.
2737 enable_default_channel_playout = true;
2738 }
2739 if (enable_default_channel_playout && playout_) {
2740 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2741 SetPlayout(voe_channel(), true);
2742 }
2743
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002744 return true;
2745}
2746
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002747bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2748 AudioRenderer* renderer) {
2749 ChannelMap::iterator it = receive_channels_.find(ssrc);
2750 if (it == receive_channels_.end()) {
2751 if (renderer) {
2752 // Return an error if trying to set a valid renderer with an invalid ssrc.
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002753 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002754 return false;
2755 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002756
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002757 // The channel likely has gone away, do nothing.
2758 return true;
2759 }
2760
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002761 if (renderer)
2762 it->second->Start(renderer);
2763 else
2764 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002765
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002766 return true;
2767}
2768
2769bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2770 AudioRenderer* renderer) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00002771 ChannelMap::iterator it = send_channels_.find(ssrc);
2772 if (it == send_channels_.end()) {
2773 if (renderer) {
2774 // Return an error if trying to set a valid renderer with an invalid ssrc.
2775 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2776 return false;
2777 }
2778
2779 // The channel likely has gone away, do nothing.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002780 return true;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002781 }
2782
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002783 if (renderer)
2784 it->second->Start(renderer);
2785 else
2786 it->second->Stop();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002787
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002788 return true;
2789}
2790
2791bool WebRtcVoiceMediaChannel::GetActiveStreams(
2792 AudioInfo::StreamList* actives) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002793 // In conference mode, the default channel should not be in
2794 // |receive_channels_|.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002795 actives->clear();
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002796 for (ChannelMap::iterator it = receive_channels_.begin();
2797 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002798 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002799 if (level > 0) {
2800 actives->push_back(std::make_pair(it->first, level));
2801 }
2802 }
2803 return true;
2804}
2805
2806int WebRtcVoiceMediaChannel::GetOutputLevel() {
2807 // return the highest output level of all streams
2808 int highest = GetOutputLevel(voe_channel());
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002809 for (ChannelMap::iterator it = receive_channels_.begin();
2810 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002811 int level = GetOutputLevel(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002812 highest = talk_base::_max(level, highest);
2813 }
2814 return highest;
2815}
2816
2817int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2818 int ret;
2819 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2820 // In case of error, log the info and continue
2821 LOG_RTCERR0(TimeSinceLastTyping);
2822 ret = -1;
2823 } else {
2824 ret *= 1000; // We return ms, webrtc returns seconds.
2825 }
2826 return ret;
2827}
2828
2829void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2830 int cost_per_typing, int reporting_threshold, int penalty_decay,
2831 int type_event_delay) {
2832 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2833 time_window, cost_per_typing,
2834 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2835 // In case of error, log the info and continue
2836 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2837 cost_per_typing, reporting_threshold, penalty_decay,
2838 type_event_delay);
2839 }
2840}
2841
2842bool WebRtcVoiceMediaChannel::SetOutputScaling(
2843 uint32 ssrc, double left, double right) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002844 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002845 // Collect the channels to scale the output volume.
2846 std::vector<int> channels;
2847 if (0 == ssrc) { // Collect all channels, including the default one.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002848 // Default channel is not in receive_channels_ if it is not being used for
2849 // playout.
2850 if (default_receive_ssrc_ == 0)
2851 channels.push_back(voe_channel());
2852 for (ChannelMap::const_iterator it = receive_channels_.begin();
2853 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002854 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002855 }
2856 } else { // Collect only the channel of the specified ssrc.
2857 int channel = GetReceiveChannelNum(ssrc);
2858 if (-1 == channel) {
2859 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2860 return false;
2861 }
2862 channels.push_back(channel);
2863 }
2864
2865 // Scale the output volume for the collected channels. We first normalize to
2866 // scale the volume and then set the left and right pan.
2867 float scale = static_cast<float>(talk_base::_max(left, right));
2868 if (scale > 0.0001f) {
2869 left /= scale;
2870 right /= scale;
2871 }
2872 for (std::vector<int>::const_iterator it = channels.begin();
2873 it != channels.end(); ++it) {
2874 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2875 *it, scale)) {
2876 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2877 return false;
2878 }
2879 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2880 *it, static_cast<float>(left), static_cast<float>(right))) {
2881 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2882 // Do not return if fails. SetOutputVolumePan is not available for all
2883 // pltforms.
2884 }
2885 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2886 << " right=" << right * scale
2887 << " for channel " << *it << " and ssrc " << ssrc;
2888 }
2889 return true;
2890}
2891
2892bool WebRtcVoiceMediaChannel::GetOutputScaling(
2893 uint32 ssrc, double* left, double* right) {
2894 if (!left || !right) return false;
2895
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00002896 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002897 // Determine which channel based on ssrc.
2898 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2899 if (channel == -1) {
2900 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2901 return false;
2902 }
2903
2904 float scaling;
2905 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2906 channel, scaling)) {
2907 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2908 return false;
2909 }
2910
2911 float left_pan;
2912 float right_pan;
2913 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2914 channel, left_pan, right_pan)) {
2915 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2916 // If GetOutputVolumePan fails, we use the default left and right pan.
2917 left_pan = 1.0f;
2918 right_pan = 1.0f;
2919 }
2920
2921 *left = scaling * left_pan;
2922 *right = scaling * right_pan;
2923 return true;
2924}
2925
2926bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2927 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2928 return true;
2929}
2930
2931bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2932 bool play, bool loop) {
2933 if (!ringback_tone_) {
2934 return false;
2935 }
2936
2937 // The voe file api is not available in chrome.
2938 if (!engine()->voe()->file()) {
2939 return false;
2940 }
2941
2942 // Determine which VoiceEngine channel to play on.
2943 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2944 if (channel == -1) {
2945 return false;
2946 }
2947
2948 // Make sure the ringtone is cued properly, and play it out.
2949 if (play) {
2950 ringback_tone_->set_loop(loop);
2951 ringback_tone_->Rewind();
2952 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2953 ringback_tone_.get()) == -1) {
2954 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2955 LOG(LS_ERROR) << "Unable to start ringback tone";
2956 return false;
2957 }
2958 ringback_channels_.insert(channel);
2959 LOG(LS_INFO) << "Started ringback on channel " << channel;
2960 } else {
2961 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2962 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2963 LOG_RTCERR1(StopPlayingFileLocally, channel);
2964 return false;
2965 }
2966 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2967 ringback_channels_.erase(channel);
2968 }
2969
2970 return true;
2971}
2972
2973bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2974 return dtmf_allowed_;
2975}
2976
2977bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2978 int duration, int flags) {
2979 if (!dtmf_allowed_) {
2980 return false;
2981 }
2982
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002983 // Send the event.
2984 if (flags & cricket::DF_SEND) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002985 int channel = -1;
2986 if (ssrc == 0) {
2987 bool default_channel_is_inuse = false;
2988 for (ChannelMap::const_iterator iter = send_channels_.begin();
2989 iter != send_channels_.end(); ++iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002990 if (IsDefaultChannel(iter->second->channel())) {
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002991 default_channel_is_inuse = true;
2992 break;
2993 }
2994 }
2995 if (default_channel_is_inuse) {
2996 channel = voe_channel();
2997 } else if (!send_channels_.empty()) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00002998 channel = send_channels_.begin()->second->channel();
wu@webrtc.orgcadf9042013-08-30 21:24:16 +00002999 }
3000 } else {
3001 channel = GetSendChannelNum(ssrc);
3002 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003003 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003004 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
3005 << ssrc << " is not in use.";
3006 return false;
3007 }
3008 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003009 if (engine()->voe()->dtmf()->SendTelephoneEvent(
3010 channel, event, true, duration) == -1) {
3011 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003012 return false;
3013 }
3014 }
3015
3016 // Play the event.
3017 if (flags & cricket::DF_PLAY) {
3018 // Play DTMF tone locally.
3019 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
3020 LOG_RTCERR2(PlayDtmfTone, event, duration);
3021 return false;
3022 }
3023 }
3024
3025 return true;
3026}
3027
wu@webrtc.orga9890802013-12-13 00:21:03 +00003028void WebRtcVoiceMediaChannel::OnPacketReceived(
3029 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003030 // Pick which channel to send this packet to. If this packet doesn't match
3031 // any multiplexed streams, just send it to the default channel. Otherwise,
3032 // send it to the specific decoder instance for that stream.
3033 int which_channel = GetReceiveChannelNum(
3034 ParseSsrc(packet->data(), packet->length(), false));
3035 if (which_channel == -1) {
3036 which_channel = voe_channel();
3037 }
3038
3039 // Stop any ringback that might be playing on the channel.
3040 // It's possible the ringback has already stopped, ih which case we'll just
3041 // use the opportunity to remove the channel from ringback_channels_.
3042 if (engine()->voe()->file()) {
3043 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3044 if (it != ringback_channels_.end()) {
3045 if (engine()->voe()->file()->IsPlayingFileLocally(
3046 which_channel) == 1) {
3047 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3048 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3049 << " due to incoming media";
3050 }
3051 ringback_channels_.erase(which_channel);
3052 }
3053 }
3054
3055 // Pass it off to the decoder.
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003056 engine()->voe()->network()->ReceivedRTPPacket(
3057 which_channel,
3058 packet->data(),
3059 static_cast<unsigned int>(packet->length()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003060}
3061
wu@webrtc.orga9890802013-12-13 00:21:03 +00003062void WebRtcVoiceMediaChannel::OnRtcpReceived(
3063 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003064 // Sending channels need all RTCP packets with feedback information.
3065 // Even sender reports can contain attached report blocks.
3066 // Receiving channels need sender reports in order to create
3067 // correct receiver reports.
3068 int type = 0;
3069 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3070 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3071 return;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003072 }
3073
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003074 // If it is a sender report, find the channel that is listening.
3075 bool has_sent_to_default_channel = false;
3076 if (type == kRtcpTypeSR) {
3077 int which_channel = GetReceiveChannelNum(
3078 ParseSsrc(packet->data(), packet->length(), true));
3079 if (which_channel != -1) {
3080 engine()->voe()->network()->ReceivedRTCPPacket(
3081 which_channel,
3082 packet->data(),
3083 static_cast<unsigned int>(packet->length()));
3084
3085 if (IsDefaultChannel(which_channel))
3086 has_sent_to_default_channel = true;
3087 }
3088 }
3089
3090 // SR may continue RR and any RR entry may correspond to any one of the send
3091 // channels. So all RTCP packets must be forwarded all send channels. VoE
3092 // will filter out RR internally.
3093 for (ChannelMap::iterator iter = send_channels_.begin();
3094 iter != send_channels_.end(); ++iter) {
3095 // Make sure not sending the same packet to default channel more than once.
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003096 if (IsDefaultChannel(iter->second->channel()) &&
3097 has_sent_to_default_channel)
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003098 continue;
3099
3100 engine()->voe()->network()->ReceivedRTCPPacket(
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003101 iter->second->channel(),
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003102 packet->data(),
3103 static_cast<unsigned int>(packet->length()));
3104 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003105}
3106
3107bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003108 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3109 if (channel == -1) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003110 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3111 return false;
3112 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003113 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3114 LOG_RTCERR2(SetInputMute, channel, muted);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003115 return false;
3116 }
3117 return true;
3118}
3119
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003120bool WebRtcVoiceMediaChannel::SetStartSendBandwidth(int bps) {
3121 // TODO(andresp): Add support for setting an independent start bandwidth when
3122 // bandwidth estimation is enabled for voice engine.
3123 return false;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003124}
3125
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003126bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
3127 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
3128
3129 return SetSendBandwidthInternal(bps);
3130}
3131
3132bool WebRtcVoiceMediaChannel::SetSendBandwidthInternal(int bps) {
3133 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBandwidthInternal.";
3134
3135 send_bw_setting_ = true;
3136 send_bw_bps_ = bps;
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003137
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003138 if (!send_codec_) {
wu@webrtc.org1d1ffc92013-10-16 18:12:02 +00003139 LOG(LS_INFO) << "The send codec has not been set up yet. "
3140 << "The send bandwidth setting will be applied later.";
3141 return true;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003142 }
3143
3144 // Bandwidth is auto by default.
sergeyu@chromium.org4b26e2e2014-01-15 23:15:54 +00003145 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3146 // SetMaxSendBandwith(0), the second call removes the previous limit.
3147 if (bps <= 0)
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003148 return true;
3149
3150 webrtc::CodecInst codec = *send_codec_;
3151 bool is_multi_rate = IsCodecMultiRate(codec);
3152
3153 if (is_multi_rate) {
3154 // If codec is multi-rate then just set the bitrate.
3155 codec.rate = bps;
3156 if (!SetSendCodec(codec)) {
3157 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3158 << " to bitrate " << bps << " bps.";
3159 return false;
3160 }
3161 return true;
3162 } else {
3163 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3164 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3165 // fixed bitrate then ignore.
3166 if (bps < codec.rate) {
3167 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3168 << " to bitrate " << bps << " bps"
3169 << ", requires at least " << codec.rate << " bps.";
3170 return false;
3171 }
3172 return true;
3173 }
3174}
3175
3176bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003177 bool echo_metrics_on = false;
3178 // These can take on valid negative values, so use the lowest possible level
3179 // as default rather than -1.
3180 int echo_return_loss = -100;
3181 int echo_return_loss_enhancement = -100;
3182 // These can also be negative, but in practice -1 is only used to signal
3183 // insufficient data, since the resolution is limited to multiples of 4 ms.
3184 int echo_delay_median_ms = -1;
3185 int echo_delay_std_ms = -1;
3186 if (engine()->voe()->processing()->GetEcMetricsStatus(
3187 echo_metrics_on) != -1 && echo_metrics_on) {
3188 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3189 // here, but it appears to be unsuitable currently. Revisit after this is
3190 // investigated: http://b/issue?id=5666755
3191 int erl, erle, rerl, anlp;
3192 if (engine()->voe()->processing()->GetEchoMetrics(
3193 erl, erle, rerl, anlp) != -1) {
3194 echo_return_loss = erl;
3195 echo_return_loss_enhancement = erle;
3196 }
3197
3198 int median, std;
3199 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3200 echo_delay_median_ms = median;
3201 echo_delay_std_ms = std;
3202 }
3203 }
3204
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003205 webrtc::CallStatistics cs;
3206 unsigned int ssrc;
3207 webrtc::CodecInst codec;
3208 unsigned int level;
3209
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003210 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3211 channel_iter != send_channels_.end(); ++channel_iter) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003212 const int channel = channel_iter->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003213
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003214 // Fill in the sender info, based on what we know, and what the
3215 // remote side told us it got from its RTCP report.
3216 VoiceSenderInfo sinfo;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003217
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003218 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3219 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3220 continue;
3221 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003222
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003223 sinfo.add_ssrc(ssrc);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003224 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3225 sinfo.bytes_sent = cs.bytesSent;
3226 sinfo.packets_sent = cs.packetsSent;
3227 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3228 // returns 0 to indicate an error value.
3229 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3230
3231 // Get data from the last remote RTCP report. Use default values if no data
3232 // available.
3233 sinfo.fraction_lost = -1.0;
3234 sinfo.jitter_ms = -1;
3235 sinfo.packets_lost = -1;
3236 sinfo.ext_seqnum = -1;
3237 std::vector<webrtc::ReportBlock> receive_blocks;
3238 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3239 channel, &receive_blocks) != -1 &&
3240 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3241 std::vector<webrtc::ReportBlock>::iterator iter;
3242 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3243 ++iter) {
3244 // Lookup report for send ssrc only.
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003245 if (iter->source_SSRC == sinfo.ssrc()) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003246 // Convert Q8 to floating point.
3247 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3248 // Convert samples to milliseconds.
3249 if (codec.plfreq / 1000 > 0) {
3250 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3251 }
3252 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3253 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3254 break;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003255 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003256 }
3257 }
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003258
3259 // Local speech level.
3260 sinfo.audio_level = (engine()->voe()->volume()->
3261 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3262
3263 // TODO(xians): We are injecting the same APM logging to all the send
3264 // channels here because there is no good way to know which send channel
3265 // is using the APM. The correct fix is to allow the send channels to have
3266 // their own APM so that we can feed the correct APM logging to different
3267 // send channels. See issue crbug/264611 .
3268 sinfo.echo_return_loss = echo_return_loss;
3269 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3270 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3271 sinfo.echo_delay_std_ms = echo_delay_std_ms;
mallinath@webrtc.orga27be8e2013-09-27 23:04:10 +00003272 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3273 sinfo.aec_quality_min = -1;
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003274 sinfo.typing_noise_detected = typing_noise_detected_;
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003275
3276 info->senders.push_back(sinfo);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003277 }
3278
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003279 // Build the list of receivers, one for each receiving channel, or 1 in
3280 // a 1:1 call.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003281 std::vector<int> channels;
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003282 for (ChannelMap::const_iterator it = receive_channels_.begin();
3283 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003284 channels.push_back(it->second->channel());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003285 }
3286 if (channels.empty()) {
3287 channels.push_back(voe_channel());
3288 }
3289
3290 // Get the SSRC and stats for each receiver, based on our own calculations.
3291 for (std::vector<int>::const_iterator it = channels.begin();
3292 it != channels.end(); ++it) {
3293 memset(&cs, 0, sizeof(cs));
3294 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3295 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3296 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3297 VoiceReceiverInfo rinfo;
sergeyu@chromium.org5bc25c42013-12-05 00:24:06 +00003298 rinfo.add_ssrc(ssrc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003299 rinfo.bytes_rcvd = cs.bytesReceived;
3300 rinfo.packets_rcvd = cs.packetsReceived;
3301 // The next four fields are from the most recently sent RTCP report.
3302 // Convert Q8 to floating point.
3303 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3304 rinfo.packets_lost = cs.cumulativeLost;
3305 rinfo.ext_seqnum = cs.extendedMax;
buildbot@webrtc.orgb525a9d2014-06-03 09:42:15 +00003306#ifdef USE_WEBRTC_DEV_BRANCH
3307 rinfo.capture_start_ntp_time_ms = cs.capture_start_ntp_time_ms_;
3308#endif
buildbot@webrtc.org7e71b772014-06-13 01:14:01 +00003309 if (codec.pltype != -1) {
3310 rinfo.codec_name = codec.plname;
3311 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003312 // Convert samples to milliseconds.
3313 if (codec.plfreq / 1000 > 0) {
3314 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3315 }
3316
3317 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3318 webrtc::NetworkStatistics ns;
3319 if (engine()->voe()->neteq() &&
3320 engine()->voe()->neteq()->GetNetworkStatistics(
3321 *it, ns) != -1) {
3322 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3323 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3324 rinfo.expand_rate =
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003325 static_cast<float>(ns.currentExpandRate) / (1 << 14);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003326 }
henrike@webrtc.orgb8c254a2014-02-14 23:38:45 +00003327
3328 webrtc::AudioDecodingCallStats ds;
3329 if (engine()->voe()->neteq() &&
3330 engine()->voe()->neteq()->GetDecodingCallStatistics(
3331 *it, &ds) != -1) {
3332 rinfo.decoding_calls_to_silence_generator =
3333 ds.calls_to_silence_generator;
3334 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3335 rinfo.decoding_normal = ds.decoded_normal;
3336 rinfo.decoding_plc = ds.decoded_plc;
3337 rinfo.decoding_cng = ds.decoded_cng;
3338 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3339 }
3340
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003341 if (engine()->voe()->sync()) {
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003342 int jitter_buffer_delay_ms = 0;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003343 int playout_buffer_delay_ms = 0;
3344 engine()->voe()->sync()->GetDelayEstimate(
sergeyu@chromium.orga23f0ca2013-11-13 22:48:52 +00003345 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3346 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3347 playout_buffer_delay_ms;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003348 }
3349
3350 // Get speech level.
3351 rinfo.audio_level = (engine()->voe()->volume()->
3352 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3353 info->receivers.push_back(rinfo);
3354 }
3355 }
3356
3357 return true;
3358}
3359
3360void WebRtcVoiceMediaChannel::GetLastMediaError(
3361 uint32* ssrc, VoiceMediaChannel::Error* error) {
3362 ASSERT(ssrc != NULL);
3363 ASSERT(error != NULL);
3364 FindSsrc(voe_channel(), ssrc);
3365 *error = WebRtcErrorToChannelError(GetLastEngineError());
3366}
3367
3368bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003369 talk_base::CritScope lock(&receive_channels_cs_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003370 ASSERT(ssrc != NULL);
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003371 if (channel_num == -1 && send_ != SEND_NOTHING) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003372 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3373 // This means the error is not limited to a specific channel. Signal the
3374 // message using ssrc=0. If the current channel is sending, use this
3375 // channel for sending the message.
3376 *ssrc = 0;
3377 return true;
3378 } else {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003379 // Check whether this is a sending channel.
3380 for (ChannelMap::const_iterator it = send_channels_.begin();
3381 it != send_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003382 if (it->second->channel() == channel_num) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003383 // This is a sending channel.
3384 uint32 local_ssrc = 0;
3385 if (engine()->voe()->rtp()->GetLocalSSRC(
3386 channel_num, local_ssrc) != -1) {
3387 *ssrc = local_ssrc;
3388 }
3389 return true;
3390 }
3391 }
3392
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003393 // Check whether this is a receiving channel.
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003394 for (ChannelMap::const_iterator it = receive_channels_.begin();
3395 it != receive_channels_.end(); ++it) {
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003396 if (it->second->channel() == channel_num) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003397 *ssrc = it->first;
3398 return true;
3399 }
3400 }
3401 }
3402 return false;
3403}
3404
3405void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
wu@webrtc.org967bfff2013-09-19 05:49:50 +00003406 if (error == VE_TYPING_NOISE_WARNING) {
3407 typing_noise_detected_ = true;
3408 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3409 typing_noise_detected_ = false;
3410 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003411 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3412}
3413
3414int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3415 unsigned int ulevel;
3416 int ret =
3417 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3418 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3419}
3420
3421int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
henrike@webrtc.org1e09a712013-07-26 19:17:59 +00003422 ChannelMap::iterator it = receive_channels_.find(ssrc);
3423 if (it != receive_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003424 return it->second->channel();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003425 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3426}
3427
3428int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003429 ChannelMap::iterator it = send_channels_.find(ssrc);
3430 if (it != send_channels_.end())
mallinath@webrtc.org67ee6b92014-02-03 16:57:16 +00003431 return it->second->channel();
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003432
3433 return -1;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003434}
3435
3436bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3437 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3438 // Get the RED encodings from the parameter with no name. This may
3439 // change based on what is discussed on the Jingle list.
3440 // The encoding parameter is of the form "a/b"; we only support where
3441 // a == b. Verify this and parse out the value into red_pt.
3442 // If the parameter value is absent (as it will be until we wire up the
3443 // signaling of this message), use the second codec specified (i.e. the
3444 // one after "red") as the encoding parameter.
3445 int red_pt = -1;
3446 std::string red_params;
3447 CodecParameterMap::const_iterator it = red_codec.params.find("");
3448 if (it != red_codec.params.end()) {
3449 red_params = it->second;
3450 std::vector<std::string> red_pts;
3451 if (talk_base::split(red_params, '/', &red_pts) != 2 ||
3452 red_pts[0] != red_pts[1] ||
3453 !talk_base::FromString(red_pts[0], &red_pt)) {
3454 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3455 return false;
3456 }
3457 } else if (red_codec.params.empty()) {
3458 LOG(LS_WARNING) << "RED params not present, using defaults";
3459 if (all_codecs.size() > 1) {
3460 red_pt = all_codecs[1].id;
3461 }
3462 }
3463
3464 // Try to find red_pt in |codecs|.
3465 std::vector<AudioCodec>::const_iterator codec;
3466 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3467 if (codec->id == red_pt)
3468 break;
3469 }
3470
3471 // If we find the right codec, that will be the codec we pass to
3472 // SetSendCodec, with the desired payload type.
3473 if (codec != all_codecs.end() &&
3474 engine()->FindWebRtcCodec(*codec, send_codec)) {
3475 } else {
3476 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3477 return false;
3478 }
3479
3480 return true;
3481}
3482
3483bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3484 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
wu@webrtc.org9dba5252013-08-05 20:36:57 +00003485 LOG_RTCERR2(SetRTCPStatus, channel, 1);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003486 return false;
3487 }
3488 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3489 // what we want to do with them.
3490 // engine()->voe().EnableVQMon(voe_channel(), true);
3491 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3492 return true;
3493}
3494
3495bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3496 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3497 for (int i = 0; i < ncodecs; ++i) {
3498 webrtc::CodecInst voe_codec;
3499 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3500 voe_codec.pltype = -1;
3501 if (engine()->voe()->codec()->SetRecPayloadType(
3502 channel, voe_codec) == -1) {
3503 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3504 return false;
3505 }
3506 }
3507 }
3508 return true;
3509}
3510
3511bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3512 if (playout) {
3513 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3514 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3515 LOG_RTCERR1(StartPlayout, channel);
3516 return false;
3517 }
3518 } else {
3519 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3520 engine()->voe()->base()->StopPlayout(channel);
3521 }
3522 return true;
3523}
3524
3525uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3526 bool rtcp) {
3527 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3528 uint32 ssrc = 0;
3529 if (len >= (ssrc_pos + sizeof(ssrc))) {
3530 ssrc = talk_base::GetBE32(static_cast<const char*>(data) + ssrc_pos);
3531 }
3532 return ssrc;
3533}
3534
3535// Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3536VoiceMediaChannel::Error
3537 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3538 switch (err_code) {
3539 case 0:
3540 return ERROR_NONE;
3541 case VE_CANNOT_START_RECORDING:
3542 case VE_MIC_VOL_ERROR:
3543 case VE_GET_MIC_VOL_ERROR:
3544 case VE_CANNOT_ACCESS_MIC_VOL:
3545 return ERROR_REC_DEVICE_OPEN_FAILED;
3546 case VE_SATURATION_WARNING:
3547 return ERROR_REC_DEVICE_SATURATION;
3548 case VE_REC_DEVICE_REMOVED:
3549 return ERROR_REC_DEVICE_REMOVED;
3550 case VE_RUNTIME_REC_WARNING:
3551 case VE_RUNTIME_REC_ERROR:
3552 return ERROR_REC_RUNTIME_ERROR;
3553 case VE_CANNOT_START_PLAYOUT:
3554 case VE_SPEAKER_VOL_ERROR:
3555 case VE_GET_SPEAKER_VOL_ERROR:
3556 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3557 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3558 case VE_RUNTIME_PLAY_WARNING:
3559 case VE_RUNTIME_PLAY_ERROR:
3560 return ERROR_PLAY_RUNTIME_ERROR;
3561 case VE_TYPING_NOISE_WARNING:
3562 return ERROR_REC_TYPING_NOISE_DETECTED;
3563 default:
3564 return VoiceMediaChannel::ERROR_OTHER;
3565 }
3566}
3567
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003568bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3569 int channel_id, const RtpHeaderExtension* extension) {
3570 bool enable = false;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003571 int id = 0;
3572 std::string uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003573 if (extension) {
3574 enable = true;
3575 id = extension->id;
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003576 uri = extension->uri;
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003577 }
3578 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
buildbot@webrtc.org150835e2014-05-06 15:54:38 +00003579 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
henrike@webrtc.org79047f92014-03-06 23:46:59 +00003580 return false;
3581 }
3582 return true;
3583}
3584
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003585int WebRtcSoundclipStream::Read(void *buf, int len) {
3586 size_t res = 0;
3587 mem_.Read(buf, len, &res, NULL);
henrike@webrtc.org28654cb2013-07-22 21:07:49 +00003588 return static_cast<int>(res);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003589}
3590
3591int WebRtcSoundclipStream::Rewind() {
3592 mem_.Rewind();
3593 // Return -1 to keep VoiceEngine from looping.
3594 return (loop_) ? 0 : -1;
3595}
3596
3597} // namespace cricket
3598
3599#endif // HAVE_WEBRTC_VOICE