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 static const char kIsacCodecName[] = "ISAC";
111 static const char kL16CodecName[] = "L16";
112 // Codec parameters for Opus.
113 static const int kOpusMonoBitrate = 32000;
114 // Parameter used for NACK.
115 // This value is equivalent to 5 seconds of audio data at 20 ms per packet.
116 static const int kNackMaxPackets = 250;
117 static const int kOpusStereoBitrate = 64000;
118 // draft-spittka-payload-rtp-opus-03
119 // Opus bitrate should be in the range between 6000 and 510000.
120 static const int kOpusMinBitrate = 6000;
121 static const int kOpusMaxBitrate = 510000;
122 // Default audio dscp value.
123 // See http://tools.ietf.org/html/rfc2474 for details.
124 // See also http://tools.ietf.org/html/draft-jennings-rtcweb-qos-00
125 static const talk_base::DiffServCodePoint kAudioDscpValue = talk_base::DSCP_EF;
127 // Ensure we open the file in a writeable path on ChromeOS and Android. This
128 // workaround can be removed when it's possible to specify a filename for audio
129 // option based AEC dumps.
131 // TODO(grunell): Use a string in the options instead of hardcoding it here
132 // and let the embedder choose the filename (crbug.com/264223).
134 // NOTE(ajm): Don't use hardcoded paths on platforms not explicitly specified
136 #if defined(CHROMEOS)
137 static const char kAecDumpByAudioOptionFilename[] = "/tmp/audio.aecdump";
138 #elif defined(ANDROID)
139 static const char kAecDumpByAudioOptionFilename[] = "/sdcard/audio.aecdump";
141 static const char kAecDumpByAudioOptionFilename[] = "audio.aecdump";
144 // Dumps an AudioCodec in RFC 2327-ish format.
145 static std::string ToString(const AudioCodec& codec) {
146 std::stringstream ss;
147 ss << codec.name << "/" << codec.clockrate << "/" << codec.channels
148 << " (" << codec.id << ")";
151 static std::string ToString(const webrtc::CodecInst& codec) {
152 std::stringstream ss;
153 ss << codec.plname << "/" << codec.plfreq << "/" << codec.channels
154 << " (" << codec.pltype << ")";
158 static void LogMultiline(talk_base::LoggingSeverity sev, char* text) {
159 const char* delim = "\r\n";
160 for (char* tok = strtok(text, delim); tok; tok = strtok(NULL, delim)) {
165 // Severity is an integer because it comes is assumed to be from command line.
166 static int SeverityToFilter(int severity) {
167 int filter = webrtc::kTraceNone;
169 case talk_base::LS_VERBOSE:
170 filter |= webrtc::kTraceAll;
171 case talk_base::LS_INFO:
172 filter |= (webrtc::kTraceStateInfo | webrtc::kTraceInfo);
173 case talk_base::LS_WARNING:
174 filter |= (webrtc::kTraceTerseInfo | webrtc::kTraceWarning);
175 case talk_base::LS_ERROR:
176 filter |= (webrtc::kTraceError | webrtc::kTraceCritical);
181 static bool IsCodecMultiRate(const webrtc::CodecInst& codec) {
182 for (size_t i = 0; i < ARRAY_SIZE(kCodecPrefs); ++i) {
183 if (_stricmp(kCodecPrefs[i].name, codec.plname) == 0 &&
184 kCodecPrefs[i].clockrate == codec.plfreq) {
185 return kCodecPrefs[i].is_multi_rate;
191 static bool IsTelephoneEventCodec(const std::string& name) {
192 return _stricmp(name.c_str(), "telephone-event") == 0;
195 static bool IsCNCodec(const std::string& name) {
196 return _stricmp(name.c_str(), "CN") == 0;
199 static bool IsRedCodec(const std::string& name) {
200 return _stricmp(name.c_str(), "red") == 0;
203 static bool FindCodec(const std::vector<AudioCodec>& codecs,
204 const AudioCodec& codec,
205 AudioCodec* found_codec) {
206 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
207 it != codecs.end(); ++it) {
208 if (it->Matches(codec)) {
209 if (found_codec != NULL) {
218 static bool IsNackEnabled(const AudioCodec& codec) {
219 return codec.HasFeedbackParam(FeedbackParam(kRtcpFbParamNack,
223 // Gets the default set of options applied to the engine. Historically, these
224 // were supplied as a combination of flags from the channel manager (ec, agc,
225 // ns, and highpass) and the rest hardcoded in InitInternal.
226 static AudioOptions GetDefaultEngineOptions() {
227 AudioOptions options;
228 options.echo_cancellation.Set(true);
229 options.auto_gain_control.Set(true);
230 options.noise_suppression.Set(true);
231 options.highpass_filter.Set(true);
232 options.stereo_swapping.Set(false);
233 options.typing_detection.Set(true);
234 options.conference_mode.Set(false);
235 options.adjust_agc_delta.Set(0);
236 options.experimental_agc.Set(false);
237 options.experimental_aec.Set(false);
238 options.experimental_ns.Set(false);
239 options.aec_dump.Set(false);
243 class WebRtcSoundclipMedia : public SoundclipMedia {
245 explicit WebRtcSoundclipMedia(WebRtcVoiceEngine *engine)
246 : engine_(engine), webrtc_channel_(-1) {
247 engine_->RegisterSoundclip(this);
250 virtual ~WebRtcSoundclipMedia() {
251 engine_->UnregisterSoundclip(this);
252 if (webrtc_channel_ != -1) {
253 // We shouldn't have to call Disable() here. DeleteChannel() should call
254 // StopPlayout() while deleting the channel. We should fix the bug
255 // inside WebRTC and remove the Disable() call bellow. This work is
256 // tracked by bug http://b/issue?id=5382855.
257 PlaySound(NULL, 0, 0);
259 if (engine_->voe_sc()->base()->DeleteChannel(webrtc_channel_)
261 LOG_RTCERR1(DeleteChannel, webrtc_channel_);
267 if (!engine_->voe_sc()) {
270 webrtc_channel_ = engine_->CreateSoundclipVoiceChannel();
271 if (webrtc_channel_ == -1) {
272 LOG_RTCERR0(CreateChannel);
279 if (engine_->voe_sc()->base()->StartPlayout(webrtc_channel_) == -1) {
280 LOG_RTCERR1(StartPlayout, webrtc_channel_);
287 if (engine_->voe_sc()->base()->StopPlayout(webrtc_channel_) == -1) {
288 LOG_RTCERR1(StopPlayout, webrtc_channel_);
294 virtual bool PlaySound(const char *buf, int len, int flags) {
295 // The voe file api is not available in chrome.
296 if (!engine_->voe_sc()->file()) {
299 // Must stop playing the current sound (if any), because we are about to
300 // modify the stream.
301 if (engine_->voe_sc()->file()->StopPlayingFileLocally(webrtc_channel_)
303 LOG_RTCERR1(StopPlayingFileLocally, webrtc_channel_);
308 stream_.reset(new WebRtcSoundclipStream(buf, len));
309 stream_->set_loop((flags & SF_LOOP) != 0);
313 if (engine_->voe_sc()->file()->StartPlayingFileLocally(
314 webrtc_channel_, stream_.get()) == -1) {
315 LOG_RTCERR2(StartPlayingFileLocally, webrtc_channel_, stream_.get());
316 LOG(LS_ERROR) << "Unable to start soundclip";
325 int GetLastEngineError() const { return engine_->voe_sc()->error(); }
328 WebRtcVoiceEngine *engine_;
330 talk_base::scoped_ptr<WebRtcSoundclipStream> stream_;
333 WebRtcVoiceEngine::WebRtcVoiceEngine()
334 : voe_wrapper_(new VoEWrapper()),
335 voe_wrapper_sc_(new VoEWrapper()),
336 voe_wrapper_sc_initialized_(false),
337 tracing_(new VoETraceWrapper()),
340 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
341 is_dumping_aec_(false),
342 desired_local_monitor_enable_(false),
343 tx_processor_ssrc_(0),
344 rx_processor_ssrc_(0) {
348 WebRtcVoiceEngine::WebRtcVoiceEngine(VoEWrapper* voe_wrapper,
349 VoEWrapper* voe_wrapper_sc,
350 VoETraceWrapper* tracing)
351 : voe_wrapper_(voe_wrapper),
352 voe_wrapper_sc_(voe_wrapper_sc),
353 voe_wrapper_sc_initialized_(false),
357 log_filter_(SeverityToFilter(kDefaultLogSeverity)),
358 is_dumping_aec_(false),
359 desired_local_monitor_enable_(false),
360 tx_processor_ssrc_(0),
361 rx_processor_ssrc_(0) {
365 void WebRtcVoiceEngine::Construct() {
366 SetTraceFilter(log_filter_);
367 initialized_ = false;
368 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::WebRtcVoiceEngine";
370 if (tracing_->SetTraceCallback(this) == -1) {
371 LOG_RTCERR0(SetTraceCallback);
373 if (voe_wrapper_->base()->RegisterVoiceEngineObserver(*this) == -1) {
374 LOG_RTCERR0(RegisterVoiceEngineObserver);
376 // Clear the default agc state.
377 memset(&default_agc_config_, 0, sizeof(default_agc_config_));
379 // Load our audio codec list.
382 // Load our RTP Header extensions.
383 rtp_header_extensions_.push_back(
384 RtpHeaderExtension(kRtpAudioLevelHeaderExtension,
385 kRtpAudioLevelHeaderExtensionDefaultId));
386 rtp_header_extensions_.push_back(
387 RtpHeaderExtension(kRtpAbsoluteSenderTimeHeaderExtension,
388 kRtpAbsoluteSenderTimeHeaderExtensionDefaultId));
389 options_ = GetDefaultEngineOptions();
392 static bool IsOpus(const AudioCodec& codec) {
393 return (_stricmp(codec.name.c_str(), kOpusCodecName) == 0);
396 static bool IsIsac(const AudioCodec& codec) {
397 return (_stricmp(codec.name.c_str(), kIsacCodecName) == 0);
400 // True if params["stereo"] == "1"
401 static bool IsOpusStereoEnabled(const AudioCodec& codec) {
402 CodecParameterMap::const_iterator param =
403 codec.params.find(kCodecParamStereo);
404 if (param == codec.params.end()) {
407 return param->second == kParamValueTrue;
410 static bool IsValidOpusBitrate(int bitrate) {
411 return (bitrate >= kOpusMinBitrate && bitrate <= kOpusMaxBitrate);
414 // Returns 0 if params[kCodecParamMaxAverageBitrate] is not defined or invalid.
415 // Returns the value of params[kCodecParamMaxAverageBitrate] otherwise.
416 static int GetOpusBitrateFromParams(const AudioCodec& codec) {
418 if (!codec.GetParam(kCodecParamMaxAverageBitrate, &bitrate)) {
421 if (!IsValidOpusBitrate(bitrate)) {
422 LOG(LS_WARNING) << "Codec parameter \"maxaveragebitrate\" has an "
423 << "invalid value: " << bitrate;
429 void WebRtcVoiceEngine::ConstructCodecs() {
430 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
431 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
432 for (int i = 0; i < ncodecs; ++i) {
433 webrtc::CodecInst voe_codec;
434 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
435 // Skip uncompressed formats.
436 if (_stricmp(voe_codec.plname, kL16CodecName) == 0) {
440 const CodecPref* pref = NULL;
441 for (size_t j = 0; j < ARRAY_SIZE(kCodecPrefs); ++j) {
442 if (_stricmp(kCodecPrefs[j].name, voe_codec.plname) == 0 &&
443 kCodecPrefs[j].clockrate == voe_codec.plfreq &&
444 kCodecPrefs[j].channels == voe_codec.channels) {
445 pref = &kCodecPrefs[j];
451 // Use the payload type that we've configured in our pref table;
452 // use the offset in our pref table to determine the sort order.
453 AudioCodec codec(pref->payload_type, voe_codec.plname, voe_codec.plfreq,
454 voe_codec.rate, voe_codec.channels,
455 ARRAY_SIZE(kCodecPrefs) - (pref - kCodecPrefs));
456 LOG(LS_INFO) << ToString(codec);
458 // Indicate auto-bandwidth in signaling.
462 // Only add fmtp parameters that differ from the spec.
463 if (kPreferredMinPTime != kOpusDefaultMinPTime) {
464 codec.params[kCodecParamMinPTime] =
465 talk_base::ToString(kPreferredMinPTime);
467 if (kPreferredMaxPTime != kOpusDefaultMaxPTime) {
468 codec.params[kCodecParamMaxPTime] =
469 talk_base::ToString(kPreferredMaxPTime);
471 // TODO(hellner): Add ptime, sprop-stereo, stereo and useinbandfec
472 // when they can be set to values other than the default.
474 codecs_.push_back(codec);
476 LOG(LS_WARNING) << "Unexpected codec: " << ToString(voe_codec);
480 // Make sure they are in local preference order.
481 std::sort(codecs_.begin(), codecs_.end(), &AudioCodec::Preferable);
484 WebRtcVoiceEngine::~WebRtcVoiceEngine() {
485 LOG(LS_VERBOSE) << "WebRtcVoiceEngine::~WebRtcVoiceEngine";
486 if (voe_wrapper_->base()->DeRegisterVoiceEngineObserver() == -1) {
487 LOG_RTCERR0(DeRegisterVoiceEngineObserver);
490 voe_wrapper_.reset();
495 voe_wrapper_sc_.reset();
500 // Test to see if the media processor was deregistered properly
501 ASSERT(SignalRxMediaFrame.is_empty());
502 ASSERT(SignalTxMediaFrame.is_empty());
504 tracing_->SetTraceCallback(NULL);
507 bool WebRtcVoiceEngine::Init(talk_base::Thread* worker_thread) {
508 LOG(LS_INFO) << "WebRtcVoiceEngine::Init";
509 bool res = InitInternal();
511 LOG(LS_INFO) << "WebRtcVoiceEngine::Init Done!";
513 LOG(LS_ERROR) << "WebRtcVoiceEngine::Init failed";
519 bool WebRtcVoiceEngine::InitInternal() {
520 // Temporarily turn logging level up for the Init call
521 int old_filter = log_filter_;
522 int extended_filter = log_filter_ | SeverityToFilter(talk_base::LS_INFO);
523 SetTraceFilter(extended_filter);
526 // Init WebRtc VoiceEngine.
527 if (voe_wrapper_->base()->Init(adm_) == -1) {
528 LOG_RTCERR0_EX(Init, voe_wrapper_->error());
529 SetTraceFilter(old_filter);
533 SetTraceFilter(old_filter);
534 SetTraceOptions(log_options_);
536 // Log the VoiceEngine version info
537 char buffer[1024] = "";
538 voe_wrapper_->base()->GetVersion(buffer);
539 LOG(LS_INFO) << "WebRtc VoiceEngine Version:";
540 LogMultiline(talk_base::LS_INFO, buffer);
542 // Save the default AGC configuration settings. This must happen before
543 // calling SetOptions or the default will be overwritten.
544 if (voe_wrapper_->processing()->GetAgcConfig(default_agc_config_) == -1) {
545 LOG_RTCERR0(GetAgcConfig);
549 // Set defaults for options, so that ApplyOptions applies them explicitly
550 // when we clear option (channel) overrides. External clients can still
551 // modify the defaults via SetOptions (on the media engine).
552 if (!SetOptions(GetDefaultEngineOptions())) {
556 // Print our codec list again for the call diagnostic log
557 LOG(LS_INFO) << "WebRtc VoiceEngine codecs:";
558 for (std::vector<AudioCodec>::const_iterator it = codecs_.begin();
559 it != codecs_.end(); ++it) {
560 LOG(LS_INFO) << ToString(*it);
563 // Disable the DTMF playout when a tone is sent.
564 // PlayDtmfTone will be used if local playout is needed.
565 if (voe_wrapper_->dtmf()->SetDtmfFeedbackStatus(false) == -1) {
566 LOG_RTCERR1(SetDtmfFeedbackStatus, false);
573 bool WebRtcVoiceEngine::EnsureSoundclipEngineInit() {
574 if (voe_wrapper_sc_initialized_) {
577 // Note that, if initialization fails, voe_wrapper_sc_initialized_ will still
578 // be false, so subsequent calls to EnsureSoundclipEngineInit will
579 // probably just fail again. That's acceptable behavior.
580 #if defined(LINUX) && !defined(HAVE_LIBPULSE)
581 voe_wrapper_sc_->hw()->SetAudioDeviceLayer(webrtc::kAudioLinuxAlsa);
584 // Initialize the VoiceEngine instance that we'll use to play out sound clips.
585 if (voe_wrapper_sc_->base()->Init(adm_sc_) == -1) {
586 LOG_RTCERR0_EX(Init, voe_wrapper_sc_->error());
590 // On Windows, tell it to use the default sound (not communication) devices.
591 // First check whether there is a valid sound device for playback.
592 // TODO(juberti): Clean this up when we support setting the soundclip device.
594 // The SetPlayoutDevice may not be implemented in the case of external ADM.
595 // TODO(ronghuawu): We should only check the adm_sc_ here, but current
596 // PeerConnection interface never set the adm_sc_, so need to check both
597 // in order to determine if the external adm is used.
598 if (!adm_ && !adm_sc_) {
599 int num_of_devices = 0;
600 if (voe_wrapper_sc_->hw()->GetNumOfPlayoutDevices(num_of_devices) != -1 &&
601 num_of_devices > 0) {
602 if (voe_wrapper_sc_->hw()->SetPlayoutDevice(kDefaultSoundclipDeviceId)
604 LOG_RTCERR1_EX(SetPlayoutDevice, kDefaultSoundclipDeviceId,
605 voe_wrapper_sc_->error());
609 LOG(LS_WARNING) << "No valid sound playout device found.";
613 voe_wrapper_sc_initialized_ = true;
614 LOG(LS_INFO) << "Initialized WebRtc soundclip engine.";
618 void WebRtcVoiceEngine::Terminate() {
619 LOG(LS_INFO) << "WebRtcVoiceEngine::Terminate";
620 initialized_ = false;
624 if (voe_wrapper_sc_) {
625 voe_wrapper_sc_initialized_ = false;
626 voe_wrapper_sc_->base()->Terminate();
628 voe_wrapper_->base()->Terminate();
629 desired_local_monitor_enable_ = false;
632 int WebRtcVoiceEngine::GetCapabilities() {
633 return AUDIO_SEND | AUDIO_RECV;
636 VoiceMediaChannel *WebRtcVoiceEngine::CreateChannel() {
637 WebRtcVoiceMediaChannel* ch = new WebRtcVoiceMediaChannel(this);
645 SoundclipMedia *WebRtcVoiceEngine::CreateSoundclip() {
646 if (!EnsureSoundclipEngineInit()) {
647 LOG(LS_ERROR) << "Unable to create soundclip: soundclip engine failed to "
651 WebRtcSoundclipMedia *soundclip = new WebRtcSoundclipMedia(this);
652 if (!soundclip->Init() || !soundclip->Enable()) {
659 bool WebRtcVoiceEngine::SetOptions(const AudioOptions& options) {
660 if (!ApplyOptions(options)) {
667 bool WebRtcVoiceEngine::SetOptionOverrides(const AudioOptions& overrides) {
668 LOG(LS_INFO) << "Setting option overrides: " << overrides.ToString();
669 if (!ApplyOptions(overrides)) {
672 option_overrides_ = overrides;
676 bool WebRtcVoiceEngine::ClearOptionOverrides() {
677 LOG(LS_INFO) << "Clearing option overrides.";
678 AudioOptions options = options_;
679 // Only call ApplyOptions if |options_overrides_| contains overrided options.
680 // ApplyOptions affects NS, AGC other options that is shared between
681 // all WebRtcVoiceEngineChannels.
682 if (option_overrides_ == AudioOptions()) {
686 if (!ApplyOptions(options)) {
689 option_overrides_ = AudioOptions();
693 // AudioOptions defaults are set in InitInternal (for options with corresponding
694 // MediaEngineInterface flags) and in SetOptions(int) for flagless options.
695 bool WebRtcVoiceEngine::ApplyOptions(const AudioOptions& options_in) {
696 AudioOptions options = options_in; // The options are modified below.
697 // kEcConference is AEC with high suppression.
698 webrtc::EcModes ec_mode = webrtc::kEcConference;
699 webrtc::AecmModes aecm_mode = webrtc::kAecmSpeakerphone;
700 webrtc::AgcModes agc_mode = webrtc::kAgcAdaptiveAnalog;
701 webrtc::NsModes ns_mode = webrtc::kNsHighSuppression;
702 bool aecm_comfort_noise = false;
703 if (options.aecm_generate_comfort_noise.Get(&aecm_comfort_noise)) {
704 LOG(LS_VERBOSE) << "Comfort noise explicitly set to "
705 << aecm_comfort_noise << " (default is false).";
709 // On iOS, VPIO provides built-in EC and AGC.
710 options.echo_cancellation.Set(false);
711 options.auto_gain_control.Set(false);
712 #elif defined(ANDROID)
713 ec_mode = webrtc::kEcAecm;
716 #if defined(IOS) || defined(ANDROID)
717 // Set the AGC mode for iOS as well despite disabling it above, to avoid
718 // unsupported configuration errors from webrtc.
719 agc_mode = webrtc::kAgcFixedDigital;
720 options.typing_detection.Set(false);
721 options.experimental_agc.Set(false);
722 options.experimental_aec.Set(false);
723 options.experimental_ns.Set(false);
726 LOG(LS_INFO) << "Applying audio options: " << options.ToString();
728 webrtc::VoEAudioProcessing* voep = voe_wrapper_->processing();
730 bool echo_cancellation;
731 if (options.echo_cancellation.Get(&echo_cancellation)) {
732 if (voep->SetEcStatus(echo_cancellation, ec_mode) == -1) {
733 LOG_RTCERR2(SetEcStatus, echo_cancellation, ec_mode);
736 LOG(LS_VERBOSE) << "Echo control set to " << echo_cancellation
737 << " with mode " << ec_mode;
739 #if !defined(ANDROID)
740 // TODO(ajm): Remove the error return on Android from webrtc.
741 if (voep->SetEcMetricsStatus(echo_cancellation) == -1) {
742 LOG_RTCERR1(SetEcMetricsStatus, echo_cancellation);
746 if (ec_mode == webrtc::kEcAecm) {
747 if (voep->SetAecmMode(aecm_mode, aecm_comfort_noise) != 0) {
748 LOG_RTCERR2(SetAecmMode, aecm_mode, aecm_comfort_noise);
754 bool auto_gain_control;
755 if (options.auto_gain_control.Get(&auto_gain_control)) {
756 if (voep->SetAgcStatus(auto_gain_control, agc_mode) == -1) {
757 LOG_RTCERR2(SetAgcStatus, auto_gain_control, agc_mode);
760 LOG(LS_VERBOSE) << "Auto gain set to " << auto_gain_control
761 << " with mode " << agc_mode;
765 if (options.tx_agc_target_dbov.IsSet() ||
766 options.tx_agc_digital_compression_gain.IsSet() ||
767 options.tx_agc_limiter.IsSet()) {
768 // Override default_agc_config_. Generally, an unset option means "leave
769 // the VoE bits alone" in this function, so we want whatever is set to be
770 // stored as the new "default". If we didn't, then setting e.g.
771 // tx_agc_target_dbov would reset digital compression gain and limiter
773 // Also, if we don't update default_agc_config_, then adjust_agc_delta
774 // would be an offset from the original values, and not whatever was set
776 default_agc_config_.targetLeveldBOv =
777 options.tx_agc_target_dbov.GetWithDefaultIfUnset(
778 default_agc_config_.targetLeveldBOv);
779 default_agc_config_.digitalCompressionGaindB =
780 options.tx_agc_digital_compression_gain.GetWithDefaultIfUnset(
781 default_agc_config_.digitalCompressionGaindB);
782 default_agc_config_.limiterEnable =
783 options.tx_agc_limiter.GetWithDefaultIfUnset(
784 default_agc_config_.limiterEnable);
785 if (voe_wrapper_->processing()->SetAgcConfig(default_agc_config_) == -1) {
786 LOG_RTCERR3(SetAgcConfig,
787 default_agc_config_.targetLeveldBOv,
788 default_agc_config_.digitalCompressionGaindB,
789 default_agc_config_.limiterEnable);
794 bool noise_suppression;
795 if (options.noise_suppression.Get(&noise_suppression)) {
796 if (voep->SetNsStatus(noise_suppression, ns_mode) == -1) {
797 LOG_RTCERR2(SetNsStatus, noise_suppression, ns_mode);
800 LOG(LS_VERBOSE) << "Noise suppression set to " << noise_suppression
801 << " with mode " << ns_mode;
805 bool experimental_ns;
806 if (options.experimental_ns.Get(&experimental_ns)) {
807 webrtc::AudioProcessing* audioproc =
808 voe_wrapper_->base()->audio_processing();
809 // We check audioproc for the benefit of tests, since FakeWebRtcVoiceEngine
810 // returns NULL on audio_processing().
812 if (audioproc->EnableExperimentalNs(experimental_ns) == -1) {
813 LOG_RTCERR1(EnableExperimentalNs, experimental_ns);
817 LOG(LS_VERBOSE) << "Experimental noise suppression set to "
822 bool highpass_filter;
823 if (options.highpass_filter.Get(&highpass_filter)) {
824 LOG(LS_INFO) << "High pass filter enabled? " << highpass_filter;
825 if (voep->EnableHighPassFilter(highpass_filter) == -1) {
826 LOG_RTCERR1(SetHighpassFilterStatus, highpass_filter);
831 bool stereo_swapping;
832 if (options.stereo_swapping.Get(&stereo_swapping)) {
833 LOG(LS_INFO) << "Stereo swapping enabled? " << stereo_swapping;
834 voep->EnableStereoChannelSwapping(stereo_swapping);
835 if (voep->IsStereoChannelSwappingEnabled() != stereo_swapping) {
836 LOG_RTCERR1(EnableStereoChannelSwapping, stereo_swapping);
841 bool typing_detection;
842 if (options.typing_detection.Get(&typing_detection)) {
843 LOG(LS_INFO) << "Typing detection is enabled? " << typing_detection;
844 if (voep->SetTypingDetectionStatus(typing_detection) == -1) {
845 // In case of error, log the info and continue
846 LOG_RTCERR1(SetTypingDetectionStatus, typing_detection);
850 int adjust_agc_delta;
851 if (options.adjust_agc_delta.Get(&adjust_agc_delta)) {
852 LOG(LS_INFO) << "Adjust agc delta is " << adjust_agc_delta;
853 if (!AdjustAgcLevel(adjust_agc_delta)) {
859 if (options.aec_dump.Get(&aec_dump)) {
860 LOG(LS_INFO) << "Aec dump is enabled? " << aec_dump;
862 StartAecDump(kAecDumpByAudioOptionFilename);
867 bool experimental_aec;
868 if (options.experimental_aec.Get(&experimental_aec)) {
869 LOG(LS_INFO) << "Experimental aec is " << 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 LOG(LS_INFO) << "Recording sample rate is " << recording_sample_rate;
885 if (voe_wrapper_->hw()->SetRecordingSampleRate(recording_sample_rate)) {
886 LOG_RTCERR1(SetRecordingSampleRate, recording_sample_rate);
890 uint32 playout_sample_rate;
891 if (options.playout_sample_rate.Get(&playout_sample_rate)) {
892 LOG(LS_INFO) << "Playout sample rate is " << playout_sample_rate;
893 if (voe_wrapper_->hw()->SetPlayoutSampleRate(playout_sample_rate)) {
894 LOG_RTCERR1(SetPlayoutSampleRate, playout_sample_rate);
901 bool WebRtcVoiceEngine::SetDelayOffset(int offset) {
902 voe_wrapper_->processing()->SetDelayOffsetMs(offset);
903 if (voe_wrapper_->processing()->DelayOffsetMs() != offset) {
904 LOG_RTCERR1(SetDelayOffsetMs, offset);
912 ResumeEntry(WebRtcVoiceMediaChannel *c, bool p, SendFlags s)
918 WebRtcVoiceMediaChannel *channel;
923 // TODO(juberti): Refactor this so that the core logic can be used to set the
924 // soundclip device. At that time, reinstate the soundclip pause/resume code.
925 bool WebRtcVoiceEngine::SetDevices(const Device* in_device,
926 const Device* out_device) {
928 int in_id = in_device ? talk_base::FromString<int>(in_device->id) :
929 kDefaultAudioDeviceId;
930 int out_id = out_device ? talk_base::FromString<int>(out_device->id) :
931 kDefaultAudioDeviceId;
932 // The device manager uses -1 as the default device, which was the case for
933 // VoE 3.5. VoE 4.0, however, uses 0 as the default in Linux and Mac.
936 in_id = kDefaultAudioDeviceId;
939 out_id = kDefaultAudioDeviceId;
943 std::string in_name = (in_id != kDefaultAudioDeviceId) ?
944 in_device->name : "Default device";
945 std::string out_name = (out_id != kDefaultAudioDeviceId) ?
946 out_device->name : "Default device";
947 LOG(LS_INFO) << "Setting microphone to (id=" << in_id << ", name=" << in_name
948 << ") and speaker to (id=" << out_id << ", name=" << out_name
951 // If we're running the local monitor, we need to stop it first.
953 if (!PauseLocalMonitor()) {
954 LOG(LS_WARNING) << "Failed to pause local monitor";
958 // Must also pause all audio playback and capture.
959 for (ChannelList::const_iterator i = channels_.begin();
960 i != channels_.end(); ++i) {
961 WebRtcVoiceMediaChannel *channel = *i;
962 if (!channel->PausePlayout()) {
963 LOG(LS_WARNING) << "Failed to pause playout";
966 if (!channel->PauseSend()) {
967 LOG(LS_WARNING) << "Failed to pause send";
972 // Find the recording device id in VoiceEngine and set recording device.
973 if (!FindWebRtcAudioDeviceId(true, in_name, in_id, &in_id)) {
977 if (voe_wrapper_->hw()->SetRecordingDevice(in_id) == -1) {
978 LOG_RTCERR2(SetRecordingDevice, in_name, in_id);
983 // Find the playout device id in VoiceEngine and set playout device.
984 if (!FindWebRtcAudioDeviceId(false, out_name, out_id, &out_id)) {
985 LOG(LS_WARNING) << "Failed to find VoiceEngine device id for " << out_name;
989 if (voe_wrapper_->hw()->SetPlayoutDevice(out_id) == -1) {
990 LOG_RTCERR2(SetPlayoutDevice, out_name, out_id);
995 // Resume all audio playback and capture.
996 for (ChannelList::const_iterator i = channels_.begin();
997 i != channels_.end(); ++i) {
998 WebRtcVoiceMediaChannel *channel = *i;
999 if (!channel->ResumePlayout()) {
1000 LOG(LS_WARNING) << "Failed to resume playout";
1003 if (!channel->ResumeSend()) {
1004 LOG(LS_WARNING) << "Failed to resume send";
1009 // Resume local monitor.
1010 if (!ResumeLocalMonitor()) {
1011 LOG(LS_WARNING) << "Failed to resume local monitor";
1016 LOG(LS_INFO) << "Set microphone to (id=" << in_id <<" name=" << in_name
1017 << ") and speaker to (id="<< out_id << " name=" << out_name
1027 bool WebRtcVoiceEngine::FindWebRtcAudioDeviceId(
1028 bool is_input, const std::string& dev_name, int dev_id, int* rtc_id) {
1029 // In Linux, VoiceEngine uses the same device dev_id as the device manager.
1030 #if defined(LINUX) || defined(ANDROID)
1034 // In Windows and Mac, we need to find the VoiceEngine device id by name
1035 // unless the input dev_id is the default device id.
1036 if (kDefaultAudioDeviceId == dev_id) {
1041 // Get the number of VoiceEngine audio devices.
1044 if (-1 == voe_wrapper_->hw()->GetNumOfRecordingDevices(count)) {
1045 LOG_RTCERR0(GetNumOfRecordingDevices);
1049 if (-1 == voe_wrapper_->hw()->GetNumOfPlayoutDevices(count)) {
1050 LOG_RTCERR0(GetNumOfPlayoutDevices);
1055 for (int i = 0; i < count; ++i) {
1059 voe_wrapper_->hw()->GetRecordingDeviceName(i, name, guid);
1060 LOG(LS_VERBOSE) << "VoiceEngine microphone " << i << ": " << name;
1062 voe_wrapper_->hw()->GetPlayoutDeviceName(i, name, guid);
1063 LOG(LS_VERBOSE) << "VoiceEngine speaker " << i << ": " << name;
1066 std::string webrtc_name(name);
1067 if (dev_name.compare(0, webrtc_name.size(), webrtc_name) == 0) {
1072 LOG(LS_WARNING) << "VoiceEngine cannot find device: " << dev_name;
1077 bool WebRtcVoiceEngine::GetOutputVolume(int* level) {
1078 unsigned int ulevel;
1079 if (voe_wrapper_->volume()->GetSpeakerVolume(ulevel) == -1) {
1080 LOG_RTCERR1(GetSpeakerVolume, level);
1087 bool WebRtcVoiceEngine::SetOutputVolume(int level) {
1088 ASSERT(level >= 0 && level <= 255);
1089 if (voe_wrapper_->volume()->SetSpeakerVolume(level) == -1) {
1090 LOG_RTCERR1(SetSpeakerVolume, level);
1096 int WebRtcVoiceEngine::GetInputLevel() {
1097 unsigned int ulevel;
1098 return (voe_wrapper_->volume()->GetSpeechInputLevel(ulevel) != -1) ?
1099 static_cast<int>(ulevel) : -1;
1102 bool WebRtcVoiceEngine::SetLocalMonitor(bool enable) {
1103 desired_local_monitor_enable_ = enable;
1104 return ChangeLocalMonitor(desired_local_monitor_enable_);
1107 bool WebRtcVoiceEngine::ChangeLocalMonitor(bool enable) {
1108 // The voe file api is not available in chrome.
1109 if (!voe_wrapper_->file()) {
1112 if (enable && !monitor_) {
1113 monitor_.reset(new WebRtcMonitorStream);
1114 if (voe_wrapper_->file()->StartRecordingMicrophone(monitor_.get()) == -1) {
1115 LOG_RTCERR1(StartRecordingMicrophone, monitor_.get());
1116 // Must call Stop() because there are some cases where Start will report
1117 // failure but still change the state, and if we leave VE in the on state
1118 // then it could crash later when trying to invoke methods on our monitor.
1119 voe_wrapper_->file()->StopRecordingMicrophone();
1123 } else if (!enable && monitor_) {
1124 voe_wrapper_->file()->StopRecordingMicrophone();
1130 bool WebRtcVoiceEngine::PauseLocalMonitor() {
1131 return ChangeLocalMonitor(false);
1134 bool WebRtcVoiceEngine::ResumeLocalMonitor() {
1135 return ChangeLocalMonitor(desired_local_monitor_enable_);
1138 const std::vector<AudioCodec>& WebRtcVoiceEngine::codecs() {
1142 bool WebRtcVoiceEngine::FindCodec(const AudioCodec& in) {
1143 return FindWebRtcCodec(in, NULL);
1146 // Get the VoiceEngine codec that matches |in|, with the supplied settings.
1147 bool WebRtcVoiceEngine::FindWebRtcCodec(const AudioCodec& in,
1148 webrtc::CodecInst* out) {
1149 int ncodecs = voe_wrapper_->codec()->NumOfCodecs();
1150 for (int i = 0; i < ncodecs; ++i) {
1151 webrtc::CodecInst voe_codec;
1152 if (voe_wrapper_->codec()->GetCodec(i, voe_codec) != -1) {
1153 AudioCodec codec(voe_codec.pltype, voe_codec.plname, voe_codec.plfreq,
1154 voe_codec.rate, voe_codec.channels, 0);
1155 bool multi_rate = IsCodecMultiRate(voe_codec);
1156 // Allow arbitrary rates for ISAC to be specified.
1158 // Set codec.bitrate to 0 so the check for codec.Matches() passes.
1161 if (codec.Matches(in)) {
1163 // Fixup the payload type.
1164 voe_codec.pltype = in.id;
1166 // Set bitrate if specified.
1167 if (multi_rate && in.bitrate != 0) {
1168 voe_codec.rate = in.bitrate;
1171 // Apply codec-specific settings.
1172 if (IsIsac(codec)) {
1173 // If ISAC and an explicit bitrate is not specified,
1174 // enable auto bandwidth adjustment.
1175 voe_codec.rate = (in.bitrate > 0) ? in.bitrate : -1;
1185 const std::vector<RtpHeaderExtension>&
1186 WebRtcVoiceEngine::rtp_header_extensions() const {
1187 return rtp_header_extensions_;
1190 void WebRtcVoiceEngine::SetLogging(int min_sev, const char* filter) {
1191 // if min_sev == -1, we keep the current log level.
1193 SetTraceFilter(SeverityToFilter(min_sev));
1195 log_options_ = filter;
1196 SetTraceOptions(initialized_ ? log_options_ : "");
1199 int WebRtcVoiceEngine::GetLastEngineError() {
1200 return voe_wrapper_->error();
1203 void WebRtcVoiceEngine::SetTraceFilter(int filter) {
1204 log_filter_ = filter;
1205 tracing_->SetTraceFilter(filter);
1208 // We suppport three different logging settings for VoiceEngine:
1209 // 1. Observer callback that goes into talk diagnostic logfile.
1210 // Use --logfile and --loglevel
1212 // 2. Encrypted VoiceEngine log for debugging VoiceEngine.
1213 // Use --voice_loglevel --voice_logfilter "tracefile file_name"
1215 // 3. EC log and dump for debugging QualityEngine.
1216 // Use --voice_loglevel --voice_logfilter "recordEC file_name"
1218 // For more details see: "https://sites.google.com/a/google.com/wavelet/Home/
1219 // Magic-Flute--RTC-Engine-/Magic-Flute-Command-Line-Parameters"
1220 void WebRtcVoiceEngine::SetTraceOptions(const std::string& options) {
1221 // Set encrypted trace file.
1222 std::vector<std::string> opts;
1223 talk_base::tokenize(options, ' ', '"', '"', &opts);
1224 std::vector<std::string>::iterator tracefile =
1225 std::find(opts.begin(), opts.end(), "tracefile");
1226 if (tracefile != opts.end() && ++tracefile != opts.end()) {
1227 // Write encrypted debug output (at same loglevel) to file
1228 // EncryptedTraceFile no longer supported.
1229 if (tracing_->SetTraceFile(tracefile->c_str()) == -1) {
1230 LOG_RTCERR1(SetTraceFile, *tracefile);
1234 // Allow trace options to override the trace filter. We default
1235 // it to log_filter_ (as a translation of libjingle log levels)
1236 // elsewhere, but this allows clients to explicitly set webrtc
1238 std::vector<std::string>::iterator tracefilter =
1239 std::find(opts.begin(), opts.end(), "tracefilter");
1240 if (tracefilter != opts.end() && ++tracefilter != opts.end()) {
1241 if (!tracing_->SetTraceFilter(talk_base::FromString<int>(*tracefilter))) {
1242 LOG_RTCERR1(SetTraceFilter, *tracefilter);
1246 // Set AEC dump file
1247 std::vector<std::string>::iterator recordEC =
1248 std::find(opts.begin(), opts.end(), "recordEC");
1249 if (recordEC != opts.end()) {
1251 if (recordEC != opts.end())
1252 StartAecDump(recordEC->c_str());
1258 // Ignore spammy trace messages, mostly from the stats API when we haven't
1259 // gotten RTCP info yet from the remote side.
1260 bool WebRtcVoiceEngine::ShouldIgnoreTrace(const std::string& trace) {
1261 static const char* kTracesToIgnore[] = {
1262 "\tfailed to GetReportBlockInformation",
1263 "GetRecCodec() failed to get received codec",
1264 "GetReceivedRtcpStatistics: Could not get received RTP statistics",
1265 "GetRemoteRTCPData() failed to measure statistics due to lack of received RTP and/or RTCP packets", // NOLINT
1266 "GetRemoteRTCPData() failed to retrieve sender info for remote side",
1267 "GetRTPStatistics() failed to measure RTT since no RTP packets have been received yet", // NOLINT
1268 "GetRTPStatistics() failed to read RTP statistics from the RTP/RTCP module",
1269 "GetRTPStatistics() failed to retrieve RTT from the RTP/RTCP module",
1270 "SenderInfoReceived No received SR",
1271 "StatisticsRTP() no statistics available",
1272 "TransmitMixer::TypingDetection() VE_TYPING_NOISE_WARNING message has been posted", // NOLINT
1273 "TransmitMixer::TypingDetection() pending noise-saturation warning exists", // NOLINT
1274 "GetRecPayloadType() failed to retrieve RX payload type (error=10026)", // NOLINT
1275 "StopPlayingFileAsMicrophone() isnot playing (error=8088)",
1278 for (const char* const* p = kTracesToIgnore; *p; ++p) {
1279 if (trace.find(*p) != std::string::npos) {
1286 void WebRtcVoiceEngine::Print(webrtc::TraceLevel level, const char* trace,
1288 talk_base::LoggingSeverity sev = talk_base::LS_VERBOSE;
1289 if (level == webrtc::kTraceError || level == webrtc::kTraceCritical)
1290 sev = talk_base::LS_ERROR;
1291 else if (level == webrtc::kTraceWarning)
1292 sev = talk_base::LS_WARNING;
1293 else if (level == webrtc::kTraceStateInfo || level == webrtc::kTraceInfo)
1294 sev = talk_base::LS_INFO;
1295 else if (level == webrtc::kTraceTerseInfo)
1296 sev = talk_base::LS_INFO;
1298 // Skip past boilerplate prefix text
1300 std::string msg(trace, length);
1301 LOG(LS_ERROR) << "Malformed webrtc log message: ";
1304 std::string msg(trace + 71, length - 72);
1305 if (!ShouldIgnoreTrace(msg)) {
1306 LOG_V(sev) << "webrtc: " << msg;
1311 void WebRtcVoiceEngine::CallbackOnError(int channel_num, int err_code) {
1312 talk_base::CritScope lock(&channels_cs_);
1313 WebRtcVoiceMediaChannel* channel = NULL;
1315 LOG(LS_WARNING) << "VoiceEngine error " << err_code << " reported on channel "
1316 << channel_num << ".";
1317 if (FindChannelAndSsrc(channel_num, &channel, &ssrc)) {
1318 ASSERT(channel != NULL);
1319 channel->OnError(ssrc, err_code);
1321 LOG(LS_ERROR) << "VoiceEngine channel " << channel_num
1322 << " could not be found in channel list when error reported.";
1326 bool WebRtcVoiceEngine::FindChannelAndSsrc(
1327 int channel_num, WebRtcVoiceMediaChannel** channel, uint32* ssrc) const {
1328 ASSERT(channel != NULL && ssrc != NULL);
1332 // Find corresponding channel and ssrc
1333 for (ChannelList::const_iterator it = channels_.begin();
1334 it != channels_.end(); ++it) {
1335 ASSERT(*it != NULL);
1336 if ((*it)->FindSsrc(channel_num, ssrc)) {
1345 // This method will search through the WebRtcVoiceMediaChannels and
1346 // obtain the voice engine's channel number.
1347 bool WebRtcVoiceEngine::FindChannelNumFromSsrc(
1348 uint32 ssrc, MediaProcessorDirection direction, int* channel_num) {
1349 ASSERT(channel_num != NULL);
1350 ASSERT(direction == MPD_RX || direction == MPD_TX);
1353 // Find corresponding channel for ssrc.
1354 for (ChannelList::const_iterator it = channels_.begin();
1355 it != channels_.end(); ++it) {
1356 ASSERT(*it != NULL);
1357 if (direction & MPD_RX) {
1358 *channel_num = (*it)->GetReceiveChannelNum(ssrc);
1360 if (*channel_num == -1 && (direction & MPD_TX)) {
1361 *channel_num = (*it)->GetSendChannelNum(ssrc);
1363 if (*channel_num != -1) {
1367 LOG(LS_WARNING) << "FindChannelFromSsrc. No Channel Found for Ssrc: " << ssrc;
1371 void WebRtcVoiceEngine::RegisterChannel(WebRtcVoiceMediaChannel *channel) {
1372 talk_base::CritScope lock(&channels_cs_);
1373 channels_.push_back(channel);
1376 void WebRtcVoiceEngine::UnregisterChannel(WebRtcVoiceMediaChannel *channel) {
1377 talk_base::CritScope lock(&channels_cs_);
1378 ChannelList::iterator i = std::find(channels_.begin(),
1381 if (i != channels_.end()) {
1386 void WebRtcVoiceEngine::RegisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1387 soundclips_.push_back(soundclip);
1390 void WebRtcVoiceEngine::UnregisterSoundclip(WebRtcSoundclipMedia *soundclip) {
1391 SoundclipList::iterator i = std::find(soundclips_.begin(),
1394 if (i != soundclips_.end()) {
1395 soundclips_.erase(i);
1399 // Adjusts the default AGC target level by the specified delta.
1400 // NB: If we start messing with other config fields, we'll want
1401 // to save the current webrtc::AgcConfig as well.
1402 bool WebRtcVoiceEngine::AdjustAgcLevel(int delta) {
1403 webrtc::AgcConfig config = default_agc_config_;
1404 config.targetLeveldBOv -= delta;
1406 LOG(LS_INFO) << "Adjusting AGC level from default -"
1407 << default_agc_config_.targetLeveldBOv << "dB to -"
1408 << config.targetLeveldBOv << "dB";
1410 if (voe_wrapper_->processing()->SetAgcConfig(config) == -1) {
1411 LOG_RTCERR1(SetAgcConfig, config.targetLeveldBOv);
1417 bool WebRtcVoiceEngine::SetAudioDeviceModule(webrtc::AudioDeviceModule* adm,
1418 webrtc::AudioDeviceModule* adm_sc) {
1420 LOG(LS_WARNING) << "SetAudioDeviceModule can not be called after Init.";
1443 bool WebRtcVoiceEngine::StartAecDump(talk_base::PlatformFile file) {
1444 FILE* aec_dump_file_stream = talk_base::FdopenPlatformFileForWriting(file);
1445 if (!aec_dump_file_stream) {
1446 LOG(LS_ERROR) << "Could not open AEC dump file stream.";
1447 if (!talk_base::ClosePlatformFile(file))
1448 LOG(LS_WARNING) << "Could not close file.";
1452 if (voe_wrapper_->processing()->StartDebugRecording(aec_dump_file_stream) !=
1453 webrtc::AudioProcessing::kNoError) {
1454 LOG_RTCERR0(StartDebugRecording);
1455 fclose(aec_dump_file_stream);
1458 is_dumping_aec_ = true;
1462 bool WebRtcVoiceEngine::RegisterProcessor(
1464 VoiceProcessor* voice_processor,
1465 MediaProcessorDirection direction) {
1466 bool register_with_webrtc = false;
1467 int channel_id = -1;
1468 bool success = false;
1469 uint32* processor_ssrc = NULL;
1470 bool found_channel = FindChannelNumFromSsrc(ssrc, direction, &channel_id);
1471 if (voice_processor == NULL || !found_channel) {
1472 LOG(LS_WARNING) << "Media Processing Registration Failed. ssrc: " << ssrc
1473 << " foundChannel: " << found_channel;
1477 webrtc::ProcessingTypes processing_type;
1479 talk_base::CritScope cs(&signal_media_critical_);
1480 if (direction == MPD_RX) {
1481 processing_type = webrtc::kPlaybackAllChannelsMixed;
1482 if (SignalRxMediaFrame.is_empty()) {
1483 register_with_webrtc = true;
1484 processor_ssrc = &rx_processor_ssrc_;
1486 SignalRxMediaFrame.connect(voice_processor,
1487 &VoiceProcessor::OnFrame);
1489 processing_type = webrtc::kRecordingPerChannel;
1490 if (SignalTxMediaFrame.is_empty()) {
1491 register_with_webrtc = true;
1492 processor_ssrc = &tx_processor_ssrc_;
1494 SignalTxMediaFrame.connect(voice_processor,
1495 &VoiceProcessor::OnFrame);
1498 if (register_with_webrtc) {
1499 // TODO(janahan): when registering consider instantiating a
1500 // a VoeMediaProcess object and not make the engine extend the interface.
1501 if (voe()->media() && voe()->media()->
1502 RegisterExternalMediaProcessing(channel_id,
1505 LOG(LS_INFO) << "Media Processing Registration Succeeded. channel:"
1507 *processor_ssrc = ssrc;
1510 LOG_RTCERR2(RegisterExternalMediaProcessing,
1516 // If we don't have to register with the engine, we just needed to
1517 // connect a new processor, set success to true;
1523 bool WebRtcVoiceEngine::UnregisterProcessorChannel(
1524 MediaProcessorDirection channel_direction,
1526 VoiceProcessor* voice_processor,
1527 MediaProcessorDirection processor_direction) {
1528 bool success = true;
1529 FrameSignal* signal;
1530 webrtc::ProcessingTypes processing_type;
1531 uint32* processor_ssrc = NULL;
1532 if (channel_direction == MPD_RX) {
1533 signal = &SignalRxMediaFrame;
1534 processing_type = webrtc::kPlaybackAllChannelsMixed;
1535 processor_ssrc = &rx_processor_ssrc_;
1537 signal = &SignalTxMediaFrame;
1538 processing_type = webrtc::kRecordingPerChannel;
1539 processor_ssrc = &tx_processor_ssrc_;
1542 int deregister_id = -1;
1544 talk_base::CritScope cs(&signal_media_critical_);
1545 if ((processor_direction & channel_direction) != 0 && !signal->is_empty()) {
1546 signal->disconnect(voice_processor);
1547 int channel_id = -1;
1548 bool found_channel = FindChannelNumFromSsrc(ssrc,
1551 if (signal->is_empty() && found_channel) {
1552 deregister_id = channel_id;
1556 if (deregister_id != -1) {
1557 if (voe()->media() &&
1558 voe()->media()->DeRegisterExternalMediaProcessing(deregister_id,
1559 processing_type) != -1) {
1560 *processor_ssrc = 0;
1561 LOG(LS_INFO) << "Media Processing DeRegistration Succeeded. channel:"
1564 LOG_RTCERR2(DeRegisterExternalMediaProcessing,
1573 bool WebRtcVoiceEngine::UnregisterProcessor(
1575 VoiceProcessor* voice_processor,
1576 MediaProcessorDirection direction) {
1577 bool success = true;
1578 if (voice_processor == NULL) {
1579 LOG(LS_WARNING) << "Media Processing Deregistration Failed. ssrc: "
1583 if (!UnregisterProcessorChannel(MPD_RX, ssrc, voice_processor, direction)) {
1586 if (!UnregisterProcessorChannel(MPD_TX, ssrc, voice_processor, direction)) {
1592 // Implementing method from WebRtc VoEMediaProcess interface
1593 // Do not lock mux_channel_cs_ in this callback.
1594 void WebRtcVoiceEngine::Process(int channel,
1595 webrtc::ProcessingTypes type,
1596 int16_t audio10ms[],
1600 talk_base::CritScope cs(&signal_media_critical_);
1601 AudioFrame frame(audio10ms, length, sampling_freq, is_stereo);
1602 if (type == webrtc::kPlaybackAllChannelsMixed) {
1603 SignalRxMediaFrame(rx_processor_ssrc_, MPD_RX, &frame);
1604 } else if (type == webrtc::kRecordingPerChannel) {
1605 SignalTxMediaFrame(tx_processor_ssrc_, MPD_TX, &frame);
1607 LOG(LS_WARNING) << "Media Processing invoked unexpectedly."
1608 << " channel: " << channel << " type: " << type
1609 << " tx_ssrc: " << tx_processor_ssrc_
1610 << " rx_ssrc: " << rx_processor_ssrc_;
1614 void WebRtcVoiceEngine::StartAecDump(const std::string& filename) {
1615 if (!is_dumping_aec_) {
1616 // Start dumping AEC when we are not dumping.
1617 if (voe_wrapper_->processing()->StartDebugRecording(
1618 filename.c_str()) != webrtc::AudioProcessing::kNoError) {
1619 LOG_RTCERR1(StartDebugRecording, filename.c_str());
1621 is_dumping_aec_ = true;
1626 void WebRtcVoiceEngine::StopAecDump() {
1627 if (is_dumping_aec_) {
1628 // Stop dumping AEC when we are dumping.
1629 if (voe_wrapper_->processing()->StopDebugRecording() !=
1630 webrtc::AudioProcessing::kNoError) {
1631 LOG_RTCERR0(StopDebugRecording);
1633 is_dumping_aec_ = false;
1637 int WebRtcVoiceEngine::CreateVoiceChannel(VoEWrapper* voice_engine_wrapper) {
1638 return voice_engine_wrapper->base()->CreateChannel(voe_config_);
1641 int WebRtcVoiceEngine::CreateMediaVoiceChannel() {
1642 return CreateVoiceChannel(voe_wrapper_.get());
1645 int WebRtcVoiceEngine::CreateSoundclipVoiceChannel() {
1646 return CreateVoiceChannel(voe_wrapper_sc_.get());
1649 class WebRtcVoiceMediaChannel::WebRtcVoiceChannelRenderer
1650 : public AudioRenderer::Sink {
1652 WebRtcVoiceChannelRenderer(int ch,
1653 webrtc::AudioTransport* voe_audio_transport)
1655 voe_audio_transport_(voe_audio_transport),
1658 virtual ~WebRtcVoiceChannelRenderer() {
1662 // Starts the rendering by setting a sink to the renderer to get data
1664 // This method is called on the libjingle worker thread.
1665 // TODO(xians): Make sure Start() is called only once.
1666 void Start(AudioRenderer* renderer) {
1667 talk_base::CritScope lock(&lock_);
1668 ASSERT(renderer != NULL);
1669 if (renderer_ != NULL) {
1670 ASSERT(renderer_ == renderer);
1674 // TODO(xians): Remove AddChannel() call after Chrome turns on APM
1675 // in getUserMedia by default.
1676 renderer->AddChannel(channel_);
1677 renderer->SetSink(this);
1678 renderer_ = renderer;
1681 // Stops rendering by setting the sink of the renderer to NULL. No data
1682 // callback will be received after this method.
1683 // This method is called on the libjingle worker thread.
1685 talk_base::CritScope lock(&lock_);
1686 if (renderer_ == NULL)
1689 renderer_->RemoveChannel(channel_);
1690 renderer_->SetSink(NULL);
1694 // AudioRenderer::Sink implementation.
1695 // This method is called on the audio thread.
1696 virtual void OnData(const void* audio_data,
1697 int bits_per_sample,
1699 int number_of_channels,
1700 int number_of_frames) OVERRIDE {
1701 voe_audio_transport_->OnData(channel_,
1709 // Callback from the |renderer_| when it is going away. In case Start() has
1710 // never been called, this callback won't be triggered.
1711 virtual void OnClose() OVERRIDE {
1712 talk_base::CritScope lock(&lock_);
1713 // Set |renderer_| to NULL to make sure no more callback will get into
1718 // Accessor to the VoE channel ID.
1719 int channel() const { return channel_; }
1723 webrtc::AudioTransport* const voe_audio_transport_;
1725 // Raw pointer to AudioRenderer owned by LocalAudioTrackHandler.
1726 // PeerConnection will make sure invalidating the pointer before the object
1728 AudioRenderer* renderer_;
1730 // Protects |renderer_| in Start(), Stop() and OnClose().
1731 talk_base::CriticalSection lock_;
1734 // WebRtcVoiceMediaChannel
1735 WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel(WebRtcVoiceEngine *engine)
1736 : WebRtcMediaChannel<VoiceMediaChannel, WebRtcVoiceEngine>(
1738 engine->CreateMediaVoiceChannel()),
1739 send_bw_setting_(false),
1742 dtmf_allowed_(false),
1743 desired_playout_(false),
1744 nack_enabled_(false),
1746 typing_noise_detected_(false),
1747 desired_send_(SEND_NOTHING),
1748 send_(SEND_NOTHING),
1749 default_receive_ssrc_(0) {
1750 engine->RegisterChannel(this);
1751 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::WebRtcVoiceMediaChannel "
1754 ConfigureSendChannel(voe_channel());
1757 WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel() {
1758 LOG(LS_VERBOSE) << "WebRtcVoiceMediaChannel::~WebRtcVoiceMediaChannel "
1761 // Remove any remaining send streams, the default channel will be deleted
1763 while (!send_channels_.empty())
1764 RemoveSendStream(send_channels_.begin()->first);
1766 // Unregister ourselves from the engine.
1767 engine()->UnregisterChannel(this);
1768 // Remove any remaining streams.
1769 while (!receive_channels_.empty()) {
1770 RemoveRecvStream(receive_channels_.begin()->first);
1773 // Delete the default channel.
1774 DeleteChannel(voe_channel());
1777 bool WebRtcVoiceMediaChannel::SetOptions(const AudioOptions& options) {
1778 LOG(LS_INFO) << "Setting voice channel options: "
1779 << options.ToString();
1781 // Check if DSCP value is changed from previous.
1782 bool dscp_option_changed = (options_.dscp != options.dscp);
1784 // TODO(xians): Add support to set different options for different send
1785 // streams after we support multiple APMs.
1787 // We retain all of the existing options, and apply the given ones
1788 // on top. This means there is no way to "clear" options such that
1789 // they go back to the engine default.
1790 options_.SetAll(options);
1792 if (send_ != SEND_NOTHING) {
1793 if (!engine()->SetOptionOverrides(options_)) {
1795 "Failed to engine SetOptionOverrides during channel SetOptions.";
1799 // Will be interpreted when appropriate.
1802 // Receiver-side auto gain control happens per channel, so set it here from
1803 // options. Note that, like conference mode, setting it on the engine won't
1804 // have the desired effect, since voice channels don't inherit options from
1805 // the media engine when those options are applied per-channel.
1806 bool rx_auto_gain_control;
1807 if (options.rx_auto_gain_control.Get(&rx_auto_gain_control)) {
1808 if (engine()->voe()->processing()->SetRxAgcStatus(
1809 voe_channel(), rx_auto_gain_control,
1810 webrtc::kAgcFixedDigital) == -1) {
1811 LOG_RTCERR1(SetRxAgcStatus, rx_auto_gain_control);
1814 LOG(LS_VERBOSE) << "Rx auto gain set to " << rx_auto_gain_control
1815 << " with mode " << webrtc::kAgcFixedDigital;
1818 if (options.rx_agc_target_dbov.IsSet() ||
1819 options.rx_agc_digital_compression_gain.IsSet() ||
1820 options.rx_agc_limiter.IsSet()) {
1821 webrtc::AgcConfig config;
1822 // If only some of the options are being overridden, get the current
1823 // settings for the channel and bail if they aren't available.
1824 if (!options.rx_agc_target_dbov.IsSet() ||
1825 !options.rx_agc_digital_compression_gain.IsSet() ||
1826 !options.rx_agc_limiter.IsSet()) {
1827 if (engine()->voe()->processing()->GetRxAgcConfig(
1828 voe_channel(), config) != 0) {
1829 LOG(LS_ERROR) << "Failed to get default rx agc configuration for "
1830 << "channel " << voe_channel() << ". Since not all rx "
1831 << "agc options are specified, unable to safely set rx "
1836 config.targetLeveldBOv =
1837 options.rx_agc_target_dbov.GetWithDefaultIfUnset(
1838 config.targetLeveldBOv);
1839 config.digitalCompressionGaindB =
1840 options.rx_agc_digital_compression_gain.GetWithDefaultIfUnset(
1841 config.digitalCompressionGaindB);
1842 config.limiterEnable = options.rx_agc_limiter.GetWithDefaultIfUnset(
1843 config.limiterEnable);
1844 if (engine()->voe()->processing()->SetRxAgcConfig(
1845 voe_channel(), config) == -1) {
1846 LOG_RTCERR4(SetRxAgcConfig, voe_channel(), config.targetLeveldBOv,
1847 config.digitalCompressionGaindB, config.limiterEnable);
1851 if (dscp_option_changed) {
1852 talk_base::DiffServCodePoint dscp = talk_base::DSCP_DEFAULT;
1853 if (options_.dscp.GetWithDefaultIfUnset(false))
1854 dscp = kAudioDscpValue;
1855 if (MediaChannel::SetDscp(dscp) != 0) {
1856 LOG(LS_WARNING) << "Failed to set DSCP settings for audio channel";
1860 LOG(LS_INFO) << "Set voice channel options. Current options: "
1861 << options_.ToString();
1865 bool WebRtcVoiceMediaChannel::SetRecvCodecs(
1866 const std::vector<AudioCodec>& codecs) {
1867 // Set the payload types to be used for incoming media.
1868 LOG(LS_INFO) << "Setting receive voice codecs:";
1870 std::vector<AudioCodec> new_codecs;
1871 // Find all new codecs. We allow adding new codecs but don't allow changing
1872 // the payload type of codecs that is already configured since we might
1873 // already be receiving packets with that payload type.
1874 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1875 it != codecs.end(); ++it) {
1876 AudioCodec old_codec;
1877 if (FindCodec(recv_codecs_, *it, &old_codec)) {
1878 if (old_codec.id != it->id) {
1879 LOG(LS_ERROR) << it->name << " payload type changed.";
1883 new_codecs.push_back(*it);
1886 if (new_codecs.empty()) {
1887 // There are no new codecs to configure. Already configured codecs are
1893 // Receive codecs can not be changed while playing. So we temporarily
1899 for (std::vector<AudioCodec>::const_iterator it = new_codecs.begin();
1900 it != new_codecs.end() && ret; ++it) {
1901 webrtc::CodecInst voe_codec;
1902 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
1903 LOG(LS_INFO) << ToString(*it);
1904 voe_codec.pltype = it->id;
1905 if (default_receive_ssrc_ == 0) {
1906 // Set the receive codecs on the default channel explicitly if the
1907 // default channel is not used by |receive_channels_|, this happens in
1908 // conference mode or in non-conference mode when there is no playout
1910 // TODO(xians): Figure out how we use the default channel in conference
1912 if (engine()->voe()->codec()->SetRecPayloadType(
1913 voe_channel(), voe_codec) == -1) {
1914 LOG_RTCERR2(SetRecPayloadType, voe_channel(), ToString(voe_codec));
1919 // Set the receive codecs on all receiving channels.
1920 for (ChannelMap::iterator it = receive_channels_.begin();
1921 it != receive_channels_.end() && ret; ++it) {
1922 if (engine()->voe()->codec()->SetRecPayloadType(
1923 it->second->channel(), voe_codec) == -1) {
1924 LOG_RTCERR2(SetRecPayloadType, it->second->channel(),
1925 ToString(voe_codec));
1930 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1935 recv_codecs_ = codecs;
1938 if (desired_playout_ && !playout_) {
1944 bool WebRtcVoiceMediaChannel::SetSendCodecs(
1945 int channel, const std::vector<AudioCodec>& codecs) {
1946 // Disable VAD, and FEC unless we know the other side wants them.
1947 engine()->voe()->codec()->SetVADStatus(channel, false);
1948 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
1949 engine()->voe()->rtp()->SetFECStatus(channel, false);
1951 // Scan through the list to figure out the codec to use for sending, along
1952 // with the proper configuration for VAD and DTMF.
1953 bool found_send_codec = false;
1954 webrtc::CodecInst send_codec;
1955 memset(&send_codec, 0, sizeof(send_codec));
1957 bool nack_enabled = nack_enabled_;
1959 // Set send codec (the first non-telephone-event/CN codec)
1960 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
1961 it != codecs.end(); ++it) {
1962 // Ignore codecs we don't know about. The negotiation step should prevent
1963 // this, but double-check to be sure.
1964 webrtc::CodecInst voe_codec;
1965 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
1966 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
1970 if (IsTelephoneEventCodec(it->name) || IsCNCodec(it->name)) {
1971 // Skip telephone-event/CN codec, which will be handled later.
1975 // If OPUS, change what we send according to the "stereo" codec
1976 // parameter, and not the "channels" parameter. We set
1977 // voe_codec.channels to 2 if "stereo=1" and 1 otherwise. If
1978 // the bitrate is not specified, i.e. is zero, we set it to the
1979 // appropriate default value for mono or stereo Opus.
1981 if (IsOpusStereoEnabled(*it)) {
1982 voe_codec.channels = 2;
1983 if (!IsValidOpusBitrate(it->bitrate)) {
1984 if (it->bitrate != 0) {
1985 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
1987 << ") with default opus stereo bitrate: "
1988 << kOpusStereoBitrate;
1990 voe_codec.rate = kOpusStereoBitrate;
1993 voe_codec.channels = 1;
1994 if (!IsValidOpusBitrate(it->bitrate)) {
1995 if (it->bitrate != 0) {
1996 LOG(LS_WARNING) << "Overrides the invalid supplied bitrate("
1998 << ") with default opus mono bitrate: "
1999 << kOpusMonoBitrate;
2001 voe_codec.rate = kOpusMonoBitrate;
2004 int bitrate_from_params = GetOpusBitrateFromParams(*it);
2005 if (bitrate_from_params != 0) {
2006 voe_codec.rate = bitrate_from_params;
2010 // We'll use the first codec in the list to actually send audio data.
2011 // Be sure to use the payload type requested by the remote side.
2012 // "red", for FEC audio, is a special case where the actual codec to be
2013 // used is specified in params.
2014 if (IsRedCodec(it->name)) {
2015 // Parse out the RED parameters. If we fail, just ignore RED;
2016 // we don't support all possible params/usage scenarios.
2017 if (!GetRedSendCodec(*it, codecs, &send_codec)) {
2021 // Enable redundant encoding of the specified codec. Treat any
2022 // failure as a fatal internal error.
2023 LOG(LS_INFO) << "Enabling FEC";
2024 if (engine()->voe()->rtp()->SetFECStatus(channel, true, it->id) == -1) {
2025 LOG_RTCERR3(SetFECStatus, channel, true, it->id);
2029 send_codec = voe_codec;
2030 nack_enabled = IsNackEnabled(*it);
2032 found_send_codec = true;
2036 if (nack_enabled_ != nack_enabled) {
2037 SetNack(channel, nack_enabled);
2038 nack_enabled_ = nack_enabled;
2041 if (!found_send_codec) {
2042 LOG(LS_WARNING) << "Received empty list of codecs.";
2046 // Set the codec immediately, since SetVADStatus() depends on whether
2047 // the current codec is mono or stereo.
2048 if (!SetSendCodec(channel, send_codec))
2051 // Always update the |send_codec_| to the currently set send codec.
2052 send_codec_.reset(new webrtc::CodecInst(send_codec));
2054 if (send_bw_setting_) {
2055 SetSendBandwidthInternal(send_bw_bps_);
2058 // Loop through the codecs list again to config the telephone-event/CN codec.
2059 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2060 it != codecs.end(); ++it) {
2061 // Ignore codecs we don't know about. The negotiation step should prevent
2062 // this, but double-check to be sure.
2063 webrtc::CodecInst voe_codec;
2064 if (!engine()->FindWebRtcCodec(*it, &voe_codec)) {
2065 LOG(LS_WARNING) << "Unknown codec " << ToString(*it);
2069 // Find the DTMF telephone event "codec" and tell VoiceEngine channels
2071 if (IsTelephoneEventCodec(it->name)) {
2072 if (engine()->voe()->dtmf()->SetSendTelephoneEventPayloadType(
2073 channel, it->id) == -1) {
2074 LOG_RTCERR2(SetSendTelephoneEventPayloadType, channel, it->id);
2077 } else if (IsCNCodec(it->name)) {
2078 // Turn voice activity detection/comfort noise on if supported.
2079 // Set the wideband CN payload type appropriately.
2080 // (narrowband always uses the static payload type 13).
2081 webrtc::PayloadFrequencies cn_freq;
2082 switch (it->clockrate) {
2084 cn_freq = webrtc::kFreq8000Hz;
2087 cn_freq = webrtc::kFreq16000Hz;
2090 cn_freq = webrtc::kFreq32000Hz;
2093 LOG(LS_WARNING) << "CN frequency " << it->clockrate
2094 << " not supported.";
2097 // Set the CN payloadtype and the VAD status.
2098 // The CN payload type for 8000 Hz clockrate is fixed at 13.
2099 if (cn_freq != webrtc::kFreq8000Hz) {
2100 if (engine()->voe()->codec()->SetSendCNPayloadType(
2101 channel, it->id, cn_freq) == -1) {
2102 LOG_RTCERR3(SetSendCNPayloadType, channel, it->id, cn_freq);
2103 // TODO(ajm): This failure condition will be removed from VoE.
2104 // Restore the return here when we update to a new enough webrtc.
2106 // Not returning false because the SetSendCNPayloadType will fail if
2107 // the channel is already sending.
2108 // This can happen if the remote description is applied twice, for
2109 // example in the case of ROAP on top of JSEP, where both side will
2113 // Only turn on VAD if we have a CN payload type that matches the
2114 // clockrate for the codec we are going to use.
2115 if (it->clockrate == send_codec.plfreq) {
2116 LOG(LS_INFO) << "Enabling VAD";
2117 if (engine()->voe()->codec()->SetVADStatus(channel, true) == -1) {
2118 LOG_RTCERR2(SetVADStatus, channel, true);
2127 bool WebRtcVoiceMediaChannel::SetSendCodecs(
2128 const std::vector<AudioCodec>& codecs) {
2129 dtmf_allowed_ = false;
2130 for (std::vector<AudioCodec>::const_iterator it = codecs.begin();
2131 it != codecs.end(); ++it) {
2132 // Find the DTMF telephone event "codec".
2133 if (_stricmp(it->name.c_str(), "telephone-event") == 0 ||
2134 _stricmp(it->name.c_str(), "audio/telephone-event") == 0) {
2135 dtmf_allowed_ = true;
2139 // Cache the codecs in order to configure the channel created later.
2140 send_codecs_ = codecs;
2141 for (ChannelMap::iterator iter = send_channels_.begin();
2142 iter != send_channels_.end(); ++iter) {
2143 if (!SetSendCodecs(iter->second->channel(), codecs)) {
2148 // Set nack status on receive channels and update |nack_enabled_|.
2149 SetNack(receive_channels_, nack_enabled_);
2153 void WebRtcVoiceMediaChannel::SetNack(const ChannelMap& channels,
2154 bool nack_enabled) {
2155 for (ChannelMap::const_iterator it = channels.begin();
2156 it != channels.end(); ++it) {
2157 SetNack(it->second->channel(), nack_enabled);
2161 void WebRtcVoiceMediaChannel::SetNack(int channel, bool nack_enabled) {
2163 LOG(LS_INFO) << "Enabling NACK for channel " << channel;
2164 engine()->voe()->rtp()->SetNACKStatus(channel, true, kNackMaxPackets);
2166 LOG(LS_INFO) << "Disabling NACK for channel " << channel;
2167 engine()->voe()->rtp()->SetNACKStatus(channel, false, 0);
2171 bool WebRtcVoiceMediaChannel::SetSendCodec(
2172 const webrtc::CodecInst& send_codec) {
2173 LOG(LS_INFO) << "Selected voice codec " << ToString(send_codec)
2174 << ", bitrate=" << send_codec.rate;
2175 for (ChannelMap::iterator iter = send_channels_.begin();
2176 iter != send_channels_.end(); ++iter) {
2177 if (!SetSendCodec(iter->second->channel(), send_codec))
2184 bool WebRtcVoiceMediaChannel::SetSendCodec(
2185 int channel, const webrtc::CodecInst& send_codec) {
2186 LOG(LS_INFO) << "Send channel " << channel << " selected voice codec "
2187 << ToString(send_codec) << ", bitrate=" << send_codec.rate;
2189 webrtc::CodecInst current_codec;
2190 if (engine()->voe()->codec()->GetSendCodec(channel, current_codec) == 0 &&
2191 (send_codec == current_codec)) {
2192 // Codec is already configured, we can return without setting it again.
2196 if (engine()->voe()->codec()->SetSendCodec(channel, send_codec) == -1) {
2197 LOG_RTCERR2(SetSendCodec, channel, ToString(send_codec));
2203 bool WebRtcVoiceMediaChannel::SetRecvRtpHeaderExtensions(
2204 const std::vector<RtpHeaderExtension>& extensions) {
2205 if (receive_extensions_ == extensions) {
2209 // The default channel may or may not be in |receive_channels_|. Set the rtp
2210 // header extensions for default channel regardless.
2211 if (!SetChannelRecvRtpHeaderExtensions(voe_channel(), extensions)) {
2215 // Loop through all receive channels and enable/disable the extensions.
2216 for (ChannelMap::const_iterator channel_it = receive_channels_.begin();
2217 channel_it != receive_channels_.end(); ++channel_it) {
2218 if (!SetChannelRecvRtpHeaderExtensions(channel_it->second->channel(),
2224 receive_extensions_ = extensions;
2228 bool WebRtcVoiceMediaChannel::SetChannelRecvRtpHeaderExtensions(
2229 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
2230 #ifdef USE_WEBRTC_DEV_BRANCH
2231 const RtpHeaderExtension* audio_level_extension =
2232 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2233 if (!SetHeaderExtension(
2234 &webrtc::VoERTP_RTCP::SetReceiveAudioLevelIndicationStatus, channel_id,
2235 audio_level_extension)) {
2238 #endif // USE_WEBRTC_DEV_BRANCH
2240 const RtpHeaderExtension* send_time_extension =
2241 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2242 if (!SetHeaderExtension(
2243 &webrtc::VoERTP_RTCP::SetReceiveAbsoluteSenderTimeStatus, channel_id,
2244 send_time_extension)) {
2250 bool WebRtcVoiceMediaChannel::SetSendRtpHeaderExtensions(
2251 const std::vector<RtpHeaderExtension>& extensions) {
2252 if (send_extensions_ == extensions) {
2256 // The default channel may or may not be in |send_channels_|. Set the rtp
2257 // header extensions for default channel regardless.
2259 if (!SetChannelSendRtpHeaderExtensions(voe_channel(), extensions)) {
2263 // Loop through all send channels and enable/disable the extensions.
2264 for (ChannelMap::const_iterator channel_it = send_channels_.begin();
2265 channel_it != send_channels_.end(); ++channel_it) {
2266 if (!SetChannelSendRtpHeaderExtensions(channel_it->second->channel(),
2272 send_extensions_ = extensions;
2276 bool WebRtcVoiceMediaChannel::SetChannelSendRtpHeaderExtensions(
2277 int channel_id, const std::vector<RtpHeaderExtension>& extensions) {
2278 const RtpHeaderExtension* audio_level_extension =
2279 FindHeaderExtension(extensions, kRtpAudioLevelHeaderExtension);
2281 if (!SetHeaderExtension(
2282 &webrtc::VoERTP_RTCP::SetSendAudioLevelIndicationStatus, channel_id,
2283 audio_level_extension)) {
2287 const RtpHeaderExtension* send_time_extension =
2288 FindHeaderExtension(extensions, kRtpAbsoluteSenderTimeHeaderExtension);
2289 if (!SetHeaderExtension(
2290 &webrtc::VoERTP_RTCP::SetSendAbsoluteSenderTimeStatus, channel_id,
2291 send_time_extension)) {
2298 bool WebRtcVoiceMediaChannel::SetPlayout(bool playout) {
2299 desired_playout_ = playout;
2300 return ChangePlayout(desired_playout_);
2303 bool WebRtcVoiceMediaChannel::PausePlayout() {
2304 return ChangePlayout(false);
2307 bool WebRtcVoiceMediaChannel::ResumePlayout() {
2308 return ChangePlayout(desired_playout_);
2311 bool WebRtcVoiceMediaChannel::ChangePlayout(bool playout) {
2312 if (playout_ == playout) {
2316 // Change the playout of all channels to the new state.
2318 if (receive_channels_.empty()) {
2319 // Only toggle the default channel if we don't have any other channels.
2320 result = SetPlayout(voe_channel(), playout);
2322 for (ChannelMap::iterator it = receive_channels_.begin();
2323 it != receive_channels_.end() && result; ++it) {
2324 if (!SetPlayout(it->second->channel(), playout)) {
2325 LOG(LS_ERROR) << "SetPlayout " << playout << " on channel "
2326 << it->second->channel() << " failed";
2337 bool WebRtcVoiceMediaChannel::SetSend(SendFlags send) {
2338 desired_send_ = send;
2339 if (!send_channels_.empty())
2340 return ChangeSend(desired_send_);
2344 bool WebRtcVoiceMediaChannel::PauseSend() {
2345 return ChangeSend(SEND_NOTHING);
2348 bool WebRtcVoiceMediaChannel::ResumeSend() {
2349 return ChangeSend(desired_send_);
2352 bool WebRtcVoiceMediaChannel::ChangeSend(SendFlags send) {
2353 if (send_ == send) {
2357 // Change the settings on each send channel.
2358 if (send == SEND_MICROPHONE)
2359 engine()->SetOptionOverrides(options_);
2361 // Change the settings on each send channel.
2362 for (ChannelMap::iterator iter = send_channels_.begin();
2363 iter != send_channels_.end(); ++iter) {
2364 if (!ChangeSend(iter->second->channel(), send))
2368 // Clear up the options after stopping sending.
2369 if (send == SEND_NOTHING)
2370 engine()->ClearOptionOverrides();
2376 bool WebRtcVoiceMediaChannel::ChangeSend(int channel, SendFlags send) {
2377 if (send == SEND_MICROPHONE) {
2378 if (engine()->voe()->base()->StartSend(channel) == -1) {
2379 LOG_RTCERR1(StartSend, channel);
2382 if (engine()->voe()->file() &&
2383 engine()->voe()->file()->StopPlayingFileAsMicrophone(channel) == -1) {
2384 LOG_RTCERR1(StopPlayingFileAsMicrophone, channel);
2387 } else { // SEND_NOTHING
2388 ASSERT(send == SEND_NOTHING);
2389 if (engine()->voe()->base()->StopSend(channel) == -1) {
2390 LOG_RTCERR1(StopSend, channel);
2398 // TODO(ronghuawu): Change this method to return bool.
2399 void WebRtcVoiceMediaChannel::ConfigureSendChannel(int channel) {
2400 if (engine()->voe()->network()->RegisterExternalTransport(
2401 channel, *this) == -1) {
2402 LOG_RTCERR2(RegisterExternalTransport, channel, this);
2405 // Enable RTCP (for quality stats and feedback messages)
2406 EnableRtcp(channel);
2408 // Reset all recv codecs; they will be enabled via SetRecvCodecs.
2409 ResetRecvCodecs(channel);
2411 // Set RTP header extension for the new channel.
2412 SetChannelSendRtpHeaderExtensions(channel, send_extensions_);
2415 bool WebRtcVoiceMediaChannel::DeleteChannel(int channel) {
2416 if (engine()->voe()->network()->DeRegisterExternalTransport(channel) == -1) {
2417 LOG_RTCERR1(DeRegisterExternalTransport, channel);
2420 if (engine()->voe()->base()->DeleteChannel(channel) == -1) {
2421 LOG_RTCERR1(DeleteChannel, channel);
2428 bool WebRtcVoiceMediaChannel::AddSendStream(const StreamParams& sp) {
2429 // If the default channel is already used for sending create a new channel
2430 // otherwise use the default channel for sending.
2431 int channel = GetSendChannelNum(sp.first_ssrc());
2432 if (channel != -1) {
2433 LOG(LS_ERROR) << "Stream already exists with ssrc " << sp.first_ssrc();
2437 bool default_channel_is_available = true;
2438 for (ChannelMap::const_iterator iter = send_channels_.begin();
2439 iter != send_channels_.end(); ++iter) {
2440 if (IsDefaultChannel(iter->second->channel())) {
2441 default_channel_is_available = false;
2445 if (default_channel_is_available) {
2446 channel = voe_channel();
2448 // Create a new channel for sending audio data.
2449 channel = engine()->CreateMediaVoiceChannel();
2450 if (channel == -1) {
2451 LOG_RTCERR0(CreateChannel);
2455 ConfigureSendChannel(channel);
2458 // Save the channel to send_channels_, so that RemoveSendStream() can still
2459 // delete the channel in case failure happens below.
2460 webrtc::AudioTransport* audio_transport =
2461 engine()->voe()->base()->audio_transport();
2462 send_channels_.insert(std::make_pair(
2464 new WebRtcVoiceChannelRenderer(channel, audio_transport)));
2466 // Set the send (local) SSRC.
2467 // If there are multiple send SSRCs, we can only set the first one here, and
2468 // the rest of the SSRC(s) need to be set after SetSendCodec has been called
2469 // (with a codec requires multiple SSRC(s)).
2470 if (engine()->voe()->rtp()->SetLocalSSRC(channel, sp.first_ssrc()) == -1) {
2471 LOG_RTCERR2(SetSendSSRC, channel, sp.first_ssrc());
2475 // At this point the channel's local SSRC has been updated. If the channel is
2476 // the default channel make sure that all the receive channels are updated as
2477 // well. Receive channels have to have the same SSRC as the default channel in
2478 // order to send receiver reports with this SSRC.
2479 if (IsDefaultChannel(channel)) {
2480 for (ChannelMap::const_iterator it = receive_channels_.begin();
2481 it != receive_channels_.end(); ++it) {
2482 // Only update the SSRC for non-default channels.
2483 if (!IsDefaultChannel(it->second->channel())) {
2484 if (engine()->voe()->rtp()->SetLocalSSRC(it->second->channel(),
2485 sp.first_ssrc()) != 0) {
2486 LOG_RTCERR2(SetLocalSSRC, it->second->channel(), sp.first_ssrc());
2493 if (engine()->voe()->rtp()->SetRTCP_CNAME(channel, sp.cname.c_str()) == -1) {
2494 LOG_RTCERR2(SetRTCP_CNAME, channel, sp.cname);
2498 // Set the current codecs to be used for the new channel.
2499 if (!send_codecs_.empty() && !SetSendCodecs(channel, send_codecs_))
2502 return ChangeSend(channel, desired_send_);
2505 bool WebRtcVoiceMediaChannel::RemoveSendStream(uint32 ssrc) {
2506 ChannelMap::iterator it = send_channels_.find(ssrc);
2507 if (it == send_channels_.end()) {
2508 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2509 << " which doesn't exist.";
2513 int channel = it->second->channel();
2514 ChangeSend(channel, SEND_NOTHING);
2516 // Delete the WebRtcVoiceChannelRenderer object connected to the channel,
2517 // this will disconnect the audio renderer with the send channel.
2519 send_channels_.erase(it);
2521 if (IsDefaultChannel(channel)) {
2522 // Do not delete the default channel since the receive channels depend on
2523 // the default channel, recycle it instead.
2524 ChangeSend(channel, SEND_NOTHING);
2526 // Clean up and delete the send channel.
2527 LOG(LS_INFO) << "Removing audio send stream " << ssrc
2528 << " with VoiceEngine channel #" << channel << ".";
2529 if (!DeleteChannel(channel))
2533 if (send_channels_.empty())
2534 ChangeSend(SEND_NOTHING);
2539 bool WebRtcVoiceMediaChannel::AddRecvStream(const StreamParams& sp) {
2540 talk_base::CritScope lock(&receive_channels_cs_);
2542 if (!VERIFY(sp.ssrcs.size() == 1))
2544 uint32 ssrc = sp.first_ssrc();
2547 LOG(LS_WARNING) << "AddRecvStream with 0 ssrc is not supported.";
2551 if (receive_channels_.find(ssrc) != receive_channels_.end()) {
2552 LOG(LS_ERROR) << "Stream already exists with ssrc " << ssrc;
2556 // Reuse default channel for recv stream in non-conference mode call
2557 // when the default channel is not being used.
2558 webrtc::AudioTransport* audio_transport =
2559 engine()->voe()->base()->audio_transport();
2560 if (!InConferenceMode() && default_receive_ssrc_ == 0) {
2561 LOG(LS_INFO) << "Recv stream " << sp.first_ssrc()
2562 << " reuse default channel";
2563 default_receive_ssrc_ = sp.first_ssrc();
2564 receive_channels_.insert(std::make_pair(
2565 default_receive_ssrc_,
2566 new WebRtcVoiceChannelRenderer(voe_channel(), audio_transport)));
2567 return SetPlayout(voe_channel(), playout_);
2570 // Create a new channel for receiving audio data.
2571 int channel = engine()->CreateMediaVoiceChannel();
2572 if (channel == -1) {
2573 LOG_RTCERR0(CreateChannel);
2577 if (!ConfigureRecvChannel(channel)) {
2578 DeleteChannel(channel);
2582 receive_channels_.insert(
2584 ssrc, new WebRtcVoiceChannelRenderer(channel, audio_transport)));
2586 LOG(LS_INFO) << "New audio stream " << ssrc
2587 << " registered to VoiceEngine channel #"
2592 bool WebRtcVoiceMediaChannel::ConfigureRecvChannel(int channel) {
2593 // Configure to use external transport, like our default channel.
2594 if (engine()->voe()->network()->RegisterExternalTransport(
2595 channel, *this) == -1) {
2596 LOG_RTCERR2(SetExternalTransport, channel, this);
2600 // Use the same SSRC as our default channel (so the RTCP reports are correct).
2601 unsigned int send_ssrc = 0;
2602 webrtc::VoERTP_RTCP* rtp = engine()->voe()->rtp();
2603 if (rtp->GetLocalSSRC(voe_channel(), send_ssrc) == -1) {
2604 LOG_RTCERR1(GetSendSSRC, channel);
2607 if (rtp->SetLocalSSRC(channel, send_ssrc) == -1) {
2608 LOG_RTCERR1(SetSendSSRC, channel);
2612 // Use the same recv payload types as our default channel.
2613 ResetRecvCodecs(channel);
2614 if (!recv_codecs_.empty()) {
2615 for (std::vector<AudioCodec>::const_iterator it = recv_codecs_.begin();
2616 it != recv_codecs_.end(); ++it) {
2617 webrtc::CodecInst voe_codec;
2618 if (engine()->FindWebRtcCodec(*it, &voe_codec)) {
2619 voe_codec.pltype = it->id;
2620 voe_codec.rate = 0; // Needed to make GetRecPayloadType work for ISAC
2621 if (engine()->voe()->codec()->GetRecPayloadType(
2622 voe_channel(), voe_codec) != -1) {
2623 if (engine()->voe()->codec()->SetRecPayloadType(
2624 channel, voe_codec) == -1) {
2625 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
2633 if (InConferenceMode()) {
2634 // To be in par with the video, voe_channel() is not used for receiving in
2635 // a conference call.
2636 if (receive_channels_.empty() && default_receive_ssrc_ == 0 && playout_) {
2637 // This is the first stream in a multi user meeting. We can now
2638 // disable playback of the default stream. This since the default
2639 // stream will probably have received some initial packets before
2640 // the new stream was added. This will mean that the CN state from
2641 // the default channel will be mixed in with the other streams
2642 // throughout the whole meeting, which might be disturbing.
2643 LOG(LS_INFO) << "Disabling playback on the default voice channel";
2644 SetPlayout(voe_channel(), false);
2647 SetNack(channel, nack_enabled_);
2649 // Set RTP header extension for the new channel.
2650 if (!SetChannelRecvRtpHeaderExtensions(channel, receive_extensions_)) {
2654 return SetPlayout(channel, playout_);
2657 bool WebRtcVoiceMediaChannel::RemoveRecvStream(uint32 ssrc) {
2658 talk_base::CritScope lock(&receive_channels_cs_);
2659 ChannelMap::iterator it = receive_channels_.find(ssrc);
2660 if (it == receive_channels_.end()) {
2661 LOG(LS_WARNING) << "Try to remove stream with ssrc " << ssrc
2662 << " which doesn't exist.";
2666 // Delete the WebRtcVoiceChannelRenderer object connected to the channel, this
2667 // will disconnect the audio renderer with the receive channel.
2668 // Cache the channel before the deletion.
2669 const int channel = it->second->channel();
2671 receive_channels_.erase(it);
2673 if (ssrc == default_receive_ssrc_) {
2674 ASSERT(IsDefaultChannel(channel));
2675 // Recycle the default channel is for recv stream.
2677 SetPlayout(voe_channel(), false);
2679 default_receive_ssrc_ = 0;
2683 LOG(LS_INFO) << "Removing audio stream " << ssrc
2684 << " with VoiceEngine channel #" << channel << ".";
2685 if (!DeleteChannel(channel))
2688 bool enable_default_channel_playout = false;
2689 if (receive_channels_.empty()) {
2690 // The last stream was removed. We can now enable the default
2691 // channel for new channels to be played out immediately without
2692 // waiting for AddStream messages.
2693 // We do this for both conference mode and non-conference mode.
2694 // TODO(oja): Does the default channel still have it's CN state?
2695 enable_default_channel_playout = true;
2697 if (!InConferenceMode() && receive_channels_.size() == 1 &&
2698 default_receive_ssrc_ != 0) {
2699 // Only the default channel is active, enable the playout on default
2701 enable_default_channel_playout = true;
2703 if (enable_default_channel_playout && playout_) {
2704 LOG(LS_INFO) << "Enabling playback on the default voice channel";
2705 SetPlayout(voe_channel(), true);
2711 bool WebRtcVoiceMediaChannel::SetRemoteRenderer(uint32 ssrc,
2712 AudioRenderer* renderer) {
2713 ChannelMap::iterator it = receive_channels_.find(ssrc);
2714 if (it == receive_channels_.end()) {
2716 // Return an error if trying to set a valid renderer with an invalid ssrc.
2717 LOG(LS_ERROR) << "SetRemoteRenderer failed with ssrc "<< ssrc;
2721 // The channel likely has gone away, do nothing.
2726 it->second->Start(renderer);
2733 bool WebRtcVoiceMediaChannel::SetLocalRenderer(uint32 ssrc,
2734 AudioRenderer* renderer) {
2735 ChannelMap::iterator it = send_channels_.find(ssrc);
2736 if (it == send_channels_.end()) {
2738 // Return an error if trying to set a valid renderer with an invalid ssrc.
2739 LOG(LS_ERROR) << "SetLocalRenderer failed with ssrc "<< ssrc;
2743 // The channel likely has gone away, do nothing.
2748 it->second->Start(renderer);
2755 bool WebRtcVoiceMediaChannel::GetActiveStreams(
2756 AudioInfo::StreamList* actives) {
2757 // In conference mode, the default channel should not be in
2758 // |receive_channels_|.
2760 for (ChannelMap::iterator it = receive_channels_.begin();
2761 it != receive_channels_.end(); ++it) {
2762 int level = GetOutputLevel(it->second->channel());
2764 actives->push_back(std::make_pair(it->first, level));
2770 int WebRtcVoiceMediaChannel::GetOutputLevel() {
2771 // return the highest output level of all streams
2772 int highest = GetOutputLevel(voe_channel());
2773 for (ChannelMap::iterator it = receive_channels_.begin();
2774 it != receive_channels_.end(); ++it) {
2775 int level = GetOutputLevel(it->second->channel());
2776 highest = talk_base::_max(level, highest);
2781 int WebRtcVoiceMediaChannel::GetTimeSinceLastTyping() {
2783 if (engine()->voe()->processing()->TimeSinceLastTyping(ret) == -1) {
2784 // In case of error, log the info and continue
2785 LOG_RTCERR0(TimeSinceLastTyping);
2788 ret *= 1000; // We return ms, webrtc returns seconds.
2793 void WebRtcVoiceMediaChannel::SetTypingDetectionParameters(int time_window,
2794 int cost_per_typing, int reporting_threshold, int penalty_decay,
2795 int type_event_delay) {
2796 if (engine()->voe()->processing()->SetTypingDetectionParameters(
2797 time_window, cost_per_typing,
2798 reporting_threshold, penalty_decay, type_event_delay) == -1) {
2799 // In case of error, log the info and continue
2800 LOG_RTCERR5(SetTypingDetectionParameters, time_window,
2801 cost_per_typing, reporting_threshold, penalty_decay,
2806 bool WebRtcVoiceMediaChannel::SetOutputScaling(
2807 uint32 ssrc, double left, double right) {
2808 talk_base::CritScope lock(&receive_channels_cs_);
2809 // Collect the channels to scale the output volume.
2810 std::vector<int> channels;
2811 if (0 == ssrc) { // Collect all channels, including the default one.
2812 // Default channel is not in receive_channels_ if it is not being used for
2814 if (default_receive_ssrc_ == 0)
2815 channels.push_back(voe_channel());
2816 for (ChannelMap::const_iterator it = receive_channels_.begin();
2817 it != receive_channels_.end(); ++it) {
2818 channels.push_back(it->second->channel());
2820 } else { // Collect only the channel of the specified ssrc.
2821 int channel = GetReceiveChannelNum(ssrc);
2822 if (-1 == channel) {
2823 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2826 channels.push_back(channel);
2829 // Scale the output volume for the collected channels. We first normalize to
2830 // scale the volume and then set the left and right pan.
2831 float scale = static_cast<float>(talk_base::_max(left, right));
2832 if (scale > 0.0001f) {
2836 for (std::vector<int>::const_iterator it = channels.begin();
2837 it != channels.end(); ++it) {
2838 if (-1 == engine()->voe()->volume()->SetChannelOutputVolumeScaling(
2840 LOG_RTCERR2(SetChannelOutputVolumeScaling, *it, scale);
2843 if (-1 == engine()->voe()->volume()->SetOutputVolumePan(
2844 *it, static_cast<float>(left), static_cast<float>(right))) {
2845 LOG_RTCERR3(SetOutputVolumePan, *it, left, right);
2846 // Do not return if fails. SetOutputVolumePan is not available for all
2849 LOG(LS_INFO) << "SetOutputScaling to left=" << left * scale
2850 << " right=" << right * scale
2851 << " for channel " << *it << " and ssrc " << ssrc;
2856 bool WebRtcVoiceMediaChannel::GetOutputScaling(
2857 uint32 ssrc, double* left, double* right) {
2858 if (!left || !right) return false;
2860 talk_base::CritScope lock(&receive_channels_cs_);
2861 // Determine which channel based on ssrc.
2862 int channel = (0 == ssrc) ? voe_channel() : GetReceiveChannelNum(ssrc);
2863 if (channel == -1) {
2864 LOG(LS_WARNING) << "Cannot find channel for ssrc:" << ssrc;
2869 if (-1 == engine()->voe()->volume()->GetChannelOutputVolumeScaling(
2870 channel, scaling)) {
2871 LOG_RTCERR2(GetChannelOutputVolumeScaling, channel, scaling);
2877 if (-1 == engine()->voe()->volume()->GetOutputVolumePan(
2878 channel, left_pan, right_pan)) {
2879 LOG_RTCERR3(GetOutputVolumePan, channel, left_pan, right_pan);
2880 // If GetOutputVolumePan fails, we use the default left and right pan.
2885 *left = scaling * left_pan;
2886 *right = scaling * right_pan;
2890 bool WebRtcVoiceMediaChannel::SetRingbackTone(const char *buf, int len) {
2891 ringback_tone_.reset(new WebRtcSoundclipStream(buf, len));
2895 bool WebRtcVoiceMediaChannel::PlayRingbackTone(uint32 ssrc,
2896 bool play, bool loop) {
2897 if (!ringback_tone_) {
2901 // The voe file api is not available in chrome.
2902 if (!engine()->voe()->file()) {
2906 // Determine which VoiceEngine channel to play on.
2907 int channel = (ssrc == 0) ? voe_channel() : GetReceiveChannelNum(ssrc);
2908 if (channel == -1) {
2912 // Make sure the ringtone is cued properly, and play it out.
2914 ringback_tone_->set_loop(loop);
2915 ringback_tone_->Rewind();
2916 if (engine()->voe()->file()->StartPlayingFileLocally(channel,
2917 ringback_tone_.get()) == -1) {
2918 LOG_RTCERR2(StartPlayingFileLocally, channel, ringback_tone_.get());
2919 LOG(LS_ERROR) << "Unable to start ringback tone";
2922 ringback_channels_.insert(channel);
2923 LOG(LS_INFO) << "Started ringback on channel " << channel;
2925 if (engine()->voe()->file()->IsPlayingFileLocally(channel) == 1 &&
2926 engine()->voe()->file()->StopPlayingFileLocally(channel) == -1) {
2927 LOG_RTCERR1(StopPlayingFileLocally, channel);
2930 LOG(LS_INFO) << "Stopped ringback on channel " << channel;
2931 ringback_channels_.erase(channel);
2937 bool WebRtcVoiceMediaChannel::CanInsertDtmf() {
2938 return dtmf_allowed_;
2941 bool WebRtcVoiceMediaChannel::InsertDtmf(uint32 ssrc, int event,
2942 int duration, int flags) {
2943 if (!dtmf_allowed_) {
2948 if (flags & cricket::DF_SEND) {
2951 bool default_channel_is_inuse = false;
2952 for (ChannelMap::const_iterator iter = send_channels_.begin();
2953 iter != send_channels_.end(); ++iter) {
2954 if (IsDefaultChannel(iter->second->channel())) {
2955 default_channel_is_inuse = true;
2959 if (default_channel_is_inuse) {
2960 channel = voe_channel();
2961 } else if (!send_channels_.empty()) {
2962 channel = send_channels_.begin()->second->channel();
2965 channel = GetSendChannelNum(ssrc);
2967 if (channel == -1) {
2968 LOG(LS_WARNING) << "InsertDtmf - The specified ssrc "
2969 << ssrc << " is not in use.";
2972 // Send DTMF using out-of-band DTMF. ("true", as 3rd arg)
2973 if (engine()->voe()->dtmf()->SendTelephoneEvent(
2974 channel, event, true, duration) == -1) {
2975 LOG_RTCERR4(SendTelephoneEvent, channel, event, true, duration);
2981 if (flags & cricket::DF_PLAY) {
2982 // Play DTMF tone locally.
2983 if (engine()->voe()->dtmf()->PlayDtmfTone(event, duration) == -1) {
2984 LOG_RTCERR2(PlayDtmfTone, event, duration);
2992 void WebRtcVoiceMediaChannel::OnPacketReceived(
2993 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
2994 // Pick which channel to send this packet to. If this packet doesn't match
2995 // any multiplexed streams, just send it to the default channel. Otherwise,
2996 // send it to the specific decoder instance for that stream.
2997 int which_channel = GetReceiveChannelNum(
2998 ParseSsrc(packet->data(), packet->length(), false));
2999 if (which_channel == -1) {
3000 which_channel = voe_channel();
3003 // Stop any ringback that might be playing on the channel.
3004 // It's possible the ringback has already stopped, ih which case we'll just
3005 // use the opportunity to remove the channel from ringback_channels_.
3006 if (engine()->voe()->file()) {
3007 const std::set<int>::iterator it = ringback_channels_.find(which_channel);
3008 if (it != ringback_channels_.end()) {
3009 if (engine()->voe()->file()->IsPlayingFileLocally(
3010 which_channel) == 1) {
3011 engine()->voe()->file()->StopPlayingFileLocally(which_channel);
3012 LOG(LS_INFO) << "Stopped ringback on channel " << which_channel
3013 << " due to incoming media";
3015 ringback_channels_.erase(which_channel);
3019 // Pass it off to the decoder.
3020 engine()->voe()->network()->ReceivedRTPPacket(
3023 static_cast<unsigned int>(packet->length()));
3026 void WebRtcVoiceMediaChannel::OnRtcpReceived(
3027 talk_base::Buffer* packet, const talk_base::PacketTime& packet_time) {
3028 // Sending channels need all RTCP packets with feedback information.
3029 // Even sender reports can contain attached report blocks.
3030 // Receiving channels need sender reports in order to create
3031 // correct receiver reports.
3033 if (!GetRtcpType(packet->data(), packet->length(), &type)) {
3034 LOG(LS_WARNING) << "Failed to parse type from received RTCP packet";
3038 // If it is a sender report, find the channel that is listening.
3039 bool has_sent_to_default_channel = false;
3040 if (type == kRtcpTypeSR) {
3041 int which_channel = GetReceiveChannelNum(
3042 ParseSsrc(packet->data(), packet->length(), true));
3043 if (which_channel != -1) {
3044 engine()->voe()->network()->ReceivedRTCPPacket(
3047 static_cast<unsigned int>(packet->length()));
3049 if (IsDefaultChannel(which_channel))
3050 has_sent_to_default_channel = true;
3054 // SR may continue RR and any RR entry may correspond to any one of the send
3055 // channels. So all RTCP packets must be forwarded all send channels. VoE
3056 // will filter out RR internally.
3057 for (ChannelMap::iterator iter = send_channels_.begin();
3058 iter != send_channels_.end(); ++iter) {
3059 // Make sure not sending the same packet to default channel more than once.
3060 if (IsDefaultChannel(iter->second->channel()) &&
3061 has_sent_to_default_channel)
3064 engine()->voe()->network()->ReceivedRTCPPacket(
3065 iter->second->channel(),
3067 static_cast<unsigned int>(packet->length()));
3071 bool WebRtcVoiceMediaChannel::MuteStream(uint32 ssrc, bool muted) {
3072 int channel = (ssrc == 0) ? voe_channel() : GetSendChannelNum(ssrc);
3073 if (channel == -1) {
3074 LOG(LS_WARNING) << "The specified ssrc " << ssrc << " is not in use.";
3077 if (engine()->voe()->volume()->SetInputMute(channel, muted) == -1) {
3078 LOG_RTCERR2(SetInputMute, channel, muted);
3084 bool WebRtcVoiceMediaChannel::SetStartSendBandwidth(int bps) {
3085 // TODO(andresp): Add support for setting an independent start bandwidth when
3086 // bandwidth estimation is enabled for voice engine.
3090 bool WebRtcVoiceMediaChannel::SetMaxSendBandwidth(int bps) {
3091 LOG(LS_INFO) << "WebRtcVoiceMediaChanne::SetSendBandwidth.";
3093 return SetSendBandwidthInternal(bps);
3096 bool WebRtcVoiceMediaChannel::SetSendBandwidthInternal(int bps) {
3097 LOG(LS_INFO) << "WebRtcVoiceMediaChannel::SetSendBandwidthInternal.";
3099 send_bw_setting_ = true;
3103 LOG(LS_INFO) << "The send codec has not been set up yet. "
3104 << "The send bandwidth setting will be applied later.";
3108 // Bandwidth is auto by default.
3109 // TODO(bemasc): Fix this so that if SetMaxSendBandwidth(50) is followed by
3110 // SetMaxSendBandwith(0), the second call removes the previous limit.
3114 webrtc::CodecInst codec = *send_codec_;
3115 bool is_multi_rate = IsCodecMultiRate(codec);
3117 if (is_multi_rate) {
3118 // If codec is multi-rate then just set the bitrate.
3120 if (!SetSendCodec(codec)) {
3121 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3122 << " to bitrate " << bps << " bps.";
3127 // If codec is not multi-rate and |bps| is less than the fixed bitrate
3128 // then fail. If codec is not multi-rate and |bps| exceeds or equal the
3129 // fixed bitrate then ignore.
3130 if (bps < codec.rate) {
3131 LOG(LS_INFO) << "Failed to set codec " << codec.plname
3132 << " to bitrate " << bps << " bps"
3133 << ", requires at least " << codec.rate << " bps.";
3140 bool WebRtcVoiceMediaChannel::GetStats(VoiceMediaInfo* info) {
3141 bool echo_metrics_on = false;
3142 // These can take on valid negative values, so use the lowest possible level
3143 // as default rather than -1.
3144 int echo_return_loss = -100;
3145 int echo_return_loss_enhancement = -100;
3146 // These can also be negative, but in practice -1 is only used to signal
3147 // insufficient data, since the resolution is limited to multiples of 4 ms.
3148 int echo_delay_median_ms = -1;
3149 int echo_delay_std_ms = -1;
3150 if (engine()->voe()->processing()->GetEcMetricsStatus(
3151 echo_metrics_on) != -1 && echo_metrics_on) {
3152 // TODO(ajm): we may want to use VoECallReport::GetEchoMetricsSummary
3153 // here, but it appears to be unsuitable currently. Revisit after this is
3154 // investigated: http://b/issue?id=5666755
3155 int erl, erle, rerl, anlp;
3156 if (engine()->voe()->processing()->GetEchoMetrics(
3157 erl, erle, rerl, anlp) != -1) {
3158 echo_return_loss = erl;
3159 echo_return_loss_enhancement = erle;
3163 if (engine()->voe()->processing()->GetEcDelayMetrics(median, std) != -1) {
3164 echo_delay_median_ms = median;
3165 echo_delay_std_ms = std;
3169 webrtc::CallStatistics cs;
3171 webrtc::CodecInst codec;
3174 for (ChannelMap::const_iterator channel_iter = send_channels_.begin();
3175 channel_iter != send_channels_.end(); ++channel_iter) {
3176 const int channel = channel_iter->second->channel();
3178 // Fill in the sender info, based on what we know, and what the
3179 // remote side told us it got from its RTCP report.
3180 VoiceSenderInfo sinfo;
3182 if (engine()->voe()->rtp()->GetRTCPStatistics(channel, cs) == -1 ||
3183 engine()->voe()->rtp()->GetLocalSSRC(channel, ssrc) == -1) {
3187 sinfo.add_ssrc(ssrc);
3188 sinfo.codec_name = send_codec_.get() ? send_codec_->plname : "";
3189 sinfo.bytes_sent = cs.bytesSent;
3190 sinfo.packets_sent = cs.packetsSent;
3191 // RTT isn't known until a RTCP report is received. Until then, VoiceEngine
3192 // returns 0 to indicate an error value.
3193 sinfo.rtt_ms = (cs.rttMs > 0) ? cs.rttMs : -1;
3195 // Get data from the last remote RTCP report. Use default values if no data
3197 sinfo.fraction_lost = -1.0;
3198 sinfo.jitter_ms = -1;
3199 sinfo.packets_lost = -1;
3200 sinfo.ext_seqnum = -1;
3201 std::vector<webrtc::ReportBlock> receive_blocks;
3202 if (engine()->voe()->rtp()->GetRemoteRTCPReportBlocks(
3203 channel, &receive_blocks) != -1 &&
3204 engine()->voe()->codec()->GetSendCodec(channel, codec) != -1) {
3205 std::vector<webrtc::ReportBlock>::iterator iter;
3206 for (iter = receive_blocks.begin(); iter != receive_blocks.end();
3208 // Lookup report for send ssrc only.
3209 if (iter->source_SSRC == sinfo.ssrc()) {
3210 // Convert Q8 to floating point.
3211 sinfo.fraction_lost = static_cast<float>(iter->fraction_lost) / 256;
3212 // Convert samples to milliseconds.
3213 if (codec.plfreq / 1000 > 0) {
3214 sinfo.jitter_ms = iter->interarrival_jitter / (codec.plfreq / 1000);
3216 sinfo.packets_lost = iter->cumulative_num_packets_lost;
3217 sinfo.ext_seqnum = iter->extended_highest_sequence_number;
3223 // Local speech level.
3224 sinfo.audio_level = (engine()->voe()->volume()->
3225 GetSpeechInputLevelFullRange(level) != -1) ? level : -1;
3227 // TODO(xians): We are injecting the same APM logging to all the send
3228 // channels here because there is no good way to know which send channel
3229 // is using the APM. The correct fix is to allow the send channels to have
3230 // their own APM so that we can feed the correct APM logging to different
3231 // send channels. See issue crbug/264611 .
3232 sinfo.echo_return_loss = echo_return_loss;
3233 sinfo.echo_return_loss_enhancement = echo_return_loss_enhancement;
3234 sinfo.echo_delay_median_ms = echo_delay_median_ms;
3235 sinfo.echo_delay_std_ms = echo_delay_std_ms;
3236 // TODO(ajm): Re-enable this metric once we have a reliable implementation.
3237 sinfo.aec_quality_min = -1;
3238 sinfo.typing_noise_detected = typing_noise_detected_;
3240 info->senders.push_back(sinfo);
3243 // Build the list of receivers, one for each receiving channel, or 1 in
3245 std::vector<int> channels;
3246 for (ChannelMap::const_iterator it = receive_channels_.begin();
3247 it != receive_channels_.end(); ++it) {
3248 channels.push_back(it->second->channel());
3250 if (channels.empty()) {
3251 channels.push_back(voe_channel());
3254 // Get the SSRC and stats for each receiver, based on our own calculations.
3255 for (std::vector<int>::const_iterator it = channels.begin();
3256 it != channels.end(); ++it) {
3257 memset(&cs, 0, sizeof(cs));
3258 if (engine()->voe()->rtp()->GetRemoteSSRC(*it, ssrc) != -1 &&
3259 engine()->voe()->rtp()->GetRTCPStatistics(*it, cs) != -1 &&
3260 engine()->voe()->codec()->GetRecCodec(*it, codec) != -1) {
3261 VoiceReceiverInfo rinfo;
3262 rinfo.add_ssrc(ssrc);
3263 rinfo.bytes_rcvd = cs.bytesReceived;
3264 rinfo.packets_rcvd = cs.packetsReceived;
3265 // The next four fields are from the most recently sent RTCP report.
3266 // Convert Q8 to floating point.
3267 rinfo.fraction_lost = static_cast<float>(cs.fractionLost) / (1 << 8);
3268 rinfo.packets_lost = cs.cumulativeLost;
3269 rinfo.ext_seqnum = cs.extendedMax;
3270 // Convert samples to milliseconds.
3271 if (codec.plfreq / 1000 > 0) {
3272 rinfo.jitter_ms = cs.jitterSamples / (codec.plfreq / 1000);
3275 // Get jitter buffer and total delay (alg + jitter + playout) stats.
3276 webrtc::NetworkStatistics ns;
3277 if (engine()->voe()->neteq() &&
3278 engine()->voe()->neteq()->GetNetworkStatistics(
3280 rinfo.jitter_buffer_ms = ns.currentBufferSize;
3281 rinfo.jitter_buffer_preferred_ms = ns.preferredBufferSize;
3283 static_cast<float>(ns.currentExpandRate) / (1 << 14);
3286 webrtc::AudioDecodingCallStats ds;
3287 if (engine()->voe()->neteq() &&
3288 engine()->voe()->neteq()->GetDecodingCallStatistics(
3290 rinfo.decoding_calls_to_silence_generator =
3291 ds.calls_to_silence_generator;
3292 rinfo.decoding_calls_to_neteq = ds.calls_to_neteq;
3293 rinfo.decoding_normal = ds.decoded_normal;
3294 rinfo.decoding_plc = ds.decoded_plc;
3295 rinfo.decoding_cng = ds.decoded_cng;
3296 rinfo.decoding_plc_cng = ds.decoded_plc_cng;
3299 if (engine()->voe()->sync()) {
3300 int jitter_buffer_delay_ms = 0;
3301 int playout_buffer_delay_ms = 0;
3302 engine()->voe()->sync()->GetDelayEstimate(
3303 *it, &jitter_buffer_delay_ms, &playout_buffer_delay_ms);
3304 rinfo.delay_estimate_ms = jitter_buffer_delay_ms +
3305 playout_buffer_delay_ms;
3308 // Get speech level.
3309 rinfo.audio_level = (engine()->voe()->volume()->
3310 GetSpeechOutputLevelFullRange(*it, level) != -1) ? level : -1;
3311 info->receivers.push_back(rinfo);
3318 void WebRtcVoiceMediaChannel::GetLastMediaError(
3319 uint32* ssrc, VoiceMediaChannel::Error* error) {
3320 ASSERT(ssrc != NULL);
3321 ASSERT(error != NULL);
3322 FindSsrc(voe_channel(), ssrc);
3323 *error = WebRtcErrorToChannelError(GetLastEngineError());
3326 bool WebRtcVoiceMediaChannel::FindSsrc(int channel_num, uint32* ssrc) {
3327 talk_base::CritScope lock(&receive_channels_cs_);
3328 ASSERT(ssrc != NULL);
3329 if (channel_num == -1 && send_ != SEND_NOTHING) {
3330 // Sometimes the VoiceEngine core will throw error with channel_num = -1.
3331 // This means the error is not limited to a specific channel. Signal the
3332 // message using ssrc=0. If the current channel is sending, use this
3333 // channel for sending the message.
3337 // Check whether this is a sending channel.
3338 for (ChannelMap::const_iterator it = send_channels_.begin();
3339 it != send_channels_.end(); ++it) {
3340 if (it->second->channel() == channel_num) {
3341 // This is a sending channel.
3342 uint32 local_ssrc = 0;
3343 if (engine()->voe()->rtp()->GetLocalSSRC(
3344 channel_num, local_ssrc) != -1) {
3351 // Check whether this is a receiving channel.
3352 for (ChannelMap::const_iterator it = receive_channels_.begin();
3353 it != receive_channels_.end(); ++it) {
3354 if (it->second->channel() == channel_num) {
3363 void WebRtcVoiceMediaChannel::OnError(uint32 ssrc, int error) {
3364 if (error == VE_TYPING_NOISE_WARNING) {
3365 typing_noise_detected_ = true;
3366 } else if (error == VE_TYPING_NOISE_OFF_WARNING) {
3367 typing_noise_detected_ = false;
3369 SignalMediaError(ssrc, WebRtcErrorToChannelError(error));
3372 int WebRtcVoiceMediaChannel::GetOutputLevel(int channel) {
3373 unsigned int ulevel;
3375 engine()->voe()->volume()->GetSpeechOutputLevel(channel, ulevel);
3376 return (ret == 0) ? static_cast<int>(ulevel) : -1;
3379 int WebRtcVoiceMediaChannel::GetReceiveChannelNum(uint32 ssrc) {
3380 ChannelMap::iterator it = receive_channels_.find(ssrc);
3381 if (it != receive_channels_.end())
3382 return it->second->channel();
3383 return (ssrc == default_receive_ssrc_) ? voe_channel() : -1;
3386 int WebRtcVoiceMediaChannel::GetSendChannelNum(uint32 ssrc) {
3387 ChannelMap::iterator it = send_channels_.find(ssrc);
3388 if (it != send_channels_.end())
3389 return it->second->channel();
3394 bool WebRtcVoiceMediaChannel::GetRedSendCodec(const AudioCodec& red_codec,
3395 const std::vector<AudioCodec>& all_codecs, webrtc::CodecInst* send_codec) {
3396 // Get the RED encodings from the parameter with no name. This may
3397 // change based on what is discussed on the Jingle list.
3398 // The encoding parameter is of the form "a/b"; we only support where
3399 // a == b. Verify this and parse out the value into red_pt.
3400 // If the parameter value is absent (as it will be until we wire up the
3401 // signaling of this message), use the second codec specified (i.e. the
3402 // one after "red") as the encoding parameter.
3404 std::string red_params;
3405 CodecParameterMap::const_iterator it = red_codec.params.find("");
3406 if (it != red_codec.params.end()) {
3407 red_params = it->second;
3408 std::vector<std::string> red_pts;
3409 if (talk_base::split(red_params, '/', &red_pts) != 2 ||
3410 red_pts[0] != red_pts[1] ||
3411 !talk_base::FromString(red_pts[0], &red_pt)) {
3412 LOG(LS_WARNING) << "RED params " << red_params << " not supported.";
3415 } else if (red_codec.params.empty()) {
3416 LOG(LS_WARNING) << "RED params not present, using defaults";
3417 if (all_codecs.size() > 1) {
3418 red_pt = all_codecs[1].id;
3422 // Try to find red_pt in |codecs|.
3423 std::vector<AudioCodec>::const_iterator codec;
3424 for (codec = all_codecs.begin(); codec != all_codecs.end(); ++codec) {
3425 if (codec->id == red_pt)
3429 // If we find the right codec, that will be the codec we pass to
3430 // SetSendCodec, with the desired payload type.
3431 if (codec != all_codecs.end() &&
3432 engine()->FindWebRtcCodec(*codec, send_codec)) {
3434 LOG(LS_WARNING) << "RED params " << red_params << " are invalid.";
3441 bool WebRtcVoiceMediaChannel::EnableRtcp(int channel) {
3442 if (engine()->voe()->rtp()->SetRTCPStatus(channel, true) == -1) {
3443 LOG_RTCERR2(SetRTCPStatus, channel, 1);
3446 // TODO(juberti): Enable VQMon and RTCP XR reports, once we know what
3447 // what we want to do with them.
3448 // engine()->voe().EnableVQMon(voe_channel(), true);
3449 // engine()->voe().EnableRTCP_XR(voe_channel(), true);
3453 bool WebRtcVoiceMediaChannel::ResetRecvCodecs(int channel) {
3454 int ncodecs = engine()->voe()->codec()->NumOfCodecs();
3455 for (int i = 0; i < ncodecs; ++i) {
3456 webrtc::CodecInst voe_codec;
3457 if (engine()->voe()->codec()->GetCodec(i, voe_codec) != -1) {
3458 voe_codec.pltype = -1;
3459 if (engine()->voe()->codec()->SetRecPayloadType(
3460 channel, voe_codec) == -1) {
3461 LOG_RTCERR2(SetRecPayloadType, channel, ToString(voe_codec));
3469 bool WebRtcVoiceMediaChannel::SetPlayout(int channel, bool playout) {
3471 LOG(LS_INFO) << "Starting playout for channel #" << channel;
3472 if (engine()->voe()->base()->StartPlayout(channel) == -1) {
3473 LOG_RTCERR1(StartPlayout, channel);
3477 LOG(LS_INFO) << "Stopping playout for channel #" << channel;
3478 engine()->voe()->base()->StopPlayout(channel);
3483 uint32 WebRtcVoiceMediaChannel::ParseSsrc(const void* data, size_t len,
3485 size_t ssrc_pos = (!rtcp) ? 8 : 4;
3487 if (len >= (ssrc_pos + sizeof(ssrc))) {
3488 ssrc = talk_base::GetBE32(static_cast<const char*>(data) + ssrc_pos);
3493 // Convert VoiceEngine error code into VoiceMediaChannel::Error enum.
3494 VoiceMediaChannel::Error
3495 WebRtcVoiceMediaChannel::WebRtcErrorToChannelError(int err_code) {
3499 case VE_CANNOT_START_RECORDING:
3500 case VE_MIC_VOL_ERROR:
3501 case VE_GET_MIC_VOL_ERROR:
3502 case VE_CANNOT_ACCESS_MIC_VOL:
3503 return ERROR_REC_DEVICE_OPEN_FAILED;
3504 case VE_SATURATION_WARNING:
3505 return ERROR_REC_DEVICE_SATURATION;
3506 case VE_REC_DEVICE_REMOVED:
3507 return ERROR_REC_DEVICE_REMOVED;
3508 case VE_RUNTIME_REC_WARNING:
3509 case VE_RUNTIME_REC_ERROR:
3510 return ERROR_REC_RUNTIME_ERROR;
3511 case VE_CANNOT_START_PLAYOUT:
3512 case VE_SPEAKER_VOL_ERROR:
3513 case VE_GET_SPEAKER_VOL_ERROR:
3514 case VE_CANNOT_ACCESS_SPEAKER_VOL:
3515 return ERROR_PLAY_DEVICE_OPEN_FAILED;
3516 case VE_RUNTIME_PLAY_WARNING:
3517 case VE_RUNTIME_PLAY_ERROR:
3518 return ERROR_PLAY_RUNTIME_ERROR;
3519 case VE_TYPING_NOISE_WARNING:
3520 return ERROR_REC_TYPING_NOISE_DETECTED;
3522 return VoiceMediaChannel::ERROR_OTHER;
3526 bool WebRtcVoiceMediaChannel::SetHeaderExtension(ExtensionSetterFunction setter,
3527 int channel_id, const RtpHeaderExtension* extension) {
3528 bool enable = false;
3534 uri = extension->uri;
3536 if ((engine()->voe()->rtp()->*setter)(channel_id, enable, id) != 0) {
3537 LOG_RTCERR4(*setter, uri, channel_id, enable, id);
3543 int WebRtcSoundclipStream::Read(void *buf, int len) {
3545 mem_.Read(buf, len, &res, NULL);
3546 return static_cast<int>(res);
3549 int WebRtcSoundclipStream::Rewind() {
3551 // Return -1 to keep VoiceEngine from looping.
3552 return (loop_) ? 0 : -1;
3555 } // namespace cricket
3557 #endif // HAVE_WEBRTC_VOICE