3 * Copyright 2004 Google Inc.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
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.
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.
32 #ifdef HAVE_WEBRTC_VOICE
34 #include "talk/media/webrtc/webrtcvoiceengine.h"
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"
53 #include "webrtc/common.h"
54 #include "webrtc/modules/audio_processing/include/audio_processing.h"
57 #include <objbase.h> // NOLINT
70 static 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 },
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).
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).
95 // On Windows systems which only support Wave Audio style default, uses either
96 // -1 or 0 to select the default device.
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.
104 static const int kDefaultAudioDeviceId = -1;
105 static const int kDefaultSoundclipDeviceId = -2;
107 static const int kDefaultAudioDeviceId = 0;
110 // extension header for audio levels, as defined in
111 // http://tools.ietf.org/html/draft-ietf-avtext-client-to-mixer-audio-level-03
112 static const char kRtpAudioLevelHeaderExtension[] =
113 "urn:ietf:params:rtp-hdrext:ssrc-audio-level";
114 static const int kRtpAudioLevelHeaderExtensionId = 1;
116 static const char kIsacCodecName[] = "ISAC";
117 static const char kL16CodecName[] = "L16";
118 // Codec parameters for Opus.
119 static const int kOpusMonoBitrate = 32000;
120 // Parameter used for NACK.
121 // This value is equivalent to 5 seconds of audio data at 20 ms per packet.
122 static const int kNackMaxPackets = 250;
123 static const int kOpusStereoBitrate = 64000;
124 // draft-spittka-payload-rtp-opus-03
125 // Opus bitrate should be in the range between 6000 and 510000.
126 static const int kOpusMinBitrate = 6000;
127 static const int kOpusMaxBitrate = 510000;
128 // Default audio dscp value.
129 // See http://tools.ietf.org/html/rfc2474 for details.
130 // See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
131 static const talk_base::DiffServCodePoint kAudioDscpValue = talk_base::DSCP_EF;
133 // Ensure we open the file in a writeable path on ChromeOS and Android. This
134 // workaround can be removed when it's possible to specify a filename for audio
135 // option based AEC dumps.
137 // TODO(grunell): Use a string in the options instead of hardcoding it here
138 // and let the embedder choose the filename (crbug.com/264223).
140 // NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
142 #if defined(CHROMEOS)
143 static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
144 #elif defined(ANDROID)
145 static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
147 static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
150 // Dumps an AudioCodec in RFC 2327-ish format.
151 static std::string ToString(const AudioCodec& codec) {
152 std::stringstream ss;
153 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
154 << " (" << codec.id << ")";
157 static std::string ToString(const webrtc::CodecInst& codec) {
158 std::stringstream ss;
159 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
160 << " (" << codec.pltype << ")";
164 static void LogMultiline(talk_base::LoggingSeverity sev, char* text) {
165 const char* delim = "\r\n";
166 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
171 // Severity is an integer because it comes is assumed to be from command line.
172 static int SeverityToFilter(int severity) {
173 int filter = webrtc::kTraceNone;
175 case talk_base::LS_VERBOSE:
176 filter |= webrtc::kTraceAll;
177 case talk_base::LS_INFO:
178 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
179 case talk_base::LS_WARNING:
180 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
181 case talk_base::LS_ERROR:
182 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
187 static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
188 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
189 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
190 kCodecPrefs[i].clockrate == codec.plfreq) {
191 return kCodecPrefs[i].is_multi_rate;
197 static bool FindCodec(const std::vector<AudioCodec>& codecs,
198 const AudioCodec& codec,
199 AudioCodec* found_codec) {
200 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
201 it != codecs.end(); ++it) {
202 if (it->Matches(codec)) {
203 if (found_codec != NULL) {
212 static bool IsNackEnabled(const AudioCodec& codec) {
213 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
217 // Gets the default set of options applied to the engine. Historically, these
218 // were supplied as a combination of flags from the channel manager (ec, agc,
219 // ns, and highpass) and the rest hardcoded in InitInternal.
220 static AudioOptions GetDefaultEngineOptions() {
221 AudioOptions options;
222 options.echo_cancellation.Set(true);
223 options.auto_gain_control.Set(true);
224 options.noise_suppression.Set(true);
225 options.highpass_filter.Set(true);
226 options.stereo_swapping.Set(false);
227 options.typing_detection.Set(true);
228 options.conference_mode.Set(false);
229 options.adjust_agc_delta.Set(0);
230 options.experimental_agc.Set(false);
231 options.experimental_aec.Set(false);
232 options.experimental_ns.Set(false);
233 options.aec_dump.Set(false);
234 options.experimental_acm.Set(false);
238 class WebRtcSoundclipMedia : public SoundclipMedia {
240 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
241 : engine_(engine), webrtc_channel_(-1) {
242 engine_->RegisterSoundclip(this);
245 virtual ~WebRtcSoundclipMedia() {
246 engine_->UnregisterSoundclip(this);
247 if (webrtc_channel_ != -1) {
248 // We shouldn't have to call Disable() here. DeleteChannel() should call
249 // StopPlayout() while deleting the channel. We should fix the bug
250 // inside WebRTC and remove the Disable() call bellow. This work is
251 // tracked by bug http://b/issue?id=5382855.
252 PlaySound(NULL, 0, 0);
254 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
256 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
262 if (!engine_->voe_sc()) {
265 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
266 if (webrtc_channel_ == -1) {
267 LOG_RTCERR0(CreateChannel);
274 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
275 LOG_RTCERR1(StartPlayout, webrtc_channel_);
282 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
283 LOG_RTCERR1(StopPlayout, webrtc_channel_);
289 virtual bool PlaySound(const char *buf, int len, int flags) {
290 // The voe file api is not available in chrome.
291 if (!engine_->voe_sc()->file()) {
294 // Must stop playing the current sound (if any), because we are about to
295 // modify the stream.
296 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
298 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
303 stream_.reset(new WebRtcSoundclipStream(buf, len));
304 stream_->set_loop((flags & SF_LOOP) != 0);
308 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
309 webrtc_channel_, stream_.get()) == -1) {
310 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
311 LOG(LS_ERROR) << "Unable to start soundclip";
320 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
323 WebRtcVoiceEngine *engine_;
325 talk_base::scoped_ptr<WebRtcSoundclipStream> stream_;
328 WebRtcVoiceEngine::WebRtcVoiceEngine()
329 : voe_wrapper_(new VoEWrapper()),
330 voe_wrapper_sc_(new VoEWrapper()),
331 voe_wrapper_sc_initialized_(false),
332 tracing_(new VoETraceWrapper()),
335 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
336 is_dumping_aec_(false),
337 desired_local_monitor_enable_(false),
338 use_experimental_acm_(false),
339 tx_processor_ssrc_(0),
340 rx_processor_ssrc_(0) {
344 WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
345 VoEWrapper* voe_wrapper_sc,
346 VoETraceWrapper* tracing)
347 : voe_wrapper_(voe_wrapper),
348 voe_wrapper_sc_(voe_wrapper_sc),
349 voe_wrapper_sc_initialized_(false),
353 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
354 is_dumping_aec_(false),
355 desired_local_monitor_enable_(false),
356 use_experimental_acm_(false),
357 tx_processor_ssrc_(0),
358 rx_processor_ssrc_(0) {
362 void WebRtcVoiceEngine::Construct() {
363 SetTraceFilter(log_filter_);
364 initialized_ = false;
365 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
367 if (tracing_->SetTraceCallback(this) == -1) {
368 LOG_RTCERR0(SetTraceCallback);
370 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
371 LOG_RTCERR0(RegisterVoiceEngineObserver);
373 // Clear the default agc state.
374 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
376 // Load our audio codec list.
379 // Load our RTP Header extensions.
380 rtp_header_extensions_.push_back(
381 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
382 kRtpAudioLevelHeaderExtensionId));
383 options_ = GetDefaultEngineOptions();
385 // Initialize the VoE Configuration to the default ACM.
386 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
387 new webrtc::AudioCodingModuleFactory);
390 static bool IsOpus(const AudioCodec& codec) {
391 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
394 static bool IsIsac(const AudioCodec& codec) {
395 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
398 // True if params["stereo"] == "1"
399 static bool IsOpusStereoEnabled(const AudioCodec& codec) {
400 CodecParameterMap::const_iterator param =
401 codec.params.find(kCodecParamStereo);
402 if (param == codec.params.end()) {
405 return param->second == kParamValueTrue;
408 static bool IsValidOpusBitrate(int bitrate) {
409 return (bitrate >= kOpusMinBitrate && bitrate <= kOpusMaxBitrate);
412 // Returns 0 if params[kCodecParamMaxAverageBitrate] is not defined or invalid.
413 // Returns the value of params[kCodecParamMaxAverageBitrate] otherwise.
414 static int GetOpusBitrateFromParams(const AudioCodec& codec) {
416 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
419 if (!IsValidOpusBitrate(bitrate)) {
420 LOG(LS_WARNING) << "Codec parameter \"maxaveragebitrate\" has an "
421 << "invalid value: " << bitrate;
427 void WebRtcVoiceEngine::ConstructCodecs() {
428 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
429 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
430 for (int i = 0; i < ncodecs; ++i) {
431 webrtc::CodecInst voe_codec;
432 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
433 // Skip uncompressed formats.
434 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
438 const CodecPref* pref = NULL;
439 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
440 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
441 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
442 kCodecPrefs[j].channels == voe_codec.channels) {
443 pref = &kCodecPrefs[j];
449 // Use the payload type that we've configured in our pref table;
450 // use the offset in our pref table to determine the sort order.
451 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
452 voe_codec.rate, voe_codec.channels,
453 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
454 LOG(LS_INFO) << ToString(codec);
456 // Indicate auto-bandwidth in signaling.
460 // Only add fmtp parameters that differ from the spec.
461 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
462 codec.params[kCodecParamMinPTime] =
463 talk_base::ToString(kPreferredMinPTime);
465 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
466 codec.params[kCodecParamMaxPTime] =
467 talk_base::ToString(kPreferredMaxPTime);
469 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
470 // when they can be set to values other than the default.
472 codecs_.push_back(codec);
474 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
478 // Make sure they are in local preference order.
479 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
482 WebRtcVoiceEngine::~WebRtcVoiceEngine() {
483 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
484 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
485 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
488 voe_wrapper_.reset();
493 voe_wrapper_sc_.reset();
498 // Test to see if the media processor was deregistered properly
499 ASSERT(SignalRxMediaFrame.is_empty());
500 ASSERT(SignalTxMediaFrame.is_empty());
502 tracing_->SetTraceCallback(NULL);
505 bool WebRtcVoiceEngine::Init(talk_base::Thread* worker_thread) {
506 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
507 bool res = InitInternal();
509 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
511 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
517 bool WebRtcVoiceEngine::InitInternal() {
518 // Temporarily turn logging level up for the Init call
519 int old_filter = log_filter_;
520 int extended_filter = log_filter_ | SeverityToFilter(talk_base::LS_INFO);
521 SetTraceFilter(extended_filter);
524 // Init WebRtc VoiceEngine.
525 if (voe_wrapper_->base()->Init(adm_) == -1) {
526 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
527 SetTraceFilter(old_filter);
531 SetTraceFilter(old_filter);
532 SetTraceOptions(log_options_);
534 // Log the VoiceEngine version info
535 char buffer[1024] = "";
536 voe_wrapper_->base()->GetVersion(buffer);
537 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
538 LogMultiline(talk_base::LS_INFO, buffer);
540 // Save the default AGC configuration settings. This must happen before
541 // calling SetOptions or the default will be overwritten.
542 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
543 LOG_RTCERR0(GetAgcConfig);
547 // Set defaults for options, so that ApplyOptions applies them explicitly
548 // when we clear option (channel) overrides. External clients can still
549 // modify the defaults via SetOptions (on the media engine).
550 if (!SetOptions(GetDefaultEngineOptions())) {
554 // Print our codec list again for the call diagnostic log
555 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
556 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
557 it != codecs_.end(); ++it) {
558 LOG(LS_INFO) << ToString(*it);
561 // Disable the DTMF playout when a tone is sent.
562 // PlayDtmfTone will be used if local playout is needed.
563 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
564 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
571 bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
572 if (voe_wrapper_sc_initialized_) {
575 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
576 // be false, so subsequent calls to EnsureSoundclipEngineInit will
577 // probably just fail again. That's acceptable behavior.
578 #if defined(LINUX) && !defined(HAVE_LIBPULSE)
579 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
582 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
583 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
584 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
588 // On Windows, tell it to use the default sound (not communication) devices.
589 // First check whether there is a valid sound device for playback.
590 // TODO(juberti): Clean this up when we support setting the soundclip device.
592 // The SetPlayoutDevice may not be implemented in the case of external ADM.
593 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
594 // PeerConnection interface never set the adm_sc_, so need to check both
595 // in order to determine if the external adm is used.
596 if (!adm_ && !adm_sc_) {
597 int num_of_devices = 0;
598 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
599 num_of_devices > 0) {
600 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
602 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
603 voe_wrapper_sc_->error());
607 LOG(LS_WARNING) << "No valid sound playout device found.";
611 voe_wrapper_sc_initialized_ = true;
612 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
616 void WebRtcVoiceEngine::Terminate() {
617 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
618 initialized_ = false;
622 if (voe_wrapper_sc_) {
623 voe_wrapper_sc_initialized_ = false;
624 voe_wrapper_sc_->base()->Terminate();
626 voe_wrapper_->base()->Terminate();
627 desired_local_monitor_enable_ = false;
630 int WebRtcVoiceEngine::GetCapabilities() {
631 return AUDIO_SEND | AUDIO_RECV;
634 VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
635 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
643 SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
644 if (!EnsureSoundclipEngineInit()) {
645 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
649 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
650 if (!soundclip->Init() || !soundclip->Enable()) {
657 bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
658 if (!ApplyOptions(options)) {
665 bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
666 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
667 if (!ApplyOptions(overrides)) {
670 option_overrides_ = overrides;
674 bool WebRtcVoiceEngine::ClearOptionOverrides() {
675 LOG(LS_INFO) << "Clearing option overrides.";
676 AudioOptions options = options_;
677 // Only call ApplyOptions if |options_overrides_| contains overrided options.
678 // ApplyOptions affects NS, AGC other options that is shared between
679 // all WebRtcVoiceEngineChannels.
680 if (option_overrides_ == AudioOptions()) {
684 if (!ApplyOptions(options)) {
687 option_overrides_ = AudioOptions();
691 // AudioOptions defaults are set in InitInternal (for options with corresponding
692 // MediaEngineInterface flags) and in SetOptions(int) for flagless options.
693 bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
694 AudioOptions options = options_in; // The options are modified below.
695 // kEcConference is AEC with high suppression.
696 webrtc::EcModes ec_mode = webrtc::kEcConference;
697 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
698 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
699 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
700 bool aecm_comfort_noise = false;
701 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
702 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
703 << aecm_comfort_noise << " (default is false).";
707 // On iOS, VPIO provides built-in EC and AGC.
708 options.echo_cancellation.Set(false);
709 options.auto_gain_control.Set(false);
710 #elif defined(ANDROID)
711 ec_mode = webrtc::kEcAecm;
714 #if defined(IOS) || defined(ANDROID)
715 // Set the AGC mode for iOS as well despite disabling it above, to avoid
716 // unsupported configuration errors from webrtc.
717 agc_mode = webrtc::kAgcFixedDigital;
718 options.typing_detection.Set(false);
719 options.experimental_agc.Set(false);
720 options.experimental_aec.Set(false);
721 options.experimental_ns.Set(false);
724 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
726 // Configure whether ACM1 or ACM2 is used.
727 bool enable_acm2 = false;
728 if (options.experimental_acm.Get(&enable_acm2)) {
729 EnableExperimentalAcm(enable_acm2);
732 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
734 bool echo_cancellation;
735 if (options.echo_cancellation.Get(&echo_cancellation)) {
736 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
737 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
740 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
741 << " with mode " << ec_mode;
743 #if !defined(ANDROID)
744 // TODO(ajm): Remove the error return on Android from webrtc.
745 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
746 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
750 if (ec_mode == webrtc::kEcAecm) {
751 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
752 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
758 bool auto_gain_control;
759 if (options.auto_gain_control.Get(&auto_gain_control)) {
760 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
761 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
764 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
765 << " with mode " << agc_mode;
769 if (options.tx_agc_target_dbov.IsSet() ||
770 options.tx_agc_digital_compression_gain.IsSet() ||
771 options.tx_agc_limiter.IsSet()) {
772 // Override default_agc_config_. Generally, an unset option means "leave
773 // the VoE bits alone" in this function, so we want whatever is set to be
774 // stored as the new "default". If we didn't, then setting e.g.
775 // tx_agc_target_dbov would reset digital compression gain and limiter
777 // Also, if we don't update default_agc_config_, then adjust_agc_delta
778 // would be an offset from the original values, and not whatever was set
780 default_agc_config_.targetLeveldBOv =
781 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
782 default_agc_config_.targetLeveldBOv);
783 default_agc_config_.digitalCompressionGaindB =
784 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
785 default_agc_config_.digitalCompressionGaindB);
786 default_agc_config_.limiterEnable =
787 options.tx_agc_limiter.GetWithDefaultIfUnset(
788 default_agc_config_.limiterEnable);
789 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
790 LOG_RTCERR3(SetAgcConfig,
791 default_agc_config_.targetLeveldBOv,
792 default_agc_config_.digitalCompressionGaindB,
793 default_agc_config_.limiterEnable);
798 bool noise_suppression;
799 if (options.noise_suppression.Get(&noise_suppression)) {
800 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
801 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
804 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
805 << " with mode " << ns_mode;
809 #ifdef USE_WEBRTC_DEV_BRANCH
810 bool experimental_ns;
811 if (options.experimental_ns.Get(&experimental_ns)) {
812 webrtc::AudioProcessing* audioproc =
813 voe_wrapper_->base()->audio_processing();
814 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
815 // returns NULL on audio_processing().
817 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
818 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
822 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
826 #endif // USE_WEBRTC_DEV_BRANCH
828 bool highpass_filter;
829 if (options.highpass_filter.Get(&highpass_filter)) {
830 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
831 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
836 bool stereo_swapping;
837 if (options.stereo_swapping.Get(&stereo_swapping)) {
838 voep->EnableStereoChannelSwapping(stereo_swapping);
839 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
840 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
845 bool typing_detection;
846 if (options.typing_detection.Get(&typing_detection)) {
847 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
848 // In case of error, log the info and continue
849 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
853 int adjust_agc_delta;
854 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
855 if (!AdjustAgcLevel(adjust_agc_delta)) {
861 if (options.aec_dump.Get(&aec_dump)) {
863 StartAecDump(kAecDumpByAudioOptionFilename);
868 bool experimental_aec;
869 if (options.experimental_aec.Get(&experimental_aec)) {
870 webrtc::AudioProcessing* audioproc =
871 voe_wrapper_->base()->audio_processing();
872 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
873 // returns NULL on audio_processing().
875 webrtc::Config config;
876 config.Set<webrtc::DelayCorrection>(
877 new webrtc::DelayCorrection(experimental_aec));
878 audioproc->SetExtraOptions(config);
882 uint32 recording_sample_rate;
883 if (options.recording_sample_rate.Get(&recording_sample_rate)) {
884 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
885 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
889 uint32 playout_sample_rate;
890 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
891 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
892 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
900 bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
901 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
902 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
903 LOG_RTCERR1(SetDelayOffsetMs, offset);
911 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
917 WebRtcVoiceMediaChannel *channel;
922 // TODO(juberti): Refactor this so that the core logic can be used to set the
923 // soundclip device. At that time, reinstate the soundclip pause/resume code.
924 bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
925 const Device* out_device) {
927 int in_id = in_device ? talk_base::FromString<int>(in_device->id) :
928 kDefaultAudioDeviceId;
929 int out_id = out_device ? talk_base::FromString<int>(out_device->id) :
930 kDefaultAudioDeviceId;
931 // The device manager uses -1 as the default device, which was the case for
932 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
935 in_id = kDefaultAudioDeviceId;
938 out_id = kDefaultAudioDeviceId;
942 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
943 in_device->name : "Default device";
944 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
945 out_device->name : "Default device";
946 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
947 << ") and speaker to (id=" << out_id << ", name=" << out_name
950 // If we're running the local monitor, we need to stop it first.
952 if (!PauseLocalMonitor()) {
953 LOG(LS_WARNING) << "Failed to pause local monitor";
957 // Must also pause all audio playback and capture.
958 for (ChannelList::const_iterator i = channels_.begin();
959 i != channels_.end(); ++i) {
960 WebRtcVoiceMediaChannel *channel = *i;
961 if (!channel->PausePlayout()) {
962 LOG(LS_WARNING) << "Failed to pause playout";
965 if (!channel->PauseSend()) {
966 LOG(LS_WARNING) << "Failed to pause send";
971 // Find the recording device id in VoiceEngine and set recording device.
972 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
976 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
977 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
982 // Find the playout device id in VoiceEngine and set playout device.
983 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
984 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
988 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
989 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
994 // Resume all audio playback and capture.
995 for (ChannelList::const_iterator i = channels_.begin();
996 i != channels_.end(); ++i) {
997 WebRtcVoiceMediaChannel *channel = *i;
998 if (!channel->ResumePlayout()) {
999 LOG(LS_WARNING) << "Failed to resume playout";
1002 if (!channel->ResumeSend()) {
1003 LOG(LS_WARNING) << "Failed to resume send";
1008 // Resume local monitor.
1009 if (!ResumeLocalMonitor()) {
1010 LOG(LS_WARNING) << "Failed to resume local monitor";
1015 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1016 << ") and speaker to (id="<< out_id << " name=" << out_name
1026 bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1027 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1028 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
1029 #if defined(LINUX) || defined(ANDROID)
1033 // In Windows and Mac, we need to find the VoiceEngine device id by name
1034 // unless the input dev_id is the default device id.
1035 if (kDefaultAudioDeviceId == dev_id) {
1040 // Get the number of VoiceEngine audio devices.
1043 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1044 LOG_RTCERR0(GetNumOfRecordingDevices);
1048 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1049 LOG_RTCERR0(GetNumOfPlayoutDevices);
1054 for (int i = 0; i < count; ++i) {
1058 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1059 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1061 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1062 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1065 std::string webrtc_name(name);
1066 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1071 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1076 bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1077 unsigned int ulevel;
1078 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1079 LOG_RTCERR1(GetSpeakerVolume, level);
1086 bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1087 ASSERT(level >= 0 && level <= 255);
1088 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1089 LOG_RTCERR1(SetSpeakerVolume, level);
1095 int WebRtcVoiceEngine::GetInputLevel() {
1096 unsigned int ulevel;
1097 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1098 static_cast<int>(ulevel) : -1;
1101 bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1102 desired_local_monitor_enable_ = enable;
1103 return ChangeLocalMonitor(desired_local_monitor_enable_);
1106 bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1107 // The voe file api is not available in chrome.
1108 if (!voe_wrapper_->file()) {
1111 if (enable && !monitor_) {
1112 monitor_.reset(new WebRtcMonitorStream);
1113 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1114 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1115 // Must call Stop() because there are some cases where Start will report
1116 // failure but still change the state, and if we leave VE in the on state
1117 // then it could crash later when trying to invoke methods on our monitor.
1118 voe_wrapper_->file()->StopRecordingMicrophone();
1122 } else if (!enable && monitor_) {
1123 voe_wrapper_->file()->StopRecordingMicrophone();
1129 bool WebRtcVoiceEngine::PauseLocalMonitor() {
1130 return ChangeLocalMonitor(false);
1133 bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1134 return ChangeLocalMonitor(desired_local_monitor_enable_);
1137 const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1141 bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1142 return FindWebRtcCodec(in, NULL);
1145 // Get the VoiceEngine codec that matches |in|, with the supplied settings.
1146 bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1147 webrtc::CodecInst* out) {
1148 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1149 for (int i = 0; i < ncodecs; ++i) {
1150 webrtc::CodecInst voe_codec;
1151 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1152 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1153 voe_codec.rate, voe_codec.channels, 0);
1154 bool multi_rate = IsCodecMultiRate(voe_codec);
1155 // Allow arbitrary rates for ISAC to be specified.
1157 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1160 if (codec.Matches(in)) {
1162 // Fixup the payload type.
1163 voe_codec.pltype = in.id;
1165 // Set bitrate if specified.
1166 if (multi_rate && in.bitrate != 0) {
1167 voe_codec.rate = in.bitrate;
1170 // Apply codec-specific settings.
1171 if (IsIsac(codec)) {
1172 // If ISAC and an explicit bitrate is not specified,
1173 // enable auto bandwidth adjustment.
1174 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1184 const std::vector<RtpHeaderExtension>&
1185 WebRtcVoiceEngine::rtp_header_extensions() const {
1186 return rtp_header_extensions_;
1189 void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1190 // if min_sev == -1, we keep the current log level.
1192 SetTraceFilter(SeverityToFilter(min_sev));
1194 log_options_ = filter;
1195 SetTraceOptions(initialized_ ? log_options_ : "");
1198 int WebRtcVoiceEngine::GetLastEngineError() {
1199 return voe_wrapper_->error();
1202 void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1203 log_filter_ = filter;
1204 tracing_->SetTraceFilter(filter);
1207 // We suppport three different logging settings for VoiceEngine:
1208 // 1. Observer callback that goes into talk diagnostic logfile.
1209 // Use --logfile and --loglevel
1211 // 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1212 // Use --voice_loglevel --voice_logfilter "tracefile file_name"
1214 // 3. EC log and dump for debugging QualityEngine.
1215 // Use --voice_loglevel --voice_logfilter "recordEC file_name"
1217 // For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1218 // Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1219 void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1220 // Set encrypted trace file.
1221 std::vector<std::string> opts;
1222 talk_base::tokenize(options, ' ', '"', '"', &opts);
1223 std::vector<std::string>::iterator tracefile =
1224 std::find(opts.begin(), opts.end(), "tracefile");
1225 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1226 // Write encrypted debug output (at same loglevel) to file
1227 // EncryptedTraceFile no longer supported.
1228 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1229 LOG_RTCERR1(SetTraceFile, *tracefile);
1233 // Allow trace options to override the trace filter. We default
1234 // it to log_filter_ (as a translation of libjingle log levels)
1235 // elsewhere, but this allows clients to explicitly set webrtc
1237 std::vector<std::string>::iterator tracefilter =
1238 std::find(opts.begin(), opts.end(), "tracefilter");
1239 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
1240 if (!tracing_->SetTraceFilter(talk_base::FromString<int>(*tracefilter))) {
1241 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1245 // Set AEC dump file
1246 std::vector<std::string>::iterator recordEC =
1247 std::find(opts.begin(), opts.end(), "recordEC");
1248 if (recordEC != opts.end()) {
1250 if (recordEC != opts.end())
1251 StartAecDump(recordEC->c_str());
1257 // Ignore spammy trace messages, mostly from the stats API when we haven't
1258 // gotten RTCP info yet from the remote side.
1259 bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1260 static const char* kTracesToIgnore[] = {
1261 "\tfailed to GetReportBlockInformation",
1262 "GetRecCodec() failed to get received codec",
1263 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1264 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1265 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1266 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1267 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1268 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1269 "SenderInfoReceived No received SR",
1270 "StatisticsRTP() no statistics available",
1271 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1272 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1273 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1274 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1277 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1278 if (trace.find(*p) != std::string::npos) {
1285 void WebRtcVoiceEngine::EnableExperimentalAcm(bool enable) {
1286 if (enable == use_experimental_acm_)
1289 LOG(LS_INFO) << "VoiceEngine is set to use new ACM (ACM2 + NetEq4).";
1290 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
1291 new webrtc::NewAudioCodingModuleFactory());
1293 LOG(LS_INFO) << "VoiceEngine is set to use legacy ACM (ACM1 + Neteq3).";
1294 voe_config_.Set<webrtc::AudioCodingModuleFactory>(
1295 new webrtc::AudioCodingModuleFactory());
1297 use_experimental_acm_ = enable;
1300 void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1302 talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
1303 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
1304 sev = talk_base::LS_ERROR;
1305 else if (level == webrtc::kTraceWarning)
1306 sev = talk_base::LS_WARNING;
1307 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
1308 sev = talk_base::LS_INFO;
1309 else if (level == webrtc::kTraceTerseInfo)
1310 sev = talk_base::LS_INFO;
1312 // Skip past boilerplate prefix text
1314 std::string msg(trace, length);
1315 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1318 std::string msg(trace + 71, length - 72);
1319 if (!ShouldIgnoreTrace(msg)) {
1320 LOG_V(sev) << "webrtc: " << msg;
1325 void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
1326 talk_base::CritScope lock(&channels_cs_);
1327 WebRtcVoiceMediaChannel* channel = NULL;
1329 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1330 << channel_num << ".";
1331 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1332 ASSERT(channel != NULL);
1333 channel->OnError(ssrc, err_code);
1335 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1336 << " could not be found in channel list when error reported.";
1340 bool WebRtcVoiceEngine::FindChannelAndSsrc(
1341 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1342 ASSERT(channel != NULL && ssrc != NULL);
1346 // Find corresponding channel and ssrc
1347 for (ChannelList::const_iterator it = channels_.begin();
1348 it != channels_.end(); ++it) {
1349 ASSERT(*it != NULL);
1350 if ((*it)->FindSsrc(channel_num, ssrc)) {
1359 // This method will search through the WebRtcVoiceMediaChannels and
1360 // obtain the voice engine's channel number.
1361 bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1362 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1363 ASSERT(channel_num != NULL);
1364 ASSERT(direction == MPD_RX || direction == MPD_TX);
1367 // Find corresponding channel for ssrc.
1368 for (ChannelList::const_iterator it = channels_.begin();
1369 it != channels_.end(); ++it) {
1370 ASSERT(*it != NULL);
1371 if (direction & MPD_RX) {
1372 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1374 if (*channel_num == -1 && (direction & MPD_TX)) {
1375 *channel_num = (*it)->GetSendChannelNum(ssrc);
1377 if (*channel_num != -1) {
1381 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1385 void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
1386 talk_base::CritScope lock(&channels_cs_);
1387 channels_.push_back(channel);
1390 void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
1391 talk_base::CritScope lock(&channels_cs_);
1392 ChannelList::iterator i = std::find(channels_.begin(),
1395 if (i != channels_.end()) {
1400 void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1401 soundclips_.push_back(soundclip);
1404 void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1405 SoundclipList::iterator i = std::find(soundclips_.begin(),
1408 if (i != soundclips_.end()) {
1409 soundclips_.erase(i);
1413 // Adjusts the default AGC target level by the specified delta.
1414 // NB: If we start messing with other config fields, we'll want
1415 // to save the current webrtc::AgcConfig as well.
1416 bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1417 webrtc::AgcConfig config = default_agc_config_;
1418 config.targetLeveldBOv -= delta;
1420 LOG(LS_INFO) << "Adjusting AGC level from default -"
1421 << default_agc_config_.targetLeveldBOv << "dB to -"
1422 << config.targetLeveldBOv << "dB";
1424 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1425 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1431 bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1432 webrtc::AudioDeviceModule* adm_sc) {
1434 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1457 bool WebRtcVoiceEngine::StartAecDump(talk_base::PlatformFile file) {
1458 FILE* aec_dump_file_stream = talk_base::FdopenPlatformFileForWriting(file);
1459 if (!aec_dump_file_stream) {
1460 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
1461 if (!talk_base::ClosePlatformFile(file))
1462 LOG(LS_WARNING) << "Could not close file.";
1466 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
1467 webrtc::AudioProcessing::kNoError) {
1468 LOG_RTCERR0(StartDebugRecording);
1469 fclose(aec_dump_file_stream);
1472 is_dumping_aec_ = true;
1476 bool WebRtcVoiceEngine::RegisterProcessor(
1478 VoiceProcessor* voice_processor,
1479 MediaProcessorDirection direction) {
1480 bool register_with_webrtc = false;
1481 int channel_id = -1;
1482 bool success = false;
1483 uint32* processor_ssrc = NULL;
1484 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1485 if (voice_processor == NULL || !found_channel) {
1486 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1487 << " foundChannel: " << found_channel;
1491 webrtc::ProcessingTypes processing_type;
1493 talk_base::CritScope cs(&signal_media_critical_);
1494 if (direction == MPD_RX) {
1495 processing_type = webrtc::kPlaybackAllChannelsMixed;
1496 if (SignalRxMediaFrame.is_empty()) {
1497 register_with_webrtc = true;
1498 processor_ssrc = &rx_processor_ssrc_;
1500 SignalRxMediaFrame.connect(voice_processor,
1501 &VoiceProcessor::OnFrame);
1503 processing_type = webrtc::kRecordingPerChannel;
1504 if (SignalTxMediaFrame.is_empty()) {
1505 register_with_webrtc = true;
1506 processor_ssrc = &tx_processor_ssrc_;
1508 SignalTxMediaFrame.connect(voice_processor,
1509 &VoiceProcessor::OnFrame);
1512 if (register_with_webrtc) {
1513 // TODO(janahan): when registering consider instantiating a
1514 // a VoeMediaProcess object and not make the engine extend the interface.
1515 if (voe()->media() && voe()->media()->
1516 RegisterExternalMediaProcessing(channel_id,
1519 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1521 *processor_ssrc = ssrc;
1524 LOG_RTCERR2(RegisterExternalMediaProcessing,
1530 // If we don't have to register with the engine, we just needed to
1531 // connect a new processor, set success to true;
1537 bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1538 MediaProcessorDirection channel_direction,
1540 VoiceProcessor* voice_processor,
1541 MediaProcessorDirection processor_direction) {
1542 bool success = true;
1543 FrameSignal* signal;
1544 webrtc::ProcessingTypes processing_type;
1545 uint32* processor_ssrc = NULL;
1546 if (channel_direction == MPD_RX) {
1547 signal = &SignalRxMediaFrame;
1548 processing_type = webrtc::kPlaybackAllChannelsMixed;
1549 processor_ssrc = &rx_processor_ssrc_;
1551 signal = &SignalTxMediaFrame;
1552 processing_type = webrtc::kRecordingPerChannel;
1553 processor_ssrc = &tx_processor_ssrc_;
1556 int deregister_id = -1;
1558 talk_base::CritScope cs(&signal_media_critical_);
1559 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1560 signal->disconnect(voice_processor);
1561 int channel_id = -1;
1562 bool found_channel = FindChannelNumFromSsrc(ssrc,
1565 if (signal->is_empty() && found_channel) {
1566 deregister_id = channel_id;
1570 if (deregister_id != -1) {
1571 if (voe()->media() &&
1572 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1573 processing_type) != -1) {
1574 *processor_ssrc = 0;
1575 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1578 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1587 bool WebRtcVoiceEngine::UnregisterProcessor(
1589 VoiceProcessor* voice_processor,
1590 MediaProcessorDirection direction) {
1591 bool success = true;
1592 if (voice_processor == NULL) {
1593 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1597 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1600 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1606 // Implementing method from WebRtc VoEMediaProcess interface
1607 // Do not lock mux_channel_cs_ in this callback.
1608 void WebRtcVoiceEngine::Process(int channel,
1609 webrtc::ProcessingTypes type,
1610 int16_t audio10ms[],
1614 talk_base::CritScope cs(&signal_media_critical_);
1615 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1616 if (type == webrtc::kPlaybackAllChannelsMixed) {
1617 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1618 } else if (type == webrtc::kRecordingPerChannel) {
1619 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1621 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1622 << " channel: " << channel << " type: " << type
1623 << " tx_ssrc: " << tx_processor_ssrc_
1624 << " rx_ssrc: " << rx_processor_ssrc_;
1628 void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1629 if (!is_dumping_aec_) {
1630 // Start dumping AEC when we are not dumping.
1631 if (voe_wrapper_->processing()->StartDebugRecording(
1632 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
1633 LOG_RTCERR1(StartDebugRecording, filename.c_str());
1635 is_dumping_aec_ = true;
1640 void WebRtcVoiceEngine::StopAecDump() {
1641 if (is_dumping_aec_) {
1642 // Stop dumping AEC when we are dumping.
1643 if (voe_wrapper_->processing()->StopDebugRecording() !=
1644 webrtc::AudioProcessing::kNoError) {
1645 LOG_RTCERR0(StopDebugRecording);
1647 is_dumping_aec_ = false;
1651 int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
1652 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
1655 int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1656 return CreateVoiceChannel(voe_wrapper_.get());
1659 int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1660 return CreateVoiceChannel(voe_wrapper_sc_.get());
1663 class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1664 : public AudioRenderer::Sink {
1666 WebRtcVoiceChannelRenderer(int ch,
1667 webrtc::AudioTransport* voe_audio_transport)
1669 voe_audio_transport_(voe_audio_transport),
1672 virtual ~WebRtcVoiceChannelRenderer() {
1676 // Starts the rendering by setting a sink to the renderer to get data
1678 // TODO(xians): Make sure Start() is called only once.
1679 void Start(AudioRenderer* renderer) {
1680 ASSERT(renderer != NULL);
1682 ASSERT(renderer_ == renderer);
1686 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1687 // in getUserMedia by default.
1688 renderer->AddChannel(channel_);
1689 renderer->SetSink(this);
1690 renderer_ = renderer;
1693 // Stops rendering by setting the sink of the renderer to NULL. No data
1694 // callback will be received after this method.
1699 renderer_->RemoveChannel(channel_);
1700 renderer_->SetSink(NULL);
1704 // AudioRenderer::Sink implementation.
1705 virtual void OnData(const void* audio_data,
1706 int bits_per_sample,
1708 int number_of_channels,
1709 int number_of_frames) OVERRIDE {
1710 // TODO(xians): Make new interface in AudioTransport to pass the data to
1711 // WebRtc VoE channel.
1714 // Accessor to the VoE channel ID.
1715 int channel() const { return channel_; }
1719 webrtc::AudioTransport* const voe_audio_transport_;
1721 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1722 // PeerConnection will make sure invalidating the pointer before the object
1724 AudioRenderer* renderer_;
1727 // WebRtcVoiceMediaChannel
1728 WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1729 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1731 engine->CreateMediaVoiceChannel()),
1732 send_bw_setting_(false),
1735 dtmf_allowed_(false),
1736 desired_playout_(false),
1737 nack_enabled_(false),
1739 typing_noise_detected_(false),
1740 desired_send_(SEND_NOTHING),
1741 send_(SEND_NOTHING),
1742 default_receive_ssrc_(0) {
1743 engine->RegisterChannel(this);
1744 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1747 ConfigureSendChannel(voe_channel());
1750 WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1751 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1754 // Remove any remaining send streams, the default channel will be deleted
1756 while (!send_channels_.empty())
1757 RemoveSendStream(send_channels_.begin()->first);
1759 // Unregister ourselves from the engine.
1760 engine()->UnregisterChannel(this);
1761 // Remove any remaining streams.
1762 while (!receive_channels_.empty()) {
1763 RemoveRecvStream(receive_channels_.begin()->first);
1766 // Delete the default channel.
1767 DeleteChannel(voe_channel());
1770 bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1771 LOG(LS_INFO) << "Setting voice channel options: "
1772 << options.ToString();
1774 // Check if DSCP value is changed from previous.
1775 bool dscp_option_changed = (options_.dscp != options.dscp);
1777 // TODO(xians): Add support to set different options for different send
1778 // streams after we support multiple APMs.
1780 // We retain all of the existing options, and apply the given ones
1781 // on top. This means there is no way to "clear" options such that
1782 // they go back to the engine default.
1783 options_.SetAll(options);
1785 if (send_ != SEND_NOTHING) {
1786 if (!engine()->SetOptionOverrides(options_)) {
1788 "Failed to engine SetOptionOverrides during channel SetOptions.";
1792 // Will be interpreted when appropriate.
1795 // Receiver-side auto gain control happens per channel, so set it here from
1796 // options. Note that, like conference mode, setting it on the engine won't
1797 // have the desired effect, since voice channels don't inherit options from
1798 // the media engine when those options are applied per-channel.
1799 bool rx_auto_gain_control;
1800 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1801 if (engine()->voe()->processing()->SetRxAgcStatus(
1802 voe_channel(), rx_auto_gain_control,
1803 webrtc::kAgcFixedDigital) == -1) {
1804 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1807 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1808 << " with mode " << webrtc::kAgcFixedDigital;
1811 if (options.rx_agc_target_dbov.IsSet() ||
1812 options.rx_agc_digital_compression_gain.IsSet() ||
1813 options.rx_agc_limiter.IsSet()) {
1814 webrtc::AgcConfig config;
1815 // If only some of the options are being overridden, get the current
1816 // settings for the channel and bail if they aren't available.
1817 if (!options.rx_agc_target_dbov.IsSet() ||
1818 !options.rx_agc_digital_compression_gain.IsSet() ||
1819 !options.rx_agc_limiter.IsSet()) {
1820 if (engine()->voe()->processing()->GetRxAgcConfig(
1821 voe_channel(), config) != 0) {
1822 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1823 << "channel " << voe_channel() << ". Since not all rx "
1824 << "agc options are specified, unable to safely set rx "
1829 config.targetLeveldBOv =
1830 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1831 config.targetLeveldBOv);
1832 config.digitalCompressionGaindB =
1833 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1834 config.digitalCompressionGaindB);
1835 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1836 config.limiterEnable);
1837 if (engine()->voe()->processing()->SetRxAgcConfig(
1838 voe_channel(), config) == -1) {
1839 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1840 config.digitalCompressionGaindB, config.limiterEnable);
1844 if (dscp_option_changed) {
1845 talk_base::DiffServCodePoint dscp = talk_base::DSCP_DEFAULT;
1846 if (options_.dscp.GetWithDefaultIfUnset(false))
1847 dscp = kAudioDscpValue;
1848 if (MediaChannel::SetDscp(dscp) != 0) {
1849 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1853 LOG(LS_INFO) << "Set voice channel options. Current options: "
1854 << options_.ToString();
1858 bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1859 const std::vector<AudioCodec>& codecs) {
1860 // Set the payload types to be used for incoming media.
1861 LOG(LS_INFO) << "Setting receive voice codecs:";
1863 std::vector<AudioCodec> new_codecs;
1864 // Find all new codecs. We allow adding new codecs but don't allow changing
1865 // the payload type of codecs that is already configured since we might
1866 // already be receiving packets with that payload type.
1867 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1868 it != codecs.end(); ++it) {
1869 AudioCodec old_codec;
1870 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1871 if (old_codec.id != it->id) {
1872 LOG(LS_ERROR) << it->name << " payload type changed.";
1876 new_codecs.push_back(*it);
1879 if (new_codecs.empty()) {
1880 // There are no new codecs to configure. Already configured codecs are
1886 // Receive codecs can not be changed while playing. So we temporarily
1892 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1893 it != new_codecs.end() && ret; ++it) {
1894 webrtc::CodecInst voe_codec;
1895 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1896 LOG(LS_INFO) << ToString(*it);
1897 voe_codec.pltype = it->id;
1898 if (default_receive_ssrc_ == 0) {
1899 // Set the receive codecs on the default channel explicitly if the
1900 // default channel is not used by |receive_channels_|, this happens in
1901 // conference mode or in non-conference mode when there is no playout
1903 // TODO(xians): Figure out how we use the default channel in conference
1905 if (engine()->voe()->codec()->SetRecPayloadType(
1906 voe_channel(), voe_codec) == -1) {
1907 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1912 // Set the receive codecs on all receiving channels.
1913 for (ChannelMap::iterator it = receive_channels_.begin();
1914 it != receive_channels_.end() && ret; ++it) {
1915 if (engine()->voe()->codec()->SetRecPayloadType(
1916 it->second->channel(), voe_codec) == -1) {
1917 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
1918 ToString(voe_codec));
1923 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1928 recv_codecs_ = codecs;
1931 if (desired_playout_ && !playout_) {
1937 bool WebRtcVoiceMediaChannel::SetSendCodecs(
1938 int channel, const std::vector<AudioCodec>& codecs) {
1939 // Disable VAD, and FEC unless we know the other side wants them.
1940 engine()->voe()->codec()->SetVADStatus(channel, false);
1941 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1942 engine()->voe()->rtp()->SetFECStatus(channel, false);
1944 // Scan through the list to figure out the codec to use for sending, along
1945 // with the proper configuration for VAD and DTMF.
1947 webrtc::CodecInst send_codec;
1948 memset(&send_codec, 0, sizeof(send_codec));
1950 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1951 it != codecs.end(); ++it) {
1952 // Ignore codecs we don't know about. The negotiation step should prevent
1953 // this, but double-check to be sure.
1954 webrtc::CodecInst voe_codec;
1955 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
1956 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1960 // If OPUS, change what we send according to the "stereo" codec
1961 // parameter, and not the "channels" parameter. We set
1962 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
1963 // the bitrate is not specified, i.e. is zero, we set it to the
1964 // appropriate default value for mono or stereo Opus.
1966 if (IsOpusStereoEnabled(*it)) {
1967 voe_codec.channels = 2;
1968 if (!IsValidOpusBitrate(it->bitrate)) {
1969 if (it->bitrate != 0) {
1970 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
1972 << ") with default opus stereo bitrate: "
1973 << kOpusStereoBitrate;
1975 voe_codec.rate = kOpusStereoBitrate;
1978 voe_codec.channels = 1;
1979 if (!IsValidOpusBitrate(it->bitrate)) {
1980 if (it->bitrate != 0) {
1981 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
1983 << ") with default opus mono bitrate: "
1984 << kOpusMonoBitrate;
1986 voe_codec.rate = kOpusMonoBitrate;
1989 int bitrate_from_params = GetOpusBitrateFromParams(*it);
1990 if (bitrate_from_params != 0) {
1991 voe_codec.rate = bitrate_from_params;
1995 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
1997 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
1998 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
1999 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2000 channel, it->id) == -1) {
2001 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2006 // Turn voice activity detection/comfort noise on if supported.
2007 // Set the wideband CN payload type appropriately.
2008 // (narrowband always uses the static payload type 13).
2009 if (_stricmp(it->name.c_str(), "CN") == 0) {
2010 webrtc::PayloadFrequencies cn_freq;
2011 switch (it->clockrate) {
2013 cn_freq = webrtc::kFreq8000Hz;
2016 cn_freq = webrtc::kFreq16000Hz;
2019 cn_freq = webrtc::kFreq32000Hz;
2022 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2023 << " not supported.";
2026 // Set the CN payloadtype and the VAD status.
2027 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2028 if (cn_freq != webrtc::kFreq8000Hz) {
2029 if (engine()->voe()->codec()->SetSendCNPayloadType(
2030 channel, it->id, cn_freq) == -1) {
2031 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2032 // TODO(ajm): This failure condition will be removed from VoE.
2033 // Restore the return here when we update to a new enough webrtc.
2035 // Not returning false because the SetSendCNPayloadType will fail if
2036 // the channel is already sending.
2037 // This can happen if the remote description is applied twice, for
2038 // example in the case of ROAP on top of JSEP, where both side will
2043 // Only turn on VAD if we have a CN payload type that matches the
2044 // clockrate for the codec we are going to use.
2045 if (it->clockrate == send_codec.plfreq) {
2046 LOG(LS_INFO) << "Enabling VAD";
2047 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2048 LOG_RTCERR2(SetVADStatus, channel, true);
2054 // We'll use the first codec in the list to actually send audio data.
2055 // Be sure to use the payload type requested by the remote side.
2056 // "red", for FEC audio, is a special case where the actual codec to be
2057 // used is specified in params.
2059 if (_stricmp(it->name.c_str(), "red") == 0) {
2060 // Parse out the RED parameters. If we fail, just ignore RED;
2061 // we don't support all possible params/usage scenarios.
2062 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2066 // Enable redundant encoding of the specified codec. Treat any
2067 // failure as a fatal internal error.
2068 LOG(LS_INFO) << "Enabling FEC";
2069 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2070 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
2074 send_codec = voe_codec;
2075 nack_enabled_ = IsNackEnabled(*it);
2076 SetNack(channel, nack_enabled_);
2079 // Set the codec immediately, since SetVADStatus() depends on whether
2080 // the current codec is mono or stereo.
2081 if (!SetSendCodec(channel, send_codec))
2086 // If we're being asked to set an empty list of codecs, due to a buggy client,
2087 // choose the most common format: PCMU
2089 LOG(LS_WARNING) << "Received empty list of codecs; using PCMU/8000";
2090 AudioCodec codec(0, "PCMU", 8000, 0, 1, 0);
2091 engine()->FindWebRtcCodec(codec, &send_codec);
2092 if (!SetSendCodec(channel, send_codec))
2096 // Always update the |send_codec_| to the currently set send codec.
2097 send_codec_.reset(new webrtc::CodecInst(send_codec));
2099 if (send_bw_setting_) {
2100 SetSendBandwidthInternal(send_bw_bps_);
2106 bool WebRtcVoiceMediaChannel::SetSendCodecs(
2107 const std::vector<AudioCodec>& codecs) {
2108 dtmf_allowed_ = false;
2109 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2110 it != codecs.end(); ++it) {
2111 // Find the DTMF telephone event "codec".
2112 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2113 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2114 dtmf_allowed_ = true;
2118 // Cache the codecs in order to configure the channel created later.
2119 send_codecs_ = codecs;
2120 for (ChannelMap::iterator iter = send_channels_.begin();
2121 iter != send_channels_.end(); ++iter) {
2122 if (!SetSendCodecs(iter->second->channel(), codecs)) {
2127 SetNack(receive_channels_, nack_enabled_);
2132 void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2133 bool nack_enabled) {
2134 for (ChannelMap::const_iterator it = channels.begin();
2135 it != channels.end(); ++it) {
2136 SetNack(it->second->channel(), nack_enabled);
2140 void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
2142 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
2143 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2145 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
2146 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2150 bool WebRtcVoiceMediaChannel::SetSendCodec(
2151 const webrtc::CodecInst& send_codec) {
2152 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2153 << ", bitrate=" << send_codec.rate;
2154 for (ChannelMap::iterator iter = send_channels_.begin();
2155 iter != send_channels_.end(); ++iter) {
2156 if (!SetSendCodec(iter->second->channel(), send_codec))
2163 bool WebRtcVoiceMediaChannel::SetSendCodec(
2164 int channel, const webrtc::CodecInst& send_codec) {
2165 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2166 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2168 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2169 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
2175 bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2176 const std::vector<RtpHeaderExtension>& extensions) {
2177 // We don't support any incoming extensions headers right now.
2181 bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2182 const std::vector<RtpHeaderExtension>& extensions) {
2183 // Enable the audio level extension header if requested.
2184 std::vector<RtpHeaderExtension>::const_iterator it;
2185 for (it = extensions.begin(); it != extensions.end(); ++it) {
2186 if (it->uri == kRtpAudioLevelHeaderExtension) {
2191 bool enable = (it != extensions.end());
2196 if (id < kMinRtpHeaderExtensionId ||
2197 id > kMaxRtpHeaderExtensionId) {
2198 LOG(LS_WARNING) << "Invalid RTP header extension id " << id;
2203 LOG(LS_INFO) << "Enabling audio level header extension with ID " << id;
2204 for (ChannelMap::const_iterator iter = send_channels_.begin();
2205 iter != send_channels_.end(); ++iter) {
2206 if (engine()->voe()->rtp()->SetRTPAudioLevelIndicationStatus(
2207 iter->second->channel(), enable, id) == -1) {
2208 LOG_RTCERR3(SetRTPAudioLevelIndicationStatus,
2209 iter->second->channel(), enable, id);
2217 bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2218 desired_playout_ = playout;
2219 return ChangePlayout(desired_playout_);
2222 bool WebRtcVoiceMediaChannel::PausePlayout() {
2223 return ChangePlayout(false);
2226 bool WebRtcVoiceMediaChannel::ResumePlayout() {
2227 return ChangePlayout(desired_playout_);
2230 bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2231 if (playout_ == playout) {
2235 // Change the playout of all channels to the new state.
2237 if (receive_channels_.empty()) {
2238 // Only toggle the default channel if we don't have any other channels.
2239 result = SetPlayout(voe_channel(), playout);
2241 for (ChannelMap::iterator it = receive_channels_.begin();
2242 it != receive_channels_.end() && result; ++it) {
2243 if (!SetPlayout(it->second->channel(), playout)) {
2244 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
2245 << it->second->channel() << " failed";
2256 bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2257 desired_send_ = send;
2258 if (!send_channels_.empty())
2259 return ChangeSend(desired_send_);
2263 bool WebRtcVoiceMediaChannel::PauseSend() {
2264 return ChangeSend(SEND_NOTHING);
2267 bool WebRtcVoiceMediaChannel::ResumeSend() {
2268 return ChangeSend(desired_send_);
2271 bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2272 if (send_ == send) {
2276 // Change the settings on each send channel.
2277 if (send == SEND_MICROPHONE)
2278 engine()->SetOptionOverrides(options_);
2280 // Change the settings on each send channel.
2281 for (ChannelMap::iterator iter = send_channels_.begin();
2282 iter != send_channels_.end(); ++iter) {
2283 if (!ChangeSend(iter->second->channel(), send))
2287 // Clear up the options after stopping sending.
2288 if (send == SEND_NOTHING)
2289 engine()->ClearOptionOverrides();
2295 bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2296 if (send == SEND_MICROPHONE) {
2297 if (engine()->voe()->base()->StartSend(channel) == -1) {
2298 LOG_RTCERR1(StartSend, channel);
2301 if (engine()->voe()->file() &&
2302 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2303 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2306 } else { // SEND_NOTHING
2307 ASSERT(send == SEND_NOTHING);
2308 if (engine()->voe()->base()->StopSend(channel) == -1) {
2309 LOG_RTCERR1(StopSend, channel);
2317 void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2318 if (engine()->voe()->network()->RegisterExternalTransport(
2319 channel, *this) == -1) {
2320 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2323 // Enable RTCP (for quality stats and feedback messages)
2324 EnableRtcp(channel);
2326 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2327 ResetRecvCodecs(channel);
2330 bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2331 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2332 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2335 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2336 LOG_RTCERR1(DeleteChannel, channel);
2343 bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2344 // If the default channel is already used for sending create a new channel
2345 // otherwise use the default channel for sending.
2346 int channel = GetSendChannelNum(sp.first_ssrc());
2347 if (channel != -1) {
2348 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2352 bool default_channel_is_available = true;
2353 for (ChannelMap::const_iterator iter = send_channels_.begin();
2354 iter != send_channels_.end(); ++iter) {
2355 if (IsDefaultChannel(iter->second->channel())) {
2356 default_channel_is_available = false;
2360 if (default_channel_is_available) {
2361 channel = voe_channel();
2363 // Create a new channel for sending audio data.
2364 channel = engine()->CreateMediaVoiceChannel();
2365 if (channel == -1) {
2366 LOG_RTCERR0(CreateChannel);
2370 ConfigureSendChannel(channel);
2373 // Save the channel to send_channels_, so that RemoveSendStream() can still
2374 // delete the channel in case failure happens below.
2375 #ifdef USE_WEBRTC_DEV_BRANCH
2376 webrtc::AudioTransport* audio_transport =
2377 engine()->voe()->base()->audio_transport();
2379 webrtc::AudioTransport* audio_transport = NULL;
2381 send_channels_.insert(std::make_pair(
2383 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
2385 // Set the send (local) SSRC.
2386 // If there are multiple send SSRCs, we can only set the first one here, and
2387 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2388 // (with a codec requires multiple SSRC(s)).
2389 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2390 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2394 // At this point the channel's local SSRC has been updated. If the channel is
2395 // the default channel make sure that all the receive channels are updated as
2396 // well. Receive channels have to have the same SSRC as the default channel in
2397 // order to send receiver reports with this SSRC.
2398 if (IsDefaultChannel(channel)) {
2399 for (ChannelMap::const_iterator it = receive_channels_.begin();
2400 it != receive_channels_.end(); ++it) {
2401 // Only update the SSRC for non-default channels.
2402 if (!IsDefaultChannel(it->second->channel())) {
2403 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
2404 sp.first_ssrc()) != 0) {
2405 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
2412 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
2413 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2417 // Set the current codecs to be used for the new channel.
2418 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
2421 return ChangeSend(channel, desired_send_);
2424 bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2425 ChannelMap::iterator it = send_channels_.find(ssrc);
2426 if (it == send_channels_.end()) {
2427 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2428 << " which doesn't exist.";
2432 int channel = it->second->channel();
2433 ChangeSend(channel, SEND_NOTHING);
2435 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2436 // this will disconnect the audio renderer with the send channel.
2438 send_channels_.erase(it);
2440 if (IsDefaultChannel(channel)) {
2441 // Do not delete the default channel since the receive channels depend on
2442 // the default channel, recycle it instead.
2443 ChangeSend(channel, SEND_NOTHING);
2445 // Clean up and delete the send channel.
2446 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2447 << " with VoiceEngine channel #" << channel << ".";
2448 if (!DeleteChannel(channel))
2452 if (send_channels_.empty())
2453 ChangeSend(SEND_NOTHING);
2458 bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
2459 talk_base::CritScope lock(&receive_channels_cs_);
2461 if (!VERIFY(sp.ssrcs.size() == 1))
2463 uint32 ssrc = sp.first_ssrc();
2466 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2470 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2471 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
2475 // Reuse default channel for recv stream in non-conference mode call
2476 // when the default channel is not being used.
2477 #ifdef USE_WEBRTC_DEV_BRANCH
2478 webrtc::AudioTransport* audio_transport =
2479 engine()->voe()->base()->audio_transport();
2481 webrtc::AudioTransport* audio_transport = NULL;
2483 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2484 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2485 << " reuse default channel";
2486 default_receive_ssrc_ = sp.first_ssrc();
2487 receive_channels_.insert(std::make_pair(
2488 default_receive_ssrc_,
2489 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
2490 return SetPlayout(voe_channel(), playout_);
2493 // Create a new channel for receiving audio data.
2494 int channel = engine()->CreateMediaVoiceChannel();
2495 if (channel == -1) {
2496 LOG_RTCERR0(CreateChannel);
2500 if (!ConfigureRecvChannel(channel)) {
2501 DeleteChannel(channel);
2505 receive_channels_.insert(
2507 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
2509 LOG(LS_INFO) << "New audio stream " << ssrc
2510 << " registered to VoiceEngine channel #"
2515 bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
2516 // Configure to use external transport, like our default channel.
2517 if (engine()->voe()->network()->RegisterExternalTransport(
2518 channel, *this) == -1) {
2519 LOG_RTCERR2(SetExternalTransport, channel, this);
2523 // Use the same SSRC as our default channel (so the RTCP reports are correct).
2524 unsigned int send_ssrc = 0;
2525 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2526 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
2527 LOG_RTCERR1(GetSendSSRC, channel);
2530 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
2531 LOG_RTCERR1(SetSendSSRC, channel);
2535 // Use the same recv payload types as our default channel.
2536 ResetRecvCodecs(channel);
2537 if (!recv_codecs_.empty()) {
2538 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2539 it != recv_codecs_.end(); ++it) {
2540 webrtc::CodecInst voe_codec;
2541 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2542 voe_codec.pltype = it->id;
2543 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2544 if (engine()->voe()->codec()->GetRecPayloadType(
2545 voe_channel(), voe_codec) != -1) {
2546 if (engine()->voe()->codec()->SetRecPayloadType(
2547 channel, voe_codec) == -1) {
2548 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2556 if (InConferenceMode()) {
2557 // To be in par with the video, voe_channel() is not used for receiving in
2558 // a conference call.
2559 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2560 // This is the first stream in a multi user meeting. We can now
2561 // disable playback of the default stream. This since the default
2562 // stream will probably have received some initial packets before
2563 // the new stream was added. This will mean that the CN state from
2564 // the default channel will be mixed in with the other streams
2565 // throughout the whole meeting, which might be disturbing.
2566 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2567 SetPlayout(voe_channel(), false);
2570 SetNack(channel, nack_enabled_);
2572 return SetPlayout(channel, playout_);
2575 bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
2576 talk_base::CritScope lock(&receive_channels_cs_);
2577 ChannelMap::iterator it = receive_channels_.find(ssrc);
2578 if (it == receive_channels_.end()) {
2579 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2580 << " which doesn't exist.";
2584 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2585 // will disconnect the audio renderer with the receive channel.
2586 // Cache the channel before the deletion.
2587 const int channel = it->second->channel();
2589 receive_channels_.erase(it);
2591 if (ssrc == default_receive_ssrc_) {
2592 ASSERT(IsDefaultChannel(channel));
2593 // Recycle the default channel is for recv stream.
2595 SetPlayout(voe_channel(), false);
2597 default_receive_ssrc_ = 0;
2601 LOG(LS_INFO) << "Removing audio stream " << ssrc
2602 << " with VoiceEngine channel #" << channel << ".";
2603 if (!DeleteChannel(channel))
2606 bool enable_default_channel_playout = false;
2607 if (receive_channels_.empty()) {
2608 // The last stream was removed. We can now enable the default
2609 // channel for new channels to be played out immediately without
2610 // waiting for AddStream messages.
2611 // We do this for both conference mode and non-conference mode.
2612 // TODO(oja): Does the default channel still have it's CN state?
2613 enable_default_channel_playout = true;
2615 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2616 default_receive_ssrc_ != 0) {
2617 // Only the default channel is active, enable the playout on default
2619 enable_default_channel_playout = true;
2621 if (enable_default_channel_playout && playout_) {
2622 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2623 SetPlayout(voe_channel(), true);
2629 bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2630 AudioRenderer* renderer) {
2631 ChannelMap::iterator it = receive_channels_.find(ssrc);
2632 if (it == receive_channels_.end()) {
2634 // Return an error if trying to set a valid renderer with an invalid ssrc.
2635 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
2639 // The channel likely has gone away, do nothing.
2644 it->second->Start(renderer);
2651 bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2652 AudioRenderer* renderer) {
2653 ChannelMap::iterator it = send_channels_.find(ssrc);
2654 if (it == send_channels_.end()) {
2656 // Return an error if trying to set a valid renderer with an invalid ssrc.
2657 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2661 // The channel likely has gone away, do nothing.
2666 it->second->Start(renderer);
2673 bool WebRtcVoiceMediaChannel::GetActiveStreams(
2674 AudioInfo::StreamList* actives) {
2675 // In conference mode, the default channel should not be in
2676 // |receive_channels_|.
2678 for (ChannelMap::iterator it = receive_channels_.begin();
2679 it != receive_channels_.end(); ++it) {
2680 int level = GetOutputLevel(it->second->channel());
2682 actives->push_back(std::make_pair(it->first, level));
2688 int WebRtcVoiceMediaChannel::GetOutputLevel() {
2689 // return the highest output level of all streams
2690 int highest = GetOutputLevel(voe_channel());
2691 for (ChannelMap::iterator it = receive_channels_.begin();
2692 it != receive_channels_.end(); ++it) {
2693 int level = GetOutputLevel(it->second->channel());
2694 highest = talk_base::_max(level, highest);
2699 int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2701 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2702 // In case of error, log the info and continue
2703 LOG_RTCERR0(TimeSinceLastTyping);
2706 ret *= 1000; // We return ms, webrtc returns seconds.
2711 void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2712 int cost_per_typing, int reporting_threshold, int penalty_decay,
2713 int type_event_delay) {
2714 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2715 time_window, cost_per_typing,
2716 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2717 // In case of error, log the info and continue
2718 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2719 cost_per_typing, reporting_threshold, penalty_decay,
2724 bool WebRtcVoiceMediaChannel::SetOutputScaling(
2725 uint32 ssrc, double left, double right) {
2726 talk_base::CritScope lock(&receive_channels_cs_);
2727 // Collect the channels to scale the output volume.
2728 std::vector<int> channels;
2729 if (0 == ssrc) { // Collect all channels, including the default one.
2730 // Default channel is not in receive_channels_ if it is not being used for
2732 if (default_receive_ssrc_ == 0)
2733 channels.push_back(voe_channel());
2734 for (ChannelMap::const_iterator it = receive_channels_.begin();
2735 it != receive_channels_.end(); ++it) {
2736 channels.push_back(it->second->channel());
2738 } else { // Collect only the channel of the specified ssrc.
2739 int channel = GetReceiveChannelNum(ssrc);
2740 if (-1 == channel) {
2741 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2744 channels.push_back(channel);
2747 // Scale the output volume for the collected channels. We first normalize to
2748 // scale the volume and then set the left and right pan.
2749 float scale = static_cast<float>(talk_base::_max(left, right));
2750 if (scale > 0.0001f) {
2754 for (std::vector<int>::const_iterator it = channels.begin();
2755 it != channels.end(); ++it) {
2756 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2758 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2761 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2762 *it, static_cast<float>(left), static_cast<float>(right))) {
2763 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2764 // Do not return if fails. SetOutputVolumePan is not available for all
2767 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2768 << " right=" << right * scale
2769 << " for channel " << *it << " and ssrc " << ssrc;
2774 bool WebRtcVoiceMediaChannel::GetOutputScaling(
2775 uint32 ssrc, double* left, double* right) {
2776 if (!left || !right) return false;
2778 talk_base::CritScope lock(&receive_channels_cs_);
2779 // Determine which channel based on ssrc.
2780 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2781 if (channel == -1) {
2782 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2787 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2788 channel, scaling)) {
2789 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2795 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2796 channel, left_pan, right_pan)) {
2797 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2798 // If GetOutputVolumePan fails, we use the default left and right pan.
2803 *left = scaling * left_pan;
2804 *right = scaling * right_pan;
2808 bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2809 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2813 bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2814 bool play, bool loop) {
2815 if (!ringback_tone_) {
2819 // The voe file api is not available in chrome.
2820 if (!engine()->voe()->file()) {
2824 // Determine which VoiceEngine channel to play on.
2825 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2826 if (channel == -1) {
2830 // Make sure the ringtone is cued properly, and play it out.
2832 ringback_tone_->set_loop(loop);
2833 ringback_tone_->Rewind();
2834 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2835 ringback_tone_.get()) == -1) {
2836 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2837 LOG(LS_ERROR) << "Unable to start ringback tone";
2840 ringback_channels_.insert(channel);
2841 LOG(LS_INFO) << "Started ringback on channel " << channel;
2843 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2844 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2845 LOG_RTCERR1(StopPlayingFileLocally, channel);
2848 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2849 ringback_channels_.erase(channel);
2855 bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2856 return dtmf_allowed_;
2859 bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2860 int duration, int flags) {
2861 if (!dtmf_allowed_) {
2866 if (flags & cricket::DF_SEND) {
2869 bool default_channel_is_inuse = false;
2870 for (ChannelMap::const_iterator iter = send_channels_.begin();
2871 iter != send_channels_.end(); ++iter) {
2872 if (IsDefaultChannel(iter->second->channel())) {
2873 default_channel_is_inuse = true;
2877 if (default_channel_is_inuse) {
2878 channel = voe_channel();
2879 } else if (!send_channels_.empty()) {
2880 channel = send_channels_.begin()->second->channel();
2883 channel = GetSendChannelNum(ssrc);
2885 if (channel == -1) {
2886 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2887 << ssrc << " is not in use.";
2890 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
2891 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2892 channel, event, true, duration) == -1) {
2893 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
2899 if (flags & cricket::DF_PLAY) {
2900 // Play DTMF tone locally.
2901 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
2902 LOG_RTCERR2(PlayDtmfTone, event, duration);
2910 void WebRtcVoiceMediaChannel::OnPacketReceived(
2911 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
2912 // Pick which channel to send this packet to. If this packet doesn't match
2913 // any multiplexed streams, just send it to the default channel. Otherwise,
2914 // send it to the specific decoder instance for that stream.
2915 int which_channel = GetReceiveChannelNum(
2916 ParseSsrc(packet->data(), packet->length(), false));
2917 if (which_channel == -1) {
2918 which_channel = voe_channel();
2921 // Stop any ringback that might be playing on the channel.
2922 // It's possible the ringback has already stopped, ih which case we'll just
2923 // use the opportunity to remove the channel from ringback_channels_.
2924 if (engine()->voe()->file()) {
2925 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
2926 if (it != ringback_channels_.end()) {
2927 if (engine()->voe()->file()->IsPlayingFileLocally(
2928 which_channel) == 1) {
2929 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
2930 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
2931 << " due to incoming media";
2933 ringback_channels_.erase(which_channel);
2937 // Pass it off to the decoder.
2938 engine()->voe()->network()->ReceivedRTPPacket(
2941 static_cast<unsigned int>(packet->length()));
2944 void WebRtcVoiceMediaChannel::OnRtcpReceived(
2945 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
2946 // Sending channels need all RTCP packets with feedback information.
2947 // Even sender reports can contain attached report blocks.
2948 // Receiving channels need sender reports in order to create
2949 // correct receiver reports.
2951 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
2952 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
2956 // If it is a sender report, find the channel that is listening.
2957 bool has_sent_to_default_channel = false;
2958 if (type == kRtcpTypeSR) {
2959 int which_channel = GetReceiveChannelNum(
2960 ParseSsrc(packet->data(), packet->length(), true));
2961 if (which_channel != -1) {
2962 engine()->voe()->network()->ReceivedRTCPPacket(
2965 static_cast<unsigned int>(packet->length()));
2967 if (IsDefaultChannel(which_channel))
2968 has_sent_to_default_channel = true;
2972 // SR may continue RR and any RR entry may correspond to any one of the send
2973 // channels. So all RTCP packets must be forwarded all send channels. VoE
2974 // will filter out RR internally.
2975 for (ChannelMap::iterator iter = send_channels_.begin();
2976 iter != send_channels_.end(); ++iter) {
2977 // Make sure not sending the same packet to default channel more than once.
2978 if (IsDefaultChannel(iter->second->channel()) &&
2979 has_sent_to_default_channel)
2982 engine()->voe()->network()->ReceivedRTCPPacket(
2983 iter->second->channel(),
2985 static_cast<unsigned int>(packet->length()));
2989 bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
2990 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
2991 if (channel == -1) {
2992 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
2995 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
2996 LOG_RTCERR2(SetInputMute, channel, muted);
3002 bool WebRtcVoiceMediaChannel::SetStartSendBandwidth(int bps) {
3003 // TODO(andresp): Add support for setting an independent start bandwidth when
3004 // bandwidth estimation is enabled for voice engine.
3008 bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
3009 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
3011 return SetSendBandwidthInternal(bps);
3014 bool WebRtcVoiceMediaChannel::SetSendBandwidthInternal(int bps) {
3015 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBandwidthInternal.";
3017 send_bw_setting_ = true;
3021 LOG(LS_INFO) << "The send codec has not been set up yet. "
3022 << "The send bandwidth setting will be applied later.";
3026 // Bandwidth is auto by default.
3027 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3028 // SetMaxSendBandwith(0), the second call removes the previous limit.
3032 webrtc::CodecInst codec = *send_codec_;
3033 bool is_multi_rate = IsCodecMultiRate(codec);
3035 if (is_multi_rate) {
3036 // If codec is multi-rate then just set the bitrate.
3038 if (!SetSendCodec(codec)) {
3039 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3040 << " to bitrate " << bps << " bps.";
3045 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3046 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3047 // fixed bitrate then ignore.
3048 if (bps < codec.rate) {
3049 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3050 << " to bitrate " << bps << " bps"
3051 << ", requires at least " << codec.rate << " bps.";
3058 bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
3059 bool echo_metrics_on = false;
3060 // These can take on valid negative values, so use the lowest possible level
3061 // as default rather than -1.
3062 int echo_return_loss = -100;
3063 int echo_return_loss_enhancement = -100;
3064 // These can also be negative, but in practice -1 is only used to signal
3065 // insufficient data, since the resolution is limited to multiples of 4 ms.
3066 int echo_delay_median_ms = -1;
3067 int echo_delay_std_ms = -1;
3068 if (engine()->voe()->processing()->GetEcMetricsStatus(
3069 echo_metrics_on) != -1 && echo_metrics_on) {
3070 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3071 // here, but it appears to be unsuitable currently. Revisit after this is
3072 // investigated: http://b/issue?id=5666755
3073 int erl, erle, rerl, anlp;
3074 if (engine()->voe()->processing()->GetEchoMetrics(
3075 erl, erle, rerl, anlp) != -1) {
3076 echo_return_loss = erl;
3077 echo_return_loss_enhancement = erle;
3081 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3082 echo_delay_median_ms = median;
3083 echo_delay_std_ms = std;
3087 webrtc::CallStatistics cs;
3089 webrtc::CodecInst codec;
3092 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3093 channel_iter != send_channels_.end(); ++channel_iter) {
3094 const int channel = channel_iter->second->channel();
3096 // Fill in the sender info, based on what we know, and what the
3097 // remote side told us it got from its RTCP report.
3098 VoiceSenderInfo sinfo;
3100 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3101 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3105 sinfo.add_ssrc(ssrc);
3106 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3107 sinfo.bytes_sent = cs.bytesSent;
3108 sinfo.packets_sent = cs.packetsSent;
3109 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3110 // returns 0 to indicate an error value.
3111 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3113 // Get data from the last remote RTCP report. Use default values if no data
3115 sinfo.fraction_lost = -1.0;
3116 sinfo.jitter_ms = -1;
3117 sinfo.packets_lost = -1;
3118 sinfo.ext_seqnum = -1;
3119 std::vector<webrtc::ReportBlock> receive_blocks;
3120 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3121 channel, &receive_blocks) != -1 &&
3122 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3123 std::vector<webrtc::ReportBlock>::iterator iter;
3124 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3126 // Lookup report for send ssrc only.
3127 if (iter->source_SSRC == sinfo.ssrc()) {
3128 // Convert Q8 to floating point.
3129 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3130 // Convert samples to milliseconds.
3131 if (codec.plfreq / 1000 > 0) {
3132 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3134 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3135 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3141 // Local speech level.
3142 sinfo.audio_level = (engine()->voe()->volume()->
3143 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3145 // TODO(xians): We are injecting the same APM logging to all the send
3146 // channels here because there is no good way to know which send channel
3147 // is using the APM. The correct fix is to allow the send channels to have
3148 // their own APM so that we can feed the correct APM logging to different
3149 // send channels. See issue crbug/264611 .
3150 sinfo.echo_return_loss = echo_return_loss;
3151 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3152 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3153 sinfo.echo_delay_std_ms = echo_delay_std_ms;
3154 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3155 sinfo.aec_quality_min = -1;
3156 sinfo.typing_noise_detected = typing_noise_detected_;
3158 info->senders.push_back(sinfo);
3161 // Build the list of receivers, one for each receiving channel, or 1 in
3163 std::vector<int> channels;
3164 for (ChannelMap::const_iterator it = receive_channels_.begin();
3165 it != receive_channels_.end(); ++it) {
3166 channels.push_back(it->second->channel());
3168 if (channels.empty()) {
3169 channels.push_back(voe_channel());
3172 // Get the SSRC and stats for each receiver, based on our own calculations.
3173 for (std::vector<int>::const_iterator it = channels.begin();
3174 it != channels.end(); ++it) {
3175 memset(&cs, 0, sizeof(cs));
3176 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3177 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3178 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3179 VoiceReceiverInfo rinfo;
3180 rinfo.add_ssrc(ssrc);
3181 rinfo.bytes_rcvd = cs.bytesReceived;
3182 rinfo.packets_rcvd = cs.packetsReceived;
3183 // The next four fields are from the most recently sent RTCP report.
3184 // Convert Q8 to floating point.
3185 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3186 rinfo.packets_lost = cs.cumulativeLost;
3187 rinfo.ext_seqnum = cs.extendedMax;
3188 // Convert samples to milliseconds.
3189 if (codec.plfreq / 1000 > 0) {
3190 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3193 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3194 webrtc::NetworkStatistics ns;
3195 if (engine()->voe()->neteq() &&
3196 engine()->voe()->neteq()->GetNetworkStatistics(
3198 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3199 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3201 static_cast<float>(ns.currentExpandRate) / (1 << 14);
3204 webrtc::AudioDecodingCallStats ds;
3205 if (engine()->voe()->neteq() &&
3206 engine()->voe()->neteq()->GetDecodingCallStatistics(
3208 rinfo.decoding_calls_to_silence_generator =
3209 ds.calls_to_silence_generator;
3210 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3211 rinfo.decoding_normal = ds.decoded_normal;
3212 rinfo.decoding_plc = ds.decoded_plc;
3213 rinfo.decoding_cng = ds.decoded_cng;
3214 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3217 if (engine()->voe()->sync()) {
3218 int jitter_buffer_delay_ms = 0;
3219 int playout_buffer_delay_ms = 0;
3220 engine()->voe()->sync()->GetDelayEstimate(
3221 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3222 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3223 playout_buffer_delay_ms;
3226 // Get speech level.
3227 rinfo.audio_level = (engine()->voe()->volume()->
3228 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3229 info->receivers.push_back(rinfo);
3236 void WebRtcVoiceMediaChannel::GetLastMediaError(
3237 uint32* ssrc, VoiceMediaChannel::Error* error) {
3238 ASSERT(ssrc != NULL);
3239 ASSERT(error != NULL);
3240 FindSsrc(voe_channel(), ssrc);
3241 *error = WebRtcErrorToChannelError(GetLastEngineError());
3244 bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
3245 talk_base::CritScope lock(&receive_channels_cs_);
3246 ASSERT(ssrc != NULL);
3247 if (channel_num == -1 && send_ != SEND_NOTHING) {
3248 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3249 // This means the error is not limited to a specific channel. Signal the
3250 // message using ssrc=0. If the current channel is sending, use this
3251 // channel for sending the message.
3255 // Check whether this is a sending channel.
3256 for (ChannelMap::const_iterator it = send_channels_.begin();
3257 it != send_channels_.end(); ++it) {
3258 if (it->second->channel() == channel_num) {
3259 // This is a sending channel.
3260 uint32 local_ssrc = 0;
3261 if (engine()->voe()->rtp()->GetLocalSSRC(
3262 channel_num, local_ssrc) != -1) {
3269 // Check whether this is a receiving channel.
3270 for (ChannelMap::const_iterator it = receive_channels_.begin();
3271 it != receive_channels_.end(); ++it) {
3272 if (it->second->channel() == channel_num) {
3281 void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
3282 if (error == VE_TYPING_NOISE_WARNING) {
3283 typing_noise_detected_ = true;
3284 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3285 typing_noise_detected_ = false;
3287 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3290 int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3291 unsigned int ulevel;
3293 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3294 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3297 int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
3298 ChannelMap::iterator it = receive_channels_.find(ssrc);
3299 if (it != receive_channels_.end())
3300 return it->second->channel();
3301 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3304 int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
3305 ChannelMap::iterator it = send_channels_.find(ssrc);
3306 if (it != send_channels_.end())
3307 return it->second->channel();
3312 bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3313 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3314 // Get the RED encodings from the parameter with no name. This may
3315 // change based on what is discussed on the Jingle list.
3316 // The encoding parameter is of the form "a/b"; we only support where
3317 // a == b. Verify this and parse out the value into red_pt.
3318 // If the parameter value is absent (as it will be until we wire up the
3319 // signaling of this message), use the second codec specified (i.e. the
3320 // one after "red") as the encoding parameter.
3322 std::string red_params;
3323 CodecParameterMap::const_iterator it = red_codec.params.find("");
3324 if (it != red_codec.params.end()) {
3325 red_params = it->second;
3326 std::vector<std::string> red_pts;
3327 if (talk_base::split(red_params, '/', &red_pts) != 2 ||
3328 red_pts[0] != red_pts[1] ||
3329 !talk_base::FromString(red_pts[0], &red_pt)) {
3330 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3333 } else if (red_codec.params.empty()) {
3334 LOG(LS_WARNING) << "RED params not present, using defaults";
3335 if (all_codecs.size() > 1) {
3336 red_pt = all_codecs[1].id;
3340 // Try to find red_pt in |codecs|.
3341 std::vector<AudioCodec>::const_iterator codec;
3342 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3343 if (codec->id == red_pt)
3347 // If we find the right codec, that will be the codec we pass to
3348 // SetSendCodec, with the desired payload type.
3349 if (codec != all_codecs.end() &&
3350 engine()->FindWebRtcCodec(*codec, send_codec)) {
3352 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3359 bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3360 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
3361 LOG_RTCERR2(SetRTCPStatus, channel, 1);
3364 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3365 // what we want to do with them.
3366 // engine()->voe().EnableVQMon(voe_channel(), true);
3367 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3371 bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3372 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3373 for (int i = 0; i < ncodecs; ++i) {
3374 webrtc::CodecInst voe_codec;
3375 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3376 voe_codec.pltype = -1;
3377 if (engine()->voe()->codec()->SetRecPayloadType(
3378 channel, voe_codec) == -1) {
3379 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3387 bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3389 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3390 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3391 LOG_RTCERR1(StartPlayout, channel);
3395 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3396 engine()->voe()->base()->StopPlayout(channel);
3401 uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3403 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3405 if (len >= (ssrc_pos + sizeof(ssrc))) {
3406 ssrc = talk_base::GetBE32(static_cast<const char*>(data) + ssrc_pos);
3411 // Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3412 VoiceMediaChannel::Error
3413 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3417 case VE_CANNOT_START_RECORDING:
3418 case VE_MIC_VOL_ERROR:
3419 case VE_GET_MIC_VOL_ERROR:
3420 case VE_CANNOT_ACCESS_MIC_VOL:
3421 return ERROR_REC_DEVICE_OPEN_FAILED;
3422 case VE_SATURATION_WARNING:
3423 return ERROR_REC_DEVICE_SATURATION;
3424 case VE_REC_DEVICE_REMOVED:
3425 return ERROR_REC_DEVICE_REMOVED;
3426 case VE_RUNTIME_REC_WARNING:
3427 case VE_RUNTIME_REC_ERROR:
3428 return ERROR_REC_RUNTIME_ERROR;
3429 case VE_CANNOT_START_PLAYOUT:
3430 case VE_SPEAKER_VOL_ERROR:
3431 case VE_GET_SPEAKER_VOL_ERROR:
3432 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3433 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3434 case VE_RUNTIME_PLAY_WARNING:
3435 case VE_RUNTIME_PLAY_ERROR:
3436 return ERROR_PLAY_RUNTIME_ERROR;
3437 case VE_TYPING_NOISE_WARNING:
3438 return ERROR_REC_TYPING_NOISE_DETECTED;
3440 return VoiceMediaChannel::ERROR_OTHER;
3444 int WebRtcSoundclipStream::Read(void *buf, int len) {
3446 mem_.Read(buf, len, &res, NULL);
3447 return static_cast<int>(res);
3450 int WebRtcSoundclipStream::Rewind() {
3452 // Return -1 to keep VoiceEngine from looping.
3453 return (loop_) ? 0 : -1;
3456 } // namespace cricket
3458 #endif // HAVE_WEBRTC_VOICE